Re: graph edge generators

2009-06-09 Thread Rafael
William Clifford  writes:

> I've become interested in basic graphs and networks and I'm wondering
> about what algorithms are there for generating basic regular graphs
> like the simplex graph or dodecahedron graph, etc (I'm sure there are
> many). I'm particularly keen on understanding the very basic functions
> for determining edges in the graphs. If one didn't want the complete
> graph but just a function generates the edges connected to a given
> node.

probably the SAGE system (www.sagemath.org) would be of interest to you.
-- 
http://mail.python.org/mailman/listinfo/python-list


Reinstalling

2021-01-29 Thread Rafael Llera
Good day;

I installed Python3.9.1 and PyCharm two days ago and did a basic tutorial
and all went well.  My laptop got glitchy and I decided to uninstall and
reinstall both apps (don't ask).

Now I am having problems starting a project with the interpreter,  I cannot
find python3.

I just uninstalled both apps again and found a lot of *.pyc files, my
questions would it help to delete them all before reinstalling again, or is
this a different issue.  thank you in advance.

best regards,
Rafael
-- 
https://mail.python.org/mailman/listinfo/python-list


Running Jupyter Notebook

2021-02-10 Thread Rafael Llera
I installed Python and jupyter via pip, but when I run jupyter notebook I
keep getting the following error.

 Requirement already satisfied: pyparsing>=2.0.2 in
c:\users\mitzi\appdata\roaming\python\python39\site-packages (from
packaging->bleach->nbconvert->jupyter) (2.4.7)
Requirement already satisfied: qtpy in
c:\users\mitzi\appdata\roaming\python\python39\site-packages (from
qtconsole->jupyter) (1.9.0)

C:\WINDOWS\system32>jupyter notebook
'jupyter' is not recognized as an internal or external command,
operable program or batch file.

C:\WINDOWS\system32>
-- 
https://mail.python.org/mailman/listinfo/python-list


Pompem Exploit and Vulnerability Finder Tool v0.2.0 Python 3.5

2016-08-05 Thread Rafael Francischini
Hello,  I would like to share with you my personal project, Pompem.

https://github.com/rfunix/Pompem/

I hope you enjoy it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Problem with lists

2015-09-15 Thread Rafael David
Hi guys,

I'm newbie in Python (but not a newbie developer). I'm facing a problem with a 
bidimensional list (list of lists) containing dictionaries. I don't know if I 
didn't understand how lists and dictionaries work in Python or if there is a 
mistake in my code that I can't see. In the code I'm printing the list values 
just after the assignment and they are ok, but when I try to print the list at 
the end of the function the values are different (repeated). Below is the code 
and the result in Python 3.4.0. Could you guys please help me with that?

Thanks a lot!

Rafael

>>> def preencherTabuleiroInicial():
tabuleiro = [[None for x in range(8)] for y in range(8)]
peca = {}
for lin in range(8):
for col in range(8):
if lin == 0 or lin == 1 or lin == 6 or lin == 7:
if lin == 0 or lin == 1:
peca['cor'] = 'b'
elif lin == 6 or lin == 7:
peca['cor'] = 'p'
if lin == 1 or lin == 6:
peca['nome'] = 'p'   
elif col == 0 or col == 7:
peca['nome'] = 't'
elif col == 1 or col == 6:
peca['nome'] = 'c'
elif col == 2 or col == 5:
peca['nome'] = 'b'
elif col == 3:
peca['nome'] = 'd'
else:
peca['nome'] = 'r'
tabuleiro[lin][col] = peca
print(str(lin) + ' ' + str(col) + ' ' + str(tabuleiro[lin][col]))
print()
print(tabuleiro)

>>> 
>>> preencherTabuleiroInicial()
0 0 {'nome': 't', 'cor': 'b'}
0 1 {'nome': 'c', 'cor': 'b'}
0 2 {'nome': 'b', 'cor': 'b'}
0 3 {'nome': 'd', 'cor': 'b'}
0 4 {'nome': 'r', 'cor': 'b'}
0 5 {'nome': 'b', 'cor': 'b'}
0 6 {'nome': 'c', 'cor': 'b'}
0 7 {'nome': 't', 'cor': 'b'}
1 0 {'nome': 'p', 'cor': 'b'}
1 1 {'nome': 'p', 'cor': 'b'}
1 2 {'nome': 'p', 'cor': 'b'}
1 3 {'nome': 'p', 'cor': 'b'}
1 4 {'nome': 'p', 'cor': 'b'}
1 5 {'nome': 'p', 'cor': 'b'}
1 6 {'nome': 'p', 'cor': 'b'}
1 7 {'nome': 'p', 'cor': 'b'}
2 0 None
2 1 None
2 2 None
2 3 None
2 4 None
2 5 None
2 6 None
2 7 None
3 0 None
3 1 None
3 2 None
3 3 None
3 4 None
3 5 None
3 6 None
3 7 None
4 0 None
4 1 None
4 2 None
4 3 None
4 4 None
4 5 None
4 6 None
4 7 None
5 0 None
5 1 None
5 2 None
5 3 None
5 4 None
5 5 None
5 6 None
5 7 None
6 0 {'nome': 'p', 'cor': 'p'}
6 1 {'nome': 'p', 'cor': 'p'}
6 2 {'nome': 'p', 'cor': 'p'}
6 3 {'nome': 'p', 'cor': 'p'}
6 4 {'nome': 'p', 'cor': 'p'}
6 5 {'nome': 'p', 'cor': 'p'}
6 6 {'nome': 'p', 'cor': 'p'}
6 7 {'nome': 'p', 'cor': 'p'}
7 0 {'nome': 't', 'cor': 'p'}
7 1 {'nome': 'c', 'cor': 'p'}
7 2 {'nome': 'b', 'cor': 'p'}
7 3 {'nome': 'd', 'cor': 'p'}
7 4 {'nome': 'r', 'cor': 'p'}
7 5 {'nome': 'b', 'cor': 'p'}
7 6 {'nome': 'c', 'cor': 'p'}
7 7 {'nome': 't', 'cor': 'p'}

[[{'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 
'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 
'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}], [{'nome': 
't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, 
{'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 
'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}], [None, None, None, 
None, None, None, None, None], [None, None, None, None, None, None, None, 
None], [None, None, None, None, None, None, None, None], [None, None, None, 
None, None, None, None, None], [{'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 
'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 
'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 
't', 'cor': 'p'}], [{'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, 
{'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 
'p'}, {'nome'
 : 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}, {'nome': 't', 'cor': 'p'}]]
>>> 
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Problem with lists

2015-09-15 Thread Rafael David
Em terça-feira, 15 de setembro de 2015 21:11:38 UTC-3, MRAB  escreveu:
> On 2015-09-16 00:45, Rafael David wrote:
> > Hi guys,
> >
> > I'm newbie in Python (but not a newbie developer). I'm facing a
> > problem with a bidimensional list (list of lists) containing
> > dictionaries. I don't know if I didn't understand how lists and
> > dictionaries work in Python or if there is a mistake in my code that
> > I can't see. In the code I'm printing the list values just after the
> > assignment and they are ok, but when I try to print the list at the
> > end of the function the values are different (repeated). Below is
> > the code and the result in Python 3.4.0. Could you guys please help
> > me with that?
> >
> > Thanks a lot!
> >
> > Rafael
> >
> >>>> def preencherTabuleiroInicial():
> >  tabuleiro = [[None for x in range(8)] for y in range(8)]
> >  peca = {}
> >  for lin in range(8):
> >  for col in range(8):
> >  if lin == 0 or lin == 1 or lin == 6 or lin == 7:
> >  if lin == 0 or lin == 1:
> >  peca['cor'] = 'b'
> >  elif lin == 6 or lin == 7:
> >  peca['cor'] = 'p'
> >  if lin == 1 or lin == 6:
> >  peca['nome'] = 'p'
> >  elif col == 0 or col == 7:
> >  peca['nome'] = 't'
> >  elif col == 1 or col == 6:
> >  peca['nome'] = 'c'
> >  elif col == 2 or col == 5:
> >  peca['nome'] = 'b'
> >  elif col == 3:
> >  peca['nome'] = 'd'
> >  else:
> >  peca['nome'] = 'r'
> >  tabuleiro[lin][col] = peca
> >  print(str(lin) + ' ' + str(col) + ' ' + 
> > str(tabuleiro[lin][col]))
> >  print()
> >  print(tabuleiro)
> >
> >>>>
> >>>> preencherTabuleiroInicial()
> > 0 0 {'nome': 't', 'cor': 'b'}
> > 0 1 {'nome': 'c', 'cor': 'b'}
> > 0 2 {'nome': 'b', 'cor': 'b'}
> > 0 3 {'nome': 'd', 'cor': 'b'}
> > 0 4 {'nome': 'r', 'cor': 'b'}
> > 0 5 {'nome': 'b', 'cor': 'b'}
> > 0 6 {'nome': 'c', 'cor': 'b'}
> > 0 7 {'nome': 't', 'cor': 'b'}
> > 1 0 {'nome': 'p', 'cor': 'b'}
> > 1 1 {'nome': 'p', 'cor': 'b'}
> > 1 2 {'nome': 'p', 'cor': 'b'}
> > 1 3 {'nome': 'p', 'cor': 'b'}
> > 1 4 {'nome': 'p', 'cor': 'b'}
> > 1 5 {'nome': 'p', 'cor': 'b'}
> > 1 6 {'nome': 'p', 'cor': 'b'}
> > 1 7 {'nome': 'p', 'cor': 'b'}
> > 2 0 None
> > 2 1 None
> > 2 2 None
> > 2 3 None
> > 2 4 None
> > 2 5 None
> > 2 6 None
> > 2 7 None
> > 3 0 None
> > 3 1 None
> > 3 2 None
> > 3 3 None
> > 3 4 None
> > 3 5 None
> > 3 6 None
> > 3 7 None
> > 4 0 None
> > 4 1 None
> > 4 2 None
> > 4 3 None
> > 4 4 None
> > 4 5 None
> > 4 6 None
> > 4 7 None
> > 5 0 None
> > 5 1 None
> > 5 2 None
> > 5 3 None
> > 5 4 None
> > 5 5 None
> > 5 6 None
> > 5 7 None
> > 6 0 {'nome': 'p', 'cor': 'p'}
> > 6 1 {'nome': 'p', 'cor': 'p'}
> > 6 2 {'nome': 'p', 'cor': 'p'}
> > 6 3 {'nome': 'p', 'cor': 'p'}
> > 6 4 {'nome': 'p', 'cor': 'p'}
> > 6 5 {'nome': 'p', 'cor': 'p'}
> > 6 6 {'nome': 'p', 'cor': 'p'}
> > 6 7 {'nome': 'p', 'cor': 'p'}
> > 7 0 {'nome

Re: Problem with lists

2015-09-16 Thread Rafael David
Em terça-feira, 15 de setembro de 2015 21:47:10 UTC-3, Chris Angelico  escreveu:
> On Wed, Sep 16, 2015 at 10:29 AM, Rafael David  wrote:
> > Oooohhh ... I think I got it! I'm assigning a reference to peca and not the 
> > value itself! Thank you very much MRAB and C Smith for the enlightenment :)
> 
> Right! That's how Python's assignment always works. You may find, in
> your case, that you can simply reassign peca={} every time through the
> loop. No copying necessary - just make yourself a new dict for each
> iteration.
> 
> And you might be able to do the whole thing with a gigantic
> list/list/dict comprehension, but that may or may not be an
> improvement on your code :)
> 
> ChrisA

Yes, got it. Thanks Chris!

Guys, this group rocks :)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMatch Tool.

2014-08-18 Thread Rafael Francischini
Em sexta-feira, 15 de agosto de 2014 17h59min28s UTC-3, Christian Gollwitzer  
escreveu:
> Am 14.08.14 21:50, schrieb [email protected]:
> 
> > Hello, I created this tool to help me develop on formatting text using 
> > regular expressions.
> 
> > Any questions, I am available.
> 
> > Thank you.
> 
> >
> 
> > Tool -> https://github.com/rfunix/PyMatch
> 
> 
> 
> I expected something like visual regexp:
> 
> 
> 
>   http://laurent.riesterer.free.fr/regexp/
> 
> 
> 
> Since RegExp-Syntax is very similar across tools, yours is almost 
> 
> identical to grep. Is it not?
> 
> 
> 
>   Christian

Hi Christian, it is quite similar. 
The difference is with her can extract and use the values stored in groups.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PyMatch Tool.

2014-08-18 Thread Rafael Francischini
Cristian you are right, never experienced visual regexp, is incredible. 
I created pyMatch to help me in the automation scripts and text formatting, so 
I decided to work from the command line. 
You're right, you can also do this with sed, but sed has a small defect "in my 
view", you will be able to use a maximum of 10 groups in it and  also the 
visual regexp. 

If you want to read more: 
http://stackoverflow.com/questions/10992650/how-to-get-10th-grouping-value-in-sed
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Subprocess and pipe-fork-exec primitive

2007-08-01 Thread Rafael V.
Hi Martin,

   the operating system I'm using is SUSE Linux 10, kernel 2.6.13.

   You're right, I was missing something. After you told me that it
couldn't be Python preforming wait() on SIGCHLD, I decided to
investigate further.

   My application requires access to a Informix database, and uses
informixdb. The problem seems to be related to that module. I wrote a
small piece of code to test it:

---
#!/usr/bin/env python

from os import fork, execl, waitpid
from informixdb import connect

try:
   conf = {}
   conf['dsn'] = '[EMAIL PROTECTED]'
   conf['user'] = 'user'
   conf['password'] = 'password'
   connection = connect(**conf)

except:
   pass

pid = fork()

if pid == 0:
   # Child
   execl("/bin/sh", "/bin/sh", "-c", "true")

# Parent
waitpid(pid, 0)

print pid
---

   If you run the code above multiple times, some runs will trigger
exceptions on the waitpid calls. Commenting the call to
informixdb.connect(), no exceptions are triggered. I am concluding that
informixdb, not Python, is handling the signals and reaping the
subprocesses.

   Now Martin, do you think I can use informixdb.py and subprocess.py in
the same application? I was thinking on forking subprocesses from the
main thread and using other threads to access the Informix database,
would that work?

Thanks,
Rafael.

Martin v. Löwis escreveu:
>>   From my experience, this primitive will fail with 'no child processes'
>> at the waitpid call if the forked child dies very quickly - before the
>> parent is scheduled back for execution. This seems to happen because
>> Python has a default SIGCHLD handler that, in this case, will reap the
>> process before the parent has the chance to do it.
> 
> What operating system is your experience from? On a POSIX system,
> this should not happen - i.e. delivery of SIGCHLD should not cause
> to make the child waited-for. Python itself does not perform wait()
> in response to SIGCHLD.
> 
>>   I would like to know if this is correct, or am I missing something here?
> 
> You must be missing something, although I'm uncertain what precisely
> that is.
> 
> Regards,
> Martin



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


Understanding Python's interpreter

2007-04-06 Thread Rafael Almeida
Hello,

I'm studying compilers now on my university and I can't quite
understand one thing about the python interpreter. Why is its input a
binary file (pyc)? The LOAD_CONST opcode is 100 (dec) and STORE_FAST's
is 125 (dec). The translation of the following code:

foo.py:
x = 10

Could be this:

foo.pyc:
100 10
125 0

That way you wouldn't need code such as 
static void
w_long(long x, WFILE *p)
{
w_byte((char)( x  & 0xff), p);
w_byte((char)((x>> 8) & 0xff), p);
w_byte((char)((x>>16) & 0xff), p);
w_byte((char)((x>>24) & 0xff), p);
}
since you could read it with strtol and write back using a simple
printf. So you wouldn't need a buch of casts by simple using ascii
input and output.

What's the reason for having it in a binary form instead of writting
it in ascii? (yeah, I know ascii would be binary also, but I think you
get my point.)

So I was writting this interpreter for some assembly language defined
in class and I did something like python does, so I had a binary file
to interpret. After a while I thought it was far harder to program.
And when I tried to code an assembler my problems got greater, as I
wanted to code it in python (the interpreter was in C++) and I had a
hard time trying to figure out how I would print something that's not a
ascii or unicode string. As for the benefits, I couldn't figure out any.

I hope I'm not too offtopic here, but I thought this was probably the
best news to ask this. If someone thinks there's another news that's
more appropriate, please tell me.

[]'s
Rafael
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Understanding Python's interpreter

2007-04-07 Thread Rafael Almeida
On Sat, 07 Apr 2007 04:35:49 +0200
Gabriel Genellina <[EMAIL PROTECTED]> wrote:

> Speed? Eficiency? File size? Ease of use?
> A .pyc *could* be written in ASCII, but what do you gain? Replacing a 
> few trivial functions in the Python core with a printf/scanf equivalent? 
>   At the same time you lose a lot of speed, so I don't see the point.

Hm, I didn't realise that it would be that much slower.

> Why harder? Once you read the file, they're just numbers. Anyway, being 
> harder to program the *interpreter* is not a problem, if you gain 
> something like speed or eficiency for the interpreted language.

Well, it's harder to get 4 bytes and create an int out of it in a
portable way than just call strtol or scanf, that's what I thought
while I was coding my interpreter. It's not the hardest thing to do,
of course, but it made me wonder why not just do the simplest thing.

Since I've never seen a .pyc bigger than a few kilobytes, I thought an
ascii file would take more space, but it wouldn't be anything really
prohibitive.

I didn't think using strtol would make that much difference in speed.
But now you talked about it, and after thinking a little bit more about
it, I'm convinced that the speed difference may be relevant.

> > And when I tried to code an assembler my problems got greater, as I
> > wanted to code it in python (the interpreter was in C++) and I had a
> > hard time trying to figure out how I would print something that's not a
> > ascii or unicode string. As for the benefits, I couldn't figure out any.
> 
> Sorry, I could not understand what you said here.

It's not anything important, I was just saying that I had to write a
little more code to make an integer such as 0xff into '\0\0\0\377' than
it would need to just print the integer. Well, unless there's already a
python function that does just that and I didn't know about. It's was
just an example on how writting in ascii is easier.
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: cannot create python packages

2007-10-10 Thread Rafael Sachetto
Try to put a empty file named __init__.py on current_dir/level1/On 10/10/07,
Konstantinos Pachopoulos <[EMAIL PROTECTED]> wrote:
>
> Hi,
> i have the following files:
> current_dir/level1/Called.py
> current_dir/Caller.py
>
>
> Called.py:
> ---
> class Called:
>def exec1(self):
>  print "Hello"
>
>
> Caller.py:
> --
> from level1.Called import *
>
> c=Called()
> c.exec1()
>
> However it is impossible for Caller.py to find
> Called.py. I even tried to place the level1 structure
> inside /usr/lib/pythonX.Y/, whithout success however.
> Any ideas?
>
> Thnx
>
>
>   ___
> Want ideas for reducing your carbon footprint? Visit Yahoo! For Good
> http://uk.promotions.yahoo.com/forgood/environment.html
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Rafael Sachetto
Try this:

test = u"Hello World"

n = range(len(test))

for i in n:
   cur  =  test[i]
   try:
  next = test[i+1]
   except:
  next = ""
print cur, next

just

On 10/10/07, Robert Dailey <[EMAIL PROTECTED]> wrote:
>
> Hi,
>
> I'm currently writing my own CSV parser since the built in one doesn't
> support Unicode. I'm wondering if there's a way to iterate over the
> characters in a unicode string and have access to both the 'current' and the
> 'next' characters each iteration. For example:
>
> test = u"Hello World"
>
> for cur,next in test:
> print cur,next
>
> Ideally, this would output:
>
> 'H', 'e'
> 'e', 'l'
> 'l', 'l'
> 'l', 'o'
> etc...
>
> Of course, the for loop above isn't valid at all. I am just giving an
> example of what I'm trying to accomplish. Anyone know how I can achieve the
> goal in the example above? Thanks.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: for loop question

2007-10-10 Thread Rafael Sachetto
Very nice solution :)

On 10/10/07, Paul Hankin <[EMAIL PROTECTED]> wrote:
>
> On Oct 10, 9:12 pm, Tim Chase <[EMAIL PROTECTED]> wrote:
> > > test = u"Hello World"
> >
> > > for cur,next in test:
> > > print cur,next
> >
> > > Ideally, this would output:
> >
> > > 'H', 'e'
> > > 'e', 'l'
> > > 'l', 'l'
> > > 'l', 'o'
> > > etc...
> >
> > > Of course, the for loop above isn't valid at all. I am just giving an
> > > example of what I'm trying to accomplish. Anyone know how I can
> achieve the
> > > goal in the example above? Thanks.
> >
> > A "works-for-me":
> >
> >  >>> pairs = (test[i:i+2] for i in xrange(len(test)-1))
> >  >>> for a,b in pairs:
> > ... print a,b
>
> for a, b in zip(test, test[1:]):
>   print a, b
>
> --
> Paul Hankin
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Best Python Linux distribution

2007-10-17 Thread Rafael Sachetto
You could try this
http://www.ibiblio.org/onebase/onebaselinux.com/About/features/developgo.php

On 10/17/07, Joe Riopel <[EMAIL PROTECTED]> wrote:
>
> On 10/17/07, Joe Riopel <[EMAIL PROTECTED]> wrote:
> > IDLE and Python came installed on Slackware 12, I am not 100% sure
> > about previous versions.
>
>
> Also, I am sure a lot of it (with most distributions)  depends on the
> packages you select during the  installation.
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: open remote terminal

2007-10-20 Thread Rafael Sachetto
Take a look at this documentation:

http://pexpect.sourceforge.net/pxssh.html

On 10/20/07, Fabian Braennstroem <[EMAIL PROTECTED]> wrote:
>
> Fabian Braennstroem wrote:
>
> > Hi Steve,
> >
> > Steve Holden wrote:
> >
> >> Fabian Braennstroem wrote:
> >>> Hi,
> >>>
> >>> I would like to use python to start an terminal, e.g. xterm, and login
> >>> on a remote machine using rsh or ssh. This could be done using 'xterm
> -e
> >>> ssh machine', but after the login I would like to jump to a given
> >>> directory. Does anyone have an idea how to do this with python?
> >>>
> >>> Regards!
> >>> Fabian
> >>>
> >> pexpect would be the usual solution, I believe, if you could get it to
> >> interact correctly with your virtual terminal.
> >>
> >>http://pexpect.sourceforge.net/
>
> I actually gave it a first very simple try:
>
> import pexpect
> child=pexpect.spawn('xterm')
> child.sendline('ls')
>
> Unfortunately nothing happens expect the start of xterm!? Does anyone have
> an idea, what I am doing wrong?
> Fabian
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Iteration for Factorials

2007-10-22 Thread Rafael Sachetto
The right way is:

import operator
def fact(x):
   return reduce(operator.mul, xrange(1,x+1))

On 10/22/07, Paul Rudin <[EMAIL PROTECTED]> wrote:
>
> "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
>
> > On Oct 22, 7:50 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> >> Py-Fun <[EMAIL PROTECTED]> wrote:
> >> > I'm stuck trying to write a function that generates a factorial of a
> >> > number using iteration and not recursion.  Any simple ideas would be
> >> > appreciated.
> >>
> >> This version avoids doing anything fancier than adding 1, so it should
> be
> >> simple enough for anyone:
> >>
> >> def factorial(e):
> >> a = 1
> >> for b in range(e):
> >> c = 0
> >> for j in range(b, -1, -1):
> >> for d in range(a):
> >> c += 1
> >> a = c
> >> return a
> >
> > Not simple enough for my taste:
> >
> >>>> import gmpy
> >>>> gmpy.fac(10)
> > mpz(3628800)
>
> I haven't followed all this thread, but has anyone yet done:
>
> import operator
> def fact(x):
> return reduce(operator.mul, xrange(1,x))
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: Iteration for Factorials

2007-10-22 Thread Rafael Sachetto
This works:

def fact(x):
if x == 0 or x == 1:
return 1
else:
return reduce(operator.mul, xrange(1,x+1))

or

def factorial(n):

acc = 1

while n > 1:
  acc = acc * n
  n = n - 1

return acc

On 10/22/07, [EMAIL PROTECTED] <[EMAIL PROTECTED]> wrote:
>
> On Oct 22, 1:35 pm, Paul Rudin <[EMAIL PROTECTED]> wrote:
> > "[EMAIL PROTECTED]" <[EMAIL PROTECTED]> writes:
> > > On Oct 22, 7:50 am, Duncan Booth <[EMAIL PROTECTED]> wrote:
> > >> Py-Fun <[EMAIL PROTECTED]> wrote:
> > >> > I'm stuck trying to write a function that generates a factorial of
> a
> > >> > number using iteration and not recursion.  Any simple ideas would
> be
> > >> > appreciated.
> >
> > >> This version avoids doing anything fancier than adding 1, so it
> should be
> > >> simple enough for anyone:
> >
> > >> def factorial(e):
> > >> a = 1
> > >> for b in range(e):
> > >> c = 0
> > >> for j in range(b, -1, -1):
> > >> for d in range(a):
> > >> c += 1
> > >> a = c
> > >> return a
> >
> > > Not simple enough for my taste:
> >
> > >>>> import gmpy
> > >>>> gmpy.fac(10)
> > > mpz(3628800)
> >
> > I haven't followed all this thread, but has anyone yet done:
> >
> > import operator
> > def fact(x):
> > return reduce(operator.mul, xrange(1,x))
>
> I hope not.
>
> >>> import operator
> >>> def fact(x):
> return reduce(operator.mul,xrange(1,x))
>
> >>> fact(3)
> 2
> >>> fact(2)
> 1
> >>> fact(1)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> fact(1)
>   File "", line 2, in fact
> return reduce(operator.mul,xrange(1,x))
> TypeError: reduce() of empty sequence with no initial value
>
> >>> fact(0)
>
> Traceback (most recent call last):
>   File "", line 1, in 
> fact(0)
>   File "", line 2, in fact
> return reduce(operator.mul,xrange(1,x))
> TypeError: reduce() of empty sequence with no initial value
>
> I think you need to make it a bit more complicated.
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: pyuno and calc

2007-11-06 Thread Rafael Sachetto
Maybe here: http://www.broffice.org/odfpy1

On 11/6/07, luca72 <[EMAIL PROTECTED]> wrote:
>
> Hello
> Can you tell me where i can find some example that's show how to open
> an existing oocalc document and get some data from it?
>
> Thanks Luca
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list

Re: How to browse a C Library with Python

2007-12-05 Thread Rafael Sachetto
This could be a solution

import commands

callables = commands.getoutput("nm -D /lib/libc.so.6 | egrep ' T '
").split("\n")
callables = [c.split()[2] for c in callables]

print callables

On Dec 5, 2007 5:26 PM, Rafael Sachetto <[EMAIL PROTECTED]> wrote:
> > > with Python it is simple to call direct functions from c-librarys.
> > > Is there a way to browse over a library i.e. '/lib/libc.so' with
> > > python, to see all possible functions in a library?
> >
> > You could use the subprocess module to execute 'nm /lib/libc.so' and look
> > at lines with type T.
>
> To do this on a dynamic library you have to use nm -D /lib/libc.so
>
>
> --
> Rafael Sachetto Oliveira
>
> Sir - Simple Image Resizer
> http://rsachetto.googlepages.com
>



-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to browse a C Library with Python

2007-12-05 Thread Rafael Sachetto
> > with Python it is simple to call direct functions from c-librarys.
> > Is there a way to browse over a library i.e. '/lib/libc.so' with
> > python, to see all possible functions in a library?
>
> You could use the subprocess module to execute 'nm /lib/libc.so' and look
> at lines with type T.

To do this on a dynamic library you have to use nm -D /lib/libc.so


-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: arrays in lists

2007-12-17 Thread Rafael Sachetto
No problem here too.
Using python 2.5 on Ubuntu Gutsy and the newest NumPy

2007/12/17, Robert Kern <[EMAIL PROTECTED]>:
> Peter Stahlir wrote:
> > Hi!
> >
> > I have a list of arrays and want to find an array with list.index(x).
> > Is that possible. I get an
> > ValueError: The truth value of an array with more than one element is
> > ambiguous. Use a.any() or a.all()
> >
> >
> > For example:
> > from numpy import array
> > a = array([1])
> > b = array([2])
> > c = [a,b]
> > d = c.index(a)
>
> You can't use .index() to do this. numpy arrays use rich comparisons such that
> (a == b) returns another array, not a boolean.
>
> --
> Robert Kern
>
> "I have come to believe that the whole world is an enigma, a harmless enigma
>  that is made terrible by our own mad attempt to interpret it as though it had
>  an underlying truth."
>   -- Umberto Eco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Fwd: Regular Expression for Prime Numbers (or How I came to fail at them, and love the bomb)

2008-02-13 Thread Rafael Sachetto
with this works:

 return re.match(r"^1?$|^(11+?)\1+$", convert)

but it match the non-prime numbers. So re_prime(2) will return null
and  re_prime(4) will return a match

2008/2/13, Carsten Haese <[EMAIL PROTECTED]>:
> On Wed, 2008-02-13 at 07:31 -0800, [EMAIL PROTECTED] wrote:
> > return re.match("^1?$|^(11+?)\1+$", convert)
>
> That needs to be either
>
> return re.match(r"^1?$|^(11+?)\1+$", convert)
>
> or
>
> return re.match("^1?$|^(11+?)\\1+$", convert)
>
> in order to prevent "\1" from being read as "\x01".
>
> --
> Carsten Haese
> http://informixdb.sourceforge.net
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>


--
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I execute a command from within python and wait on that command?

2008-02-15 Thread Rafael Sachetto
os.system(command)

or

proc = popen2.Popen3(command)
proc.wait()

2008/2/15, black_13 <[EMAIL PROTECTED]>:
> how do i exec a command (such as xcopy) from with win32 python and
>  wait on that command
>  to come to completion? and also cleanly terminate the command shell?
>  thanks
>  black_13
>
> --
>  http://mail.python.org/mailman/listinfo/python-list
>


-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Last 4 Letters of String

2008-02-21 Thread Rafael Sachetto
Try this

>>> s = "abcdefgh"
>>> s[-4:]
'efgh

2008/2/21, Robert Rawlins - Think Blue <[EMAIL PROTECTED]>:
>
>
>
>
> Hello Guys,
>
>
>
> I'm looking for a function which will give me the last 4 characters of a
> given string. I'm sure it's a very simple task but I couldn't find anything
> of it.
>
>
>
> Any ideas?
>
>
>
> Rob
> --
>  http://mail.python.org/mailman/listinfo/python-list
>


-- 
Rafael Sachetto Oliveira

Sir - Simple Image Resizer
http://rsachetto.googlepages.com
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting a list of lists to a single list

2013-07-23 Thread Rafael Durán Castañeda

El 23/07/13 23:52, [email protected] escribió:

[[A0,A1,A2], [B0,B1,B2] [C0,C1,C2]]

Hi,

I think you are looking for itertools.chain, or in this case, 
itertools.chain.from_iterable:


In [1]: x = [['A0','A1','A2'], ['B0','B1','B2'], ['C0','C1','C2']]

In [2]: import itertools

In [3]: [ y for y in itertools.chain.from_iterable(x)]
Out[3]: ['A0', 'A1', 'A2', 'B0', 'B1', 'B2', 'C0', 'C1', 'C2']

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


Re: Can't get around HTTP/401 response using SUDS

2012-03-08 Thread Rafael Durán Castañeda

El 08/03/12 16:44, Adam Tauno Williams escribió:

SUDS version 0.4 pn x86_64 Python 2.7

I'm having a bear of a time getting HTTP Basic Authentication to work
for a SOAP request via suds.  Also using an HTTP proxy server.

In WireShark I just see a request -
GET http://./services/services/JobService-0.0.1?wsdl HTTP/1.1
Accept-Encoding: identity
Host: ...
Connection: close
User-Agent: Python-urllib/2.7

This doesn't contain any authentication credentials so the response is
HTTP/401, and the client doesn't retry with credentials.  The response
does come from the remote as I can see there is a WWW-Authenticate
header and it is from an Apache Tomcat server - so it makes it through
the proxy server.

Code

  url = 'http://../services/services/JobService-0.0.1?wsdl'
  proxy = urllib2.ProxyHandler({'http': 'http://.:3128'})
  transport = suds.transport.http.HttpAuthenticated()
  transport.urlopener = urllib2.build_opener(proxy)
  client = suds.client.Client(url, transport=transport,
username='**', password='')


I've tried the above as well as the method described at

   It has the same problem.


Back Trace

Traceback (most recent call last):
   File "etrace.py", line 30, in
 client = suds.client.Client(url, transport=transport,
username='***', password='*')
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/client.py", 
line 112, in __init__
 self.wsdl = reader.open(url)
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/reader.py", 
line 152, in open
 d = self.fn(url, self.options)
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/wsdl.py", line 
136, in __init__
 d = reader.open(url)
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/reader.py", 
line 79, in open
 d = self.download(url)
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/reader.py", 
line 95, in download
 fp = self.options.transport.open(Request(url))
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/transport/http.py",
 line 173, in open
 return HttpTransport.open(self, request)
   File
"/usr/local/lib/python2.7/site-packages/suds-0.4-py2.7.egg/suds/transport/http.py",
 line 64, in open
 raise TransportError(str(e), e.code, e.fp)
suds.transport.TransportError: HTTP Error 401: Unauthorized

When I've got issues like yours, I usually try using a console client 
(telnet/curl/wget,...) adding all needed headers/data manually so I'm 
totally sure the request is OK, if everything goes Ok you know your 
python code need to be reviewed but when you are under proxies you can 
find a lot of not python related issues (bad gateways, using proxy when 
it shouldn't or vice-versa, requests changed by proxy,).


wireshark can be very useful but in situations like this I usually 
prefer tcpflow output, I think the request/response flow showed is 
really useful, but that's a personal preference.


HTH,
bye
--
http://mail.python.org/mailman/listinfo/python-list


try/except KeyboardInterrupt vs signal handler for SIGINT

2012-05-07 Thread Rafael Durán Castañeda

Hi,

I was wondering which approach is better to stop several servers from 
just on python application when 'ctrl-c' is pressed, a try/except 
KeyboardInterrupt or just registering a SIGINT handler and exit when the 
signal is triggered. Any advantage/disadvantage from one approach over 
the other?


P.S.: Since several servers are started just one 'ctrl-c' doesn't work 
without any extra change and I have some concerns about the signal handler.


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


Re: Is that safe to use ramdom.random() for key to encrypt?

2012-06-17 Thread Rafael Durán Castañeda

El 17/06/12 06:48, Chris Angelico escribió:

On Sun, Jun 17, 2012 at 2:18 PM, Steven D'Aprano
  wrote:

Safe from what? What is your threat model? Are you worried about your
little sister reading your diary? Or the NSA discovering your plans to
assassinate the President? Or something in between?

Python's random module is not cryptographically strong, which means that
it will probably take an organisation like the NSA, MI5, ASIO, Mossad,
etc. about 10 or 20 minutes to crack your password. But your little
sister will probably take a hundred million years to guess it.

Your little sister would quite possibly be kept off by rot13, which
everyone knows isn't cryptographically secure. All it takes is making
something look encrypted and most people won't bother to try (plus
it's the whole "this isn't public kthx" thing, which many people will
respect).

Of course, if you're just trying to fool the BOFH's technical manager,
it's even easier.

http://bofh.ch/newbofh/bofh4oct.html

ChrisA

Hi,

When generating random strings I usually do something like this 
wikepedia extract (http://en.wikipedia.org/wiki/Random_password_generator):


The language Python 
 
includes a SystemRandom class that obtains cryptographic grade random 
bits from /dev/urandom on a Unix-like system, including Linux and Mac OS 
X, while on Windows it uses CryptGenRandom.^[4] 
 
^[5] 
 
Here is a simple Python 2 script that demonstrates the use of this class:


#!/usr/bin/python
import  random,  string
myrg=  random.SystemRandom()
length=  10
# If you want non-English characters, remove the [0:52]
alphabet=  string.letters[0:52]  +string.digits
pw=  str().join(myrg.choice(alphabet)  for  _in  range(length))
print  pw

Do you think is secure enough for token generation? (40 chars long tokens are 
used for password reset links in a website, there isn't any special security 
concern for the web).


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


Re: How can I make a program automatically run once per day?

2011-07-10 Thread Rafael Durán Castañeda

On 10/07/11 04:01, John Salerno wrote:

Thanks everyone! I probably should have said something like "Python,
if possible and efficient, otherwise any other method" ! :)

I'll look into the Task Scheduler. Thanks again!
You may use Celery 
http://docs.celeryproject.org/en/latest/userguide/periodic-tasks.html

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


Python ++ Operator?

2011-07-15 Thread Rafael Durán Castañeda
Hello all,

I seem something like this on python code:

for  :
for  :
 spam[i][eggs] = ham
   ++i
.
.
.

What's the meaning of using i++? Even, does exist ++ operator in python?

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


Re: How do I implement two decorators in Python both of which would eventually want to call the calling function

2011-08-06 Thread Rafael Durán Castañeda
You don't need doing something special, each decorator returns a new 
function that and only the result function formed by all decorators will 
be run. Consider this:


def clear_cache(func):
def decorator(*args, **kwargs):
print "cache cleared"
return func(*args, **kwargs)
return decorator


def login(func):
def decorator(*args, **kwargs):
print "login"
return func(*args, **kwargs)
return decorator

@login
@clear_cache
def post(msg= "POST", *args):
print msg
return args


result = post("POST", "something")
print result

The output will be:

login
cache cleared
POST
('something',)

On 06/08/11 07:49, Devraj wrote:

Hi all,

I am trying to simply my Web application handlers, by using Python
decorators.

Essentially I want to use decorators to abstract code that checks for
authenticated sessions and the other that checks to see if the cache
provider (Memcache in this instance) has a suitable response.

Consider this method definition with the decorators:

@auth.login_required
@cache.clear
def post(self, facility_type_id = None):

auth.login_required checks to see if the user is logged in, otherwise
returns an appropriate error message, or executes the original
function.

cache.clear would check to to see if the cache has a particular key
and drop that, before it executes the calling method.

Both auth.login_required and cache.clear would want to eventually
execute the calling method (post).

> From what I've read both, doing what I am doing now would execute the
calling method (post) twice.

My question, how do I chain decorators that end up executing the
calling method, but ensure that it's only called once.

Appreciate any pointers and thanks for your time.


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


Re: Restricted attribute writing

2011-08-07 Thread Rafael Durán Castañeda
I think you might use a tuple instead of a list for OrderElement, that would
make much easier your code:

class
OrderElement(tuple):

def __new__(cls, x, y):
if not isinstance(x, int) or not isinstance(y, int):
raise TypeError("Order element must receives two
integers")

return tuple.__new__(cls, (x, y))


class Order(list):
def __setitem__(self, item):
assert isinstance(item, OrderElement)
super(Order, self).__setitem__(item)


I didn't check your module condition since it isn't quite clear to me, but
you could add a second condition two Order class.

2011/8/7 Steven D'Aprano 

> Roy Smith wrote:
>
> > In article ,
> >  John O'Hagan  wrote:
> >
> >> I'm looking for good ways to ensure that attributes are only writable
> >> such that they retain the characteristics the class requires.
> >
> > Sounds like you're trying to do
> > http://en.wikipedia.org/wiki/Design_by_contract.  Which is not a bad
> > thing.  But, I think a more pythonic way to implement this would be to
> > verify behaviors, not types.
> >
> > I would start by writing a assert_invarient() method which validates the
> > object.  I'm guessing all you really need is that you can index [0] and
> > [1] and get ints, so test for that.  Something like:
> >
> > def assert_invarient(self):
> >try:
> >   assert isinstance(data[0], int)
> >   assert isinstance(data[1], int)
> >except:
> >   raise ValueError
>
> Don't do that. assert is for testing program logic, not verifying data. The
> problem with assert is that the user can turn all assertions off, simply by
> launching Python with the -O switch. Your verification code then becomes:
>
> def assert_invarient(self):
>try:
> pass
>except:
>raise ValueError
>
> which is useless.
>
> When should you use an assertion? If you've ever written code like this:
>
> if condition:
>do_something()
> else:
># This should never happen. But you know what they say: code that
># can't happen, does!
>raise RuntimeError('condition unexpectedly false')
>
>
> that's a prime candidate for turning into an assertion:
>
>
> assert condition, 'condition unexpectedly false'
> do_something()
>
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Restricted attribute writing

2011-08-07 Thread Rafael Durán Castañeda
The assert on Order should be an if ... raise, like OrderElement, sorry for
the mistake and repost

El 7 de agosto de 2011 18:53, Rafael Durán Castañeda <
[email protected]> escribió:

> I think you might use a tuple instead of a list for OrderElement, that
> would make much easier your code:
>
> class
> OrderElement(tuple):
>
> def __new__(cls, x, y):
> if not isinstance(x, int) or not isinstance(y, int):
> raise TypeError("Order element must receives two
> integers")
>
> return tuple.__new__(cls, (x, y))
>
>
> class Order(list):
> def __setitem__(self, item):
> assert isinstance(item, OrderElement)
> super(Order, self).__setitem__(item)
>
>
> I didn't check your module condition since it isn't quite clear to me, but
> you could add a second condition two Order class.
>
>
> 2011/8/7 Steven D'Aprano 
>
>> Roy Smith wrote:
>>
>> > In article ,
>> >  John O'Hagan  wrote:
>> >
>> >> I'm looking for good ways to ensure that attributes are only writable
>> >> such that they retain the characteristics the class requires.
>> >
>> > Sounds like you're trying to do
>> > http://en.wikipedia.org/wiki/Design_by_contract.  Which is not a bad
>> > thing.  But, I think a more pythonic way to implement this would be to
>> > verify behaviors, not types.
>> >
>> > I would start by writing a assert_invarient() method which validates the
>> > object.  I'm guessing all you really need is that you can index [0] and
>> > [1] and get ints, so test for that.  Something like:
>> >
>> > def assert_invarient(self):
>> >try:
>> >   assert isinstance(data[0], int)
>> >   assert isinstance(data[1], int)
>> >except:
>> >   raise ValueError
>>
>> Don't do that. assert is for testing program logic, not verifying data.
>> The
>> problem with assert is that the user can turn all assertions off, simply
>> by
>> launching Python with the -O switch. Your verification code then becomes:
>>
>> def assert_invarient(self):
>>try:
>> pass
>>except:
>>raise ValueError
>>
>> which is useless.
>>
>> When should you use an assertion? If you've ever written code like this:
>>
>> if condition:
>>do_something()
>> else:
>># This should never happen. But you know what they say: code that
>># can't happen, does!
>>raise RuntimeError('condition unexpectedly false')
>>
>>
>> that's a prime candidate for turning into an assertion:
>>
>>
>> assert condition, 'condition unexpectedly false'
>> do_something()
>>
>>
>>
>> --
>> Steven
>>
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How do I convert String into Date object

2011-08-13 Thread Rafael Durán Castañeda

You can use datetime objects:

>>> dt1 = datetime.datetime.strptime('07/27/2011',"%m/%d/%Y")
>>> dt2 =datetime.datetime.strptime('07/28/2011',"%m/%d/%Y")
>>> dt1 == dt2
False
>>> dt1 > dt2
False
>>> dt1 < dt2
True
>>> dt1 - dt2
datetime.timedelta(-1)


On 13/08/11 21:26, MrPink wrote:

I have file of records delimited by spaces.
I need to import the date string and convert them into date datatypes.

'07/27/2011' 'Event 1 Description'
'07/28/2011' 'Event 2 Description'
'07/29/2011' 'Event 3 Description'

I just discovered that my oDate is not an object, but a structure and
not a date datatype.
I'm stumped.  Is there a way to convert a string into a date datatype
for comparisons, equality, etc?

Thanks,

On Aug 13, 3:14 pm, MrPink  wrote:

Is this the correct way to convert a String into a Date?
I only have dates and no time.

import time, datetime

oDate = time.strptime('07/27/2011', '%m/%d/%Y')
print oDate

Thanks,


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


Re: login with urllib2

2011-08-14 Thread Rafael Durán Castañeda
I'm not sure but you probably need using HTTPS handler, but without 
exact error code/message...


On 14/08/11 16:50, 守株待兔 wrote:

please to see my code:
import urllib
import urllib2

url = 'http://hi.baidu.com/'
values = {'username' : '**','password' : '**' }

data = urllib.urlencode(values)
req = urllib2.Request(url,data)
response = urllib2.urlopen(req)
the_page = response.read()

i can't to login ,why?username and password  are  right.
any word  appreciated.


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


Re: same code to login,one is ok,another is not

2011-08-15 Thread Rafael Durán Castañeda
First one is using http and second one https, did you try an https handler?
as I already pointed out to you in other thread with the same topic...

Please don't spam the list, if you aren 't getting the answers you was
looking for, wait for a while and then repost not just open threads until
get the answer

2011/8/15 Steven D'Aprano 

> 守株待兔 wrote:
>
> > 1.http://www.renren.com/Login.do
> > it is ok,my code:
> [...]
> > 2.https://passport.baidu.com/?login
> > can't login,my code:
> [...]
>
> Do you have a question, or are you just sharing the bad news?
>
> Websites may choose to respond to login attempts differently. Some may
> require cookies, some may not. Some may check the referrer, some may not.
> Some may look at the user agent, some may not.
>
> If the web developer of the site insists that you log in with a browser, or
> Internet Explorer, you have to fight to convince the web server to let you
> in. Many websites really try hard to prevent bots and scripts logging in.
> The closer you can imitate what a real human being in a browser does, the
> better the chances you can fool the server that you are a real human being
> using a browser and not a bot. (Since your script *is* a bot, you may also
> be in violation of the web site's terms of service.)
>
> Some web sites may even check how often you try to log in, or how fast.
>
> But what makes you think you can't log in? Given the response below, it
> looks to me that you did log in, and got a blank page with some javascript
> to redirect you to the real content page. (If you are a web developer and
> you do this, I hate you.) But I may be wrong -- I'm not an expert on these
> things.
>
>
> > 
> > ��§  
> > 
> > 
> > 
> > 
> >
> >
> >
> > 
> > var url="./?pwd=1"
> > url=url.replace(/^\.\//gi,"http://passport.baidu.com/";);
> > location.href=url;
> > 
> >
> >
> >
> > 
> > 
>
>
> --
> Steven
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to structure packages

2011-09-07 Thread Rafael Durán Castañeda

Check python pep8: http://www.python.org/dev/peps/pep-0008/

And you will see than you shouldn't named modules as you did, so you 
should do something like:


mypackage
__init__.py
mymodule
...

mypackage.mymodule.MyClass

On 07/09/11 18:11, John Gordon wrote:

In<2a4f542c-a8c1-46c7-9899-a3fad0940...@x11g2000yqc.googlegroups.com>  
bclark76  writes:


mypackage
 __init__.py
 myfunc.py
 MyClass.py
from mypackage import MyClass

Try this instead:

   from mypackage.MyClass import MyClass



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


Re: Problem with python 3.2 and circular imports

2011-02-28 Thread Rafael Durán Castañeda
I'm stil totally stuck with relative imports, i' ve tried the example tree
from PEP 328 without any result:

package/
__init__.py
subpackage1/
__init__.py
moduleX.py
moduleY.py
subpackage2/
__init__.py
moduleZ.py
moduleA.py

Assuming that the current file is either moduleX.py or
subpackage1/__init__.py, following are correct usages of the new
syntax:

from .moduleY import spam
from .moduleY import spam as ham
from . import moduleY
from ..subpackage1 import moduleY
from ..subpackage2.moduleZ import eggs
from ..moduleA import foo
from ...package import bar
from ...sys import path

I always get:

Traceback (most recent call last):
  File "moduleY.py", line 1, in 
from ..moduleA import a
ValueError: Attempted relative import in non-package


2011/2/27 Frank Millman 

>
> "Steven D'Aprano"  wrote in message
> news:[email protected]...
>
>  On Sun, 27 Feb 2011 12:08:12 +0200, Frank Millman wrote:
>>
>>  Assume the following structure -
>>>
>>> main.py
>>> /pkg
>>>__init__.py
>>>mod1.py
>>>mod2.py
>>>
>>> main.py
>>>from pkg import mod1
>>>
>>> mod1.py
>>>import mod2
>>>
>>> mod2.py
>>>  import mod1
>>>
>>
>>
>> If you change the "import mod*" lines to "import pkg.mod*" it works for
>> me in Python 3.1 and 3.2.
>>
>> According to my understand of PEP 328, "from . import mod*" should work,
>> but I agree with you that it doesn't.
>>
>> If you get rid of the circular import, it does work. So I suspect a bug.
>>
>>
>>
> Thanks, Steven.
>
> I confirm that 'import pkg.mod* works. Unfortunately I am using
> sub-packages as well, which means that to refer to an object in the
> sub-package I need to use w.x.y.z every time, which gets to be a lot of
> typing! I will stick to my hack of putting the package name in sys.path for
> now, unless someone comes up with a better idea.
>
> Frank
>
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: question about endswith()

2011-03-03 Thread Rafael Durán Castañeda
I think you want do this:

>>> files = ['file1.hdf', 'file2.hdf', 'file3.hdf5','file4.hdf']
>>> print(''.join(x for x in files if x.endswith('5')))
file3.hdf5
>>>

But if you need to use it later:

>>> file_hdf5 = [x for x in files if x.endswith('5')]
>>> file_hdf5
['file3.hdf5']
>>>


2011/3/4 Grant Edwards 

> On 2011-03-04, Matt Funk  wrote:
> > Hi Grant,
> > first of all sorry for the many typos in my previous email.
> >
> > To clarify, I have a python list full of file names called 'files'.
> > Every single filename has extension='.hdf' except for one file which has
> > an '.hdf5' extension. When i do (and yes, this is pasted):
> > for filename in files:
> > if (any(filename.endswith(x) for x in extensions)):
> > print filename
>
> I was unable to run that code:
>
> $ cat testit.py
>
> for filename in files:
> if (any(filename.endswith(x) for x in extensions)):
> print filename
>
> $ python testit.py
>
> Traceback (most recent call last):
>  File "testit.py", line 1, in 
>for filename in files:
> NameError: name 'files' is not defined
>
> > However, it will print all the files in list 'files' (that is all
> > files with file extension '.hdf'). My question is why it doesn't just
> > print the filename with extensions '.hdf5'?
>
> Dunno.  You didn't provide enough information for us to answer your
> question: the code you posted won't run and don't tell us what values
> you're using for any of the variables.
>
> Here's a piece of runnable code that I think does what you want:
>
> $ cat testit.py
> files = ["foo.bar", "foo.baz", "foo.bax"]
> extensions = [".baz",".spam",".eggs"]
>
> for filename in files:
> if (any(filename.endswith(x) for x in extensions)):
> print filename
>
> $ python testit.py
> foo.baz
>
> --
> Grant
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Problem with python 3.2 and circular imports

2011-03-05 Thread Rafael Durán Castañeda
Thank you for your answer Frank, I think I've found the problem. I was
calling modules from inside subpackages, and I need to use them from
outside, so I have package in PYTHONPATH. is that correct? But now I have
another question: Can I execute an script inside subpackage1 importig
modules from subpackage2?

2011/3/4 Frank Millman 

>
> On February 28 2011 Rafael Durán Castañeda wrote
>
>  I'm stil totally stuck with relative imports, i' ve tried the example tree
>> from PEP 328 without any result:
>>
>> package/
>>   __init__.py
>>   subpackage1/
>>   __init__.py
>>   moduleX.py
>>   moduleY.py
>>   subpackage2/
>>   __init__.py
>>   moduleZ.py
>>   moduleA.py
>>
>> Assuming that the current file is either moduleX.py or
>> subpackage1/__init__.py, following are correct usages of the new
>> syntax:
>>
>> from .moduleY import spam
>> from .moduleY import spam as ham
>> from . import moduleY
>> from ..subpackage1 import moduleY
>> from ..subpackage2.moduleZ import eggs
>> from ..moduleA import foo
>> from ...package import bar
>> from ...sys import path
>>
>> I always get:
>>
>> Traceback (most recent call last):
>>  File "moduleY.py", line 1, in 
>>   from ..moduleA import a
>> ValueError: Attempted relative import in non-package
>>
>>
>>
> Hi Rafael
>
> I only just noticed your message now. For some reason it did not appear on
> google.groups.
>
> I just tried it and it worked for me. This is what I did.
>
> I set up the above structure. I added a 'def spam()' to moduleY, 'def
> eggs()' to moduleZ, and 'def foo()' to moduleA.
>
> I pasted all of the 'from ... import ...' lines above into moduleX.
>
> In the same directory that contains the subdirectory 'package' I create a
> test script containing the following line -
>   import package.subpackage1.moduleX
>
> To begin with it failed on the last two lines starting with 'from ...' [how
> do you indicate three dots followed by etc etc, which would normally be
> indicated by three dots!]. The traceback said 'Attempted relative import
> beyond toplevel package'.
>
> I did not want to investigate too deeply so I just commented those lines
> out, and now it runs with no errors. I even put a couple of print statements
> (or must I call them print functions now) into the modules being imported,
> and the messages do appear, so the modules are being imported.
>
> HTH
>
> Frank Millman
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: strange QLineEdit problem in PyQt

2011-03-16 Thread Rafael Durán Castañeda
Just one remark about this line:

QtGui.QWidget.__init__(self, parent)

I think you should use this:

super(Contract, self).__init__(parent)

so you will be following PEP 3135


2011/3/16 taco 

> taco wrote:
>
> ah, I solved it myself. for completeness reasons. I had upgraded python for
> reportlab which needed this python version, while still using a pyqt which
> was compiled for 2.6. After compilation and changing pythonpath to the
> right
> site-packages dir it's working
>
>
> > hi,
> > I have a form containing a few QLineedits and I wish to retrieve the
> > contents only after pressing a QPushButton.
> > a looks like:
> > class Contract(QtGui.QWidget):
> >   def __init__(self,fileInfo, parent=None):
> > QtGui.QWidget.__init__(self,parent)
> > self.name = QtGui.QLineEdit("")
> > .
> > self.createDoc = QtGui.QPushButton("do it")
> > self.connect(createDoc,QtCore.SIGNAL("clicked()"),self.Foo)
> > mainLayout.addWidget(self.name)
> > mainLayout.addWidget(sef.createDoc)
> >
> >  def Foo(self):
> >print self.name.text()
> >
> > when executing this I get only a few characters back from the line. It's
> > incomplete. How to retrieve the complete string? I don't need a signal
> for
> > every typed character.
> >
> > taco
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use cookies from a script in a browser

2011-03-21 Thread Rafael Durán Castañeda
I think 
thiscould
help you

2011/3/18 gervaz 

> On 18 Mar, 22:52, Miki Tebeka  wrote:
> > You can use mechanize, which holds a cookie jar and can user the browser
> cookies as well.
>
> I use:
> opener =
> urllib.request.build_opener(urllib.request.HTTPCookieProcessor())
> urllib.request.install_opener(opener)
> I start scraping from http://page.com/home.html that need the cookies
> enabled, then, once I found what I was looking for, I've got
> http://page.com/pageX.html and http://page.com/pageY.html. Those page
> cannot be viewed if I just copy & paste the url in the browser,
> because they need the cookies.
>
> What can I do?
>
> Thanks,
> Mattia
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Converting an array of string to array of float

2011-03-25 Thread Rafael Durán Castañeda
But you must be sure that the list only contains objects than can be
converted into float, if not you'll get:

>>> float('something')
Traceback (most recent call last):
  File "", line 1, in 
float('something')
ValueError: could not convert string to float: something
>>>

2011/3/25 Blockheads Oi Oi 

> On 25/03/2011 15:27, Jason Swails wrote:
>
>> I'm guessing you have something like
>>
>> list1=['1.0', '2.3', '4.4', '5.5', ...], right?
>>
>> You can do this:
>>
>> for i in range(len(list1)):
>>   list1[i] = float(list1[i])
>>
>>
> or
>
> for i, x in enumerate(list1):
>list1[i] = float(x)
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Amazon Simple Queue Service Worker

2011-04-07 Thread Rafael Durán Castañeda
I'm not sure about what you want to do, but you could check
http://www.openstack.org/ web and look for ideas for using with Amazon.

2011/4/7 Joseph Ziegler 

> Hi all,
>
> Little new to the python world, please excuse the Noobness.
>
> We are writing a server which will subscribe to the Amazon Simple Queue
> Service.  I am looking for a good service container.  I saw Twisted and Zope
> out there. It's going to be a server which polls on a queue via the Boto
> api.  Do you have any suggestions for a framework to start?
>
> Best Regards,
>
> Joe
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: How to re import a module

2011-04-08 Thread Rafael Durán Castañeda
That's really easy:

>>> import re
>>> reload(re)

>>>

In python2.x, but if you are using python3.x I think is different, really
easy to know if you search in python docs.

2011/4/8 

> Hello i want to know the best way to re import a module, because i have a
> web server with just one Apache session for all my domains and applications,
> and i if i need to make some changes on one application restart the server
> will affect the others, so i was thinking in 2 ways the first will be 're
> imported' the module, the second use subprocess. First the less unsecured
> that in this case i think is re import the module, give me your opinions
> please.
>
>
> ---
> Thanks in advance
> Diego Hidalgo
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Signal on qt

2011-04-12 Thread Rafael Durán Castañeda
I don't know what are you trying with this for, but I think you may be
connecting signal to a combo_test and after that changing combo_test, losing
connection, but I'm not really sure. Anyway, this is a python list for PyQt
(I think you are using it) you should ask in PyQt list.

2011/4/12 luca72 

> hello i have this:
> def mytest(self):
>for a in xrange(self.tableWidget.rowCount()):
>self.combo_test = QtGui.QComboBox()
>self.connect(self.combo_test,
> QtCore.SIGNAL("currentIndexChanged(int)"), self.metto_test)
>self.combo_test.addItems(self.lista_def)
>self.tableWidget.setCellWidget(a, 4, self.combo_test)
> def metto_test(self, index):
>print index
>
> I he no connection what is wrong?
>
> Thanks
>
> Luca
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: A question about Python Classes

2011-04-21 Thread Rafael Durán Castañeda
You did:

>>> class BaseHandler:
... def foo(self):
... print "Hello"
...
>>> class HomerHandler(BaseHandler):
... pass
...
>>> test = HomerHandler()
>>> test.foo()
Hello
>>> isinstance(test, BaseHandler)
True
>>> isinstance(test, HomerHandler)
True
>>>

You could say test is a "BaseHandler of type HomerHandler"



2011/4/21 chad 

> Let's say I have the following
>
> class BaseHandler:
>def foo(self):
>print "Hello"
>
> class HomeHandler(BaseHandler):
>pass
>
>
> Then I do the following...
>
> test = HomeHandler()
> test.foo()
>
> How can HomeHandler call foo() when I never created an instance of
> BaseHandler?
>
> Chad
> --
> http://mail.python.org/mailman/listinfo/python-list
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Py / VNC Automation

2011-05-03 Thread Rafael Durán Castañeda
You can check this https://github.com/kanaka/noVNC

2011/5/3 Dan Stromberg 

>
> On Mon, May 2, 2011 at 5:23 PM, PyNewbie  wrote:
>
>> Hi,
>> I'm looking for a python class or open source code that is tightly
>> integrated with VNC protocols - any ideas?
>> --
>> http://mail.python.org/mailman/listinfo/python-list
>>
>
> I've not updated this in a while, but it's got a python vnc viewer in the
> list:
>
> http://stromberg.dnsalias.org/~dstromberg/vnc.html
>
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python drawing library?

2011-05-15 Thread Rafael Durán Castañeda

On 15/05/11 01:01, OKB (not okblacke) wrote:

Is there any Python library for interactive drawing?  I've done
some googling but most searches for "drawing" lead me to libraries for
programmatic creation of shapes on some GUI canvas.  I'm looking for GUI
widgets that allow the user to draw with the mouse, like a paint
program, and let me get info about the drawing as its made (get color at
mouse location, etc.).  I'd prefer a wxPython solution, although any
Python solution would be better than none.

Thanks,
I'm not suere, but I think you should be able to do that using PyQt 
QPaintDevice.

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


Re: python logging

2011-05-17 Thread Rafael Durán Castañeda

On 17/05/11 22:55, Fei wrote:

where is default logging file on Mac? I saw lots of app just import
logging, and begins to logging.info(...) etc.  I'm not sure where to
look at the logging configuration to figure out the log location.

I just get in touch of python about 1month ago, and I appreciate your
help.

Looking at python docs you will find:

http://docs.python.org/howto/logging.html#logging-basic-tutorial

First example explains what you are asking.

P.S.: Next time you may try to look for the info you need before asking
--
http://mail.python.org/mailman/listinfo/python-list


Re: python logging

2011-05-18 Thread Rafael Durán Castañeda

On 18/05/11 03:09, Fei wrote:

On May 17, 6:55 pm, Ian Kelly  wrote:

On Tue, May 17, 2011 at 2:55 PM, Fei  wrote:

where is default logging file on Mac? I saw lots of app just import
logging, and begins to logging.info(...) etc.  I'm not sure where to
look at the logging configuration to figure out the log location.

There is no default log file.  You're seeing that because logging only
needs to be configured by the program once, not on a per-module basis.
  Thus most modules will just do import logging on the assumption that
the configuration has already been performed somewhere else.

If no logging configuration is done at all, then the logging
statements will have no effect.

Thanks Ian.
That's not exactly how it works. You can use logging without any 
configuration and the default output will be console. In addition 
default logging level is warning, so:


logging.info("Some text")

won't  show anything and

logging.warning("Other text")

will show:

WARNING:root:Other text

Please check the link I gave before.

Bye


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


Re: python logging

2011-05-18 Thread Rafael Durán Castañeda

On 18/05/11 23:29, Ian Kelly wrote:

2011/5/18 Rafael Durán Castañeda:

That's not exactly how it works. You can use logging without any
configuration and the default output will be console. In addition default
logging level is warning, so:

logging.info("Some text")

won't  show anything and

logging.warning("Other text")

will show:

WARNING:root:Other text

Please check the link I gave before.

Bye

Odd.  That seems to work, but it contradicts the documentation at:

http://docs.python.org/howto/logging.html#what-happens-if-no-configuration-is-provided
I think you are confuse because of you are looking at advanced logging, 
where getLogger is being used. Simple logging works without any 
configuration, getLogger doesn't.

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


Re: python logging

2011-05-18 Thread Rafael Durán Castañeda

On 19/05/11 00:10, Ian Kelly wrote:

2011/5/18 Rafael Durán Castañeda:

I think you are confuse because of you are looking at advanced logging,
where getLogger is being used. Simple logging works without any
configuration, getLogger doesn't.

It seems to work without any configuration just as well as the root logger:


import logging
logging.getLogger('foo').warning('test')

WARNING:foo:test

Or am I misunderstanding you?

Are you using python 2.x or 3.x? At python 2.7 using:

import logging
logging.getLogger('log').warning('test')

I got:

No handlers could be found for logger "log"


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


Re: python logging

2011-05-19 Thread Rafael Durán Castañeda
You are right that behavior isn't documented and might be a bug. You could
report it.

Bye

El 19 de mayo de 2011 00:42, Ian Kelly  escribió:

> 2011/5/18 Ian Kelly :
> > Ah, that's it.  I was using Python 2.5.  Using 2.7 I get the same
> > result that you do.
> >
> > Still, it's a surprising change that doesn't seem to be documented as
> > such.  I'm not sure whether it's a regression or an intentional
> > change.
>
> I was wrong, it's more complicated than that.
>
> Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit
> (Intel)] on win32
> Type "help", "copyright", "credits" or "license" for more information.
> >>> import logging
> >>> logging.getLogger('log').warning('test')
> No handlers could be found for logger "log"
> >>> logging.warning('test')
> WARNING:root:test
> >>> logging.getLogger('log').warning('test')
> WARNING:log:test
>
> Apparently, getLogger() is unconfigured by default, but if you just
> use the root logger once, then they magically get configured.
>
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Python Style Question

2014-10-29 Thread Rafael Romero Carmona
Hi, first in Python 2.7.6 and Python 3.4.0 list haven't got any add
function but they have append.

I think you could do better with something like

==
import json
l = [1, -1, 0, '1', '-1', '0', json.dumps(-1), json.dumps(1),
json.dumps(0), 'x', 'sqjklsqjk__', (1, 2)]

values = []

for c in l:
try:
c_int = int(c)
except ValueError:
pass
except TypeError:
pass
else:
values.append(c_int)
continue
print(values)
==

The code has been tested in Python 2.7.6 and 3.4 and returns [1, -1,
0, 1, -1, 0, -1, 1, 0]

You don't need to do two try because you can process both exceptions
in the same way. You don't really need to do json.loads because if you
have a json string which is an integer, you could do that directly
with int(c) which can take a string and transform in an integer.

With ValueError it captures the exception when it tries to transform
the characters' strings and with TypeError it captures the exception
when it tries to work with the tuples.

Have a good day and hope it works for you!

2014-10-29 11:42 GMT+01:00 Anton :
> Let's say I have an incoming list of values *l*. Every element of *l* can be 
> one of the following options:
> 1) an integer value
> 2) a string in form of '', e.g. '7'
> 3) a string with a json serialization of an integer value, e.g. '"7"'
> 4) something else that should be ignored
>
> I need to transform this list into another list with values from options 
> 1)-3) coerced to int. The code below should do this.
>
>
> Variant 1
> ===
>
> values = []
> for c in l:
> # Case 1) or 2)
> try:
> c_int = int(c)
> except ValueError:
> pass
> else:
> values.add(c_int)
> continue
>
> # Case 3)
> try:
> c_int = int(json.loads(c))
> except ValueError:
> pass
> else:
> values.add(c_int)
> continue
>
> ===
>
> Is this code ugly?
> Does it follow EAFP?
> Am I missing something in language best practice?
>
> Or maybe below is more preferable way with a nested try...except clause?
>
> Variant 2
> ===
> values = []
> for c in l:
> # Case 1) or 2)
> try:
> c_int = int(c)
> except ValueError:
>
> # Case 3)
> try:
> c_int = int(json.loads(c))
> except ValueError:
> pass
> else:
> values.add(c_int)
> continue
>
> else:
> values.add(c_int)
> continue
> ===
>
> Thanks,
> Anton.
>
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python Style Question

2014-10-29 Thread Rafael Romero Carmona
2014-10-29 12:25 GMT+01:00 Martin Kemp :
> -BEGIN PGP SIGNED MESSAGE-
> Hash: SHA1
>
> On 29/10/2014 10:45, Anton wrote:
>> Let's say I have an incoming list of values *l*. Every element of
>> *l* can be one of the following options: 1) an integer value 2) a
>> string in form of '', e.g. '7' 3) a string with a json
>> serialization of an integer value, e.g. '"7"' 4) something else
>> that should be ignored
>>
>> I need to transform this list into another list with values from
>> options 1)-3) coerced to int. The code below should do this.
>>
>>
>> Variant 1 ===
>>
>> values = [] for c in l: # Case 1) or 2) try: c_int = int(c) except
>> ValueError: pass else: values.add(c_int) continue
>>
>> # Case 3) try: c_int = int(json.loads(c)) except ValueError: pass
>> else: values.add(c_int) continue
>>
>> ===
>>
>> Is this code ugly? Does it follow EAFP? Am I missing something in
>> language best practice?
>>
>> Or maybe below is more preferable way with a nested try...except
>> clause?
>>
>> Variant 2 === values = [] for c in l: # Case 1) or 2) try: c_int =
>> int(c) except ValueError:  # Case 3) try: c_int =
>> int(json.loads(c)) except ValueError: pass else: values.add(c_int)
>> continue  else: values.add(c_int) continue ===
>>
>> Thanks, Anton.
>>
>>
>
> Your first example is perfectly fine and is EAFP
>

Actually it doesn't work because there is no add function and it
doesn't catch the TypeError function to ignore other exceptions than
ValueError. Doesn't it? I tested in Python 2.7.6 and 3.4.

> Personally, I prefer to avoid nesting when it's not necessary.
>
> - --
> Martin Kemp ([email protected])
> -BEGIN PGP SIGNATURE-
> Version: GnuPG v2
>
> iQEcBAEBAgAGBQJUUM7zAAoJEJ0Re0UIDzSucugIALn/zY8RdpP8iaMShHoszzqf
> I0zl0mFHyqhNtwgQ0ZF7VGO+H+U0Dk8rhzTYOmEMzPTKNBGwll3fda9mOnrK9Xvp
> 9gQjII6DyQIWH7Z3dLcLr2e1j8OMNUSL6UmAYs8urNSIKZLowdV3JI4G/bLyW0KS
> y5Ko8dI6y5nOJ1P9XCmPTmags43UZfR8DrBUaAbzNcS8FGwmUE2KBkEhLQOvmpJi
> jmMc7wMOpq0jL+XbA+7pHUqoVZ7w1tUFjuy9I3h45tgPuTFAFB0gX+FpE+oVgO5o
> spQpVaOPEYN9ceLgHdKSxzdVIhOQLE6H/SYNHlsEW/ZNM6aR9n4yipgkOmtJ0+M=
> =WzHA
> -END PGP SIGNATURE-
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: [argparse] mutually exclusive group with 2 sets of options

2013-08-05 Thread Rafael Durán Castañeda

El 04/08/13 04:10, Francois Lafont escribió:

Hi,

Is it possible with argparse to have this syntax for a script?

my-script (-a -b VALUE-B | -c -d VALUE-D)

I would like to do this with the argparse module.

Thanks in advance.



I think you are looking for exclusive groups:

http://docs.python.org/2.7/library/argparse.html#argparse.add_mutually_exclusive_group

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


Re: Python Debugger tool

2013-09-05 Thread Rafael Durán Castañeda

El 06/09/2013, a las 08:14, chandan kumar  escribió:

> Hi 
> 
> Is any one aware of  free ipython debugger tool.How good is this tool for a 
> beginner to use like ,placing breakpoints,checking variables ,call stack 
> (function flow) etc.I don't like to use python PDB .
> I have heard about wingware ,pycharm  which are licensed versions.Used 
> wingware trail version and felt pretty good tool for beginners.
> 
> Please let know your views on ipython.Let me know about any python free 
> debugger tools
> 
> 
> Best Regards,
> Chandan
> -- 
> https://mail.python.org/mailman/listinfo/python-list
Ipdb works fine for me.

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


Re: optionparse: how to add a line break to the help text

2011-09-10 Thread Rafael Durán Castañeda

On 10/09/11 22:43, Gelonida N wrote:

I'm having a small question about optionparse.

Normaly optionparser will format the help text according to the
console's width.

I just wondered if there is any way to insert a line breakk into an
options help text.

Example:

from optparse import OptionParser

parser = OptionParser()
parser.add_option("-f", action="store",
 help="This option is really really complicated"
  " and I'd like to write"
  " a few paragrpahs to explain how it works."
  "\nHowever the line breaks are stripped off"
  " and it's thus difficult to structure the help text")

args = ['-h']
parser.parse_args(args)

Is there any trick to force a new paragraph/ line break before the word
'However'?


Thanks in advance for suggestions.



You can use """ for multiple line texts:
>>> text = \
... """fsdfsfsdfsdf
... sfsdfsfsdf
... sdfsdf  s
...
... """
>>> text
'fsdfsfsdfsdf\nsfsdfsfsdf\nsdfsdf  s\n\n'


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


Re: create a directory structure

2011-09-17 Thread Rafael Durán Castañeda
2011/9/16 Andrea Crotti 

> After some research, I think that paste-script is the best choice in this
> case.
>
> I can define templates and I'll get my directory structure nicely populated
> for me.
>
> --
> http://mail.python.org/**mailman/listinfo/python-list
>
I think you might want to look at
Fabricor
vagrant 
-- 
http://mail.python.org/mailman/listinfo/python-list


Re: Use and usefulness of the as syntax

2011-11-12 Thread Rafael Durán Castañeda

El 12/11/11 13:43, Tim Chase escribió:

  I hate trying to track down variable-names if one did something like

  from Tkinter import *


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


Re: redis beginner question

2011-11-16 Thread Rafael Durán Castañeda

El 16/11/11 03:22, Jabba Laci escribió:

Hi,

I'm reading the redis documentation and there is one thing that
bothers me. For redis, you need to start a server on localhost. Is
there an easy way that my Python script starts this server
automatically? Before using my script, I don't want to start
redis-server each time. When my program terminates, the server could
be shut down automatically.

Thanks,

Laszlo
I think you are misunderstanding the docs, on ubuntu (or whatever you 
use) you can do apt-get install redis-server and you'll get what you want.


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


Re: memory efficient set/dictionary

2007-06-10 Thread Rafael Darder Calvo
> > > Please recommend a module that allows persistent set/dict storage +
> > > fast query that best fits my problem,
> >
> > What is the problem you are trying to solve? How many keys do you have?
>
> Corpus processing. There are in the order of billions to tens of
> billions keys (64bit integers).
>
I would recommend you to use a database since it meets your
requirements (off-memory, fast, persistent). The bsdddb module
(berkeley db) even gives you a dictionary like interface.
http://www.python.org/doc/lib/module-bsddb.html

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


Re: skip next item in list

2007-06-11 Thread Rafael Darder Calvo
On 6/11/07, Andre Engels <[EMAIL PROTECTED]> wrote:
> 2007/6/11, ahlongxp <[EMAIL PROTECTED]>:
> > list=('a','d','c','d')
> > for a in list:
> > if a=='a' :
> > #skip the letter affer 'a'
> >
> > what am I supposed to do?
>
> There might be better ways to do it, but I would do:
>
> flag_last_a = False
> for a in list:
>if flag_last_a:
>flag_last_a = False
>continue
>if a=='a':
>flag_last_a = True
># Whatever is done when you don't skip
>
> --
> Andre Engels, [EMAIL PROTECTED]
> ICQ: 6260644  --  Skype: a_engels
> --
> http://mail.python.org/mailman/listinfo/python-list
>
another way:

def skip_after(l):
i = iter(l)
for x in i:
yield x
while x == 'a':
x = i.next()

depending on what to do in case of consecutive 'a's, change the
'while' for an 'if'
list(skip_after('spam aand eggs'))
['s', 'p', 'a', ' ', 'a', 'd', ' ', 'e', 'g', 'g', 's']
-- 
http://mail.python.org/mailman/listinfo/python-list


Subprocess and pipe-fork-exec primitive

2007-07-30 Thread Rafael Giannetti Viotti
Hi,

   I am working with the subprocess.py module in Python 2.4.4 and I am 
confused about it's functionality. It uses the standard pipe-fork-exec 
method to start a subprocess:

   # create pipes

   pid = fork()

   if pid == 0:
 # child
 exec(...)

   # parent
   status = waitpid(pid, 0)

   From my experience, this primitive will fail with 'no child 
processes' at the waitpid call if the forked child dies very quickly - 
before the parent is scheduled back for execution. This seems to happen 
because Python has a default SIGCHLD handler that, in this case, will 
reap the process before the parent has the chance to do it.

   I would like to know if this is correct, or am I missing something here?

---
Rafael.

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


compile for ARM

2007-09-19 Thread Rafael Marin Perez
Hello

I'm Rafael Marin, and work as reseacher in University of Murcia (Spain).

I want to install and compile modules of python2.4 in a ARMv5b
architecture.

Any idea?

Thank for your time.
Regards, Rafa.

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


Python for NSLU2

2007-09-20 Thread Rafael Marin Perez
Hello,

I am Rafael Marin Perez, and work as a researcher in University of
Murcia (Spain).
We are using the Network Storage Link for USB2.0 (NSLU2) device to
desploy a wireless sensor network (WSN). 

And I need to install a bootstrap-loader of MSP430 in my NSLU2 to transfer
the compiled images to the nodes. This bootstrap work over python.
Therefore, I'm trying to install and compile modules of python2.4 for
the ARM architecture of NSLU2 device.
But I don't get to compile correctly.

I'm using the cross compiler:
http://peter.korsgaard.com/articles/crosstool-armv5b-softfloat-gcc-3.3.4-glibc-2.2.5.tar.gz

Any idea, How can I do this?

Thanks for your help.
Regards, Rafa.




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


Read header and data from a binary file

2009-09-22 Thread Jose Rafael Pacheco
Hello,

I want to read from a binary file called myaudio.dat
Then I've tried the next code:

import struct
name = "myaudio.dat"
f = open(name,'rb')
f.seek(0)
chain = "< 4s 4s I 4s I 20s I I i 4s I 67s s 4s I"
s = f.read(4*1+4*1+4*1+4*1+4*1+20*1+4*1+4*1+4*1+4*1+4*1+67*1+1+4*1+4*1)
a = struct.unpack(chain, s)
header = {'identifier' : a[0],
  'cid'  : a[1],
  'clength'   : a[2],
  'hident' : a[3],
  'hcid32' : a[4],
  'hdate'  : a[5],
  'sampling' : a[6],
  'length_B'  : a[7],
  'max_cA'   : a[8],
  'max_cA1' : a[9],
  'identNOTE'  : a[10],
  'c2len'  : a[11],}

It produces:

{'length_B': 150001, 'sampling': 5, 'max_cA1': 'NOTE', 'hident': 'HEDR',
'c2len': "Normal Sustained Vowel 'A', Voice and Speech Lab., MEEI, Boston,
MA", 'hdate': 'Jul 13 11:57:41 1994', 'identNOTE': 68, 'max_cA': -44076,
'cid': 'DS16', 'hcid32': 32, 'identifier': 'FORM', 'clength': 300126}

So far when I run f.tell()
>>f.tell()
136L

The audio data length is 300126, now I need a clue to build an array with
the audio data (The Chunk SDA_), would it possible with struct?, any help ?

Thanks

The file format is:


Offset  |  Length |  Type |Contents
0   4character Identifier: "FORM"
4  4character Chunk identifier: "DS16"
8  4integer Chunk length
12  - -  Chunk data

Header 2

Offset   Length   Type   Contents
0 4 character Identifier: "HEDR" or "HDR8"
4 4 integer Chunk length (32)
8 20 character Date, e.g. "May 26 23:57:43 1995"
28 4 integer Sampling rate
32 4 integer Data length (bytes)
36 2 unsigned integer Maximum absolute value for channel A:
0x if not defined
38 2 unsigned integer Maximum absolute value for channel A:
0x if not defined

NOTE Chunk

Offset   Length   Type   Contents
0 4 character Identifier: "NOTE"
4 4 integer Chunk length
8 - character Comment string

SDA_, SD_A or SDAB Chunk
Offset Length Type Contents
0 4 character Identifier: "SDA_", "SD_B", or "SDAB"
4 4 integer Chunk length
8 - - Data
-- 
http://mail.python.org/mailman/listinfo/python-list


Read header and data from a binary file [LONG]

2009-09-23 Thread Jose Rafael Pacheco
Hello,

I want to read from a binary file called myaudio.dat
Then I've tried the next code:

import struct
name = "myaudio.dat"
f = open(name,'rb')
f.seek(0)
chain = "< 4s 4s I 4s I 20s I I i 4s I 67s s 4s I"
s = f.read(4*1+4*1+4*1+4*1+4*1+20*1+4*1+4*1+4*1+4*1+4*1+67*1+1+4*1+4*1)
a = struct.unpack(chain, s)
header = {'identifier' : a[0],
  'cid'  : a[1],
  'clength'   : a[2],
  'hident' : a[3],
  'hcid32' : a[4],
  'hdate'  : a[5],
  'sampling' : a[6],
  'length_B'  : a[7],
  'max_cA'   : a[8],
  'max_cA1' : a[9],
  'identNOTE'  : a[10],
  'c2len'  : a[11],}

It produces:

{'length_B': 150001, 'sampling': 5, 'max_cA1': 'NOTE', 'hident': 'HEDR',
'c2len': "Normal Sustained Vowel 'A', Voice and Speech Lab., MEEI, Boston,
MA", 'hdate': 'Jul 13 11:57:41 1994', 'identNOTE': 68, 'max_cA': -44076,
'cid': 'DS16', 'hcid32': 32, 'identifier': 'FORM', 'clength': 300126}

So far when I run f.tell()
>>f.tell()
136L

The audio data length is 300126, now I need a clue to build an array with
the audio data (The Chunk SDA_), would it possible with struct?, any help ?

Thanks

The file format is:


Offset  |  Length |  Type |Contents
0   4character Identifier: "FORM"
4  4character Chunk identifier: "DS16"
8  4integer Chunk length
12  - -  Chunk data

Header 2

Offset   Length   Type   Contents
0 4 character Identifier: "HEDR" or "HDR8"
4 4 integer Chunk length (32)
8 20 character Date, e.g. "May 26 23:57:43 1995"
28 4 integer Sampling rate
32 4 integer Data length (bytes)
36 2 unsigned integer Maximum absolute value for channel A:
0x if not defined
38 2 unsigned integer Maximum absolute value for channel A:
0x if not defined

NOTE Chunk

Offset   Length   Type   Contents
0 4 character Identifier: "NOTE"
4 4 integer Chunk length
8 - character Comment string

SDA_, SD_A or SDAB Chunk
Offset Length Type Contents
0 4 character Identifier: "SDA_", "SD_B", or "SDAB"
4 4 integer Chunk length
8 - - Data
-- 
http://mail.python.org/mailman/listinfo/python-list