Re: Question about weakref
On 05/07/2012 19:47, Dieter Maurer wrote: Frank Millman writes: I would still like to know why weakref.proxy raised an exception. I have re-read the manual several times, and googled for similar problems, but am none the wiser. In fact, it is documented. Accessing a proxy will raise an exception when the proxied object no longer exists. What you can ask is why your proxy has been accessed after the object was deleted. The documentation is specific: during the callback, the object should still exist. Thus, apparently, one of your proxies outlived an event that should have deleted it (probably a hole in your logic). I have investigated a bit further, and now I have a clue as to what is happening, though not a full understanding. If you use 'b = weakref.ref(obj)', 'b' refers to the weak reference, and 'b()' refers to the referenced object. If you use 'b = weakref.proxy(obj)', 'b' refers to the referenced object. I don't know how to refer to the weak reference itself. In a way that is the whole point of using 'proxy', but the difficulty comes when you want to remove the weak reference when the referenced object is deleted. This is from the manual section on weakref.ref - "If callback is provided and not None, and the returned weakref object is still alive, the callback will be called when the object is about to be finalized; the weak reference object will be passed as the only parameter to the callback; the referent will no longer be available." My callback method looks like this - del del_b(b): self.array.remove(b) It successfully removes the weak reference from self.array. This is from the manual section on weakref.proxy - "callback is the same as the parameter of the same name to the ref() function." My callback method looks the same. However, although 'b' is the weak reference, when I refer to 'b' it refers to the original object, which at this stage no longer exists. So my revised question is - How can you remove the weak reference if you use proxy? The full story is more complicated than that - why does my example work when I delete x, then y, then z, but not if I reverse the order? However, I think that I have isolated the fundamental reason. So any comments on my latest findings will be appreciated. Frank -- http://mail.python.org/mailman/listinfo/python-list
Re: Discussion on some Code Issues
[email protected] wrote: [Please don't top-post] >> start = 0 >> for match in re.finditer(r"\$", data): >> end = match.start() >> print(start, end) >> print(data[start:end]) >> start = match.end() > That is a nice one. I am thinking if I can write "for lines in f" sort of > code that is easy but then how to find out the slices then, You have to keep track both of the offset of the line and the offset within the line: def offsets(lines, pos=0): for line in lines: yield pos, line pos += len(line) start = 0 for line_start, line in offsets(lines): for pos, part in offsets(re.split(r"(\$)", line), line_start): if part == "$": print(start, pos) start = pos + 1 (untested code, I'm assuming that the file ends with a $) > btw do you > know in any case may I convert the index position of file to the list > position provided I am writing the list for the same file we are reading. Use a lookup list with the end positions of the texts and then find the relevant text with bisect. >>> ends = [10, 20, 50] >>> filepos = 15 >>> bisect.bisect(ends, filepos) 1 # position 15 belongs to the second text -- http://mail.python.org/mailman/listinfo/python-list
Re: Apology for OT posts
On Fri, Jul 6, 2012 at 3:30 PM, Simon Cropper wrote: > bet this kills the conservation though... Probably. Until someone trolls the list again and sets us all going... I'm another of the worst perps, so in the words of Pooh-Bah, "I desire to associate myself with that expression of regret". It was a pretty good discussion actually. The only real problem was the subject line. ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: Which way is best to execute a Python script in Excel?
Hi Emile Thanks for the reply. Could you provide me a more detailed 'how-to' tutorial on implementing a VBA macro that calls a script or a function from python, or tell me where on the web I can find it? The OReilly chapter seems a bit hard for me at this stage? I dont know, for example, where i should tell the macro where to locate the script... Maurizio -- http://mail.python.org/mailman/listinfo/python-list
Re: Apology for OT posts
On 06/07/2012 08:45, Chris Angelico wrote: On Fri, Jul 6, 2012 at 3:30 PM, Simon Cropper wrote: bet this kills the conservation though... Probably. Until someone trolls the list again and sets us all going... I'm another of the worst perps, so in the words of Pooh-Bah, "I desire to associate myself with that expression of regret". It was a pretty good discussion actually. The only real problem was the subject line. ChrisA As far as I'm concerned nothing is OT here unless it is blatant trolling or spamming. It makes for a far more interesting read than the groups that have a policy of "if it's not in the standard, we won't discuss it". The set of languages that start with the third letter of the English language springs instantly to my mind. Agreed that the subject line should be changed. -- Cheers. Mark Lawrence. -- http://mail.python.org/mailman/listinfo/python-list
Re: Re: code review
On Sunday, July 1, 2012 5:48:40 PM UTC+2, Evan Driscoll wrote: > On 7/1/2012 4:54, Alister wrote: > > On Sat, 30 Jun 2012 23:45:25 -0500, Evan Driscoll wrote: > >> If I had seen that in a program, I'd have assumed it was a bug. > > > > You would? > > I have only been using python for 6 - 12 months but in my past I > > programmed microcontrollers in assembly. > > > > as soon as i saw it i understood it & thought great, like a light bulb > > going on. > > It's not a matter of "I wouldn't have understood what the author was > trying to do" (with a small caveat), it's a matter of "I'd have assumed > that the author didn't understand the language semantics." > > I'm pretty sure it goes contrary to *every other programming language > I've ever used* (and a couple that I haven't). > > I understand why Python does it, and it certainly is nice in that it > matches typical mathematical notation, but the surprise quotient is > *very* high in the PL world IMO. > > Evan Avoiding suprises would mean we cannot improve languages, just reshuffle features? Cheers, Lars -- http://mail.python.org/mailman/listinfo/python-list
stuck in files!!
i want to kno how to link two applications using python for eg:notepad txt file and some docx file. like i wat to kno how to take path of those to files and run them simultaneously.like if i type something in notepad it has to come in wordpad whenever i run that code. -- http://mail.python.org/mailman/listinfo/python-list
RE: tkFileDialogs
It doesn't matter whether I pass the actual path in or the global variable name. The result is the same. Brandon L. Harris From: Karim [[email protected]] Sent: Friday, July 06, 2012 12:42 AM To: brandon harris Subject: Re: tkFileDialogs Le 06/07/2012 07:22, brandon harris a écrit : > I'm wanting to allow users to select hidden directories in windows and it > seems that using the tkFileDialog.askdirectory() won't allow for that. It's > using the tkFileDialog.Directory class which calls an internal command > 'tk_chooseDirectory' . However the file selector dialogs (askopenfilename, > asksaveasfilename, etc) has the common windows dialog which supports showing > hidden folders. It's using the tkFileDialog.Open class which is calling an > internal command of 'tk_getOpenFile'. > > Can anyone shed light on why these two dialogs are so very different and > possibly give me a solution to this hidden directory issue. I have found > that you can't really use the Open class because it's going to require a file > be selected, not a directory and the Directory class won't navigate to or > have an initialdir that is hidden (on windows the %APPDAT% folder is hidden > by default) > > Windows Example Code. > > import tkFileDialog > # Won't start in or allow navigation to APPDATA > test = tkFileDialog.askdirectory(initialdir='%APPDATA%') > # Will start in and navigate to APPDATA > test = tkFileDialog.askopenfile(initialdir='%APPDATA%') > > Thanks in advance for any help given! > > > Brandon L. Harris Heuu. Don't you use os.environ['APPDATA'] if this is an environment variable? Cheers karim -- http://mail.python.org/mailman/listinfo/python-list
Re: Which way is best to execute a Python script in Excel?
On 7/6/2012 1:31 AM Maurizio Spadaccino said...
Could you provide me a more detailed 'how-to' tutorial on implementing a VBA
macro that calls a script or a function from python, or tell me where on the
web I can find it? The OReilly chapter seems a bit hard for me at this stage?
I'm not going to write a how-to, but the relevant bits from the VBA code
look like this:
Set fpiUtils = CreateObject("fenxDCom.Util")
response = fpiUtils.FirstPartInsp(nomDiam, numFlutes, nomOAL, nomLOC)
I dont know, for example, where i should tell the macro where to locate the
script...
Registering the com server does that for you (the __name__ == __main__
part of the python script)
Again, get one of the examples working and move out from there.
Emile
--
http://mail.python.org/mailman/listinfo/python-list
Re: Creating an instance when the argument is already an instance.
On 05 Jul 2012 11:55:33 GMT
Steven D'Aprano wrote:
> On Thu, 05 Jul 2012 12:29:24 +0200, Olive wrote:
>
> > I am learning python -:)
> >
> > I am creating a new class: package (to analyse the packages
> > database in some linux distros). I have created a class package
> > such that package("string") give me an instance of package if
> > string is a correct representation of a package. I would like that
> > if pack is already an instance of package then package(pack) just
> > return pack.
>
> The built-in types only do this for immutable objects, those which
> cannot be modified.
>
> py> a = float('42.5')
> py> b = float(a)
> py> a is b
> True
>
>
> But note carefully that this is not a guarantee of the language.
> Other versions of Python may not do this.
>
> Also note carefully that it is only immutable objects which do this.
> Mutable objects do not behave this way:
>
> py> a = ['a', 1, None]
> py> b = list(a)
> py> a is b
> False
>
>
> By default, most custom-made classes are mutable, and so re-using
> instances is the wrong thing to do. Unfortunately, it is moderately
> tricky to make mutable classes in Python. One way is described here:
>
> http://northernplanets.blogspot.com.au/2007/01/immutable-instances-in-python.html
>
> You can also look at the source code for Decimal (warning: it's BIG)
> or Fraction:
>
> http://hg.python.org/cpython/file/2.7/Lib/decimal.py
> http://hg.python.org/cpython/file/2.7/Lib/fractions.py
>
>
> But suppose you make your class immutable. Then it's quite safe, and
> easy, to get the behaviour you want:
>
>
> class Package(object):
> def __new__(cls, argument):
> if isinstance(argument, Package):
> return argument
> return object.__new__(cls, argument)
>
>
> or similar, I haven't actually tested the above. But the important
> trick is to use __new__, the constructor, rather than __init__, which
> runs after the instance is already created, and to use an isinstance
> test to detect when you already have an instance.
>
Yes the trick with the __new__ works. We have to test afterwards i the
__init__ if the instance is already initialised and otherwise do
nothing. Thanks! I am learning and I didn't know the __new__ feature.
Olive
--
http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
On 07/06/2012 01:53 PM, Chirag B wrote: > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. > Not possible. (okay, within certain restrictions it might not be completely impossible) What are you trying to achieve? -- http://mail.python.org/mailman/listinfo/python-list
Re: OAuth 2.0 implementation
Supported provider list (with example code) is now: * Facebook * Google * Foursquare * bitly * GitHub * StackExchange * Instagram Other providers may also be supported out of the box, but have been untested thus far. -- http://mail.python.org/mailman/listinfo/python-list
Re: tkFileDialogs
On Jul 6, 12:22 am, brandon harris wrote:
> [...]
> import tkFileDialog
> # Won't start in or allow navigation to APPDATA
> test = tkFileDialog.askdirectory(initialdir='%APPDATA%')
> # Will start in and navigate to APPDATA
> test = tkFileDialog.askopenfile(initialdir='%APPDATA%')
Don't you just love inconsistencies! I get weird results using your
"string". Why not use expanduser?
py> path = os.path.expanduser('~\\AppData')
Of course that will not solve your main problem though. Probably since
showing hidden files is a function of the OS setting, which explorer
follows blindly. I tried your code AFTER changing "show
hidden_files_and_folders=True" and both dialogs open into the correct
directory, as expected. You could modify the setting, then show the
dialog, then revert the setting back.
Ah. The joys of Win32 scripting... *chokes*
--
http://mail.python.org/mailman/listinfo/python-list
Re: Confusing datetime.datetime
On 6/07/12 00:55:48, Damjan wrote:
> On 05.07.2012 16:10, Damjan wrote:
>> I've been struggling with an app that uses
>> Postgresql/Psycopg2/SQLAlchemy and I've come to this confusing
>> behaviour of datetime.datetime.
>
>
> Also this:
>
> #! /usr/bin/python2
> # retardations in python's datetime
>
> import pytz
> TZ = pytz.timezone('Europe/Skopje')
>
> from datetime import datetime
>
> x1 = datetime.now(tz=TZ)
> x2 = datetime(x1.year, x1.month, x1.day, tzinfo=TZ)
>
> assert x1.tzinfo == x2.tzinfo
>
> WHY does the assert throw an error???
Because x1 and x2 have different time zones.
The tzinfo field in x2 is equal to TZ and has a UTC offset of 1 hour.
The tzinfo field in x1 contains the DST version of that timezone,
with a UTC offset of 2 hours, because Skopje is currently on DST.
I think you want:
x2 = TZ.localize(datetime(x1.year, x1.month, x1.day))
That produces a datetime with the year, month and day set as indicated
and tzinfo set to the correct UTC offset for that date, at 00:00 hours.
Or maybe you need:
x2 = TZ.localize(datetime(x1.year, x1.month, x1.day, 12))
x2 = x2.replace(hour=0)
That determines whether DST should be on at noon, and then resets the
hour field to zero. This produces the same outcome as the one liner,
except on days when DST is switched on or off.
Hope this helps,
-- HansM
--
http://mail.python.org/mailman/listinfo/python-list
Re: simpler increment of time values?
On Jul 5, 12:16 pm, Chris Angelico wrote: > > So it's even easier than I said. And bonus lesson for the day: Try > things in the interactive interpreter before you post. :) but first: be sure to familiarize yourself with the many built-in "python classes"(sic). Re-inventing the wheel is breaking the lazy programmers' creed. It should only be broken if you wish to understand how things work "under the hood". -- http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
2012/7/6 Chirag B : > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. > -- > http://mail.python.org/mailman/listinfo/python-list I don't think that "I want to know" ever lead to some useful answers, it would be not polite even if people were actually paid to answer ;) Anyway it's quite an application-os specific question, probably not very easy either.. -- http://mail.python.org/mailman/listinfo/python-list
Issues with `codecs.register` and `codecs.CodecInfo` objects
Hello all,
While attempting to make a wrapper for opening multiple types of
UTF-encoded files (more on that later, in a separate post, I guess), I
ran into some oddities with the `codecs` module, specifically to do
with `.register` ing `CodecInfo` objects. I'd like to report a bug or
something, but there are several intertangled issues here and I'm not
really sure how to report it so I thought I'd open the discussion.
Apologies in advance if I get a bit rant-y, and a warning that this is
fairly long.
Observe what happens when you `register` the wrong function:
>>> import codecs
>>> def ham(name):
... # Very obviously wrong, just for demonstration purposes
... if name == 'spam': return 'eggs'
...
>>> codecs.register(ham)
Already there is a problem in that there is no error... there is no
realistic way to catch this, of course, but IMHO it points to an issue
with the interface. I don't want to register a codec lookup function;
I want to register *a codec*. The built-in lookup process would be
just fine if I could just somehow tell it about this one new codec I
have... I really don't see the use case for the added flexibility of
the current interface, and it means that every time I have a new
codec, I need to either create a new lookup function as well (to
register it), or hook into an existing one that's still of my own
creation.
Anyway, moving on, let's see what happens when we try to use the faulty codec:
>>> codecs.getencoder('spam')
Traceback (most recent call last):
File "", line 1, in
File "C:\Python32\lib\codecs.py", line 939, in getencoder
return lookup(encoding).encode
TypeError: codec search functions must return 4-tuples
Ehh?! That's odd. I thought I was supposed to return a `CodecInfo`
object, not a 4-tuple! Although as an aside, AFAICT the documentation
*doesn't actually document the CodecInfo class*, it just says what
attributes CodecInfo objects are supposed to have.
A bit of digging around with Google and existing old bugs on the
tracker suggests that this comes about due to backwards-compatibility:
in 2.4 and below, they *were* 4-tuples. But now CodecInfo objects are
expected to provide 6 functions (and a name), not 4. Clearly that
won't fit in a 4-tuple, and anyway I thought we had gotten rid of all
this deprecated stuff.
Regardless, let's see what happens if we do try to register a 4-tuple-lookup-er:
>>> def spam(name):
... # As long as we return a 4-tuple, it doesn't really matter
what the functions are;
... # errors shouldn't happen until we actually attempt to
encode/decode. Right?
... if name == 'spam': return (spam, spam, spam, spam)
Oops, we need to restart the interpreter, or otherwise reset global
state somehow, because the old lookup function has priority over this
one, and *there is no way to unregister it*. But once that's fixed:
>>> codecs.getencoder('spam')
Traceback (most recent call last):
File "", line 1, in
File "C:\Python32\lib\codecs.py", line 939, in getencoder
return lookup(encoding).encode
AttributeError: 'tuple' object has no attribute 'encode'
That's quite odd indeed. We can't actually trust the error message we
got before! 4-tuples don't work any more like they used to, so our
backwards-compatibility concession doesn't even work. Meanwhile, we're
left wondering how CodecInfo objects work at all. Is the error message
wrong?
Nope, well, not really. Let's grab an known good CodecInfo object and
see what we can find out...
>>> utf8 = codecs.lookup('utf-8')
>>> utf8.__class__.__bases__
(,)
>>> # not collections.namedtuple, which is understandable, since
that wasn't available until 2.6...
>>> len(utf8)
4
>>> # OK, apparently it magically actually is a tuple of length 4
despite needing 7 attributes. I wonder which ones are included:
>>> tuple(utf8)
(, , , )
>>> # Unsurprising: the ones mandated by the original PEP (100!
That long ago...)
... and if we try `help` (or look at examples in the standard library
or find them with Google - but I sure don't see any in the webpage
docs), we can at least find out how to construct a CodecInfo object
properly - although, curiously, it's implemented using `__new__`
rather than `__init__`.
You *can* hack around with `collections.namedtuple` and create
something that basically works:
# restarting again...
>>> import codecs, collections
>>> my_codecinfo = collections.namedtuple('my_codecinfo', 'encode
decode streamreader streamwriter')
>>> def spam(name):
... if name == 'spam': return my_codecinfo(spam, spam, spam, spam)
And now the error correctly doesn't occur until we actually attempt to
encode or decode something. Except we still don't have an incremental
decoder/encoder, and in fact those are missing attributes rather than
`None` as they're defaulted to by the `CodecInfo` class. (Of course,
we can subclass `collections.namedtup
Re: Question about weakref
On Fri, Jul 6, 2012 at 1:00 AM, Frank Millman wrote: > I have investigated a bit further, and now I have a clue as to what is > happening, though not a full understanding. > > If you use 'b = weakref.ref(obj)', 'b' refers to the weak reference, and > 'b()' refers to the referenced object. > > If you use 'b = weakref.proxy(obj)', 'b' refers to the referenced object. I > don't know how to refer to the weak reference itself. In a way that is the > whole point of using 'proxy', but the difficulty comes when you want to > remove the weak reference when the referenced object is deleted. Not quite. 'b' refers to the proxy, which uses magic methods to mimic the referenced object. It is still a separate object, however. In fact, I actually think it's not directly possible to refer to the *referenced object* via a proxy, although there are round-about ways to accomplish it. >>> import weakref >>> class Foo(object): pass >>> a = Foo() >>> id(a) 11253072 >>> b = weakref.proxy(a) >>> id(b) 11258400 >>> a is a True >>> a is b False > The full story is more complicated than that - why does my example work when > I delete x, then y, then z, but not if I reverse the order? On that, I'm really not sure. I tried to reproduce the problem locally and wasn't able to. What build of Python are you using, and on what platform? I have one suggestion, though: you might try removing the __del__ method from the listener class, as the presence of that method can interfere with garbage collection in some cases, and it is generally contra-recommended. I'm not sure why that would affect the code you posted, but it can't hurt to try it. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about weakref
On Fri, Jul 6, 2012 at 11:04 AM, Ian Kelly wrote: > On that, I'm really not sure. I tried to reproduce the problem > locally and wasn't able to. What build of Python are you using, and > on what platform? I spoke too soon, I am able to reproduce it. I think what's going on here is that when you try to remove the proxy from the list, the list.remove() call searches for the object by *equality*, not by identity. The problem is that at the time of the callback, the referent is no longer available to implement the equality test, as noted in the weakref.ref() documentation. As long as the proxy happens to be the first element of the list, this is not a problem, because the proxy evidently short-circuits self == self to return True. If it's not the first element of the list, though, then the first comparison compares the proxy to some other object, and the proxy raises an exception, because without the referent it no longer knows how to compare. If you change your del_b() method to the following, though, it works: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] This works because it carefully only handles the proxy object itself and no longer relies on any aspect of the referent for deletion. It's not a problem for weakref.ref, because ref objects require an explicit dereferencing step to access the referent. Cheers, Ian -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about weakref
On Fri, Jul 6, 2012 at 11:48 AM, Ian Kelly wrote: > def del_b(self, b): > for i, x in enumerate(self.array): > if b is x: > del self.array[i] That should probably have an explicit break on the end: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] break -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about weakref
Ian Kelly wrote: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] break Nice work, Ian. -- http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
Chirag B wrote: > i want to kno how to link two applications using python for eg:notepad > txt file and some docx file. like i wat to kno how to take path of > those to files and run them simultaneously.like if i type something in > notepad it has to come in wordpad whenever i run that code. Text and docx files are not "applications"; you don't "run" them. You can "open" them with applications like Notepad or Microsoft Word, and you can open two files simultaneously in two different applications (or in two windows within the same application). Other than that, I don't understand what you mean by "link" them or what it means for something typed in Notepad to "come in wordpad." -- http://mail.python.org/mailman/listinfo/python-list
Re: OAuth 2.0 implementation
On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht wrote: > Supported provider list (with example code) is now: > * Facebook > * Google > * Foursquare > * bitly > * GitHub > * StackExchange > * Instagram > > Other providers may also be supported out of the box, but have been untested > thus far. Looking good. Keep adding more to the list! I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn auths added to the list. Also I'll be extending it a little more at some point to make it "friendlier" :P Thanks for merging my last pull-request, Alec Taylor -- http://mail.python.org/mailman/listinfo/python-list
RE: OAuth 2.0 implementation
No worries, thanks for the request. Unfortunately AFAIK (according to the OAuth provider list on Wikipedia), both Twitter and LinkedIn still use OAuth 1.0a, so until they hop on the OAuth 2.0 bandwagon, they won't be added. -Original Message- From: Alec Taylor [mailto:[email protected]] Sent: Friday, July 06, 2012 11:42 AM To: Demian Brecht Cc: [email protected]; [email protected] Subject: Re: OAuth 2.0 implementation On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht wrote: > Supported provider list (with example code) is now: > * Facebook > * Google > * Foursquare > * bitly > * GitHub > * StackExchange > * Instagram > > Other providers may also be supported out of the box, but have been untested thus far. Looking good. Keep adding more to the list! I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn auths added to the list. Also I'll be extending it a little more at some point to make it "friendlier" :P Thanks for merging my last pull-request, Alec Taylor -- http://mail.python.org/mailman/listinfo/python-list
Re: OAuth 2.0 implementation
Yeah, seems Twitter is still stuck on 1.0a... But LinkedIn seems to support 1.0a for REST and 2 for JS: https://developer.linkedin.com/apis So that could be a definite contender for Sanction support On Sat, Jul 7, 2012 at 4:49 AM, Demian Brecht wrote: > No worries, thanks for the request. > > Unfortunately AFAIK (according to the OAuth provider list on Wikipedia), > both Twitter and LinkedIn still use OAuth 1.0a, so until they hop on the > OAuth 2.0 bandwagon, they won't be added. > > -Original Message- > From: Alec Taylor [mailto:[email protected]] > Sent: Friday, July 06, 2012 11:42 AM > To: Demian Brecht > Cc: [email protected]; [email protected] > Subject: Re: OAuth 2.0 implementation > > On Sat, Jul 7, 2012 at 1:38 AM, Demian Brecht > wrote: >> Supported provider list (with example code) is now: >> * Facebook >> * Google >> * Foursquare >> * bitly >> * GitHub >> * StackExchange >> * Instagram >> >> Other providers may also be supported out of the box, but have been > untested thus far. > > Looking good. Keep adding more to the list! > > I'd especially be interesting in seeing the 3-phase Twitter and LinkedIn > auths added to the list. > > Also I'll be extending it a little more at some point to make it > "friendlier" :P > > Thanks for merging my last pull-request, > > Alec Taylor > -- http://mail.python.org/mailman/listinfo/python-list
Re: Which way is best to execute a Python script in Excel?
On 06/07/2012 1:09 AM, Terry Reedy wrote: On 7/5/2012 10:30 PM, Karim wrote: An excellent link to derived all code example to python: http://www.pitonyak.org/AndrewMacro.sxw. Even though he only writes in OOBasic, you are right that he explains the basic concepts needed for accessing the api from any language. He is also honest. Writing non-api code is relatively easy; accessing the OO/LO api is harder. I made a start. When I get further, I will look at the examples that are close to some things I want to do. I will also study your Python examples. Thanks for the help. Terry You might be interested in pyspread (http://manns.github.com/pyspread/). It is no longer maintained for Windows. Colin W. -- http://mail.python.org/mailman/listinfo/python-list
API design question for dbf.py
I'm looking for some free advice. ;) My dbf module has three basic containers, all of which support list-like access: Table, List, and Index, each of which is filled with _DbfRecords. The fun part is that a _DbfRecord can compare equal to another _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the same locations, or a dict with the same keys/fields and values. The really fun part is __contains__: should the __contains__ method return True when a _DbfRecordTemplate, tuple, or dict is looked up in the Table, List, or Index and there is a matching record? ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
PyEval_SetProfile usage ?
Hi All, I have used the Python's C-API to call some Python code in my c code and now I want to know how much time does my Python part of the program takes. I came across the PyEval_SetProfile API and am not sure how to use it. Do I need to write my own profiling function? Any pointer to examples or how to's will be much appreciated. Thanks, Salman-- http://mail.python.org/mailman/listinfo/python-list
Re: simpler increment of time values?
Thanks to all for further comments!
Just for completeness and in case somebody would like to provide some
suggestions or corrections;
the following trivial class should be able to deal with the initial
requirement of adding or subtracting dateless time values
(hour:minute).
regards,
vbr
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
import re
class TrivialTime(object):
"""
Trivial, dateless, DST-less, TZN-less time in 24-hours cycle
only supporting hours and minutes; allows addition and subtraction.
"""
def __init__(self, hours=0, minutes=0):
self.total_minutes = (int(hours) * 60 + int(minutes)) % (60 * 24)
self.hours, self.minutes = divmod(self.total_minutes, 60)
def __add__(self, other):
return TrivialTime(minutes=self.total_minutes + other.total_minutes)
def __sub__(self, other):
return TrivialTime(minutes=self.total_minutes - other.total_minutes)
def __repr__(self):
return "TrivialTime({}, {})".format(self.hours, self.minutes)
def __str__(self):
return "{}.{:0>2}".format(self.hours, self.minutes)
@staticmethod
def fromstring(time_string, format_re=r"^([0-2]?\d?)[.:,-]\s*([0-5]\d)$"):
"""
Returns a TrivialTime instance according to the data from the
given string
with respect to the regex time format (two parethesised groups
for minutes and seconds respectively).
"""
time_string_match = re.match(format_re, time_string)
if not time_string_match:
raise ValueError("Time data cannot be obtained from the
given string and the format regex.")
return TrivialTime(hours=int(time_string_match.group(1)),
minutes=int(time_string_match.group(2)))
# # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # # #
--
http://mail.python.org/mailman/listinfo/python-list
Re: stuck in files!!
On Sat, Jul 7, 2012 at 4:21 AM, Alex wrote: > Chirag B wrote: > >> i want to kno how to link two applications using python for eg:notepad >> txt file and some docx file. like i wat to kno how to take path of >> those to files and run them simultaneously.like if i type something in >> notepad it has to come in wordpad whenever i run that code. > > Text and docx files are not "applications"; you don't "run" them. You > can "open" them with applications like Notepad or Microsoft Word, and > you can open two files simultaneously in two different applications (or > in two windows within the same application). > > Other than that, I don't understand what you mean by "link" them or > what it means for something typed in Notepad to "come in wordpad." The nearest I can think of has nothing to do with Python, but all to do with the applications concerned: DDE. Back in the early 90s it was a much-touted technology on OS/2 - you could fire up Mesa (spreadsheet), hotlink a particular group of cells to a table in DeScribe, edit one and see the other change instantly. It was pretty cool for its day. How you'd go about implementing it today I don't know, but there's a few options available. Really depends on what the OP actually wants to achieve: Duplicate typing, shared text, simultaneous editing? ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: API design question for dbf.py
On 06/07/2012 22:34, Ethan Furman wrote: I'm looking for some free advice. ;) My dbf module has three basic containers, all of which support list-like access: Table, List, and Index, each of which is filled with _DbfRecords. The fun part is that a _DbfRecord can compare equal to another _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the same locations, or a dict with the same keys/fields and values. The really fun part is __contains__: should the __contains__ method return True when a _DbfRecordTemplate, tuple, or dict is looked up in the Table, List, or Index and there is a matching record? Well, if x is in c and x == y, then y is in c. Does that help? ;-) -- http://mail.python.org/mailman/listinfo/python-list
How to print a number as if in the python interpreter?
Hi, In [2]: sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) Out[2]: 0. In ipython, I got the above output. But I got a different output from "print". Is there a way to print exact what I saw in ipython? ~/linux/test/python/man/library/math/fsum$ cat main.py #!/usr/bin/env python print sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1]) ~/linux/test/python/man/library/math/fsum$ ./main.py 1.0 Regards, Peng -- http://mail.python.org/mailman/listinfo/python-list
Re: API design question for dbf.py
MRAB wrote: On 06/07/2012 22:34, Ethan Furman wrote: I'm looking for some free advice. ;) My dbf module has three basic containers, all of which support list-like access: Table, List, and Index, each of which is filled with _DbfRecords. The fun part is that a _DbfRecord can compare equal to another _DbfRecord, a _DbfRecordTemplate, a tuple with the same values in the same locations, or a dict with the same keys/fields and values. The really fun part is __contains__: should the __contains__ method return True when a _DbfRecordTemplate, tuple, or dict is looked up in the Table, List, or Index and there is a matching record? Well, if x is in c and x == y, then y is in c. Does that help? ;-) Heh, that's pretty much the conclusion I was coming to. As a more concrete example: --> x = 4.0 --> x in [1, 4, 7, 4, 9, 3, 4] True It's checking for equality, not identity. Thinks for helping me think that through. ~Ethan~ -- http://mail.python.org/mailman/listinfo/python-list
Re: How to print a number as if in the python interpreter?
On Fri, Jul 6, 2012 at 3:38 PM, Peng Yu wrote:
> Hi,
>
> In [2]: sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
> Out[2]: 0.
>
> In ipython, I got the above output. But I got a different output from
> "print". Is there a way to print exact what I saw in ipython?
>
> ~/linux/test/python/man/library/math/fsum$ cat main.py
> #!/usr/bin/env python
> print sum([.1, .1, .1, .1, .1, .1, .1, .1, .1, .1])
> ~/linux/test/python/man/library/math/fsum$ ./main.py
> 1.0
chris@mbp ~ $ python
Python 2.7.1 (r271:86832, Jul 31 2011, 19:30:53)
[GCC 4.2.1 (Based on Apple Inc. build 5658) (LLVM build 2335.15.00)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> x = sum(0.1 for i in range(10))
>>> x # the interpreter implicitly repr()s the result of an expression
0.
>>> print x # whereas `print` str()s its operands
1.0
>>> (str(x), repr(x)) # as proof and for clarity
('1.0', '0.')
Beware the subtleties of floating-point arithmetic!
http://docs.python.org/tutorial/floatingpoint.html
Cheers,
Chris
--
http://mail.python.org/mailman/listinfo/python-list
Re: API design question for dbf.py
On Fri, Jul 6, 2012 at 6:46 PM, Ethan Furman wrote:
> It's checking for equality, not identity.
>>> x = float('nan')
>>> x in [x]
True
It's checking for equality OR identity.
-- Devin
--
http://mail.python.org/mailman/listinfo/python-list
Re: API design question for dbf.py
Devin Jeanpierre wrote:
On Fri, Jul 6, 2012 at 6:46 PM, Ethan Furman wrote:
It's checking for equality, not identity.
>>> x = float('nan')
>>> x in [x]
True
It's checking for equality OR identity.
Good point. In my case, checking for equality will cover both cases.
~Ethan~
--
http://mail.python.org/mailman/listinfo/python-list
Re: Issues with `codecs.register` and `codecs.CodecInfo` objects
On Fri, 06 Jul 2012 12:55:31 -0400, Karl Knechtel wrote: > Hello all, > > While attempting to make a wrapper for opening multiple types of > UTF-encoded files (more on that later, in a separate post, I guess), I > ran into some oddities with the `codecs` module, specifically to do with > `.register` ing `CodecInfo` objects. I'd like to report a bug or > something, but there are several intertangled issues here and I'm not > really sure how to report it so I thought I'd open the discussion. > Apologies in advance if I get a bit rant-y, and a warning that this is > fairly long. [...] Yes, it's a strangely indirect API, and yes it looks like you have identified a whole bucket full of problems with it. And no, I don't know why that API was chosen. Changing to a cleaner, more direct (sensible?) API would be a fairly big step. If you want to pursue this, the steps I recommend you take are: 1) understanding the reason for the old API (search the Internet and particularly the [email protected] archives); 2) have a plan for how to avoid breaking code that relies on the existing API; 3) raise the issue on [email protected] to gather feedback and see how much opposition or support it is likely to get; they'll suggest whether a bug report is sufficient or if you'll need a PEP; http://www.python.org/dev/peps/ If you can provide a patch and a test suite, you will have a much better chance of pushing it through. If not, you are reliant on somebody else who can being interested enough to do the work. And one last thing: any new functionality will simply *not* be considered for Python 2.x. Aim for Python 3.4, since the 2.x series is now in bug- fix only maintenance mode and the 3.3 beta is no longer accepting new functionality, only bug fixes. -- Steven -- http://mail.python.org/mailman/listinfo/python-list
What’s the differences between these two pieces of code ?
What’s the differences between these two pieces of code ? (1) for i in range(1, 7): print(2 * i, end=' ') (2) for i in range(1, 7): print(2 * i, end=' ') print() when executed both respectively in Python shell ,I get the same effect . Who can tell me why ? -- http://mail.python.org/mailman/listinfo/python-list
Re: Question about weakref
On 06/07/2012 20:12, Ethan Furman wrote: Ian Kelly wrote: def del_b(self, b): for i, x in enumerate(self.array): if b is x: del self.array[i] break Nice work, Ian. I second that. Thanks very much, Ian. Frank -- http://mail.python.org/mailman/listinfo/python-list
git_revision issues with scipy/numpy/matplotlib
I installed py27-numpy / scipy / matplotlib using macports, and it ran without
failing.
When I run Python I get the following error:
$>> which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$>> python
Python 2.7.3 (v2.7.3:70274d53c1dd, Apr 9 2012, 20:52:43)
[GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import numpy
Traceback (most recent call last):
File "", line 1, in
File
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/numpy/__init__.py",
line 128, in
from version import git_revision as __git_revision__
ImportError: cannot import name git_revision
I get the same error for all three packages. Is this a MacPorts issue or a
different issue?
I am running OS X 10.6 with the Intel Core i5 architecture. At one point I
thought this was a 64-bit versus 32-bit issue, viz.:
>>> import platform
>>> platform.architecture()
('64bit', '')
but I would have thought the MacPorts install would have resolved that.
Any help would be appreciated.
Thanks!
-s
--
http://mail.python.org/mailman/listinfo/python-list
Re: What’s the differences between these two pieces of code ?
On 07/06/2012 09:56 PM, iMath wrote: What’s the differences between these two pieces of code ? (1) for i in range(1, 7): print(2 * i, end=' ') (2) for i in range(1, 7): print(2 * i, end=' ') print() when executed both respectively in Python shell ,I get the same effect . Who can tell me why ? What "effect" are you referring to? What did you expect? What did you get? What version of Python? (3 I'd guess). As for me, the first one fails because of a syntax (indentation) error and the second prints the even numbers 2 through 12. What are we supposed to be comparing? Gary Herron -- Dr. Gary Herron Department of Computer Science DigiPen Institute of Technology (425) 895-4418 -- http://mail.python.org/mailman/listinfo/python-list
