Fw: Python installation problem

2020-04-01 Thread HERNANDEZ AGUIRRE JOSE GABRIEL DE LA DOLOROSA



En Mar, 31 Marzo, 2020 en 18:48, yo  escribió:
 

Para: python-list@python.org

I  installed  the Python software , but I could not find the python.exe file 
with the Unscramble software


What do you advise ?


Regards



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


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-30 Thread David Gabriel
Dears,

When I run this command I got this error message:

ubuntu@orchestrateur:/tmp/pack$ virtualenv -p $(which python3.5) .
Running virtualenv with interpreter /usr/local/sbin/.
Traceback (most recent call last):
  File "/usr/bin/virtualenv", line 3, in 
virtualenv.main()
  File "/usr/lib/python2.7/dist-packages/virtualenv.py", line 784, in main
popen = subprocess.Popen([interpreter, file] + sys.argv[1:], env=env)
  File "/usr/lib/python2.7/subprocess.py", line 710, in __init__
errread, errwrite)
  File "/usr/lib/python2.7/subprocess.py", line 1327, in _execute_child
raise child_exception
OSError: [Errno 13] Permission denied


This error is also reproducible using sudo.
Please advise how to fix it.

Thanks in advance.
Best regards


2017-10-28 14:33 GMT+02:00 David Gabriel :

> I forget to precise that I am using pycharm.
> And this issue is reproducible also using command line to run the code.
>
> Best regards
>
> 2017-10-28 14:31 GMT+02:00 David Gabriel :
>
>> Thanks so Lutz much for your reply.
>> I am using python2.7 and I am running this code in an Openstack instance.
>> I will apply your recommandation and let you know about the result ...
>>
>> Kind regards.
>>
>> 2017-10-27 16:13 GMT+02:00 Lutz Horn :
>>
>>> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote:
>>> > from packaging import version as pack_version
>>> > ImportError: No module named packaging
>>> >
>>> > I googled it and I have found so many suggestions regarding updating
>>> > 'pip' and installing python-setuptools but all of these did not fix
>>> > this issue.
>>>
>>> So many questions:
>>>
>>> * What is your Python version?
>>> * Do you use virtualenv?
>>> * How?
>>> * Did you install packaging in this virtualenv?
>>>
>>> Just one example of making this work:
>>>
>>> $ mkdir /tmp/pack
>>> $ cd /tmp/pack
>>> $ virtualenv -p $(which python3.5) .
>>> Running virtualenv with interpreter /usr/bin/python3.5
>>> Using base prefix '/usr'
>>> New python executable in /tmp/pack/bin/python3.5
>>> Also creating executable in /tmp/pack/bin/python
>>> Installing setuptools, pkg_resources, pip, wheel...done.
>>> $ source bin/activate
>>> $ pip3 install packaging
>>> Collecting packaging
>>>   Using cached packaging-16.8-py2.py3-none-any.whl
>>> Collecting six (from packaging)
>>>   Using cached six-1.11.0-py2.py3-none-any.whl
>>> Collecting pyparsing (from packaging)
>>>   Using cached pyparsing-2.2.0-py2.py3-none-any.whl
>>> Installing collected packages: six, pyparsing, packaging
>>> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0
>>> $ python3.5
>>> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
>>> [GCC 5.4.0 20160609] on linux
>>> Type "help", "copyright", "credits" or "license" for more
>>> information.
>>> >>> from packaging import version as pack_version
>>> >>>
>>> --
>>> https://mail.python.org/mailman/listinfo/python-list
>>>
>>
>>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-28 Thread David Gabriel
I forget to precise that I am using pycharm.
And this issue is reproducible also using command line to run the code.

Best regards

2017-10-28 14:31 GMT+02:00 David Gabriel :

> Thanks so Lutz much for your reply.
> I am using python2.7 and I am running this code in an Openstack instance.
> I will apply your recommandation and let you know about the result ...
>
> Kind regards.
>
> 2017-10-27 16:13 GMT+02:00 Lutz Horn :
>
>> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote:
>> > from packaging import version as pack_version
>> > ImportError: No module named packaging
>> >
>> > I googled it and I have found so many suggestions regarding updating
>> > 'pip' and installing python-setuptools but all of these did not fix
>> > this issue.
>>
>> So many questions:
>>
>> * What is your Python version?
>> * Do you use virtualenv?
>> * How?
>> * Did you install packaging in this virtualenv?
>>
>> Just one example of making this work:
>>
>> $ mkdir /tmp/pack
>> $ cd /tmp/pack
>> $ virtualenv -p $(which python3.5) .
>> Running virtualenv with interpreter /usr/bin/python3.5
>> Using base prefix '/usr'
>> New python executable in /tmp/pack/bin/python3.5
>> Also creating executable in /tmp/pack/bin/python
>> Installing setuptools, pkg_resources, pip, wheel...done.
>> $ source bin/activate
>> $ pip3 install packaging
>> Collecting packaging
>>   Using cached packaging-16.8-py2.py3-none-any.whl
>> Collecting six (from packaging)
>>   Using cached six-1.11.0-py2.py3-none-any.whl
>> Collecting pyparsing (from packaging)
>>   Using cached pyparsing-2.2.0-py2.py3-none-any.whl
>> Installing collected packages: six, pyparsing, packaging
>> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0
>> $ python3.5
>> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
>> [GCC 5.4.0 20160609] on linux
>> Type "help", "copyright", "credits" or "license" for more
>> information.
>> >>> from packaging import version as pack_version
>> >>>
>> --
>> https://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: from packaging import version as pack_version ImportError: No module named packaging

2017-10-28 Thread David Gabriel
Thanks so Lutz much for your reply.
I am using python2.7 and I am running this code in an Openstack instance.
I will apply your recommandation and let you know about the result ...

Kind regards.

2017-10-27 16:13 GMT+02:00 Lutz Horn :

> On Fri, Oct 27, 2017 at 03:56:39PM +0200, David Gabriel wrote:
> > from packaging import version as pack_version
> > ImportError: No module named packaging
> >
> > I googled it and I have found so many suggestions regarding updating
> > 'pip' and installing python-setuptools but all of these did not fix
> > this issue.
>
> So many questions:
>
> * What is your Python version?
> * Do you use virtualenv?
> * How?
> * Did you install packaging in this virtualenv?
>
> Just one example of making this work:
>
> $ mkdir /tmp/pack
> $ cd /tmp/pack
> $ virtualenv -p $(which python3.5) .
> Running virtualenv with interpreter /usr/bin/python3.5
> Using base prefix '/usr'
> New python executable in /tmp/pack/bin/python3.5
> Also creating executable in /tmp/pack/bin/python
> Installing setuptools, pkg_resources, pip, wheel...done.
> $ source bin/activate
> $ pip3 install packaging
> Collecting packaging
>   Using cached packaging-16.8-py2.py3-none-any.whl
> Collecting six (from packaging)
>   Using cached six-1.11.0-py2.py3-none-any.whl
> Collecting pyparsing (from packaging)
>   Using cached pyparsing-2.2.0-py2.py3-none-any.whl
> Installing collected packages: six, pyparsing, packaging
> Successfully installed packaging-16.8 pyparsing-2.2.0 six-1.11.0
> $ python3.5
> Python 3.5.2 (default, Sep 14 2017, 22:51:06)
> [GCC 5.4.0 20160609] on linux
> Type "help", "copyright", "credits" or "license" for more
> information.
> >>> from packaging import version as pack_version
> >>>
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


from packaging import version as pack_version ImportError: No module named packaging

2017-10-27 Thread David Gabriel
Dears,

I am running a python code that generates for me this error :

from packaging import version as pack_version
ImportError: No module named packaging

I googled it and I have found so many suggestions regarding updating 'pip'
and installing python-setuptools but all of these did not fix this issue.

Do you have any idea how can I solve this problem.
Thanks in advance.
-- 
https://mail.python.org/mailman/listinfo/python-list


Send mouse clicks to minimized window

2017-08-28 Thread gabriel . lins97
Hello, guys

I'm using python to automate some seriously boring stuff at work, but would 
like to improve current code.

The way it is now, PyAutoGui moves mouse and clicks the Application. I am, 
therefore, hostage of my python "assistant", as I cannot use my computer while 
the .py is running.

Is there any way to send mouse clicks to minimized windows, in so that it does 
not interfere with normal using of my computer?

I'm on Windows and have tried pywin32, but could not manage to make it to work. 
Also tried ctypes, with same results. I'm really new to python. Also, I could 
migrate to Linux if that's necessary. 

Any hints?

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


custom setup.py link argument order

2017-03-07 Thread Gabriel Ganne
Hi,


I'm currently writing a python C module which has a chained dependency:

- mymodule requires libb

- libb requires liba


To that effect, within setup.py, I link against both liba and libb

  libraries=['a', 'b'],


Also, as I'm working on Ubuntu, I want to add -Wl,--no-as-needed to make sure 
that the symbols not immediately needed will still be stripped.

  extra_link_args=['-Wl,--no-as-needed'],


However, it seems that the extra_link_args are systematically appended at the 
end of the link line, but for this to work, the '-Wl,--no-as-needed' argument 
need to be *before* the link against my two libraries.


How can I choose the order of my link arguments that I pass to gcc using 
setup.py ?


Best regards,


--

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


error sintax

2016-03-22 Thread Gabriel Forcarelli dos Santos
meu python não esta reconhecendo os sinais de calculos em geral, peço a
ajuda de vocês.
-- 
https://mail.python.org/mailman/listinfo/python-list


Another python question

2016-03-18 Thread Alan Gabriel
Sorry for the multiple questions but my while loop is not working as intended.

Here is the code :
n = 1
list1 = []
count = 0  #amount of times program repeats
steps = 0 # amount of steps to reach 1
step_list = []
while n!=0:
n= int(input())
list1.append(n)
length = len(list1)

while count < length:
num= list1[count]
while num!= 1:
if num%2 == 0:
num= int(num/2)
print(num)
steps+=1
if num%2 == 1:
num=int(3*num+1)
print(num)
steps+=1

count+=1
step_list.append(steps)
steps=0

This code is meant to get numbers from the user in different lines and convert 
into a list. When this is done the first while loop  runs until it checks all 
the numbers in the list. The 2nd while loop is meant to stop when the number is 
equal to 1 however the 2nd while loop keeps running.

Sorry for the bad naming but I was in a rush, ty anyway



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


Beginner Python Help

2016-03-18 Thread Alan Gabriel
Hey there,

I just started out python and I was doing a activity where im trying to find 
the max and min of a list of numbers i inputted.

This is my code..

num=input("Enter list of numbers")
list1=(num.split())

maxim= (max(list1))
minim= (min(list1))

print(minim, maxim)



So the problem is that when I enter numbers with an uneven amount of digits 
(e.g. I enter 400 20 36 85 100) I do not get 400 as the maximum nor 20 as the 
minimum. What have I done wrong in the code?

Thanks for the help
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: parallel (concurrent) eventlet

2016-01-18 Thread David Gabriel
Dears,

Let me add one more detail: When I add these two lines to check whether my
modules are monkey_patched or not I get *False* as a result.
I think it is strange to get this result since I patched my modules at the
beginning using: eventlet.monkey_patch() as detailed here
<http://eventlet.net/doc/patching.html#import-green>.

print "*is_monkey_patched(ldap.syncrepl) : %s*" %
eventlet.patcher.is_monkey_patched('ldap.syncrepl')
print "*is_monkey_patched(ldap.ldapobject) : %s*" %
eventlet.patcher.is_monkey_patched('ldap.ldapobject')


Please advise me how to fix this issue.
Kind regards.


2016-01-18 12:03 GMT+01:00 David Gabriel :

> Dears,
>
> I have an issue when I use eventlet Api to create parallel threads.
> In fact, when I run the below code, only the program dealing with the
> synchronozation with ldap data base is working and is continuously blocking
> the others to run.
> But, when I use the 'thread' Api the program is working fine without any
> blocking issue. However, I can not use thread Api and I must to use
> eventlet.
> So I am wondering how to get the thread Api behavior using the eventlet
> Api ?
>
> Could you please inform me how to fix this issue ?
>
> Kindly find below my code.
> But you need some configurations regarding ldap server/client.
>
>
> #!/usr/bin/python
> # -*- coding: utf-8 -*-
> """
> This script implements a syncrepl consumer which syncs data from an
> OpenLDAP
> server to a local (shelve) database.
> Notes:
> The bound user needs read access to the attributes entryDN and entryCSN.
> This needs the following software:
> Python
> pyasn1 0.1.4+
> pyasn1-modules
> python-ldap 2.4.10+
> """
>
> # Import the python-ldap modules
> import ldap,ldapurl
> # Import specific classes from python-ldap
> from ldap.ldapobject import ReconnectLDAPObject
> from ldap.syncrepl import SyncreplConsumer
>
> # Import modules from Python standard lib
> import shelve,signal,time,sys,logging
> import eventlet
> #import thread
> eventlet.monkey_patch()
>
> # Global state
> watcher_running = True
> ldap_connection = False
>
>
>
> class SyncReplConsumer(ReconnectLDAPObject,SyncreplConsumer):
> """
> Syncrepl Consumer interface
> """
> def __init__(self,db_path,*args,**kwargs):
> # Initialise the LDAP Connection first
> ldap.ldapobject.ReconnectLDAPObject.__init__(self, *args, **kwargs)
> # Now prepare the data store
> self.__data = shelve.open(db_path, 'c')
> # We need this for later internal use
> self.__presentUUIDs = dict()
>
> def __del__(self):
> # Close the data store properly to avoid corruption
> self.__data.close()
>
> def syncrepl_get_cookie(self):
> if 'cookie' in self.__data:
> return self.__data['cookie']
>
> def syncrepl_set_cookie(self,cookie):
> self.__data['cookie'] = cookie
>
> def syncrepl_entry(self,dn,attributes,uuid):
>
> # First we determine the type of change we have here (and store
> away the previous data for later if needed)
> previous_attributes = dict()
> if uuid in self.__data:
> change_type = 'modify'
> previous_attributes = self.__data[uuid]
> else:
> change_type = 'add'
> # Now we store our knowledge of the existence of this entry
> (including the DN as an attribute for convenience)
> attributes['dn'] = dn
> self.__data[uuid] = attributes
> # Debugging
> print 'Detected', change_type, 'of entry:', dn
> # If we have a cookie then this is not our first time being run,
> so it must be a change
> if 'ldap_cookie' in self.__data:
> self.perform_application_sync(dn, attributes,
> previous_attributes)
>
> def syncrepl_delete(self,uuids):
> # Make sure we know about the UUID being deleted, just in case...
> uuids = [uuid for uuid in uuids if uuid in self.__data]
> # Delete all the UUID values we know of
> for uuid in uuids:
> print 'Detected deletion of entry:', self.__data[uuid]['dn']
> del self.__data[uuid]
>
> def syncrepl_present(self,uuids,refreshDeletes=False):
> # If we have not been given any UUID values, then we have recieved
> all the present controls...
> if uuids is None:
> # We only do things if refreshDeletes is false as the syncre

parallel (concurrent) eventlet

2016-01-18 Thread David Gabriel
nal.signal(signal.SIGTERM,commenceShutdown)
# signal.signal(signal.SIGINT,commenceShutdown)
 try:
   ldap_url =
ldapurl.LDAPUrl('ldap://localhost/dc=example,dc=org?*?sub?(objectClass=*)?bindname=cn=admin%2cdc=test%2cdc=com,X-BINDPW=myPassword')#ldapurl.LDAPUrl(sys.argv[1])
 #  ldap_url = ldapurl.LDAPUrl(link)
   database_path = 'test.com'#sys.argv[2]
 #  database_path = pathName
 except IndexError,e:
   print 'Usage: syncrepl-client.py  '
   sys.exit(1)
 except ValueError,e:
   print 'Error parsing command-line arguments:',str(e)
   sys.exit(1)

 while watcher_running:
 print 'Connecting to LDAP server now...'
 # Prepare the LDAP server connection (triggers the connection as
well)
 ldap_connection =
SyncReplConsumer(database_path,ldap_url.initializeUrl())

 # Now we login to the LDAP server
 try:
 ldap_connection.simple_bind_s(ldap_url.who,ldap_url.cred)
 except ldap.INVALID_CREDENTIALS, e:
 print 'Login to LDAP server failed: ', str(e)
 sys.exit(1)
 except ldap.SERVER_DOWN:
 continue

 # Commence the syncing
 print 'Commencing sync process'
 ldap_search = ldap_connection.syncrepl_search(
   ldap_url.dn or '',
   ldap_url.scope or ldap.SCOPE_SUBTREE,
   mode = 'refreshAndPersist',
   filterstr = ldap_url.filterstr or '(objectClass=*)')
 print 'After syncrepl_search.'
 try:
 while ldap_connection.syncrepl_poll( all = 1, msgid =
ldap_search):
  pass
 except KeyboardInterrupt:
  # User asked to exit
 commenceShutdown()
 pass
 except Exception, e:
  # Handle any exception
 if watcher_running:
 print 'Encountered a problem, going to retry. Error:',
str(e)
 eventlet.sleep(5)
 pass

# Define a function for the 2nd thread
def print_time(ThreadName):
 count = 0
 delay = 3
 while 1:#count < 5:
 count += 1
 print "%s: %s" % (ThreadName, time.ctime(time.time()) )
 eventlet.sleep(delay)



print 'Before call threads'

evt1 = eventlet.spawn(mainOfSyncrepl, "Thread-1",)
evt2 = eventlet.spawn(print_time, "Thread-2",)
evt3 = eventlet.spawn(print_time, "Thread-3",)

print 'After call threads'

evt1.wait()
evt2.wait()
evt3.wait()

print 'After wait'



2016-01-12 7:20 GMT-08:00 Ned Batchelder :

> David,
>
> We aren't going to be able to debug code that we can't see.  Please post a
> link to the *actual* code that you are running.
>
> --Ned.
>
>
> On 1/12/16 7:00 AM, David Gabriel wrote:
>
> Dears
>
> For more details, I am using this code
> <https://github.com/rbarrois/python-ldap/blob/master/Demo/pyasn1/syncrepl.py>in
> order to ensure the updates from my data base.
> However, when I create an eventlet basing on this code, my program is
> blocked there and is not running other eventlets !!!
> Please advise me how to fix this issue ?
>
> Thanks in advance.
> Regards
>
> 2016-01-11 7:29 GMT-08:00 David Gabriel :
>
>> Thanks so much John
>> In fact your proposal works fine for this simple example but when I use
>> it for a complex code (a data base client that receives all updates from
>> the db), my program is continously running this db client and not other
>> programs.
>>
>> Any suggestions
>> Thanks in advance
>> regards
>>
>> 2016-01-11 5:50 GMT-08:00 John Eskew < 
>> john.es...@gmail.com>:
>>
>>> Add this line below your imports:
>>>
>>> eventlet.monkey_patch()
>>>
>>> Here's why that line should fix things:
>>>
>>> http://eventlet.net/doc/patching.html#greening-the-world
>>>
>>> On Mon, Jan 11, 2016 at 6:27 AM, David Gabriel < 
>>> davidgab...@gmail.com> wrote:
>>>
>>>> Dears,
>>>> It is the first time I am developping with python and I want to execute
>>>> parallel threads using eventlet.When I run the below code, only one thread
>>>> is executed and not both.Please could you tell me how to fix this issue ?
>>>> Please advise me how to ensure a concurrent behavior between evt1 and
>>>> evt2.
>>>>
>>>> import eventlet
>>>> import time
>>>>
>>>> def print_time(ThreadName):
>>>> count = 0
>>>> delay = 3
>>>> while 1:#count < 5:
>>>> count += 1

Re: Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
Mark Lawrence  wrote:

> I don't actually know, but could you please provide some context and 
> write in plain English, those damn ... things are extremely annoying.
> 

Hi, Mark. 

I am developing a research project, which includes video analysis (computer 
vision, big data, data mining, etc). The first part of the project is about 
building a database containing a big amount of video of urban zones. I live in 
Brazil, so the plan is collecting videos from urban areas of Brazilian big 
cities, like Sao Paulo. 

I have to make this task "automatic". in other words, I don't want to manually 
download hundreds or thousands hours of videos. So I have to develop a "robot" 
to do that assingment for me. (I wish I could do that using Python).

I have found a good website that provides me live images from several cities in 
Brazil. So that's it! That's what I need. I was expecting to develop a program 
to record & download those videos, that are being broadcasted live on that 
website. So I would be able to form my database and continue my research.

The problem is that this particular website uses a flash player application do 
broadcast the live images of the urban areas. I'm not too familiar with Flash 
Applications. I don't know how to deal with them using Python. I was wondering 
if someone could help me solve this problem. The goal is recording & 
downloading those videos, from the mentioned website. And, yes, it has to be an 
automated program (no manual work).

I wish I had been clear with you guys!

THX!

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


Re: Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
The original plan was doing it using python. But, anyway, I should build a 
robot program to do that task for me... Because I need to capture hundreds of 
hours of different videos... You mean that is difficult because it's Python... 
or it's difficult because it's a Flash Application?

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


Re: Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
Hi Paul, I presume the stream operator doesn't want to prevent me from 
downloading or recording the videos. I just wanna know more about some lib that 
could be used to deal with Flash Player Applications... Or possibly, anything 
that could lead me to be able to get those streaming videos.

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


Re: Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
I appreciate your help. I'm just afraid that Youtube-DL doesn't allow me to 
record or download a LIVE STREAMING VIDEO. Do you guys think it is possible, 
since I make some adjustments into the code of the library?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
Thanks for the Hint... But it seems not to support the website i mentioned... 
Is there a way to make it possible for any kind of video player in the net? 
Flash player... Since it's not a ordinary video... I'm trying to record & 
download a live streaming video!! 

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


Downloading videos (in flash applications) using python

2015-02-02 Thread Gabriel Ferreira
Hello, 

I need some help in downloading videos from flash applications in web using 
python. Is there any lib to deal with flash player using python?

The videos I need to download are, in fact, live streaming content.
You can see an example here:

http://vejoaovivo.com.br/sc/itapema/avenida-nereu-ramos-1029.html

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


Suggestion: PEP for popping slices from lists

2013-08-08 Thread Neatu Ovidiu Gabriel
The list.pop(index) returns the element represented by the index and also 
reduces the list by removing that element. So it a short one liner for doing 
both things.
But when it comes for popping a slice of the list there is nothing similar for 
doing in that simple way.

If you want to remove a slice and also reduce the list you will have something 
like this:

a_list, a_slice = a_list[:size], a_list[size:]

or even worser if you try to do the same for something in the middle.

My proposal is the extension of list.pop for accepting a way for popping slices.

When doing this:

a_list.pop(i,j)

pop will return the slice [i,j] and remove it from the list.

For popping from an index to the end:

a_list.pop(i, len(a_list))

Or even emptying the whole list:

a_list.pop(0, len(a_list))


So this is it :)
-- 
http://mail.python.org/mailman/listinfo/python-list


Random List Loop?!

2013-01-05 Thread Christian Gabriel
Hi

I have tried now for ages to make a loop that does the following:

Makes a new list with 9 random values, from 9 different lists, with 9 elements.

And makes sure that none of the elements repeat! 

Is there anyone that can help, with a very simple solution??

Best

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


Request META Help

2012-04-19 Thread Gabriel Novaes
I have a system that uses request.META ['HTTP_HOST'] to identify which will run 
APPLICATION.

The domains testes1.xyz.com.br, tes.xyzk.com.br, xx.xyzk.com.br through a DNS 
redirect TYPE A link to the server IP.

In most cases I get the request.META ['HTTP_HOST'] with the URL in the request 
header, but today I had a problem that a customer made an appointment for me, 
and I get the IP of the server that information. Actually I need to get 
tes.xyzk.com.br

Does anyone know better how it works? How can I overcome this?
-- 
http://mail.python.org/mailman/listinfo/python-list


[ANN] Python/Cython/SDL 2D Game Engine

2012-02-22 Thread Gabriel Jacobo
Hello list, I wanted to let you know about my pet project for the last few
months, a multiplatform (Linux64/Win32/Android at the moment),
Python/Cython/SDL open source 2D game engine called "Ignifuga".
The source code mixes Python and Cython code, then uses Cython to convert
everything to C, and compiles it all along with the Python interpreter and
SDL into a static binary.

It's still a long way of from being something serious, but you can already
make nice Android Live wallpapers with it!

You can check it out at www.ignifuga.org

Thanks!

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


Re: When I use Python under Windows. I found some file handles are not closed,

2011-11-01 Thread Gabriel Genellina
En Mon, 31 Oct 2011 12:57:15 -0300, 罗勇刚(Yonggang Luo)   
 escribió:


How did detecting where those handlers are created to tracing it and  
close

it.
Mainly because I was using C binding library(subvertpy) and file is not
closed.


A better place to ask is python-list@python.org

Please include the Python version you're using. Also, a small, complete,  
runnable code example showing the problem would be very valuable. Usually,  
in building such example, you may well find out where your problem is.


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


Re: Fast recursive generators?

2011-10-28 Thread Gabriel Genellina
En Fri, 28 Oct 2011 15:10:14 -0300, Michael McGlothlin  
 escribió:



I'm trying to generate a list of values where each value is dependent
on the previous value in the list and this bit of code needs to be
repeatedly so I'd like it to be fast. It doesn't seem that
comprehensions will work as each pass needs to take the result of the
previous pass as it's argument. map() doesn't seem likely. filter() or
reduce() seem workable but not very clean. Is there a good way to do
this? About the best I can get is this:

l = [ func ( start ) ]
f = lambda a: func ( l[-1] ) or a
filter ( f, range ( big_number, -1, -1 ) )


I guess I'm looking for something more like:

l = do ( lambda a: func ( a ), big_number, start )


What about a generator function?

def my_generator():
  prev = 1
  yield prev
  while True:
this = 2*prev
yield this
prev = this

print list(itertools.islice(my_generator(), 10))

--
Gabriel Genellina

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


Re: why msvcrt.printf show the first char only?

2011-10-15 Thread Gabriel Genellina
On 12 oct, 08:50, Nobody  wrote:
> On Wed, 12 Oct 2011 04:18:25 -0700, install...@189.cn wrote:
> > from ctypes import *
> > msvcrt = cdll.msvcrt
> > message_string = "Hello world!\n"
> > print(msvcrt.printf("Testing: %s", message_string))
>
> > when running in eclipse, the result is:
> > 1
> > T
>
> > when running in IDLE, then result is:
> > 1
>
> > why is that?
>
> Odd. I get 22 when running from IDLE.
>
> Also, when using the console, it actually prints the text. I suspect that
> stdout gets block-buffered when using an IDE. I can't see any way to get a
> reference to stdout, so you can't fflush() it.

Launch IDLE from the command line and you'll see the text output.

To the OP: I bet your Eclipse runs Python 2.x and IDLE is 3.x.

In Python 3.x, "Test..." is a Unicode string, internally represented
using two bytes per character. (In contrast, in Python 2.x, "Test..."
is a byte string, and u"Test..." is unicode). All ASCII characters
have a 0 as their second byte in its internal representation. printf
expects a byte string, and stops as soon as it sees the '\0' following
the 'T' in 'Testing'. Either use wprintf("Testing..."), or encode the
Unicode object into a byte string before calling:
printf("Testing...".encode(sys.stdout.encoding)), or tell ctypes about
the right parameter type:

printf = msvcrt.printf
printf.argtypes = [c_char_p]
printf("Testing\n")

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


Re: Deleting files on a shared server

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 04:45:32 -0300, Tim Golden   
escribió:

On 07/10/2011 02:14, Josh English wrote:



To delete the files, I am using os.unlink.

One lock file refuses to disappear, even though I have code at both
application startup and shutdown (on the OnInit and OnExit methods to
the wxPython Application object) that hunts down .lock files and
deletes them.


Assuming that your code paths succeed and that the unlink actually
happens, it is possible for files to continue to exist after they
have been successfully deleted. This happens if another process
has opened them with share-delete mode; typically this will be
a virus checker or a process like the TortoiseSVN cache (or its
counterparts for other VCS). The file won't actually disappear
until the last handle on it is released.


In such cases the openfiles command [1] is very useful for detecting who  
is holding the file open.


[1]  
http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/openfiles.mspx


--
Gabriel Genellina

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


Re: socket.getsockname is returning junk!!

2011-10-07 Thread Gabriel Genellina
En Wed, 05 Oct 2011 08:56:08 -0300, Wong Wah Meng-R32813  
 escribió:


I am migrating my application from python 1.5.2 to 2.7.1. One of the  
existing code breaks. The getsockname method from socket object somehow  
returns me with some number which I deem as junk, rather than the  
listening port as I would have expected in the older python. Has anyone  
seen the same thing or is it due to my python is built with some  
corrupted library or something?



$ python
Python 2.7.1 (r271:86832, Oct  5 2011, 18:34:15) [C] on hp-ux11
Type "help", "copyright", "credits" or "license" for more information.

import socket
sock = socket.socket( socket.AF_INET, socket.SOCK_STREAM )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_REUSEADDR, 1 )
sock.setsockopt( socket.SOL_SOCKET, socket.SO_KEEPALIVE, 1 )
sock.setsockopt( socket.IPPROTO_TCP, 1, 1 )
server_address=('zmy02hp3', 1)
sock.bind(server_address)
sock.getsockname()

(0, '\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00\x00')

In python 1.5.2

server_address=('zmy02aix04', 1)
sock.bind(server_address)
sock.getsockname()

('10.228.51.41', 1)


I'd say it's a problem with the _socket module; did the unit tests flag  
anything when you built Python?


On Windows, Python 2.7.1:


server_address=('lepton', 1)
sock.bind(server_address)
sock.getsockname()

('127.0.0.1', 1)

--
Gabriel Genellina

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


Re: sending ftp file list to mail???

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay   
escribió:


hi all. I want to get my ftp list and send the list to my mail adress...  
my codes are



baglanti = FTP("ftp.guncelyorum.org")
baglanti.login("**", "***")
print baglanti.dir()
posta = MIMEMultipart()
def posta_olustur():
posta['Subject']=konu
posta['From']=gmail_kullanici
posta['To']=kime
posta.attach(MIMEText(baglanti.retrlines("LIST")))  <-- what  
can I do for here


Ah, I didn't notice that part.
MIMEText expects a string. retrlines, by default, outputs to stdout, isn't  
very useful. Try this:


def posta_olustur():
  ...
  lines = []
  baglanti.retrlines("LIST", lines.append)
  text = '\n'.join(lines)
  posta.attach(MIMEText(text))



--
Gabriel Genellina

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


Re: sending ftp file list to mail???

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 03:23:57 -0300, selahattin ay   
escribió:


hi all. I want to get my ftp list and send the list to my mail adress...  
my codes are


And your problem is...?

--
Gabriel Genellina

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


Re: How to inspect slot wrappers arguments in Python?

2011-10-07 Thread Gabriel Genellina
En Sat, 01 Oct 2011 12:13:45 -0300, julian bilcke  
 escribió:


I would like to get the list of parameters I need to initialize an AST  
node.


I'm trying to use the `inspect` module, however it seems I can't use it  
on a

built-in (native?) class, or else I misunderstood. [...]

>>> import inspect
>>> import ast
>>> inspect.getargspec(ast.If.__init__)
Traceback (most recent call last):
  File "", line 1, in 
  File
"/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/inspect.py",
line 813, in getargspec
raise TypeError('{!r} is not a Python function'.format(func))
TypeError:  is not a
Python function

I am wondering if there is another way to get these parameters
automatically? (ie. without compiling myself a dict)


I'm afraid there is no way; this kind of introspection does not work for  
functions written in C. The function itself usually has a generic  
signature resembling (*args, **kw), and its parameters are usually  
unpacked calling a suitable variant of PyArg_ParseXXX. The information  
about the number and type of expected arguments is encoded in its 'format'  
parameter, and is not stored anywhere.


--
Gabriel Genellina

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


Re: database connection

2011-10-07 Thread Gabriel Genellina
En Fri, 07 Oct 2011 02:18:04 -0300, masood shaik   
escribió:



 can u please tell me how we can connect to database without changing
the permission of db file using sqlite3


The OS user who executes the Python script must have read (and write,  
usually) access to the database file - *any* OS user who can read the  
database file can connect to it.


sqlite does not have internal users, and does not implement GRANT/REVOKE  
statements.


--
Gabriel Genellina

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


Re: Is exec() also not used in python 2.7.1 anymore?

2011-10-04 Thread Gabriel Genellina
En Tue, 04 Oct 2011 07:32:41 -0300, Wong Wah Meng-R32813  
 escribió:


Haha... yeah I reviewed the code, it is supposed to exposed some remote  
methods locally (RMI proxy usage). However, I am not sure why what it  
does is merely a pass.


I commented out this code and haven't seen any negative implication. I  
will look into this again if I am convinced the next error I see is due  
to I commented out this code.



  exec('def %s(self, *args, **kw): pass'%methodStrName)


In case you convince yourself that defining this dynamic but empty  
function is really needed, you can avoid exec this way:


  def some_function(...)

...
# instead of exec('def ...' % methodStrName)
def empty_function(self, *args, **kw): pass
empty_function.func_name = methodStrName
...
# presumably methodStrName is referred somehow in
# the remaining code block, or perhaps locals();
# modify accordingly


--
Gabriel Genellina

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


Re: BaseHTTPServer ThreadMixIn not working

2011-10-04 Thread Gabriel Genellina

En Mon, 03 Oct 2011 12:03:18 -0300, amit  escribió:


I am really stuck in a very simple problem and wanted to know if you
could take some time to check it out -

My code is simple. Using BaseHTTPServer and ThreadInMix I want to run
a python script (Script1.py) for every request made simultaneously.
[...]

If I open multiple tabs/pages in Chrome/Firefox/IE and give URL:
http://localhost:8080, the pages wait for previous page? This does not
imply threading? Any help? Thanks


Your code is fine, and Python behaves correctly. The browser is queuing  
all similar requests when it sees they all refer to the same URI. Had the  
first response contained an Expires: header in the future, there would be  
no need to ask again for the same object; the ETag: and Last-Modified:  
headers may play a role too. So, only after the first response is  
completely read, Chrome/Firefox/IE sees it is invalid and knows she cannot  
re-use the received body and has to issue the second request and waits  
again and ...


Try with different URLs for each request:
http://localhost:8080/a
http://localhost:8080/b
http://localhost:8080/c
and you'll see they all are processed in parallel.


--
Gabriel Genellina

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


Re: Change import order with *.pth files

2011-10-03 Thread Gabriel Genellina
En Sun, 02 Oct 2011 18:29:24 -0300, Andrea Gavana  
 escribió:



Let's say I am using a package called "blah", and this package is already
installed on site-packages (and I need it to be there) with a name
"blah-1.2-win". In the site-packages folder, there is a pth file called
"blah.pth" which contains this line:

blah-1.2-win

To redirect Python to the correct folder when I type "import blah".  
Anyway,

now I am developing another version of this package and it's called
"blah-2.0-win", and it sits on my computer into a different folder (not  
on

site-packages, on an entire different drive in reality). How can I tell
Python *not* to use the version inside site-packages but to use the other
one in my development folder (without touching the pth file in
site-packages, of course)?


From Python 2.6 on, there is a per user site-packages directory, which is  
searched before the global one. See:


http://docs.python.org/whatsnew/2.6.html#pep-370-per-user-site-packages-directory

You could put your developing version on that directory.

In Python 2.5 and earlier, if you have to PREPEND a directory to sys.path,  
you may set the PYTHONPATH environment variable, or edit the site.py  
standard module. This may be fine in your development environment, but I  
would never do that in production.


--
Gabriel Genellina

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


Re: Installing Python 2.6.7 on Windows

2011-09-28 Thread Gabriel Genellina

En Wed, 28 Sep 2011 21:10:38 -0300, Nobody  escribió:


On Wed, 28 Sep 2011 15:21:25 -0700, Ned Deily wrote:


No, it was a deliberate decision.  After a release is in security-fix
mode only, we don't build Windows or Mac OS X installers for them.


But you continue to offer the installers for the unfixed version.


As well as all the previous ones back to Python 1.x

I can think of several alternatives:

* Upgrade to Python 2.7, the current stable and maintained release.

* Compile Python 2.6.7 yourself. For the 32 bits version, you may use  
Microsoft Visual C++ 2008 Express Edition (free/gratis); see  
PCbuild\readme.txt for details. Obtain the required dependencies using  
Tools\buildbot\external.bat. It compiles cleanly out of the box.


* Obtain the compiled binary somewhere else. Considering that 2.6.7 is  
just a security patch, I'm not sure if running a precompiled binary from  
untrusted sources is any better than sticking with the official, previous  
version. I've built the binaries, in case you're interested.


* Compare both source trees and look at their differences. Most of them  
are in Python modules that you can just drop over an existing 2.6.6  
install. Only two C modules have changed, and require rebuilding  
python26.dll:


 timemodule.c r87648: Issue #8013: Fixed time.asctime segfault when OS's  
asctime fails

 unicodedata.c http://bugs.python.org/issue10254

If you think you're not affected by these, just ignore 2.6.7 (or apply  
only the .py changes)


--
Gabriel Genellina

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


Re: syntactic sugar for def?

2011-09-28 Thread Gabriel Genellina
En Wed, 28 Sep 2011 18:51:00 -0300, Chris Kaynor  
 escribió:


On Wed, Sep 28, 2011 at 2:37 PM, Arnaud Delobelle   
wrote:

On 28 September 2011 22:26, Ethan Furman  wrote:

I remember that 'class' is sugar for type().

I don't remember if 'def' is sugar for something besides lambda.

Any clues for me?  Heck, I'll even be grateful for outright answers!


It's not really sugar.  But I think you mean something like this:



class A: pass

...

type(A)



type is type(A)

True

So the closest you get for functions will be:


def f(): pass

...

type(f)



Try help(type(f)) to see how to use it to create a function object.
The problem is that you need to provide a code object, and the easiest
way to create a code object is to use a def statement :)


I would say compile isn't too much harder to use:

c = compile('a = 123', 'test', 'exec')
d = {}
f = types.FunctionType(c, d, 'test')
f()
print d

{'a': 123}

Although it appears you get all of the variables defined as global
apparently (try "f = types.FunctionType(c, globals(), 'test')"
instead).


I know no way of compiling a function body alone. Suppose you have this  
function:


def foo(x):
  print x
  y = 2*x
  return y

py> compile("  print x\n  y = 2*x\n  return y", "", "exec")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 1
print x
^
IndentationError: unexpected indent
py> compile("print x\ny = 2*x\nreturn y", "", "exec")
Traceback (most recent call last):
  File "", line 1, in 
  File "", line 3
SyntaxError: 'return' outside function

If you include the 'def' statement in the source string, the resulting  
code object does not represent the function itself, but a "module"  
defining it:


py> f = FunctionType(compile("def foo(x):\n print x\n y = 2*x\n return  
y\n",

...   "", "exec"), globals(), "foo")
py> f(3)
Traceback (most recent call last):
  File "", line 1, in 
TypeError: () takes no arguments (1 given)
py> dis.dis(f)
  1   0 LOAD_CONST   0 (file "", line 1>)

  3 MAKE_FUNCTION0
  6 STORE_NAME   0 (foo)
  9 LOAD_CONST   1 (None)
 12 RETURN_VALUE

To get at the actual function code, one should use  
f.func_code.co_consts[0]; this would be the 'code' parameter for  
types.FunctionType. Very complicated, really; nothing can beat the 'def'  
statement for defining a function ;)


--
Gabriel Genellina

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


Re: Error 'module' object has no attribute "_extension_registry" when cPickle is imported from an installed Python 2.7.1

2011-09-27 Thread Gabriel Genellina
En Tue, 27 Sep 2011 06:08:54 -0300, Wong Wah Meng-R32813  
 escribió:



Hello all,

I encounter this issue whereby I am not able to load cPickle module into  
the python I newly built. There is no issue when I load it right from  
the folder where the python executable and libpython2.7.so is built.  
However, it gives me this error when I load the same module using the  
installed files (python and all its modules, shared library from default  
/use/local folder that contains bin, lib, include sub-folders) from  
"make install" command.


Does anyone know why? Here is the error:-

$ python
Python 2.7.1 (r271:86832, Sep 27 2011, 15:19:26) [C] on hp-ux11
Type "help", "copyright", "credits" or "license" for more information.

import cPickle

Traceback (most recent call last):
  File "", line 1, in 
AttributeError: 'module' object has no attribute '_extension_registry'


Looking at cPickle.c, it imports the copy_reg module and then looks for  
its "_extension_registry" attribute. Maybe your copy_reg.py is broken, or  
you have another copy_reg.py hiding the standard one.


--
Gabriel Genellina

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


Re: Handling 2.7 and 3.0 Versions of Dict

2011-09-02 Thread Gabriel Genellina
En Fri, 02 Sep 2011 13:53:37 -0300, Travis Parks   
escribió:



On Sep 2, 12:36 pm, "Gabriel Genellina" 
wrote:
En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks  
 escribi :


> On Aug 31, 7:37 pm, Gregory Ewing  wrote:
>> Ian Kelly wrote:
>> > if sys.version_info < (3,):
>> > getDictValues = dict.itervalues
>> > else:
>> > getDictValues = dict.values

>> > (which is basically what the OP was doing in the first place).

> My problem was that I didn't understand the scoping rules. It is still
> strange to me that the getValues variable is still in scope outside
> the if/else branches.

Those if/else are at global scope. An 'if' statement does not introduce  
a new scope; so getDictValues, despite being "indented", is defined at  
global scope, and may be used anywhere in the module.


Does that mean the rules would be different inside a function?


Yes: a function body *does* create a new scope, as well as the class  
statement. See

http://docs.python.org/reference/executionmodel.html

--
Gabriel Genellina

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


Re: Invoking profile from command line prevent my sys.path modification

2011-09-02 Thread Gabriel Genellina
En Thu, 01 Sep 2011 07:51:43 -0300, Yaşar Arabacı   
escribió:



I am new to profile module, so I am sorry if this is an absolute beginner
question. In order to my code to run, I need to add a directory to  
sys.path.
When I invole python -m profile myfile.py, my code won't work, saying  
that

the thing that is supposed to be in path, isn't. Code works fine without
profiling. Profiling works if I write it into the file, but I don't  
prefer

doing that, if that is possible.


You may set the PYTHONPATH environment variable, just for the profiling  
session.


http://docs.python.org/install/index.html#modifying-python-s-search-path

--
Gabriel Genellina

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


Re: Help required accessing dictionary

2011-09-02 Thread Gabriel Genellina

En Wed, 31 Aug 2011 22:46:54 -0300,  escribió:


 I need to access the dictionary of the script that I am running through
 my vc++ application by embedding python.
 I am linking to python dynamically. I want to obtain the dictionary of
 the script and access the variables declared in the script.
 However, with the PyObject * that I get from the dictionary, I am not
 able to find the type of the object. The reason being that
 GetProcAddress to PyInt_Check returns a NULL. The same thing with
 PyFloat_Check and so on. I think this is because they are macros and  
 not

 exported functions.

 What can be done to be able to perform these checks without statically
 linking to the pyhon lib ?


Just include python.h
PyInt_Check is completely implemented as a macro, it doesn't call any  
function.


/* from intobject.h */
#define PyInt_Check(op) \
 PyType_FastSubclass((op)->ob_type, Py_TPFLAGS_INT_SUBCLASS)

/* from object.h */
#define PyType_FastSubclass(t,f)  PyType_HasFeature(t,f)
#define PyType_HasFeature(t,f)  (((t)->tp_flags & (f)) != 0)

--
Gabriel Genellina

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


Re: Handling 2.7 and 3.0 Versions of Dict

2011-09-02 Thread Gabriel Genellina
En Wed, 31 Aug 2011 22:28:09 -0300, Travis Parks   
escribió:



On Aug 31, 7:37 pm, Gregory Ewing  wrote:

Ian Kelly wrote:
> if sys.version_info < (3,):
> getDictValues = dict.itervalues
> else:
> getDictValues = dict.values

> (which is basically what the OP was doing in the first place).


My problem was that I didn't understand the scoping rules. It is still
strange to me that the getValues variable is still in scope outside
the if/else branches.


Those if/else are at global scope. An 'if' statement does not introduce a  
new scope; so getDictValues, despite being "indented", is defined at  
global scope, and may be used anywhere in the module.


--
Gabriel Genellina

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


Re: [Python-ideas] allow line break at operators

2011-09-01 Thread Gabriel AHTUNE
So can be done with this syntax:

> x = firstpart * secondpart  +  #line breaks here
> anotherpart + #continue
> stillanother #continue on.

after a "+" operator the line is clearly not finished yet.

Gabriel AHTUNE


2011/9/2 Matt Joiner 

> I guess the issue here is that you can't tell if an expression is
> complete without checking the indent of the following line. This is
> likely not desirable.
>
> On Thu, Sep 1, 2011 at 11:43 PM, Yingjie Lan  wrote:
> > Hi Matt,
> > ===
> > From: Matt Joiner 
> >
> > The "trailing \" workaround is nonobvious. Wrapping in () is noisy and
> > already heavily used by other syntactical structures.
> > ===
> > How about only require indentation
> > to freely break lines? Here is an example:
> > x = firstpart * secondpart #line breaks here
> > + anotherpart #continue by indentation
> > + stillanother #continue on.
> > #until here, another line starts by dedentation
> > y = some_expression - another_one
> > All this would be completely compatible with former code, while
> > having almost free line breaking! Plus, indentation makes it pretty.
> > Really hope Python can have freedom in breaking lines.
> > Yingjie
> ___
> Python-ideas mailing list
> python-id...@python.org
> http://mail.python.org/mailman/listinfo/python-ideas
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Calling Script from Command line not working

2011-09-01 Thread Gabriel Genellina
En Mon, 29 Aug 2011 07:40:06 -0300, Sathish S   
escribió:


We created a DLL using cygwin and have written a class based python  
module

for the same. We have created a sample script for the class based python
module, that creates an object of the class and calls various methods in  
the
class. This Test script works fine while I run it from IDLE. However  
when I
run it from command prompt it either hangs or just returns without  
executing

the functions. When it returns I do not get a error trace.

When I tried to findout where exactly the issue is happening. the issue
occurs when I try to call the *cygwin_dll_init* method of the  
cygwin1.dll .

This cygwin1.dll is actualy a dependency to the DLL we have built. So we
have to load this DLL and call this *cygwin_dll_init* method before  
loading

my DLL.


cyg = cdll.LoadLibrary("cygwin1.dll")
cyg.cygwin_dll_init() #hangs or returns here
mydll=cdll.LoadLibrary("my.dll")
mydll.func1()
I'm trying to understand what exactly is the difference, when we call it
IDLE and when we call it from command prompt using the python command. I
will have to get the script working from command prompt as well.


A few comments:

* why do you initialize cygwin1.dll in Python? If it's a dependency of  
my.dll, it might be better to load and initialize it there.


* for this function prototype: void cygwin_dll_init(void);
you should declare it using:

cyg = cdll.LoadLibrary("cygwin1.dll")
cyg.restype = None
cyg.cygwin_dll_init() #hangs or returns here
...

Anyway, I don't see why a console application would fail but not inside  
IDLE.


--
Gabriel Genellina

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


Re: Execute a method in a file in an egg

2011-08-24 Thread Gabriel Genellina

En Tue, 23 Aug 2011 13:14:06 -0300, RVince  escribió:


Is there a way to do this from the command line? Thanks.


Something like this?

python -c "import the.module;the.module.someclass().method(arguments)"

--
Gabriel Genellina

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


Re: from module import * using __import__?

2011-07-04 Thread Gabriel Genellina
En Sat, 02 Jul 2011 16:52:11 -0300, Dan Stromberg   
escribió:


Is there a decent way of running "from  import *"?  Perhaps  
using

__import__?

Does it mean using the copy module or adding an element to globals()
somehow?

Yes, I think I do have a good use for this: importing either pure python  
or

cython versions of a module into a single namespace that can provide the
same interface (transparent to the caller), whether C extension modules  
are

viable in the current interpreter or not.  So you have a stub module that
provides one or the other, depending on availability and suitability.


See pickle.py in Python 3 as an example: the slow (pure Python) code  
resides in pickle.py; the fast (C code) in _pickle.so (on Windows, a  
built-in module). Near the end of pickle.py, there is a line "from _pickle  
import *" which, if successful, overrides (replaces) any previous  
definitions; if not, the ImportError is trapped and the previously defined  
Python code remains valid.


Unlike the 2.x series, where you should decide to "import cPickle" or  
"import pickle" (or attempt both, cathcing the ImportError), here you only  
have to "import pickle" in your code; if the fast module is present, it is  
automatically loaded and used; else, the slow but compatible version is  
used. You don't even have to know that an alternative implementation  
exists.


--
Gabriel Genellina

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


Re: search through this list's email archives

2011-06-24 Thread Gabriel Genellina
En Fri, 24 Jun 2011 11:33:23 -0300, Grant Edwards  
 escribió:



On 2011-06-24, Gabriel Genellina  wrote:

En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James 
escribi?:


I looked through this forum's archives, but I can't find a way to
search for a topic through the archive. Am I missing something?



Gmane provides a search capability also:
http://blog.gmane.org/gmane.comp.python.general


FWIW, I've found the Gmane search feature to be very unreliable.  It
often overlooks a lot of matching articles for no apparent reason.


It seems no single provider is perfect. Google searching capability is  
quite good, but for some reason, many posts are missing, often the initial  
post head of a thread. The "Python-URL" summaries usually include a Google  
Groups url, but sometimes I have to link to Gmane, velocityreviews.com or  
even to the list archives at python.org because of that problem.


--
Gabriel Genellina

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


Re: search through this list's email archives

2011-06-24 Thread Gabriel Genellina
En Thu, 23 Jun 2011 13:11:32 -0300, Cathy James   
escribió:



I looked through this forum's archives, but I can't find a way to
search for a topic through the archive. Am I missing something?



Gmane provides a search capability also:
http://blog.gmane.org/gmane.comp.python.general

--
Gabriel Genellina

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


Re: Python 2.7.2 for Windows reports version as 2.7.0?

2011-06-22 Thread Gabriel Genellina

En Sun, 19 Jun 2011 12:35:38 -0300,  escribió:

The version info comes from the DLL - I wonder if the DLL being found  
is somehow old?


Make sure:

>>> import sys
>>> win32api.GetModuleFileName(sys.dllhandle)

Is the DLL you expect.


After uninstalling and reinstalling for the current user only (vs. all
users), Python now reports the correct version number.

And running your code above confirms that the proper DLL is being loaded
(c:\Python27\Python27.dll).

My original version of Python 2.7.0 was installed for all users and when
I ran the 2.7.2 MSI I chose to install for all users as well.

After running the 2.7.2 MSI, my Python exe's had the correct timestamps,
but I failed to check the python27.dll timestamp to see if this file was
out-of-date.

I wonder if changing my install method to current user forced the
installation of the updated python27.dll? And perhaps the default 2.7.2
installation in all users mode (when one is updating an existing 2.7
installation) doesn't update the Python27.dll under some conditions?


In a "for all users" install, python27.dll goes into c:\windows\system32,  
not c:\python27


Maybe you installed 2.7.0 twice, "for all users" and also "for current  
user only", and both in the same directory (c:\python27). That could  
explain the old .dll in the install directory; the new one goes into  
system32, but the old one takes precedence.


--
Gabriel Genellina

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


Re: Unsupported operand type(s) for +: 'float' and 'tuple'

2011-06-10 Thread Gabriel Genellina

En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura 
escribió:


Hello all, I'm new to this and I'm having problems on summing two
values at python.

I get the following error:

Traceback (most recent call last):
  File "C:\edge-bc (2).py", line 168, in 
if (costGG <= cost + T0):
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'


I see Tim Chase already told you about this error. Let me make a few
comments about the rest.


try:
import matplotlib.pyplot as plt
except:
raise


I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.


T0 = 0.5
RO = 0.99


Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.


for i in range(len(edges)):
total = 0
cost = 0
factor = 1
   liedges = list(edges[i])
linode1 = list(liedges[0])
linode2 = list(liedges[1])


list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
linode1 = liedges[0]
linode2 = liedges[1]



distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
linode1[1])%N)^2)


That doesn't evaluate what you think it does. ^ is the "bitwise xor"
operator, and I bet you want **, the "power" operator.



total = total + cost
return(total)


return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.


def costGeasy(G):
bc = NX.edge_betweenness_centrality(G,normalized=True)
total = 0
for i in range(len(bc)):
total=total+bc.values()[i]

return (total)


bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==>

return sum(bc.values())



pos={}
for i in range(NODES):
pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))


In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
  from __future__ import division
then 1/3 returns 0....
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

  from __future__ import division
...
for node in nod:
pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)



for y in range(NK):
for x in range(ITERATIONS):
cost = costG(G)
if (cost < (best_cost)):
best_graph = G
best_cost = cost
GG = G


Again, I think this doesn't do what you think it does. GG = G means "let's
use the name GG for the object currently known as G". GG is not a "copy"
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm


a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
adj=G.adjacency_list()
while ((nod[b] in adj[a]) or (b == a)):
a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
GG.add_edge(nod[a],nod[b])


As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
a, b = random.sample(nod, 2)
if b not in G[a]:
  break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

--
Gabriel Genellina

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


Re: Unsupported operand type(s) for +: 'float' and 'tuple'

2011-06-10 Thread Gabriel Genellina

En Fri, 10 Jun 2011 07:30:28 -0300, Francesc Segura 
escribió:


Hello all, I'm new to this and I'm having problems on summing two
values at python.

I get the following error:

Traceback (most recent call last):
  File "C:\edge-bc (2).py", line 168, in 
if (costGG <= cost + T0):
TypeError: unsupported operand type(s) for +: 'float' and 'tuple'


I see Tim Chase already told you about this error. Let me make a few
comments about the rest.


try:
import matplotlib.pyplot as plt
except:
raise


I guess the above try/except was left from some earlier debugging attempt
- such an except clause is useless, just omit it.


T0 = 0.5
RO = 0.99


Perhaps those names make sense in your problem at hand, but usually I try
to use more meaningful ones. 0 and O look very similar in some fonts.


for i in range(len(edges)):
total = 0
cost = 0
factor = 1
   liedges = list(edges[i])
linode1 = list(liedges[0])
linode2 = list(liedges[1])


list(something) creates a new list out of the elements from `something`.
You're just iterating here, so there is no need to duplicate those lists.
In addition, Python is not C: the `for` statement iterates over a
collection, you don't have to iterate over the indices and dereference
each item:

for liedges in edges:
linode1 = liedges[0]
linode2 = liedges[1]



distance = (((linode2[0]-linode1[0])%N)^2)+(((linode2[1]-
linode1[1])%N)^2)


That doesn't evaluate what you think it does. ^ is the "bitwise xor"
operator, and I bet you want **, the "power" operator.



total = total + cost
return(total)


return is not a function but a statement; those () are unnecesary and
confusing.
And I think you want to initialize total=0 *before* entering the loop;
also, initializing cost and factor is unnecesary.


def costGeasy(G):
bc = NX.edge_betweenness_centrality(G,normalized=True)
total = 0
for i in range(len(bc)):
total=total+bc.values()[i]

return (total)


bc = NX.edge_betweenness_centrality(G,normalized=True)
values = bc.values()
total = sum(values)
return total

==>

return sum(bc.values())



pos={}
for i in range(NODES):
pos[nod[i]]=(nod[i][0]/(N*1.0),nod[i][1]/(N*1.0))


In Python version 2.x, 1/3 evals to 0, but that's a mistake; it is fixed
in the 3.x version. If you put this line at the top of your script:
  from __future__ import division
then 1/3 returns 0....
When you actually want integer division, use //, like 1//3

So we can rewrite the above as:

  from __future__ import division
...
for node in nod:
pos[node] = (node[0] / N, node[1] / N)

Another way, not relying on true division:

divisor = float(N)
for node in nod:
pos[node] = (node[0] / divisor, node[1] / divisor)

or even:

pos = dict((node, (node[0] / divisor, node[1] / divisor)) for node in nod)



for y in range(NK):
for x in range(ITERATIONS):
cost = costG(G)
if (cost < (best_cost)):
best_graph = G
best_cost = cost
GG = G


Again, I think this doesn't do what you think it does. GG = G means "let's
use the name GG for the object currently known as G". GG is not a "copy"
of G, just a different name for the very same object. Later operations
like GG.remove_edge(...) modify the object - and you'll see the changes in
G, and in best_graph, because those names all refer to the same object.
I think you'll benefit from reading this:
http://effbot.org/zone/python-objects.htm


a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
adj=G.adjacency_list()
while ((nod[b] in adj[a]) or (b == a)):
a = random.randint(0,NODES-1)
b = random.randint(0,NODES-1)
GG.add_edge(nod[a],nod[b])


As above, I'd avoid using indexes, take two random nodes using
random.sample instead, and avoid adjacency_list():

while True:
a, b = random.sample(nod, 2)
if b not in G[a]:
  break
GG.add_edge(a, b)

(mmm, I'm unsure of the adjacency test, I've used networkx some time ago
but I don't have it available right now)

--
Gabriel Genellina

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


Re: help on QUICKFIX

2011-06-10 Thread Gabriel Genellina
En Fri, 10 Jun 2011 04:13:05 -0300, prakash jp   
escribió:



I am using quickfix, would like to start with that

..\quickfix-1.13.3\quickfix\examples\executor\python\executor.py asks  
for a

configuration file how should it look like.


This one? http://www.quickfixengine.org/
I see a forum and a mailing list - I think you'll get more help there.

--
Gabriel Genellina

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


Re: Problems Compiling Python 2.6.7 for Win7

2011-06-08 Thread Gabriel Genellina
En Wed, 08 Jun 2011 12:28:56 -0300, Jay Osako   
escribió:



I have been trying to get PyODBC to work with Python 2.6 (the latest
version it is known to be compatible with) and Django, but have run
into a problem which, according to the information I've got elsewhere,
probably stems from a DLL incompatibility - apparently, [...]

The first of these problems is, of course, tracking down a copy of VC+
+ 2008 Express. While one would think that this would be the simplest
solution, Microsfot themselves no longer provide the installer for
this, and I'm not sure I'd trust most of the other sources claiming to
provide it.


Doesn't http://www.microsoft.com/express/Downloads/#2008-Visual-CPP work  
for you?
I didn't try past the initial download prompt, but it seems to be the  
right version.


--
Gabriel Genellina

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


Re: Function call arguments in stack trace?

2011-06-07 Thread Gabriel Genellina
En Tue, 07 Jun 2011 15:09:54 -0300, Dun Peal   
escribió:



In a stack trace, is it possible to somehow get the arguments with
which each function was called?

So for example, if function `foo` in module `bar` was called with
arguments `(1, [2])` when it raised an exception, then instead of:

Traceback (most recent call last):
  File "bar.py", line 123, in foo
build_rpms()

The stack trace would read:

Traceback (most recent call last):
  File "bar.py", line 123, in foo(1, [2])
build_rpms()

This would save a lot of debugging time!


The cgitb module does exactly that; some third-party modules offer similar  
functionality, but I don't remember any names.

Despite its name, cgitb works with any script.

Given this test script:

# begin test_traceback.py
import cgitb
cgitb.enable(format="text")

spam = []

def a(x, y):
  "This is function a"
  z = x+y
  return b(z)


def b(z, n=3):
  """This is function b.

  Its docstring is longer."""

  if n!=3:
just(to_consume_space)

  w = c(foo=z*n)

  return w


def c(foo=0, bar=1):
  "This is function c"
  baz = foo+bar
  spam.somenamethatdoesnotexist(foo+bar)
  anotherglobal("thatdoesnotexisteither")

a(10, 20)
# end test_traceback.py

the output is:


AttributeError
Python 3.2: d:\apps\Python32\python.exe
Tue Jun  7 23:36:36 2011

A problem occurred in a Python script.  Here is the sequence of
function calls leading up to the error, in the order they occurred.

 D:\TEMP\test_traceback.py in ()
   27   baz = foo+bar
   28   spam.somenamethatdoesnotexist(foo+bar)
   29   anotherglobal("thatdoesnotexisteither")
   30
   31 a(10, 20)
a = 

 D:\TEMP\test_traceback.py in a(x=10, y=20)
7   "This is function a"
8   z = x+y
9   return b(z)
   10
   11
global b = 
z = 30

 D:\TEMP\test_traceback.py in b(z=30, n=3)
   18 just(to_consume_space)
   19
   20   w = c(foo=z*n)
   21
   22   return w
w undefined
global c = 
foo undefined
z = 30
n = 3

 D:\TEMP\test_traceback.py in c(foo=90, bar=1)
   26   "This is function c"
   27   baz = foo+bar
   28   spam.somenamethatdoesnotexist(foo+bar)
   29   anotherglobal("thatdoesnotexisteither")
   30
global spam = []
spam.somenamethatdoesnotexist undefined
foo = 90
bar = 1
AttributeError: 'list' object has no attribute 'somenamethatdoesnotexist'
   [... exception attributes ...]
   [... original traceback ...]

--
Gabriel Genellina

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


Re: sys.tracebacklimit not working in Python 3.2?

2011-06-07 Thread Gabriel Genellina
En Fri, 27 May 2011 17:38:50 -0300, Thorsten Kampe  
 escribió:



sys.tracebacklimit = 0

The 3.2 documentation says "When set to 0 or less, all traceback
information is suppressed and only the exception type and value are
printed". Bug?


Yes; reported at http://bugs.python.org/issue12276

--
Gabriel Genellina

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


Re: Print Window on IDLE

2011-06-06 Thread Gabriel Genellina
En Mon, 06 Jun 2011 14:48:26 -0300, Steve Oldner   
escribió:


Seems to work using 2.7 but not 3.2.  On 3.2 it just closes all my  
python sessions.  Is this a bug?  Can someone point me to a "How To" on  
using a local printer in windows?


It's a bug. Starting IDLE from the command line, one can actually see the  
error:



Exception in Tkinter callback
Traceback (most recent call last):
  File "D:\apps\python32\lib\tkinter\__init__.py", line 1399, in __call__
return self.func(*args)
  File "D:\apps\python32\lib\idlelib\IOBinding.py", line 453, in  
print_window

command = idleConf.GetOption('main','General','print-command-win')
  File "D:\apps\python32\lib\idlelib\configHandler.py", line 245, in  
GetOption

type=type, raw=raw)
  File "D:\apps\python32\lib\idlelib\configHandler.py", line 54, in Get
return self.get(section, option, raw=raw)
  File "D:\apps\python32\lib\configparser.py", line 789, in get
d)
  File "D:\apps\python32\lib\configparser.py", line 391, in before_get
self._interpolate_some(parser, option, L, value, section, defaults, 1)
  File "D:\apps\python32\lib\configparser.py", line 440, in  
_interpolate_some

"found: %r" % (rest,))
configparser.InterpolationSyntaxError: '%' must be followed by '%' or '(',  
found

: '%s'

IDLE is attempting to read an entry from its configuration file, but fails  
because of a syntax error in the file (it's an error for a ConfigParser  
entry, %s should be %%s). The same entry was fine for earlier IDLE  
versions. As a workaround, you may edit the offending lines in your  
configuration file.



Go to the idlelib directory; if you don't know where it is, just open idle  
or Python command line and execute:


py> import idlelib
py> idlelib.__file__
'D:\\apps\\python32\\lib\\idlelib\\__init__.py'

In the same directory you'll find config-main.def; open it, and replace  
these lines in the [General] section:


print-command-posix=lpr %%s
print-command-win=start /min notepad /p %%s

(%s should become %%s). Tested on Windows, but Linux should have the same  
problem and temporary solution. You may need to roll this change back when  
the code is corrected.


Reported as http://bugs.python.org/issue12274


--
Gabriel Genellina

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


Re: GIL in alternative implementations

2011-06-06 Thread Gabriel Genellina
En Sat, 28 May 2011 14:05:16 -0300, Steven D'Aprano  
 escribió:



On Sat, 28 May 2011 09:39:08 -0700, John Nagle wrote:


Python allows patching code while the code is executing.


Can you give an example of what you mean by this?

If I have a function:


def f(a, b):
c = a + b
d = c*3
return "hello world"*d


how would I patch this function while it is executing?


I think John Nagle was thinking about rebinding names:


def f(self, a, b):
  while b>0:
b = g(b)
c = a + b
d = self.h(c*3)
  return "hello world"*d

both g and self.h may change its meaning from one iteration to the next,  
so a complete name lookup is required at each iteration. This is very  
useful sometimes, but affects performance a lot.


--
Gabriel Genellina

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


Re: except KeyError, everywhere

2011-06-06 Thread Gabriel Genellina

En Fri, 03 Jun 2011 21:02:56 -0300, Nobody  escribió:


On Fri, 03 Jun 2011 22:08:16 +0200, Wilbert Berendsen wrote:

I find myself all over the place associating objects with each other  
using

dicts as caches:


The general concept is called "memoization". There isn't an  
implementation

in the standard library


Yes, there is, in Python 3.2:
http://docs.python.org/py3k/library/functools.html#functools.lru_cache


--
Gabriel Genellina

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


Re: Best way to compute length of arbitrary dimension vector?

2011-06-03 Thread Gabriel

> The dimension is arbitrary, though, so:
>
> length = reduce(math.hypot, self._coords, 0)
>


Thanks, I was going to ask Algis that same question.

But still, is this solution really faster or better than the one using
list comprehension and the expression 'x*x'?
It seems to me that the above solution (using hypot) involves repeated
square roots (with subsequent squaring).

Best regards,
Gabriel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Alternatives to PythonPath

2011-05-31 Thread Gabriel Genellina

En Sun, 29 May 2011 18:49:28 -0300, ray  escribió:


I am using Win7 on a tightly locked down desktop.

Is there an alternative to using PythonPath?

What are the trade-offs?


Usually there is no need to define the PYTHONPATH variable; I never use it.
There is a per-user site-packages directory (2.6 and up), on Windows it is  
located at %APPDATA%\Python\PythonXX\site-packages. Every user gets its  
own %APPDATA% directory, with read and write permissions.


--
Gabriel Genellina

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


Re: Best way to compute length of arbitrary dimension vector?

2011-05-30 Thread Gabriel Genellina

En Mon, 30 May 2011 06:46:01 -0300, Peter Otten <__pete...@web.de>
escribió:


Gabriel wrote:


Well, the subject says it almost all: I'd like to write a small Vector
class for arbitrary-dimensional vectors.




class Vector(object):

... def __init__(self, *coords):
... self._coords = coords
... def __abs__(self):
... return math.sqrt(sum(x*x for x in self._coords))
...

import math
abs(Vector(1,1))

1.4142135623730951

abs(Vector(3,4))

5.0


Using math.fsum instead of sum may improve accuracy, specially when  
len(coords)≫2


py> import math
py>
py> def f1(*args):
...   return math.sqrt(sum(x*x for x in args))
...
py> def f2(*args):
...   return math.sqrt(math.fsum(x*x for x in args))
...
py> pi=math.pi
py> args=[pi]*16
py> abs(f1(*args)/4 - pi)
4.4408920985006262e-16
py> abs(f2(*args)/4 - pi)
0.0


--
Gabriel Genellina

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


Re: Best way to compute length of arbitrary dimension vector?

2011-05-30 Thread Gabriel
Thanks a lot to both of you, Chris & Peter!

(I knew the solution would be simple ... ;-) )
-- 
http://mail.python.org/mailman/listinfo/python-list


Best way to compute length of arbitrary dimension vector?

2011-05-30 Thread Gabriel
Well, the subject says it almost all: I'd like to write a small Vector
class for arbitrary-dimensional vectors.

I am wondering what would be the most efficient and/or most elegant
way to compute the length of such a Vector?

Right now, I've got

  def length(self): 
# x.length() = || x ||
total = 0.0
for k in range(len(self._coords)):
  d = self._coords[k]
  total += d*d
return sqrt(total)

However, that seems a bit awkward to me (at least in Python ;-) ).

I know there is the reduce() function, but I can't seem to find a way
to apply that to the case here (at least, not without jumping through
too many hoops).

I have also googled a bit, but found nothing really elegant.

Any ideas?

Best regards,
Gabriel.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: pexpect: TIMEOUT no longer clears child.before

2011-05-25 Thread Gabriel Genellina
En Thu, 19 May 2011 08:29:21 -0300, Adrian Casey   
escribió:


The behaviour of pexpect has changed between version 2.1 and 2.3.  In  
version 2.1, the following code would result in child.before being  
cleared -:


 >>>child.expect(pexpect.TIMEOUT,1)
 In version 2.3, this is no longer the case.  No matter how many times  
the above code is run, child.before continues to hold the output from  
previous commands.  It is important to be able to clear the contents of  
child.before between each command.  What is the correct way to do this  
in version 2.3?


Try contacting the author: www.noah.org

--
Gabriel Genellina

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


Re: Hotshoting recursive function

2011-05-25 Thread Gabriel Genellina
En Sun, 22 May 2011 10:42:08 -0300, Selvam   
escribió:



I am using  hotshot module to profile my python function.

I used the details from (
http://code.activestate.com/recipes/576656-quick-python-profiling-with-hotshot/
).

The function I profile is a recursive one and I am getting the following
error,

"ProfilerError: profiler already active"

I guess this is due to the recursive call to the profiling function.

I would like to get some suggestions.


The recursive call inside your function should call the undecorated  
function, not the decorated function again. Decorator syntax is not  
convenient anymore.


Using the same names as in the recipe example:


# a recursive function
def my_slow_function(n):
  ...
  return my_slow_function(n-1)


my_profiled_slow_function = hotshotit(my_slow_function)
my_profiled_slow_function(n)


This works, in the sense that it does not raise ProfileError anymore.  
Interpreting profile data is up to you...



--
Gabriel Genellina

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


Re: Multiple file select with tkFileDialog passes back 'decorated' strings (sometimes)

2011-05-23 Thread Gabriel Genellina

En Mon, 23 May 2011 10:00:53 -0300, Alex van der Spek 
escribió:

I switched from Mark Hammonds pywin32 extensions for file choosers as  
the multiselect there seems to crash on me when selecting more than a  
few dozen. Using Tk now. Works well but the resulting string passed back  
seems to 'decorated' when the files are on local disk and not decorated  
when retrieved over a USB interface from an external disk?


I do this:


From local disk I get back:


'{file1.bin} {file2.bin}'


From external disk I get back:


'file1.bin file2.bin'

I can handle/parse both, not an issue but it raises the question: Are  
these the only two possibilities? Is it the same across platforms (I use  
Python 2.7 on Win Vista)?


An old bug. See http://bugs.python.org/issue5712 for a workaround.

--
Gabriel Genellina

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


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker 
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 15:26:53 -0300, Neal Becker 
escribió:


Gabriel Genellina wrote:


En Tue, 17 May 2011 08:41:41 -0300, Neal Becker 
escribió:


What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic
answer, make sure you open the file in binary mode, both when writing  
and

reading.



Yes, that's the message.

Part of what is pickled is a numpy array.  I am writing on a 32-bit  
linux system
and reading on a 64-bit system.  Reading on the 64-bit system is no  
problem.


Maybe the message comes from numpy's unpickling?


Maybe, at least 'invalid signature' makes sense in Numpy. In that case, a
better place to ask would be a numpy specific list, see
http://www.scipy.org/Mailing_Lists


--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina

En Tue, 17 May 2011 16:48:29 -0300, Albert Hopkins
 escribió:

On Tue, 2011-05-17 at 10:18 -0600, Littlefield, Tyler wrote:



Not to be pedantic or anything, and I may not be able to help
regardless, but it looks like your space key is fixed, and I don't
really care to pick through and try to play hangman with your message.


I actually, at first glance, thought it was spam, ignored it, and was
wondering why people were replying to it :|


I can't remember exactly in which release 'perfect English skills' were
added to Python runtime requirements, could you please refresh my memory?

--
Gabriel Genellina

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


Re: cPickle -> invalid signature

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 08:41:41 -0300, Neal Becker   
escribió:



What does it mean when cPickle.load says:
RuntimeError: invalid signature

Is binary format not portable?


Are you sure that's the actual error message?
I cannot find such message anywhere in the sources.
The pickle format is quite portable, even cross-version. As a generic  
answer, make sure you open the file in binary mode, both when writing and  
reading.


--
Gabriel Genellina

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


Re: FW: help please

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 06:43:51 -0300, hamed azarkeshb  
 escribió:


hi dearinwant to useautomation with catiaby python,but i dont know,how  
do we can creat catsafearrayvariant in python?please help me.i need  
urhelp by one example.thank u forany thing 		 	   		


There are two sides when you want to use automation with Python:

* learn how to do automation by itself, how COM works, how to invoke a COM  
server from Python. This is mostly application-independent. A good  
resource is "Python Programming in Win32" book by Mark Hammond. Chapter 5  
"Introduction to COM" is exactly what you need, and is available for  
preview in Google Books:  
http://books.google.com.ar/books?id=fzUCGtyg0MMC&lpg=PA65&pg=PA65#v=onepage&f=false


* learn how to use the actual objects exposed by the desired application.  
Usually, documentation is available for VBA or other languages, but can be  
easily translated into Python terms.


So I'd say you first read the book, then search the documentation about  
CATSafeArrayVariant and see how to create it, and then translate that into  
Python. Feel free to post any problem you encounter, a better place would  
be the python-win32 list:  
http://mail.python.org/mailman/listinfo/python-win32


Good luck!
--
Gabriel Genellina

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


Re: Datetime.timedelta

2011-05-17 Thread Gabriel Genellina
En Tue, 17 May 2011 07:44:08 -0300, Tsolmon Narantsogt   
escribió:



I'm using datetime.timedelta and i have a problem

delta = 1 day, 2:30:00
hours = delta.days * 8

how to add 8 + 2:30:00


Just operate with it as it were a number. The timedelta class implements  
all "sane" mathematical operations.


py> from datetime import *
py> def timedelta_from_dhms(days=0, hours=0, mins=0, secs=0):
...   return timedelta(days, hours*3600 + mins*60 + secs)
...
py> delta = timedelta_from_dhms(1, 2, 30)
py> delta
datetime.timedelta(1, 9000)
py> hours = delta.days * 8
py> delta + hours
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'datetime.timedelta' and  
'int'

py> hours = timedelta_from_dhms(0, delta.days * 8)
py> hours
datetime.timedelta(0, 28800)
py> delta + hours
datetime.timedelta(1, 37800)
py> def dhms_from_timedelta(td):
...   return td.days, td.seconds // 3600, (td.seconds % 3600) // 60,  
td.seconds % 60

...
py> dhms_from_timedelta(delta + hours)
(1, 10, 30, 0)

--
Gabriel Genellina

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


Re: turn monitor off and on

2011-05-16 Thread Gabriel Genellina
En Sat, 14 May 2011 03:08:44 -0300, Astan Chee   
escribió:



I'm trying to turn off my monitor, pause and then turn it on again.
I'm doing this in python 2.6 and windows xp. Here is my script so far
(that doesn't work):

def turnOnMonitor():
  SC_MONITORPOWER = 0xF170
  win32gui.SendMessage(win32con.HWND_BROADCAST,
win32con.WM_SYSCOMMAND, SC_MONITORPOWER, -1)

For some reason, the script doesn't turn the monitor back on. What am
I doing wrong here or are there any other alternative?


Your script worked fine for me, 2.6 and XP also. Perhaps your monitor  
device driver is buggy or does not implement the required functionality.  
Mine is from Philips.


--
Gabriel Genellina

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


Re: Import on case insensitive filesystem

2011-05-16 Thread Gabriel Genellina
En Fri, 13 May 2011 15:43:23 -0300, Mitchell Hashimoto  
 escribió:



I'm developing an app which runs Python on a filesystem which is not case
sensitive (Mac OS X), but is mounted as an NFS drive on a remote machine.
This causes errors because of the import being case sensitive but  
accessing
an FS which is case insensitive. Short of copying the entire directory  
tree
over to another filesystem, is there anything I can do to flag Python to  
act

as though it were on a case sensitive FS?


Try creating an environment variable PYTHONCASEOK with any value.
See http://www.python.org/dev/peps/pep-0235/ for details.

--
Gabriel Genellina

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


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 22:59:24 -0300, Gabriel Genellina  
 escribió:


En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan  
 escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


Should read "...renamed 'builtins' in Python 3.x, just to add to the  
confusion." :)



--
Gabriel Genellina

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


Re: Peculiar Behaviour of __builtins__

2011-05-12 Thread Gabriel Genellina
En Thu, 12 May 2011 20:29:57 -0300, Aman Nijhawan   
escribió:



I was trying to call the builtin function min by using
getattr(__builtins__,'min')

This works at the interpretter prompt

However when I called it inside a module that was imported by another  
module

it fails and gives an attribute error


__builtins__ (note the final 's') is an implementation detail. You want  
the __builtin__ (no 's') module, renamed 'builtin' in Python 3.x


py> import __builtin__
py> builtin_min = __builtin__.min
py> builtin_min([8,2,5])
2

See http://docs.python.org/library/__builtin__.html

Note: using getattr with a literal name is not so useful. Better to use  
dot notation.



--
Gabriel Genellina

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


Re: NewBie Doubt in Python Thread Programming

2011-05-11 Thread Gabriel Genellina
En Wed, 11 May 2011 03:57:13 -0300, vijay swaminathan   
escribió:



Hi All,

I'm new bie to thread programming and I need some assistance in
understanding few concepts ...

I have a very simple program which runs a thread and prints a string.

import threading

class MyThread(threading.Thread):
def __init__(self, parent = None):
threading.Thread.__init__(self)

def run(self):
print 'Hello World'

def main():
for i in range(10):
MyThread_Object = MyThread()
print 'Object id is : ' , id(MyThread_Object)
print 'Staring thread --> ' , MyThread_Object.getName()
MyThread_Object.start()
count = threading.activeCount()
print 'The active thread count is: ' , count

if __name__ == '__main__':
main()

When I run this, I could see 10 thread being called. But when I print the
active thread count it is only 2.

Need some understanding on the following.

1. How the total active thread is 2?


Because most of them have already finished by then. Your run() method  
executes quite fast. Make it take more time (maybe by adding  
time.sleep(1)) and you'll see 10 active threads.


2. how do I stop a thread? does it get automatically stopped after  
execution

?


You don't; a trhread runs until the run() method exits. After that, the OS  
thread finishes. The Python object (a threading.Thread instance) is still  
alive (until the last reference to it disappears, as any other object).



3. Am I totally wrong in understanding the concepts.


I don't know...


4. what is the difference between active_count() and activeCount() since
both seem to give the same result.


Nothing. active_count is the preferred Python spelling per PEP8;  
activeCount is the original Java spelling.



5. is there a way to find out if the thread is still active or dead?



Yes, use is_alive()

--
Gabriel Genellina

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


Re: This it is the code of tmb_import.py (to matter of .tmb to blender) I need tmb_exporter.py (to export of blender to .tmb) Thanks.

2011-05-10 Thread Gabriel Genellina
En Tue, 10 May 2011 15:51:03 -0300, Jean Carlos Páez Ramírez  
 escribió:



The attached file is script of blender fact in python that .tmb serves to
concern archives (secondly attached file), unloadings to blender and uses


Por lo que pude entender, tu problema es bastante específico de Blender,  
así que tal vez te convenga preguntar en un foro como:

http://www.g-blender.org/
(específicamente dedicado a Blender 3D en español)

También está la comunidad de Python Argentina: http://python.org.ar/pyar/  
(busca la lista de correo)


Suerte!

--
Gabriel Genellina

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


Re: Testing tools classification

2011-05-09 Thread Gabriel Genellina

En Sat, 07 May 2011 02:21:02 -0300, rusi  escribió:


There is this nice page of testing tools taxonomy:
http://pycheesecake.org/wiki/PythonTestingToolsTaxonomy

But it does not list staf: http://staf.sourceforge.net/index.php.


The good thing about wikis is, you can add it yourself.

--
Gabriel Genellina

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


Re: How to upload a file

2011-04-28 Thread Gabriel Genellina
En Wed, 27 Apr 2011 11:14:54 -0300, Torsten Bronger  
 escribió:



Hallöchen!

I'm skimming through the various recipies for uploading a file via
HTTP.  Unfortunately, all of them are awkward but also rather old.
(See for example
http://stackoverflow.com/questions/68477/send-file-using-post-from-a-python-script)

In my module, I do my HTTP request like this:

opener =  
urllib2.build_opener(urllib2.HTTPCookieProcessor(cookielib.CookieJar()))

opener.open(url, urllib.urlencode(data, doseq=True))

Well, and now I'd also like to include a file upload to the POST
data.  The solution should use urllib2, otherwise I'd have to change
most of my existing code.

If you now say "Torsten, unfortunately it *is* so complicated" I'll
jump through the hoops, but I'd love to hear that with Python 2.6.5
there's an easier way.  ;-)


This particular battery isn't included (yet - see  
http://bugs.python.org/issue3244)

but this little library may help:
https://bitbucket.org/chrisatlee/poster

--
Gabriel Genellina

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


Re: Access violation reading 0x00000010

2011-04-28 Thread Gabriel Genellina
En Thu, 28 Apr 2011 03:35:48 -0300, yuan zheng   
escribió:



Sorry , the path is just an example.

This is not the question I think. Because there is lots of api
in libcommon-0.dll, and there is no fault when invoking other
api, such as libcommon.SIM_start().. It's just fault when invoking
this api -> SIM_init(). So I wanna which situation would lead to this  
error:

--
WindowsError: exception: access violation reading 0x0010
--


On Thu, Apr 28, 2011 at 4:01 PM, yuan zheng 
wrote:
>
> libcommon = CDLL("c:\libcommon-0.dll", RTLD_GLOBAL)
>
> libcommon.SIM_init() -> This is the invoking.


It's hard to guess, but if you get an access violation just from those two  
lines of code, I'd say the problem is inside SIM_init() itself.


It may be attempting to dereference a NULL pointer: accessing a field  
inside a struct, or calling a virtual function from a NULL object...


Also, make sure CDLL is the right choice; it implies a prototype like this:

int cdecl SIM_INIT(void);

--
Gabriel Genellina

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


Re: argparse parser stores lists instead of strings

2011-04-28 Thread Gabriel Genellina
En Thu, 28 Apr 2011 04:24:46 -0300, Andrew Berg  
 escribió:



I've set up groups of arguments for a script I'm writing, and any time I
give an argument a value, it gets stored as a list instead of a string,
even if I explicitly tell it to store a string. Arguments declared with
other types (e.g. float, int) and default values are stored as expected.
For example:

vidin_args=parser.add_argument_group('Video Input Options', 'Various
options that control how the video file is demuxed/decoded.')
vidin_args.add_argument('-m', dest='vmode', nargs=1, type=str,
metavar='video_mode', choices=['ntsc', 'pal', 'film', 'ivtc'],
default='ntsc', help='Valid values are "ntsc", "pal", "film" and  
"ivtc".')

...more arguments...
opts=parser.parse_args()

If I assign a value on the command line (e.g. -m pal), opts.vmode is a
list, otherwise it's a string. This is pretty bad since I can't know
whether to get opts.vmode or opts.vmode[0] later in the script. I could
loop through all the options and convert each option to a string, but
that's not really something I want to do, especially if I start adding
more options.


That's because of nargs=1. From the argparse documentation: [1]

	Note that nargs=1 produces a list of one item. This is different from the  
default, in which the item is produced by itself.


So, just remove nargs=1 from add_argument()

[1] http://docs.python.org/py3k/library/argparse.html#nargs

--
Gabriel Genellina

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


Re: PYTHONPATH

2011-04-15 Thread Gabriel Genellina
En Fri, 15 Apr 2011 05:33:18 -0300, Algis Kabaila   
escribió:



An elementary question that is bugging me, regarding sys.path
values.sys.path can be altered easily, but the changes last for
the current session only. I would like the changes to stay for
several sessions.  Is PYTHONPATH a system variable that sets the
path for several sessions and if so, where in the system is it?
Do I need to create one for setting python path for several
sessions?


PYTHONPATH is an environment variable, you set it the same way as any  
other, the details depend on the operating system/shell you're currently  
using.


But - why do you think you need to set PYTHONPATH? Don't do that. Use the  
standard places to put your library modules and packages, like  
site-packages (where third-party libraries are installed by default). From  
Python 2.6+ the search path includes per-user directories like  
~/.local/lib/python2.6/site-packages and  
%APPDATA%\Python\Python26\site-packages (see PEP370 [1] for details) so  
you don't even have to mess with the Python installation directories.



[1] http://www.python.org/dev/peps/pep-0370/

--
Gabriel Genellina

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


Re: Help Amigos

2011-04-11 Thread Gabriel Novaes
On 11 abr, 09:01, Gabriel Novaes  wrote:
> Hello community
>
> My name is Gabriel. I'am from Brazil. 27. I finished last year
> Degree in Computer Engineering and I would go to the U.S.A
> to learn the local language.
> I wonder how is the market for developers, which
> city ​​is best for this?
> I program for 5 years PHP (MVC) and for the past four months I
> working with Python and Django. Incidentally, I love it and work on it
>
> Working on a site in Brazil claims, moreover, the largest site
> latin america complaints. (ser for 'reclamação' in google.com.br).
>
> I would like to review and help the community. I am very interested in
> live in the USA.
>
> Even more.


Visit my site and to know my job. www.igrow.com.br
-- 
http://mail.python.org/mailman/listinfo/python-list


Help Amigos

2011-04-11 Thread Gabriel Novaes
Hello community

My name is Gabriel. I'am from Brazil. 27. I finished last year
Degree in Computer Engineering and I would go to the U.S.A
to learn the local language.
I wonder how is the market for developers, which
city ​​is best for this?
I program for 5 years PHP (MVC) and for the past four months I
working with Python and Django. Incidentally, I love it and work on it

Working on a site in Brazil claims, moreover, the largest site
latin america complaints. (ser for 'reclamação' in google.com.br).

I would like to review and help the community. I am very interested in
live in the USA.

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


Re: How to build and upload eggs to pypi?

2011-03-22 Thread Gabriel Genellina
On 21 mar, 08:53, morphex  wrote:
> Hi,
>
> I have a couple of project which are on PyPi, and now I'd like to
> update some of them.  Is there a good howto somewhere, showing how to
> add new versions (instead of updating one that's already there) etc?

There is a tutorial: http://wiki.python.org/moin/CheeseShopTutorial
To add a new version, simply increment the version number, and then
"python setup.py upload" should be enough.

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


Re: puzzle about file Object.readlines()

2011-03-22 Thread Gabriel Genellina
On 19 mar, 16:05, Dave Angel  wrote:
> On 01/-10/-28163 02:59 PM, MRAB wrote:
> > On 19/03/2011 13:15, 林桦 wrote:
> >> i use python 2.5. os is window 7.
> >> the puzzle is :python don't read the leave text when meet character:
> >> chr(26)
> >> the code is:
> >> /fileObject=open('d:\\temp\\1.txt','w')
> >> fileObject.write('22\r\n')
> >> fileObject.write(chr(26)+'\r\n')
> >> fileObject.write('33')
> >> fileObject.close()
> >> fileObject=open('d:\\temp\\1.txt','r')
> >> i=0
> >> for line in fileObject:
> >> i+=1
> >> print str(i)+'**'+line
> >> fileObject.close()/
>
> >> the output only print:
> >> />>>
> >> 1**22/
>
> >> but can't print next line text:/'33'' 。who tell me why?
> >> /
>
> > chr(26) can sometimes be used in text files to indicate the end of the text.
>
> > In Microsoft Windows it dates from MS-DOS, which borrowed from CP/M, an
> > operating
> > system which stored the file size as the number of 128-byte records.
> > chr(26) was used to
> > indicate where the text ended in the last record.
>
> On Win a ctrl-z is end of file.  So if you want to read beyond the end
> of a text file, you have to pretend it's binary.  Open it with  "rb"
> instead of "r"

Using mode "rU" may be more convenient, because it still translates \r
\n into \n but disregards chr(26) as a special marker.

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


Re: favicon.ico problem

2010-08-11 Thread Gabriel Genellina
En Tue, 10 Aug 2010 01:32:49 -0300, Navkirat Singh   
escribió:


I am having this strange problem. I have programmed a very basic  
multiprocessing webserver using low level sockets. Each time the server  
receives a request it spawns a new process to handle the request. Now  
when through a web browser I type http://localhost:8001/ it  
automatically creates two processes: One process to server the '/' path  
and another one to serve the '/favicon.ico' path. I have not programmed  
it to serve the latter. Infact I dont even know where that name  
'/favicon.ico' comes from. Any insight into this weird behavior would be  
greatly appreciated.


It't the browser attempting to get an icon for the page.
See http://en.wikipedia.org/wiki/Favicon

--
Gabriel Genellina

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


Re: easy question on parsing python: "is not None"

2010-08-09 Thread Gabriel Genellina
En Mon, 09 Aug 2010 08:41:23 -0300, saeed.gnu   
escribió:



"x is y"  means   "id(y) == id(y)"
"x is not y"  means   "id(x) != id(x)"


No; consider this:


py> id([])==id([])
True
py> [] is []
False

Comparing id's is the same as using the is operator only if you can  
guarantee that both operands are alive at the same time.



--
Gabriel Genellina

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


Re: easy question on parsing python: "is not None"

2010-08-07 Thread Gabriel Genellina
En Sat, 07 Aug 2010 04:04:06 -0300, Stefan Schwarzer  
 escribió:

On 2010-08-07 00:28, Steven D'Aprano wrote:



Actually, yes, equality is implemented with a short-cut

that checks for

identity first. That makes something like:
[...]


Oops, I didn't realize that the OP had mentioned the
identity check as an optimization in case the objects are
the same. I thought he was confusing the operator with `is`.


s = "abc"*1000*1000*10
s == s

nice and quick, as Python can immediately recognise that a string is
always equal to itself without having to walk the entire string  
comparing

each character with itself.


Yes, that definitely makes sense. I guess I would have
implemented it this way as well. :)


For strings and other internal types this optimization certainly makes  
sense. For user-defined types it gets in the way and prevents defining an  
object such x==x is False (like NANs).


--
Gabriel Genellina

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


Re: abstract metaclass

2010-08-06 Thread Gabriel Genellina
En Thu, 05 Aug 2010 10:46:29 -0300, Roald de Vries   
escribió:


I'm trying to create a metaclass that keeps track of its objects, and  
implement this as a collections.MutableMapping. That is, something like  
this:



class type2(type, MutableMapping):
 ...

/opt/local/Library/Frameworks/Python.framework/Versions/2.6/lib/ 
python2.6/abc.pyc in __new__(mcls, name, bases, namespace)
  83  if getattr(value, "__isabstractmethod__",  
False))

  84 for base in bases:
---> 85 for name in getattr(base, "__abstractmethods__",  
set()):

  86 value = getattr(cls, name, None)
  87 if getattr(value, "__isabstractmethod__",  
False):


TypeError: Error when calling the metaclass bases
 'getset_descriptor' object is not iterable


Anybody knows why? Every type is just an object, isn't it?


This may be an oversight in ABCMeta implementation - please file a bug  
report at http://bugs.python.org/


--
Gabriel Genellina

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


Re: How to read large amounts of output via popen

2010-08-06 Thread Gabriel Genellina

En Fri, 06 Aug 2010 06:06:29 -0300, loial  escribió:


I need to read a large amount of data that is being returned in
standard output by a shell script I am calling.

(I think the script should really be writing to a file but I have no
control over that)

Currently I have the following code. It seeems to work, however I
suspect this may not work with large amounts of standard output.

What is the best way to read a large amount of data from standard
output and write to a file?

Here is my code.

process=subprocess.Popen(['myscript', 'param1'],
shell=False,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

cmdoutput=process.communicate()

myfile = open('/home/john/myoutputfile','w')

myfile.write(cmdoutput[0])

myfile.close()



If all you do with the process' output is to write it to the output file,  
you can avoid the intermediate step:



myfile = open('/home/john/myoutputfile','w')
myerror = open('/home/john/myerrorfile','w')
process=subprocess.Popen(['myscript', 'param1'],
shell=False,stdout=myfile,stderr=myerror)
process.wait()

(untested)

--
Gabriel Genellina

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


Re: Byte Offsets of Tokens, Ngrams and Sentences?

2010-08-06 Thread Gabriel Genellina
En Fri, 06 Aug 2010 06:07:32 -0300, Muhammad Adeel   
escribió:



Does any one know how to tokenize a string in python that returns the
byte offsets and tokens? Moreover, the sentence splitter that returns
the sentences and byte offsets? Finally n-grams returned with byte
offsets.

Input:
This is a string.

Output:
This  0
is  5
a   8
string.   10


Like this?

py> import re
py> s = "This is a string."
py> for g in re.finditer("\S+", s):
...   print g.group(), g.start()
...
This 0
is 5
a 8
string. 10

--
Gabriel Genellina

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


Re: Urrlib2 IncompleteRead error

2010-08-04 Thread Gabriel Genellina
On 27 jul, 11:00, dirknbr  wrote:

> I am running urllib2.request and get this response when I do the read.
> Any ideas what causes this?
>
> return response.read()
>   File "C:\Python26\lib\socket.py", line 329, in read
>     data = self._sock.recv(rbufsize)
>   File "C:\Python26\lib\httplib.py", line 518, in read
>     return self._read_chunked(amt)
>   File "C:\Python26\lib\httplib.py", line 561, in _read_chunked
>     raise IncompleteRead(''.join(value))
> IncompleteRead: IncompleteRead(3235 bytes read)

Looks like a server error; a chunked transfer encoding finished before
reaching the expected size.

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


Re: encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna' )

2010-06-23 Thread Gabriel Genellina

En Tue, 22 Jun 2010 11:02:58 -0300,  escribió:


Python 2.6.4 (Win32): Anyone have any explanation for the
following

encodings.idna.ToASCII( unicodeStr ) != unicodeStr.encode( 'idna'
)

Given that other processes may have to use the output of these
methods, what is the recommended technique?

Demonstration:


import encodings.idna
name = u'junk\xfc\xfd.txt'
name

u'junk\xfc\xfd.txt'

encodings.idna.ToASCII( name )

'xn--junk.txt-95ak'

name.encode( 'idna' )

'xn--junk-3rag.txt'

encodings.idna.ToUnicode( encodings.idna.ToASCII( name ) )

u'junk\xfc\xfd.txt'

name.encode( 'idna' ).decode( 'idna' )

u'junk\xfc\xfd.txt'


IDNA is *specifically* designed to operate with domain names, not  
arbitrary text. (IDNA = Internationalizing Domain Names in Applications).  
Even the encoding/decoding part alone(punycode) is specifically tailored  
for use in domain names. Do not use it for any other purpose.


That said, it seems that encodings.idna.ToUnicode/ToAscii work on  
individual 'labels' only (a domain name is comprised of several labels  
separated by '.') -- and encode/decode('idna') takes the whole name,  
splits, and processes each label (following RFC 3490, I presume)


--
Gabriel Genellina

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


Re: adding new function

2010-06-23 Thread Gabriel Genellina
En Tue, 22 Jun 2010 14:18:59 -0300, Terry Reedy   
escribió:

On 6/22/2010 5:44 AM, Daniel Fetchinson wrote:

how can i simply add new functions to module after its initialization
(Py_InitModule())?  I'm missing something like
PyModule_AddCFunction().


in Python, for modules written in python

import mymod
mymod.fname = somefunc #or
setattr(mymod, namestring, funcobject)


I presume you use the C-API equivalent of setattr.


That one, or PyModule_AddObject (just for nicer error messages really).

--
Gabriel Genellina

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


Re: Using Unicode file names with ftplib and encodings.idna as a workaround?

2010-06-22 Thread Gabriel Genellina

En Tue, 22 Jun 2010 11:43:34 -0300,  escribió:


Python 2.6.5 (Win32): Is there a work around for ftplib's (and
ftputil's) apparent inability to support Unicode file names?

I'm thinking that I might be able to use the encodings.idna as a
work around for this?


According to RFC 2640, you should use UTF-8 instead.
http://www.faqs.org/rfcs/rfc2640.html


One downside is that processes on the server will also have to
wrap directory access with a similar transformation. This
wouldn't be too complicated for Python programs, but I'm not sure
how convenient this would be for our PHP and shell scripters.
(Just checked: There's a PEAR module for PHP4/5; oddly enough
nothing pops up for .NET IDNA libraries)


The server software must be able to convert from file system encoding to  
utf-8 and viceversa; check its configuration.


--
Gabriel Genellina

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


Re: Strange factory pattern

2010-06-22 Thread Gabriel Genellina

En Tue, 22 Jun 2010 23:33:55 -0300, Zac Burns  escribió:


In the threading module there are several code bits following this
convention:

###
def Class(*args, **kwargs):
return _Class(*args, **kwargs)

class _Class(...
###

This is true for Event, RLock, and others.

Why do this? It seems to violate the rule of least astonishment
(isinstance(Event(), Event) raises an exception). I assume there must be
some trade-off that the designer intended to achieve. So, what is that
trade-off and when should I follow this in my code?


Those classes are not meant to be subclassed (I don't know *why*). From  
original module documentation (1998):


http://svn.python.org/view/python/trunk/Lib/threading_api.py?view=markup&pathrev=10430


"Lock()
A factory function that returns a new primitive lock object...

RLock()
A factory function that returns..."

Same for Condition, Semaphore, Event, but:

"Thread
A class that represents a thread of control -- subclassable."

"Note that the classes marked as ''do not subclass'' are actually  
implemented as factory functions; classes are

shown here as a way to structure the documentation only."

And those classes have a big "*** DO NOT SUBCLASS THIS CLASS ***" message.  
The message never made into the documentation.



--
Gabriel Genellina

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


Re: "isinstance" question

2010-06-22 Thread Gabriel Genellina
En Tue, 22 Jun 2010 23:45:07 -0300, John Nagle   
escribió:



   I want to test whether an object is an instance of any user-defined
class.  "isinstance" is less helpful than one would expect.

 >>> import types
 >>> class foo() : # define dummy class
... pass
...
 >>> x = foo()
 >>>
 >>> type(x)

 >>>
 >>> isinstance(x, types.ClassType)
False
 >>> isinstance(x, types.InstanceType)
True
 >>> foo

 >>> x
<__main__.foo instance at 0x020080A8>

So far, so good. x is an InstanceType.  But let's try a
class with a constructor:

 >>> class bar(object) :
...def __init__(self, val) :
...  self.val = val
...
 >>> b = bar(100)
 >>> b
<__main__.bar object at 0x01FF50D0>
 >>> isinstance(b, types.InstanceType)
False
 >>> isinstance(b, types.ClassType)
False
 >>>>>> bar


Without a constructor, we get an "instance".  With a constructor,
we get an "object", one which is not an InstanceType.


That's not the relevant difference. In the first case, you don't inherit  
from object; in the second one, you do.


foo is a "classic" class (or "old-style" class); x is an instance of foo,  
its *type* is InstanceType, its *class* is foo. All instances of any other  
classic class have the same type (InstanceType).


bar is a "new-style" class, b is an instance of bar, its type is bar, its  
class is bar. class and type are equivalent for new style classes; things  
are a lot more regular and predictable. In Python 3.x classic classes are  
gone.


--
Gabriel Genellina

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


Re: Serialization, save type information in file and restore them

2010-06-22 Thread Gabriel Genellina
En Fri, 18 Jun 2010 08:24:01 -0300, Timothy Wu <2hug...@gmail.com>  
escribió:



I created a class that's able to manipulate tabulated data. I want to be
able to dump the bulk of the data and other attributes as a tab-delimited
text. I have trouble saving/restoring type information in the file. For
example, some attributes are int, others may be float, etc. So I want to
store the data type as well as the data value themselves in a file. And I
don't think I want to use Pickle because I want it to be readily opened  
in
vi and be readable as a tab-delimited file and be able to import into  
Excel

as well.

What's the best way to achieve this? I was able to write string like
"attribute = int(value)" into a file. But how do I get the value back? I
want the "int(value)" string to be loaded into the program and be  
executable

so I can actually create the instance variable in the class.


Use the csv module to write your data in the RDB file format.
The RDB format is fairly simple: first line contains the column names (tab  
separated), second line stores type information (tab separated), remaining  
lines contain actual data (also, tab separated).
(You may use any format you want, but why reinvent it, and you may even  
find an existing RDB parser/writer in Python)


--
Gabriel Genellina

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


Re: question about multiprocessing

2010-06-22 Thread Gabriel Genellina

En Sun, 20 Jun 2010 09:43:09 -0300, hywhy  escribió:


from multiprocessing.managers import BaseManager
import Queue

class CrawlerManager(BaseManager):
pass

downloader_queue = Queue.Queue()
downloader_queue.put('hello')

CrawlerManager.register('get_downloader_queue', callable=lambda:
downloader_queue)

mgr = CrawlerManager()
mgr.start()

q = mgr.get_downloader_queue()



error:

pickle.PicklingError: Can't pickle  at 0x00C02F70>:  
it's

not found as __parents_main__.


Multiprocessing uses pickle to transfer data between processes. You can't  
pickle a lambda expression - functions must have a name and be available  
at the outermost module level. (See "Programming guidelines" in the  
multiprocessing documentation, and the pickle module)
But you can't share a Queue object - use the multiprocessing one (see  
"Exchanging data between processes").


--
Gabriel Genellina

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


  1   2   3   4   5   6   7   8   9   10   >