Re: After install python2.7.3 from source code, no module named array

2014-09-23 Thread vek . m1234
not quite sure what you mean.. python uses 'list' instead of the C/C++ array 
data type. there are __builtin__ and builtins module in 2.7 and 3.2 and a 
'array' module. make install, copies files into the system dir-tree but you can 
run the interpreter from the build-dir and it should work.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Works perfectly (was Re: CSV methodology)

2014-09-23 Thread Peter Otten
jayte wrote:

> On Tue, 16 Sep 2014 13:22:02 +0200, Peter Otten <__pete...@web.de> wrote:
> 
>>jayte wrote:
>>
>>> On Mon, 15 Sep 2014 09:29:02 +0200, Peter Otten <__pete...@web.de>
>>> wrote:
> 
> [...]
> 
 but you can read raw data
with numpy. Something like

with open(filename, "rb") as f:
a = numpy.fromfile(f, dtype=[
("distance", "f16"),
("iterations", "i2"),
("zc_x", "i2"),
("zc_y", "i2"),
]).reshape(1778, 1000)

might do, assuming "extended double" takes 16 bytes.
>>> 
>>> Will try.  Double extended precision is ten bytes, but I assume
>>> changing  the "f16" to "f10" would account for that...
>>
>>Unfortunately it seems that numpy doesn't support "f10"
> 
> Thus far, this appears to work perfectly:
> 
> with open(filename, "rb") as f:
> a = numpy.fromfile(f, dtype=[
> ("distance", "f8"),
> ("iterations", "u2"),
> ("zc_x", "u2"),
> ("zc_y", "u2"),
> ])
> 
> file.close(f)
> 
> d = a["distance"]
> i = a["iterations"]
> x = a["zc_x"]
> y = a["zc_y"]
> 
> (except, of course, for the loss of precision)
> 
> "reshape()" does not appear to be necessary; the various variables
> d, i, x, y return a len() of 1778000

Assuming adjacent pixels are in the same row after 

b = a.reshape(h, w).T 

you can access a pixel as

b[x, y] # without the .T (transposition) it would be b[y, x]

instead of

a[y*w + x]

and a square of 9 pixels with

b[left:left+3, top:top+3]

> Again, thank you very much,
> 
> Jeff


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


GCD in Fractions

2014-09-23 Thread blindanagram
What is the rationale for gcd(x, y) in Fractions returning a negative
value when y is negtive?

For example gcd(3, -7) returns -1, which means that a co-prime test that
would work in many other languages 'if gcd(x, y) == 1' will fail in
Python for negative y.

And, of course, since -|x| is less than |x|, returning -|x| rather than
|x| is not returning the greatest common divisor of x and y when y is
negative.
-- 
https://mail.python.org/mailman/listinfo/python-list


PIL can't read binary

2014-09-23 Thread Frank Liou
I use PIL  Image.open()

but it show  'list' object has no attribute 'open'

this is my code

class Image2():
trans = connection.begin()
session = Session()
ProductId = 
session.query(ProductEntity.ProductId).filter(ProductEntity.CompanyId=="2").all()
Image = 
session.query(ProductImageGalleryEntity).filter(ProductImageGalleryEntity.ProductId=="20").all()
PicFromDataBase = Image[0].ProductImage
try:
b = Image.open(str(PicFromDataBase))
except Exception as e:
sad = e



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


Re: PIL can't read binary

2014-09-23 Thread Chris Angelico
On Tue, Sep 23, 2014 at 6:29 PM, Frank Liou  wrote:
> I use PIL  Image.open()
>
> but it show  'list' object has no attribute 'open'
>
> this is my code
>
> class Image2():
> trans = connection.begin()
> session = Session()
> ProductId = 
> session.query(ProductEntity.ProductId).filter(ProductEntity.CompanyId=="2").all()
> Image = 
> session.query(ProductImageGalleryEntity).filter(ProductImageGalleryEntity.ProductId=="20").all()
> PicFromDataBase = Image[0].ProductImage
> try:
> b = Image.open(str(PicFromDataBase))
> except Exception as e:
> sad = e

I suspect a lot of this ought to be in a method, probably __init__,
rather than raw in the class definition. However, the problem here is
that your Image is a list (as indicated by the exception), and you
probably want to open just one of its elements - maybe
Image[0].open(...). You may also want to iterate over the entire list,
which would cope better with the possibility of having none or
multiple.

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


Timedelta constructor with string parameter

2014-09-23 Thread felipou
Hello everyone!

I created some code recently to parse a string and create a timedelta from it.

Right now it only accepts positive integers, and only hours, minutes and 
seconds, but I think it could be easily extended to support everything that 
timedelta accepts.


time_delta_regex = re.compile(
r'((?P\d+?)h)?((?P\d+?)m)?((?P\d+?)s)?' )

def parseTimeDelta( value ):
timedelta_params = value

if isinstance( value, basestring ):
parts = time_delta_regex.match( value )
if not parts:
return None
parts = parts.groupdict()

timedelta_params = {}
for ( name, param ) in parts.iteritems():
if param:
timedelta_params[ name ] = int( param )

return datetime.timedelta( **timedelta_params )

parseTimeDelta("5h32m15s")


I was thinking this conversion could be very useful to lots of people, and so I 
thought about proposing it as an enhancement to the standard library.

But before doing anything, I thought it would be a good idea to see what people 
here think.

I think this would be a nice addition as a constructor of the timedelta class, 
but I'm not sure if it would conflict with any existing code. I can't see any 
downside to including this in the constructor or as a separate function.

So, what do you guys think?
-- 
https://mail.python.org/mailman/listinfo/python-list


ANN: Python Meeting Düsseldorf - 30.09.2014

2014-09-23 Thread eGenix Team: M.-A. Lemburg
[This announcement is in German since it targets a local user group
 meeting in Düsseldorf, Germany]


ANKÜNDIGUNG

 Python Meeting Düsseldorf

 http://pyddf.de/

   Ein Treffen von Python Enthusiasten und Interessierten
in ungezwungener Atmosphäre.

  Dienstag, 30.09.2014, 18:00 Uhr
  Raum 1, 2.OG im Bürgerhaus Stadtteilzentrum Bilk
Düsseldorfer Arcaden, Bachstr. 145, 40217 Düsseldorf

Diese Nachricht ist auch online verfügbar:
http://www.egenix.com/company/news/Python-Meeting-Duesseldorf-2014-09-30


NEUIGKEITEN

 * Bereits angemeldete Vorträge:

   Charlie Clark
   "Generator Gotchas"

   Marc-Andre Lemburg
   "Python und Fliegen - Speicherbedarf von Python Objekten
optimieren"

   Weiterhin werden wir die Ergebnisse des PyDDF Sprints 2014
   vom kommenden Wochenende (http://pyddf.de/sprint2014)
   präsentieren.

   Weitere Vorträge können gerne noch angemeldet werden: i...@pyddf.de

 * Startzeit und Ort:

   Wir treffen uns um 18:00 Uhr im Bürgerhaus in den Düsseldorfer
   Arcaden.

   Das Bürgerhaus teilt sich den Eingang mit dem Schwimmbad
   und befindet sich an der Seite der Tiefgarageneinfahrt der
   Düsseldorfer Arcaden.

   Über dem Eingang steht ein großes “Schwimm’'in Bilk”
   Logo. Hinter der Tür direkt links zu den zwei Aufzügen,
   dann in den 2. Stock hochfahren. Der Eingang zum Raum 1
   liegt direkt links, wenn man aus dem Aufzug kommt.

   Google Street View: http://bit.ly/11sCfiw


EINLEITUNG

Das Python Meeting Düsseldorf ist eine regelmäßige Veranstaltung in
Düsseldorf, die sich an Python Begeisterte aus der Region wendet:

 * http://pyddf.de/

Einen guten Überblick über die Vorträge bietet unser YouTube-Kanal,
auf dem wir die Vorträge nach den Meetings veröffentlichen:

 * http://www.youtube.com/pyddf/

Veranstaltet wird das Meeting von der eGenix.com GmbH, Langenfeld,
in Zusammenarbeit mit Clark Consulting & Research, Düsseldorf:

 * http://www.egenix.com/
 * http://www.clark-consulting.eu/


PROGRAMM

Das Python Meeting Düsseldorf nutzt eine Mischung aus Open Space
und Lightning Talks, wobei die Gewitter bei uns auch schon mal
20 Minuten dauern können ;-).

Lightning Talks können vorher angemeldet werden, oder auch
spontan während des Treffens eingebracht werden. Ein Beamer mit
XGA Auflösung steht zur Verfügung. Folien bitte als PDF auf USB
Stick mitbringen.

Lightning Talk Anmeldung bitte formlos per EMail an i...@pyddf.de


KOSTENBETEILIGUNG

Das Python Meeting Düsseldorf wird von Python Nutzern für Python
Nutzer veranstaltet. Um die Kosten zumindest teilweise zu
refinanzieren, bitten wir die Teilnehmer um einen Beitrag
in Höhe von EUR 10,00 inkl. 19% Mwst, Schüler und Studenten
zahlen EUR 5,00 inkl. 19% Mwst.

Wir möchten alle Teilnehmer bitten, den Betrag in bar mitzubringen.


ANMELDUNG

Da wir nur für ca. 20 Personen Sitzplätze haben, möchten wir
bitten, sich per EMail anzumelden. Damit wird keine Verpflichtung
eingegangen. Es erleichtert uns allerdings die Planung.

Meeting Anmeldung bitte formlos per EMail an i...@pyddf.de


WEITERE INFORMATIONEN

Weitere Informationen finden Sie auf der Webseite des Meetings:

http://pyddf.de/

Mit freundlichen Grüßen,
-- 
Marc-Andre Lemburg
eGenix.com

Professional Python Services directly from the Source  (#1, Sep 23 2014)
>>> Python Projects, Consulting and Support ...   http://www.egenix.com/
>>> mxODBC.Zope/Plone.Database.Adapter ...   http://zope.egenix.com/
>>> mxODBC, mxDateTime, mxTextTools ...http://python.egenix.com/

2014-09-27: PyDDF Sprint 2014 ...   4 days to go
2014-09-30: Python Meeting Duesseldorf ...  7 days to go

: Try our mxODBC.Connect Python Database Interface for free ! ::

   eGenix.com Software, Skills and Services GmbH  Pastor-Loeh-Str.48
D-40764 Langenfeld, Germany. CEO Dipl.-Math. Marc-Andre Lemburg
   Registered at Amtsgericht Duesseldorf: HRB 46611
   http://www.egenix.com/company/contact/
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: PIL can't read binary

2014-09-23 Thread Ned Batchelder

On 9/23/14 4:29 AM, Frank Liou wrote:

I use PIL  Image.open()

but it show  'list' object has no attribute 'open'

this is my code

class Image2():
 trans = connection.begin()
 session = Session()
 ProductId = 
session.query(ProductEntity.ProductId).filter(ProductEntity.CompanyId=="2").all()
 Image = 
session.query(ProductImageGalleryEntity).filter(ProductImageGalleryEntity.ProductId=="20").all()
 PicFromDataBase = Image[0].ProductImage
 try:
 b = Image.open(str(PicFromDataBase))
 except Exception as e:
 sad = e


Image is the name of the PIL module, but you've reassigned it to be a 
list.  Try this:


images = 
session.query(ProductImageGalleryEntity).filter(ProductImageGalleryEntity.ProductId=="20").all()

PicFromDataBase = images[0].ProductImage
try:
b = Image.open(str(PicFromDataBase))
except Exception as e:
sad = e

Also, I'll second Chris' point that this code should not be in the body 
of the class, but in a method, or perhaps just a plain-old function.


--
Ned Batchelder, http://nedbatchelder.com

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


Re: Comparison

2014-09-23 Thread Steven D'Aprano
LJ wrote:

> I have a network in which the nodes are defined as dictionaries using the
> NetworkX package. Inside each node (each dictionary) I defined a
> dictionary of dictionaries holding attributes corresponding to different
> ways in which the node can be reached (this dictionaries I refer to as
> labels). At some point in my algorithm I am looping through some subset of
> nodes and through the labels in each node and I perform some "joining"
> checks with the labels of each node in another subset of nodes. To clarify
> I check for a feasibility condition in a pairwise manner for every label
> in one node and every label of another. This nested loop is taking time. I
> wonder if the fact of defining the labels using numpy instead of
> dictionaries could imply a faster way to perform this loop.

I doubt it very much. Python dicts are extremely fast, and it doesn't sound
like your problem is that each dict lookup is slow. It sounds like your
problem is that you are doing a lot of them.

If you have 100 labels in one node, and 100 labels in the other, and you are
doing:

for label_a in A:
for label_b in B:
is_feasible(label_a, label_b)

the total number of feasibility checks is 100*100 = 1, not the 200 that
you may be expecting. The bottleneck here is probably your is_feasible
check, called many times, not the dict look-ups.

But of course we cannot be sure without seeing your code, and we can't be
certain without running the profiler and seeing exactly where your
bottlenecks are.


-- 
Steven

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


Re: GCD in Fractions

2014-09-23 Thread Wolfgang Maier

On 09/23/2014 10:16 AM, blindanagram wrote:

What is the rationale for gcd(x, y) in Fractions returning a negative
value when y is negtive?



I guess it is implemented this way because its main use is in the 
Fraction constructor.



For example gcd(3, -7) returns -1, which means that a co-prime test that
would work in many other languages 'if gcd(x, y) == 1' will fail in
Python for negative y.



On the other hand, it allows:
>>> Fraction(3, -7)
Fraction(-3, 7)

and:
>>> Fraction(3, -7) == Fraction(-3, 7)
True

Given that the implementation is particularly useful for Fraction() it 
is debatable whether the function shouldn't be called _gcd instead of 
gcd, but otherwise it makes sense.



And, of course, since -|x| is less than |x|, returning -|x| rather than
|x| is not returning the greatest common divisor of x and y when y is
negative.



however, you can always use abs on y before passing it to gcd.

Wolfgang

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


"Fuzzy" Counter?

2014-09-23 Thread Miki Tebeka
Greetings,

Before I start writing my own. Is there something like collections.Counter 
(fore frequencies) that does "fuzzy" matching?

Meaning x is considered equal to y if abs(x - y) < epsilon. (x, y and my case 
will be numpy.array).

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


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 12:53, Wolfgang Maier wrote:
> On 09/23/2014 10:16 AM, blindanagram wrote:
>> What is the rationale for gcd(x, y) in Fractions returning a negative
>> value when y is negtive?
>>
> 
> I guess it is implemented this way because its main use is in the
> Fraction constructor.

This is not guaranteed once it is exposed as a function that is
available to all Python users.

>> For example gcd(3, -7) returns -1, which means that a co-prime test that
>> would work in many other languages 'if gcd(x, y) == 1' will fail in
>> Python for negative y.

[snip]
> Given that the implementation is particularly useful for Fraction() it
> is debatable whether the function shouldn't be called _gcd instead of
> gcd, but otherwise it makes sense.

As you imply, it would make sense if it hadn't been exposed for more
general use.

However, I am less sure that it is sensible to have a gcd function
exposed for end user use when it conflicts with the function's usual
definition.

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


Re: GCD in Fractions

2014-09-23 Thread Steven D'Aprano
blindanagram wrote:

> What is the rationale for gcd(x, y) in Fractions returning a negative
> value when y is negtive?

Good question.

Normally, gcd is only defined for non-negative integers. Wolfram Mathworld,
for example, doesn't mention negative values at all (as far as I can see):

http://mathworld.wolfram.com/GreatestCommonDivisor.html

although buried deep in the documentation for Mathematica's GCD function is
hidden the fact that it treats GCD(-a, -b) the same as GCD(a, b):

http://functions.wolfram.com/IntegerFunctions/GCD/04/02/01/

and sure enough Wolfram Alpha tells me that the GCD of *all* of:

(100, 20)
(-100, 20)
(100, -20)
(-100, -20)

are equal to +20. On the other hand, Excel and LibreOffice both give an
error for the GCD of a negative value, and I've seen versions of gcd()
which do the same as fractions.gcd. So I think there is not one single
standard way to extend GCD to negative numbers.

> For example gcd(3, -7) returns -1, which means that a co-prime test that
> would work in many other languages 'if gcd(x, y) == 1' will fail in
> Python for negative y.

True, but either of:

abs(gcd(x, y)) == 1
gcd(x, y) in (1, -1)

will work.


> And, of course, since -|x| is less than |x|, returning -|x| rather than
> |x| is not returning the greatest common divisor of x and y when y is
> negative.

That's a good argument for gcd if it were in a general maths module, but
since it is specifically used for generating fractions, I guess that the
developers won't be very convinced by that.




-- 
Steven

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


Re: "Fuzzy" Counter?

2014-09-23 Thread Peter Otten
Miki Tebeka wrote:

> Before I start writing my own. Is there something like collections.Counter
> (fore frequencies) that does "fuzzy" matching?
> 
> Meaning x is considered equal to y if abs(x - y) < epsilon. (x, y and my
> case will be numpy.array).

The problem I see with that description is that for x, y, z, assumming 

x eq y 
y eq z
not (x eq z)

where eq is the test given above -- should x, y, and z land in the same bin?

I'm not really qualified here, but k-means clustering may be a direction to 
investigate:



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


Re: "Fuzzy" Counter?

2014-09-23 Thread Tim Chase
On 2014-09-23 05:34, Miki Tebeka wrote:
> Before I start writing my own. Is there something like
> collections.Counter (fore frequencies) that does "fuzzy" matching?
> 
> Meaning x is considered equal to y if abs(x - y) < epsilon. (x, y
> and my case will be numpy.array).

Not that I know of -- the performance characteristics would differ
radically from the O(1) expectations that Counter() gives you since
you'd have to compare your value against *every* value in the
container[*], and you have the possibility that two items in the
container are equidistant yet within EPSILON:

  EPSILON = 0.51
  my_counter[1.0] += 1
  my_counter[2.0] += 1
  my_counter[1.5] += 1  # which one should be incremented?

-tkc


[*]
This could be mitigated if you had some constraints on your inputs
and wanted to do some sort of bucket-hashing, limiting it to a subset
of the possible keys





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


tcp server as windows service

2014-09-23 Thread Arulnambi Nandagoban
Hello all, 

 

I developed a multithreaded tcp server with python and I converted into a
windows executable using pyinstaller. 

I would like to run the server as a windows service so that server restarts
whenever pc restarts without 

doing it manually . Help me out with some sample code . 

 

--

nambi 

 

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


how to write a html to automatically display the dictionary?

2014-09-23 Thread luofeiyu

x={'f1':1,'f2':2,'f3':3}
how can i create the following html file automatically with python to 
display x ?





f1


f2


f3



1


2


3




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


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 13:50, Steven D'Aprano wrote:
> blindanagram wrote:
> 
>> What is the rationale for gcd(x, y) in Fractions returning a negative
>> value when y is negtive?
> 
> Good question.
> 
> Normally, gcd is only defined for non-negative integers. Wolfram Mathworld,
> for example, doesn't mention negative values at all (as far as I can see):
> 
> http://mathworld.wolfram.com/GreatestCommonDivisor.html
> 
> although buried deep in the documentation for Mathematica's GCD function is
> hidden the fact that it treats GCD(-a, -b) the same as GCD(a, b):
> 
> http://functions.wolfram.com/IntegerFunctions/GCD/04/02/01/
> 
> and sure enough Wolfram Alpha tells me that the GCD of *all* of:
> 
> (100, 20)
> (-100, 20)
> (100, -20)
> (-100, -20)
> 
> are equal to +20. On the other hand, Excel and LibreOffice both give an
> error for the GCD of a negative value, and I've seen versions of gcd()
> which do the same as fractions.gcd. So I think there is not one single
> standard way to extend GCD to negative numbers.
> 
>> For example gcd(3, -7) returns -1, which means that a co-prime test that
>> would work in many other languages 'if gcd(x, y) == 1' will fail in
>> Python for negative y.
> 
> True, but either of:
> 
> abs(gcd(x, y)) == 1
> gcd(x, y) in (1, -1)
> 
> will work.
> 
> 
>> And, of course, since -|x| is less than |x|, returning -|x| rather than
>> |x| is not returning the greatest common divisor of x and y when y is
>> negative.
> 
> That's a good argument for gcd if it were in a general maths module, but
> since it is specifically used for generating fractions, I guess that the
> developers won't be very convinced by that.

That's an argument for a private gcd within the fractions module and a a
'normal' version in math.

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


Re: GCD in Fractions

2014-09-23 Thread Chris Angelico
On Wed, Sep 24, 2014 at 12:37 AM, blindanagram  wrote:
> That's an argument for a private gcd within the fractions module and a a
> 'normal' version in math.

Steven's examples show that there's not really much definition of
"normal" as regards GCD of negative numbers.

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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread Joel Goldstick
On Tue, Sep 23, 2014 at 10:18 AM, luofeiyu  wrote:
> x={'f1':1,'f2':2,'f3':3}
> how can i create the following html file automatically with python to
> display x ?
>
Generally, you would use a framework like django or others, but you
can make your html a string and use format:
html = "%d... " % x['f1']

> 
> 
> 
> f1
> 
> 
> f2
> 
> 
> f3
> 
> 
> 
> 1
> 
> 
> 2
> 
> 
> 3
> 
> 
> 
> 
> --
> https://mail.python.org/mailman/listinfo/python-list



-- 
Joel Goldstick
http://joelgoldstick.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Dynamically swapping between two algorithms

2014-09-23 Thread Steven D'Aprano
I have a certain calculation which can be performed two radically different
ways. With the first algorithm, let's call it SHORT, performance is very
fast for small values of the argument, but terrible for large values. For
the second algorithm, LARGE, performance is quite poor for small values,
but excellent for large values.

To add to the complexity, I perform this calculation repeatedly, in a loop:

value = 1
while True:
x = SHORT(value)  # Or should I use LARGE? Decisions, decisions...
process(x)
value += some_increment()
if condition: break

Luckily, the value never gets smaller. So if I could somehow determine a
cut-over point, CUTOFF, I might write my loop like this:

value = 1
while True:
f = SHORT if value < CUTOFF else LARGE
x = f(value)
process(x)
value += some_increment()
if condition: break

alas, the CUTOVER point is likely to be machine-dependent. Take it as a
given that inserting a fixed CUTOVER point into the source code (say,
``CUTOVER = 123456``) is not likely to be very effective, and dynamically
calculating it at import time is impractical.

*If* Python was a different language, I would spawn two threads, one using
SHORT and the other using LARGE, then which ever completes first, I'd just
kill the other. Alas, this won't work because (1) the GIL and (2) you
cannot forcibly kill threads, only ask them to die and hope they listen.

I am seeking other ideas for dynamically swapping between the two
algorithms, based on runtime information. Any thoughts?


(1) I can't tell in advance how many loops I will make.

(2) Both SHORT and LARGE get slower as the size of their argument increases.
This is unavoidable due to the nature of the problem.

(3) SHORT starts off relatively speedy, significantly faster than LARGE for
the first few tens of thousands of loops. I'm not talking about trivial
micro-optimizations here, I'm talking about the difference between 0.1
second for SHORT versus 10 seconds for LARGE.

(4) But as the size of the argument increases, SHORT suffers catastrophic
quadratic slowdown, while LARGE slows down only linearly. (Give or take.)

(5) Consequently, by the time I reach a few million loops, the difference is
now between (say) 5 minutes for LARGE versus 15 hours for SHORT.

(6) There is no single algorithm which performs acceptably across the entire
range of values I'm expecting to process in practice.

(7) Leaving the choice up to the caller is not an option. I am the caller.




-- 
Steven

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


Re: Python advice

2014-09-23 Thread Ian Kelly
On Mon, Sep 22, 2014 at 6:55 PM, Chris Angelico  wrote:
> Lua is a much simpler language than ECMAScript, incredibly
> light-weight, and easily sandboxed. It doesn't work with Unicode (I
> think its string type is eight-bit, so you have to work with encoded
> bytes), which is a serious downside in my opinion. Learn Lua if you
> want to work with something that embeds it. Otherwise, don't bother
> for now.

Apart from the Unicode issue, I'm curious what makes you describe it
as "much simpler" than ECMAScript.  Lua has coroutines built into the
language, stricter typing than ES (still not as strict as Python, but
at least you don't have to deal with a === operator because the ==
operator is broken), operator overloading, iterators, block-level
scoping, closure construction that binds loop variables the way the
programmer expects (unlike both Python and ES), and associative arrays
that allow arbitrary keys rather than coercing the keys to strings.

> * SQL is the one and only database query language you should ever need
> to bother with. (You might skip SQL too, if you use something like
> SQLAlchemy, but you certainly won't need any other query language -
> not in 2014.) It's well worth getting to know SQL at some point;
> whether you use Python, Pike, C, or any other language for the
> application, your SQL code will be the same.

SQLAlchemy lets you use SQL without actually writing SQL, but I would
argue that it's still basically necessary to understand SQL and what
the SQLAlchemy calls translate to in order to use it.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Python advice

2014-09-23 Thread Chris Angelico
On Wed, Sep 24, 2014 at 12:48 AM, Ian Kelly  wrote:
> On Mon, Sep 22, 2014 at 6:55 PM, Chris Angelico  wrote:
>> Lua is a much simpler language than ECMAScript, incredibly
>> light-weight, and easily sandboxed. It doesn't work with Unicode (I
>> think its string type is eight-bit, so you have to work with encoded
>> bytes), which is a serious downside in my opinion. Learn Lua if you
>> want to work with something that embeds it. Otherwise, don't bother
>> for now.
>
> Apart from the Unicode issue, I'm curious what makes you describe it
> as "much simpler" than ECMAScript.  Lua has coroutines built into the
> language, stricter typing than ES (still not as strict as Python, but
> at least you don't have to deal with a === operator because the ==
> operator is broken), operator overloading, iterators, block-level
> scoping, closure construction that binds loop variables the way the
> programmer expects (unlike both Python and ES), and associative arrays
> that allow arbitrary keys rather than coercing the keys to strings.

Mainly that's based on a feeling, rather than anything specific; I've
worked with both Lua and JS from both ends (although the extent of my
experience with embedding Lua is an evaluation exercise only; the
project ended up going with ECMAScript via the V8 engine, which was
the other major choice), and Lua seems rather less featured. Partly
this might be a consequence of using a very full-featured JavaScript
implementation (V8), but it felt like embedding Lua meant doing a lot
more of the work myself. Also, from the script writer's point of view,
Lua's table type seems less powerful than the JS object, although that
may be a flawed appearance due to my greater experience with the
latter.

In any case, it fits into a very specific niche: you learn Lua if you
want to script something that offers Lua scripting. That's technically
the same as the JavaScript niche, except that there's a really big
"something" that everyone wants to script, and that's web browsers.
(Plus, node.js means you can write server-side code in JS, though
personally I wouldn't recommend it; I've seen nothing that node.js can
do that Python with a good framework can't do just as easily, and
without UTF-16 baggage.)

>> * SQL is the one and only database query language you should ever need
>> to bother with. (You might skip SQL too, if you use something like
>> SQLAlchemy, but you certainly won't need any other query language -
>> not in 2014.) It's well worth getting to know SQL at some point;
>> whether you use Python, Pike, C, or any other language for the
>> application, your SQL code will be the same.
>
> SQLAlchemy lets you use SQL without actually writing SQL, but I would
> argue that it's still basically necessary to understand SQL and what
> the SQLAlchemy calls translate to in order to use it.

What I'd say is that you have to understand database design. There are
concepts that go beyond the actual language used (figuring out what a
table's primary and unique keys are, handling joins, knowing how to
trace logical structure through a series of tables, etc) that you're
never going to get away from. With a framework like SQLAlchemy, you
shouldn't have to worry about things like the esoteric quoting rules
of different DBMSes (why, oh why, can't we just stick to the standard
- 'quoted string', "identifier", and not use backticks at all??), but
you still have to craft a sane database structure.

When I say that you won't need any *other* query language, I mean that
you're unlikely, in 2014, to use the BTrieve API calls that I worked
with in the 1990s to interface with Pastel Accounting, nor the DBase
calls that manipulate those fragile .dbf files that oh so easily get
damaged if two people try to use them at once, etc, etc, etc. You
might use a wrapper around SQL if you choose, but certainly if you
know SQL you should be able to handle any database. And that's a Good
Thing.

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


Re: Dynamically swapping between two algorithms

2014-09-23 Thread Chris Angelico
On Wed, Sep 24, 2014 at 12:48 AM, Steven D'Aprano
 wrote:
> (3) SHORT starts off relatively speedy, significantly faster than LARGE for
> the first few tens of thousands of loops. I'm not talking about trivial
> micro-optimizations here, I'm talking about the difference between 0.1
> second for SHORT versus 10 seconds for LARGE.
>
> (4) But as the size of the argument increases, SHORT suffers catastrophic
> quadratic slowdown, while LARGE slows down only linearly. (Give or take.)
>
> (5) Consequently, by the time I reach a few million loops, the difference is
> now between (say) 5 minutes for LARGE versus 15 hours for SHORT.

Are these figures for a single call to SHORT/LARGE, or for a number of
calls aggregated? How much extra cost would a bit of timing add? If
you're making the decision no more than every 0.1s, you can probably
afford to time every call, but if you're doing a thousand iterations a
second in the early phases, you don't want to add a time-of-day call
every step.

Here's a possibility that won't be perfectly optimal, but it'll sort
itself out over time:

shorttime = -1.0
largetime = 0.0
value = 1
while True:
t = time.time()
if shorttime < largetime:
x = SHORT(value)
shorttime = time.time() - t
else:
x = LARGE(value)
largetime = time.time() - t
if largetime < shorttime: break
process(x)
value += some_increment()
if condition: break

# The SHORT algorithm is never going to be better, so
# switch to always using LARGE
while not condition:
process(x)
   x = LARGE(value)
value += some_increment()

What it'll do is try one each way, and then use whichever was quicker.
So you waste 10s early on, running the LARGE algorithm when SHORT
would have been better, but then it won't use LARGE again until SHORT
takes at least 10s. At that point, an Achilles/Tortoise race begins:
every time SHORT catches up with LARGE, LARGE takes a leap forward...
until LARGE's leap forward is insufficient for it to "catch up with"
SHORT, at which point we declare SHORT to have won the 'race' and just
run with the LARGE algorithm the whole way.

Downside: Will choose poorly if other things kick in during the timing
tests. Ideally, this should use a "CPU time used by this process"
monitor, but I'm not sure (a) if one is available to Python, and (b)
if it's at all portable, so the above just uses time.time().

(If the code is big and the overhead of merging is insignificant, the
same could be done with a flag instead of breaking out of the loop and
starting another. Take your pick.)

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


Re: Dynamically swapping between two algorithms

2014-09-23 Thread emile
Add a timing harness and use a test interval (N) and call LARGE every 
Nth loop until LARGE's timing is better than the prior SHORT's run.


Emile


On 09/23/2014 07:48 AM, Steven D'Aprano wrote:

I have a certain calculation which can be performed two radically different
ways. With the first algorithm, let's call it SHORT, performance is very
fast for small values of the argument, but terrible for large values. For
the second algorithm, LARGE, performance is quite poor for small values,
but excellent for large values.

To add to the complexity, I perform this calculation repeatedly, in a loop:

value = 1
while True:
 x = SHORT(value)  # Or should I use LARGE? Decisions, decisions...
 process(x)
 value += some_increment()
 if condition: break

Luckily, the value never gets smaller. So if I could somehow determine a
cut-over point, CUTOFF, I might write my loop like this:

value = 1
while True:
 f = SHORT if value < CUTOFF else LARGE
 x = f(value)
 process(x)
 value += some_increment()
 if condition: break

alas, the CUTOVER point is likely to be machine-dependent. Take it as a
given that inserting a fixed CUTOVER point into the source code (say,
``CUTOVER = 123456``) is not likely to be very effective, and dynamically
calculating it at import time is impractical.

*If* Python was a different language, I would spawn two threads, one using
SHORT and the other using LARGE, then which ever completes first, I'd just
kill the other. Alas, this won't work because (1) the GIL and (2) you
cannot forcibly kill threads, only ask them to die and hope they listen.

I am seeking other ideas for dynamically swapping between the two
algorithms, based on runtime information. Any thoughts?


(1) I can't tell in advance how many loops I will make.

(2) Both SHORT and LARGE get slower as the size of their argument increases.
This is unavoidable due to the nature of the problem.

(3) SHORT starts off relatively speedy, significantly faster than LARGE for
the first few tens of thousands of loops. I'm not talking about trivial
micro-optimizations here, I'm talking about the difference between 0.1
second for SHORT versus 10 seconds for LARGE.

(4) But as the size of the argument increases, SHORT suffers catastrophic
quadratic slowdown, while LARGE slows down only linearly. (Give or take.)

(5) Consequently, by the time I reach a few million loops, the difference is
now between (say) 5 minutes for LARGE versus 15 hours for SHORT.

(6) There is no single algorithm which performs acceptably across the entire
range of values I'm expecting to process in practice.

(7) Leaving the choice up to the caller is not an option. I am the caller.







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


Re: Dynamically swapping between two algorithms

2014-09-23 Thread MRAB

On 2014-09-23 15:48, Steven D'Aprano wrote:

I have a certain calculation which can be performed two radically different
ways. With the first algorithm, let's call it SHORT, performance is very
fast for small values of the argument, but terrible for large values. For
the second algorithm, LARGE, performance is quite poor for small values,
but excellent for large values.

To add to the complexity, I perform this calculation repeatedly, in a loop:

value = 1
while True:
 x = SHORT(value)  # Or should I use LARGE? Decisions, decisions...
 process(x)
 value += some_increment()
 if condition: break

Luckily, the value never gets smaller. So if I could somehow determine a
cut-over point, CUTOFF, I might write my loop like this:

value = 1
while True:
 f = SHORT if value < CUTOFF else LARGE
 x = f(value)
 process(x)
 value += some_increment()
 if condition: break

alas, the CUTOVER point is likely to be machine-dependent. Take it as a
given that inserting a fixed CUTOVER point into the source code (say,
``CUTOVER = 123456``) is not likely to be very effective, and dynamically
calculating it at import time is impractical.

*If* Python was a different language, I would spawn two threads, one using
SHORT and the other using LARGE, then which ever completes first, I'd just
kill the other. Alas, this won't work because (1) the GIL and (2) you
cannot forcibly kill threads, only ask them to die and hope they listen.

I am seeking other ideas for dynamically swapping between the two
algorithms, based on runtime information. Any thoughts?


(1) I can't tell in advance how many loops I will make.

(2) Both SHORT and LARGE get slower as the size of their argument increases.
This is unavoidable due to the nature of the problem.

(3) SHORT starts off relatively speedy, significantly faster than LARGE for
the first few tens of thousands of loops. I'm not talking about trivial
micro-optimizations here, I'm talking about the difference between 0.1
second for SHORT versus 10 seconds for LARGE.

(4) But as the size of the argument increases, SHORT suffers catastrophic
quadratic slowdown, while LARGE slows down only linearly. (Give or take.)

(5) Consequently, by the time I reach a few million loops, the difference is
now between (say) 5 minutes for LARGE versus 15 hours for SHORT.

(6) There is no single algorithm which performs acceptably across the entire
range of values I'm expecting to process in practice.

(7) Leaving the choice up to the caller is not an option. I am the caller.


How about this:

Try both of them initially, and use the faster one until it takes
longer than the slower one did initially. Then try both of them again.
Repeat.

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


Re: "Fuzzy" Counter?

2014-09-23 Thread Rob Gaddi
On Tue, 23 Sep 2014 05:34:19 -0700 (PDT)
Miki Tebeka  wrote:

> Greetings,
> 
> Before I start writing my own. Is there something like collections.Counter 
> (fore frequencies) that does "fuzzy" matching?
> 
> Meaning x is considered equal to y if abs(x - y) < epsilon. (x, y and my case 
> will be numpy.array).
> 
> Thanks,
> --
> Miki

You'll probably have to write that yourself.  While you're at it, think
long and hard about that definition of fuzziness.  If you can make it
closer to the concept of histogram "bins" you'll get much better
performance.  If, for instance, you can live with 1.anything being one
bin, and 2.anything being the next (even though this puts 1.999 and
2.000 into separate bins) then you can just floor() the number and use
the result as the key.

If you really need the continuous fuzziness you'll probably have to
keep the potential keys sorted and run a binary search against the list
of them to find the nearest.  This will still run you into some
problems based on ordering.  For instance, with an epsilon of 0.1,
you'd put 2.0 into a bin, then 1.9 into the same bin, then 2.1 into the
same bin.  If however you put 1.9 into that bin first, then 2.0 would
go into that bin, but 2.1 would go into a different one.

TL;DR you need to think very hard about your problem definition and
what you want to happen before you actually try to implement this.

-- 
Rob Gaddi, Highland Technology -- www.highlandtechnology.com
Email address domain is currently out of order.  See above to fix.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GCD in Fractions

2014-09-23 Thread Wolfgang Maier

On 09/23/2014 02:50 PM, Steven D'Aprano wrote:


Normally, gcd is only defined for non-negative integers. Wolfram Mathworld,
for example, doesn't mention negative values at all (as far as I can see):

http://mathworld.wolfram.com/GreatestCommonDivisor.html

although buried deep in the documentation for Mathematica's GCD function is
hidden the fact that it treats GCD(-a, -b) the same as GCD(a, b):

http://functions.wolfram.com/IntegerFunctions/GCD/04/02/01/

and sure enough Wolfram Alpha tells me that the GCD of *all* of:

(100, 20)
(-100, 20)
(100, -20)
(-100, -20)

are equal to +20. On the other hand, Excel and LibreOffice both give an
error for the GCD of a negative value, and I've seen versions of gcd()
which do the same as fractions.gcd. So I think there is not one single
standard way to extend GCD to negative numbers.



Well, Excel and LibreOffice can hardly be considered the gold standard 
when it comes to mathematical definitions.
I'm no mathematician either, but Wikipedia has this to say about the 
properties of gcd:

http://en.wikipedia.org/wiki/Greatest_common_divisor#Properties

fractions.gcd violates several of them, like:

#2:
gcd(a, 0) = |a|, for a ≠ 0, since any number is a divisor of 0, and the 
greatest divisor of a is |a|.


>>>fractions.gcd(-7, 0)
-7

#8:
The gcd is a commutative function: gcd(a, b) = gcd(b, a).

>>>fractions.gcd(3, -7) == fractions.gcd(-7, 3)
False

While at first I thought this to be a rather irrelevant debate over 
module private vs public naming conventions, I now think the OP is 
probably right and renaming fractions.gcd to fractions._gcd may be a 
good idea.
Googling for recipes to calculate the gcd using python brings up 
fractions.gcd as a general answer (like at stackoverflow: 
http://stackoverflow.com/questions/11175131/code-for-greatest-common-divisor-in-python) 
and it is not obvious for non-mathematicians to realize that it is NOT a 
generally acceptable solution.


Maybe fractions.gcd could be renamed, but be wrapped or reimplemented 
correctly somewhere else in the stdlib or even in fractions ?


Wolfgang


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


Re: Timedelta constructor with string parameter

2014-09-23 Thread Skip Montanaro
On Tue, Sep 23, 2014 at 4:11 AM,  wrote:

> I created some code recently to parse a string and create a timedelta from
> it.


Interesting. I notice that dateutil.parser.parse already understands you
notation:

>>> x = dateutil.parser.parse("5h32m15s")
>>> x
datetime.datetime(2014, 9, 23, 5, 32, 15)

All that would be necessary is some way to tell it to generate a timedelta
instead of a datetime. Might be better to feed changes back to the dateutil
package maintainers.

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


Re: "Fuzzy" Counter?

2014-09-23 Thread Chris Angelico
On Wed, Sep 24, 2014 at 2:32 AM, Rob Gaddi
 wrote:
> You'll probably have to write that yourself.  While you're at it, think
> long and hard about that definition of fuzziness.  If you can make it
> closer to the concept of histogram "bins" you'll get much better
> performance.  If, for instance, you can live with 1.anything being one
> bin, and 2.anything being the next (even though this puts 1.999 and
> 2.000 into separate bins) then you can just floor() the number and use
> the result as the key.

Or even check three bins based on that - the floor(), floor()+1, and
floor()-1 bins. That way, you're not running into problems at any
boundaries, and you still limit the exponential growth of the
comparisons.

But it's still fundamentally problematic.

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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread Tobiah

On 09/23/2014 07:18 AM, luofeiyu wrote:

x={'f1':1,'f2':2,'f3':3}
how can i create the following html file automatically with python to display x 
?




f1


f2


f3



1


2


3






def tablefy(values):
print ""
for value in values:
print "%s" % value
print ""

x = {'f1': 1,'f2': 2,'f3': 3}

print ""
tablefy(x.keys())
tablefy(x.values())
print ""


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


Re: Timedelta constructor with string parameter

2014-09-23 Thread Felipe Menezes Machado
On Tue, Sep 23, 2014 at 6:39 PM, Skip Montanaro  wrote:

>
> On Tue, Sep 23, 2014 at 4:11 AM,  wrote:
>
>> I created some code recently to parse a string and create a timedelta
>> from it.
>
>
> Interesting. I notice that dateutil.parser.parse already understands you
> notation:
>
> >>> x = dateutil.parser.parse("5h32m15s")
> >>> x
> datetime.datetime(2014, 9, 23, 5, 32, 15)
>
> All that would be necessary is some way to tell it to generate a timedelta
> instead of a datetime. Might be better to feed changes back to the dateutil
> package maintainers.
>
>
Cool, thanks for the tip, I didn't know dateutil yet.

I looked at the code for the dateutil.parser.parse function, and under the
hood it is so much more than my function does. It accepts many different
formats, and also handles timezones. So I'd have to study it a little to
think of a way for it to generate timedelta objects instead of datetime
ones. But I'll definitely keep that in mind!

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


Re: GCD in Fractions

2014-09-23 Thread Ian Kelly
On Tue, Sep 23, 2014 at 10:38 AM, Wolfgang Maier
 wrote:
> Maybe fractions.gcd could be renamed, but be wrapped or reimplemented
> correctly somewhere else in the stdlib or even in fractions ?

+1

I don't think the math module as suggested upthread is the right
place, as that module houses wrappers of C functions that operate on
floats. I'm also not sure where is better, though. Maybe the
reimplemented version should just keep the name fractions.gcd.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GCD in Fractions

2014-09-23 Thread Stefan Behnel
Wolfgang Maier schrieb am 23.09.2014 um 18:38:
> While at first I thought this to be a rather irrelevant debate over module
> private vs public naming conventions, I now think the OP is probably right
> and renaming fractions.gcd to fractions._gcd may be a good idea.

Making a public API private is rarely a good idea. It should be enough in
this case to document the behaviour.

And, believe it or not, it actually is documented:

https://docs.python.org/3.5/library/fractions.html#fractions.gcd


> Googling for recipes to calculate the gcd using python brings up
> fractions.gcd as a general answer (like at stackoverflow:
> http://stackoverflow.com/questions/11175131/code-for-greatest-common-divisor-in-python)
> and it is not obvious for non-mathematicians to realize that it is NOT a
> generally acceptable solution.

It is. Certainly for positive numbers, which clearly present the majority
of use cases. It's definitely the "normal" use case, wouldn't you say?

For negative numbers, the "expected" behaviour seems to be unclear, so the
current behaviour is just as good as any, so backwards compatibility
concerns clearly win this fight.

Stefan


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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread John Gordon
In  luofeiyu 
 writes:

> x={'f1':1,'f2':2,'f3':3}
> how can i create the following html file automatically with python to 
> display x ?

You might want to use something other than a dictionary, as the order
isn't guaranteed.

-- 
John Gordon Imagine what it must be like for a real medical doctor to
gor...@panix.comwatch 'House', or a real serial killer to watch 'Dexter'.

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


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 18:20, Ian Kelly wrote:
> On Tue, Sep 23, 2014 at 10:38 AM, Wolfgang Maier
>  wrote:
>> Maybe fractions.gcd could be renamed, but be wrapped or reimplemented
>> correctly somewhere else in the stdlib or even in fractions ?
> 
> +1
> 
> I don't think the math module as suggested upthread is the right
> place, as that module houses wrappers of C functions that operate on
> floats. I'm also not sure where is better, though. Maybe the
> reimplemented version should just keep the name fractions.gcd.

Since the gcd is only used once in fractions anyway, it would be easy to
change gcd here with very little impact on the performance of the
fractions module (if necessary a local version could be added to work
within fractions as it does now).

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


Re: GCD in Fractions

2014-09-23 Thread Ian Kelly
On Tue, Sep 23, 2014 at 11:26 AM, Stefan Behnel  wrote:
> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
>> While at first I thought this to be a rather irrelevant debate over module
>> private vs public naming conventions, I now think the OP is probably right
>> and renaming fractions.gcd to fractions._gcd may be a good idea.
>
> Making a public API private is rarely a good idea. It should be enough in
> this case to document the behaviour.
>
> And, believe it or not, it actually is documented:
>
> https://docs.python.org/3.5/library/fractions.html#fractions.gcd

I don't think documentation is sufficient in this case. This is the
kind of thing though that is easy to forget about if you haven't read
the documentation recently. And with a function like gcd, one
generally wouldn't expect to *need* to read the documentation.

>> Googling for recipes to calculate the gcd using python brings up
>> fractions.gcd as a general answer (like at stackoverflow:
>> http://stackoverflow.com/questions/11175131/code-for-greatest-common-divisor-in-python)
>> and it is not obvious for non-mathematicians to realize that it is NOT a
>> generally acceptable solution.
>
> It is. Certainly for positive numbers, which clearly present the majority
> of use cases. It's definitely the "normal" use case, wouldn't you say?
>
> For negative numbers, the "expected" behaviour seems to be unclear, so the
> current behaviour is just as good as any, so backwards compatibility
> concerns clearly win this fight.

I'm not convinced it's all that clear. In addition to Mathworld and
Wikipedia that were already cited, ProofWiki provides an actual proof
that gcd(a, b) = gcd(|a|, |b|), by way of noting that a and |a| have
the same factors.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 18:26, Stefan Behnel wrote:
> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
>> While at first I thought this to be a rather irrelevant debate over module
>> private vs public naming conventions, I now think the OP is probably right
>> and renaming fractions.gcd to fractions._gcd may be a good idea.
> For negative numbers, the "expected" behaviour seems to be unclear, so the
> current behaviour is just as good as any, so backwards compatibility
> concerns clearly win this fight.

The expected behaviour is not unclear for anyone who takes the
mathematical properties of the GCD seriously.  It's a shame that Python
doesn't.



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


Re: GCD in Fractions

2014-09-23 Thread Ian Kelly
On Tue, Sep 23, 2014 at 11:39 AM, Ian Kelly  wrote:
> I'm not convinced it's all that clear. In addition to Mathworld and
> Wikipedia that were already cited, ProofWiki provides an actual proof
> that gcd(a, b) = gcd(|a|, |b|), by way of noting that a and |a| have
> the same factors.

I forgot to include the link:

https://proofwiki.org/wiki/GCD_for_Negative_Integers
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: NumPy, SciPy, & Python 3X Installation/compatibility issues

2014-09-23 Thread SK
Hi EK,
Did you figure out questions 1, 2 and 3? SciPy (0.14.0) on installation asks me 
for Python 2.7. First day on Python here, I am really struggling :/
Thanks,
SK

On Saturday, May 10, 2014 7:07:33 PM UTC+2, esa...@gmail.com wrote:
> Hi All--
> 
> 
> 
> Let me state at the start that I am new to Python. I am moving away from 
> Fortran and Matlab to Python and I use all different types of numerical and 
> statistical recipes in my work. I have been reading about NumPy and SciPy and 
> could not find any definitive answers to my questions, below.  I had run into 
> many mostly installation problems that I could never get NumPy or SciPy to 
> work with Python 3.3 or newer.  I am using Windows7 64 bit OS. 
> 
> A few questions:
> 
> 1.What are the latest versions of NumPy and SciPy that are compatible 
> with Python 3.3 or newer and Windows7 64 bit? 
> 
> 2.What is the best source to download and install them on my computer?
> 
> 3.Are they all installable on my OS w/o any major problems/addition?
> 
> 4.In the long run, would it be better to use UNIX instead of Windows, if 
> I were to use Python for all of my research?
> 
> Thanks in advance. EK

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


Re: GCD in Fractions

2014-09-23 Thread Stefan Behnel
blindanagram schrieb am 23.09.2014 um 19:43:
> On 23/09/2014 18:26, Stefan Behnel wrote:
>> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
>>> While at first I thought this to be a rather irrelevant debate over module
>>> private vs public naming conventions, I now think the OP is probably right
>>> and renaming fractions.gcd to fractions._gcd may be a good idea.
>> For negative numbers, the "expected" behaviour seems to be unclear, so the
>> current behaviour is just as good as any, so backwards compatibility
>> concerns clearly win this fight.
> 
> The expected behaviour is not unclear for anyone who takes the
> mathematical properties of the GCD seriously.  It's a shame that Python
> doesn't.

May I ask how you get from one little function in the well-defined scope of
a data type module (which is not named "math" or "integers" or "natural" or
anything like it) to the extrapolation that Python doesn't take
mathematical properties serious?

If the scope of that function's applicability does not match what you want
in your specific use case, then by all means, don't use it for your
specific use case.

Stefan


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


Re: NumPy, SciPy, & Python 3X Installation/compatibility issues

2014-09-23 Thread Jerry Hill
On Tue, Sep 23, 2014 at 1:54 PM, SK  wrote:
> Hi EK,
> Did you figure out questions 1, 2 and 3? SciPy (0.14.0) on installation asks 
> me for Python 2.7. First day on Python here, I am really struggling :/
> Thanks,
> SK

Did you download the SciPy installer for python 3.3?  I see it listed
for download on the sourceforge site here:
http://sourceforge.net/projects/scipy/files/scipy/0.14.0/scipy-0.14.0-win32-superpack-python3.3.exe/download

There are also versions for python 3.4, 3.2, 2.7 and 2.6, so you have
to make sure you get the one that matches the version of python you're
using.

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


Re: GCD in Fractions

2014-09-23 Thread Stefan Behnel
Ian Kelly schrieb am 23.09.2014 um 19:39:
> On Tue, Sep 23, 2014 at 11:26 AM, Stefan Behnel wrote:
>> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
>>> While at first I thought this to be a rather irrelevant debate over module
>>> private vs public naming conventions, I now think the OP is probably right
>>> and renaming fractions.gcd to fractions._gcd may be a good idea.
>>
>> Making a public API private is rarely a good idea. It should be enough in
>> this case to document the behaviour.
>>
>> And, believe it or not, it actually is documented:
>>
>> https://docs.python.org/3.5/library/fractions.html#fractions.gcd
> 
> I don't think documentation is sufficient in this case. This is the
> kind of thing though that is easy to forget about if you haven't read
> the documentation recently. And with a function like gcd, one
> generally wouldn't expect to *need* to read the documentation.

Interesting. I would definitely consult the documentation first thing if I
were considering to pass negative values into a gcd function - into any
implementation, even if I had been the very author myself, just two months
back. I might even take a look at the source to make sure the docs are
correct and up to date, and to look for comments that give further
insights. But maybe that's just me.

Stefan


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


Re: tcp server as windows service

2014-09-23 Thread Johannes Findeisen
Hi,

On Tue, 23 Sep 2014 15:56:41 +0200
Arulnambi Nandagoban wrote:

> Hello all, 
> 
>  
> 
> I developed a multithreaded tcp server with python and I converted into a
> windows executable using pyinstaller. 
> 
> I would like to run the server as a windows service so that server restarts
> whenever pc restarts without 
> 
> doing it manually . Help me out with some sample code . 

Take a look at this post:

https://stackoverflow.com/questions/32404/is-it-possible-to-run-a-python-script-as-a-service-in-windows-if-possible-how

Read the comments below the solution to add your script to the Windows
services list.

I didn't do windows development but it seems very easy to do.

Regards,

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


Re: Dynamically swapping between two algorithms

2014-09-23 Thread Terry Reedy

On 9/23/2014 10:48 AM, Steven D'Aprano wrote:

I have a certain calculation which can be performed two radically different
ways. With the first algorithm, let's call it SHORT, performance is very
fast for small values of the argument, but terrible for large values. For
the second algorithm, LARGE, performance is quite poor for small values,
but excellent for large values.

To add to the complexity, I perform this calculation repeatedly, in a loop:

value = 1
while True:
 x = SHORT(value)  # Or should I use LARGE? Decisions, decisions...
 process(x)
 value += some_increment()
 if condition: break

Luckily, the value never gets smaller. So if I could somehow determine a
cut-over point, CUTOFF, I might write my loop like this:

value = 1
while True:
 f = SHORT if value < CUTOFF else LARGE
 x = f(value)
 process(x)
 value += some_increment()
 if condition: break

alas, the CUTOVER point is likely to be machine-dependent. Take it as a
given that inserting a fixed CUTOVER point into the source code (say,
``CUTOVER = 123456``) is not likely to be very effective, and dynamically
calculating it at import time is impractical.

*If* Python was a different language, I would spawn two threads, one using
SHORT and the other using LARGE, then which ever completes first, I'd just
kill the other. Alas, this won't work because (1) the GIL and (2) you
cannot forcibly kill threads, only ask them to die and hope they listen.

I am seeking other ideas for dynamically swapping between the two
algorithms, based on runtime information. Any thoughts?


(1) I can't tell in advance how many loops I will make.

(2) Both SHORT and LARGE get slower as the size of their argument increases.
This is unavoidable due to the nature of the problem.

(3) SHORT starts off relatively speedy, significantly faster than LARGE for
the first few tens of thousands of loops. I'm not talking about trivial
micro-optimizations here, I'm talking about the difference between 0.1
second for SHORT versus 10 seconds for LARGE.

(4) But as the size of the argument increases, SHORT suffers catastrophic
quadratic slowdown, while LARGE slows down only linearly. (Give or take.)


One possibility is to apply both algorithms to a few values below any 
plausible cutoff value, fit curves (line and quadratic), and find 
intersection of extrapolated cutoff.  Possible calculate a few more 
values to verify and refine extrapolation.




(5) Consequently, by the time I reach a few million loops, the difference is
now between (say) 5 minutes for LARGE versus 15 hours for SHORT.

(6) There is no single algorithm which performs acceptably across the entire
range of values I'm expecting to process in practice.

(7) Leaving the choice up to the caller is not an option. I am the caller.







--
Terry Jan Reedy

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


Re: GCD in Fractions

2014-09-23 Thread Mark Lawrence

On 23/09/2014 18:43, blindanagram wrote:

On 23/09/2014 18:26, Stefan Behnel wrote:

Wolfgang Maier schrieb am 23.09.2014 um 18:38:

While at first I thought this to be a rather irrelevant debate over module
private vs public naming conventions, I now think the OP is probably right
and renaming fractions.gcd to fractions._gcd may be a good idea.

For negative numbers, the "expected" behaviour seems to be unclear, so the
current behaviour is just as good as any, so backwards compatibility
concerns clearly win this fight.


The expected behaviour is not unclear for anyone who takes the
mathematical properties of the GCD seriously.  It's a shame that Python
doesn't.



All you need do is raise an issue on the bug tracker, provide a patch to 
code, test and docs and the job is done.


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: GCD in Fractions

2014-09-23 Thread Terry Reedy

On 9/23/2014 4:16 AM, blindanagram wrote:

What is the rationale for gcd(x, y) in Fractions returning a negative
value when y is negtive?



For example gcd(3, -7) returns -1,


Since the doc says "the result will have the same sign as b", this is 
intentinal.  However, I consider this a *design* bug.  Both -1 and +1 
are common divisors, and 1 is the greatest.  So I consider the previous 
line "Calculate the Greatest Common Divisor of a and b" to be incorrect.



which means that a co-prime test that
would work in many other languages 'if gcd(x, y) == 1' will fail in
Python for negative y.

And, of course, since -|x| is less than |x|, returning -|x| rather than
|x| is not returning the greatest common divisor of x and y when y is
negative.




--
Terry Jan Reedy

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


Re: SOAPpy: Expected to find node type 'Element' with name 'CountriesFetchingRequest'; Found node type 'Element' with name 'FetchCountries'

2014-09-23 Thread ldanielburr
On Sunday, September 21, 2014 9:31:46 PM UTC-5, vek@gmail.com wrote:
> I'm messing with SOAP, trying to write a small library to handle stuff I buy 
> from Aramex (shipper). I'm learning XML/SOAP and I'm familiar with RPC from C 
> (Stevens) but no other relevant experience. If this is incredibly dumb just 
> ignore it since I'll probably figure it out eventually.
> 
> 
> 
> I'm trying to get a list of countries by calling the CoutriesFetchingRequest 
> method - this is documented here:
> 
> http://www.aramex.com/developers/aramex-apis/47442/Location-Services-API
> 
> http://www.aramex.com/content/uploads/109/232/46790/aramex-location-api-manual.pdf
> 
> 
> 
> It takes as its arguments a 'ClientInfo' data-structure and 'Code' which is a 
> string.
> 
> 
> 
> There is also a 'FetchCountries' method with an 'input' and 'output' 
> something.
> 
> However python was more clear, print server.show_methods():
> 
> 
> 
> Method Name: FetchCountries 
> 
>In #0: parameters  ((u'http://ws.aramex.net/ShippingAPI/v1/', 
> u'CountriesFetchingRequest'))
> 
> 
> 
> 
> 
> The trouble is I don't understand how to call 'CoutriesFetchingRequest' or 
> pass it to FetchCountries. Could someone clarify?
> 
> 
> 
> 
> 
> The WSDL for Aramex has this:
> 
> http://www.aramex.com/content/uploads/109/232/46790/location-api-wsdl.zip
> 
> 
> 
>wsaw:Action="http://ws.aramex.net/ShippingAPI/v1/Service_1_0/FetchCountries"; 
> name="CountriesFetchingRequest" message="tns:CountriesFetchingRequest" />
> 
>wsaw:Action="http://ws.aramex.net/ShippingAPI/v1/Service_1_0/FetchCountriesResponse";
>  name="CountriesFetchingResponse" message="tns:CountriesFetchingResponse" />
> 
> 
> 
> 
> 
> 
> 
>   
> 
> 
> 
>   
> 
> 
> 
> My python code:
> 
> #!/usr/bin/python
> 
> import xml, fpconst, logging
> 
> from SOAPpy import WSDL
> 
> from suds.client import Client
> 
> 
> 
> logging.basicConfig(level=logging.INFO)
> 
> logging.getLogger('suds.client').setLevel(logging.DEBUG)
> 
> 
> 
> foo = { 'AccountCountryCode' : 'JO', 'AccountEntity' : 'AMM', 'AccountNumber' 
> : '20016', 'AccountPin' : '331421', 'UserName' : 'testing...@aramex.com', 
> 'Password' : 'R123456789$r', 'Version' : 'v1.0', 'Source' : '', 'Transaction' 
> :  { 'Reference1' : '001', 'Reference2' : '002', 'Reference3' : '003', 
> 'Reference4' : '004', 'Reference5' : '005' } }
> 
> 
> 
> wsdl_file = '/home/veek/location-api-wsdl/Location-API-WSDL.wsdl'
> 
> 
> 
> server = WSDL.Proxy(wsdl_file)
> 
> print server.methods.keys()
> 
> print dir(server)
> 
> print server.show_methods()
> 
> callInfo = server.methods['FetchCountries']
> 
> print type(callInfo)
> 
> print dir(callInfo)
> 
> 
> 
> for arg in callInfo.inparams:
> 
> print arg.name.ljust(15), arg.type
> 
> server.namespace = 'http://ws.aramex.net/ShippingAPI/v1/'
> 
> x = server.FetchCountries.CountriesFetchingRequest(foo)
> 
> 
> 
> The output i get is:
> 
> [u'FetchCountries', u'FetchCountry', u'ValidateAddress', u'FetchCities', 
> u'FetchOffices']
> 
> ['__doc__', '__getattr__', '__init__', '__module__', '__str__', 'methods', 
> 'show_methods', 'soapproxy', 'wsdl']
> 
> Method Name: FetchCountries 
> 
> 
> 
>In #0: parameters  ((u'http://ws.aramex.net/ShippingAPI/v1/', 
> u'CountriesFetchingRequest'))
> 
> 
> 
>Out #0: parameters  ((u'http://ws.aramex.net/ShippingAPI/v1/', 
> u'CountriesFetchingResponse'))
> 
> 
> 
> 
> 
> 
> 
> None
> 
> 
> 
> ['__doc__', '__init__', '__module__', 'addInHeaderInfo', 'addInParameter', 
> 'addOutHeaderInfo', 'addOutParameter', 'documentation', 'encodingStyle', 
> 'getInHeaders', 'getInParameters', 'getOutHeaders', 'getOutParameters', 
> 'getReturnParameter', 'inheaders', 'inparams', 'location', 'methodName', 
> 'namespace', 'outheaders', 'outparams', 'retval', 'setReturnParameter', 
> 'soapAction', 'style', 'transport', 'use']
> 
> parameters  (u'http://ws.aramex.net/ShippingAPI/v1/', 
> u'CountriesFetchingRequest')
> 
> 
> 
> 
> 
> 
> 
> SOAPpy.Types.faultType:  body of request message for operation 'FetchCountries'. OperationFormatter 
> encountered an invalid Message body. Expected to find node type 'Element' 
> with name 'CountriesFetchingRequest' and namespace 
> 'http://ws.aramex.net/ShippingAPI/v1/'. Found node type 'Element' with name 
> 'FetchCountries.CountriesFetchingRequest' and namespace '': 
> 
> 

Give pysimplesoap a try; you can point it at the wsdl endpoint, and it will 
provide you a client that lets you call methods in about as obvious a manner as 
you can reasonably hope for, given the mess that is SOAP.

See https://code.google.com/p/pysimplesoap/wiki/SoapClient for some examples.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread Denis McMahon
On Tue, 23 Sep 2014 09:53:40 -0700, Tobiah wrote:

> On 09/23/2014 07:18 AM, luofeiyu wrote:

>> how can i create the following html

>> f3 
>> 

No  here?

>> 
>> 1

...

>> 
>> 3
>> 
>> 

What is the above  doing there?

>> 
>> 

> [code]

Although your solution will produce valid html, it doesn't produce the 
specified output. ;)

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread Denis McMahon
On Tue, 23 Sep 2014 17:34:53 +, John Gordon wrote:

> In  luofeiyu
>  writes:
> 
>> x={'f1':1,'f2':2,'f3':3}
>> how can i create the following html file automatically with python to
>> display x ?
> 
> You might want to use something other than a dictionary, as the order
> isn't guaranteed.

Assuming you want them in order of the key field:

from string import *

x={'f1':1,'f2':2,'f3':3}
y = [ (a,x[a]) for a in x.keys() ]
y.sort( cmp=lambda a,b: cmp(a[0],b[0]) )
table = ( "\n" +
  "\n".join(["\n" +
 "\n".join(["{}".format(z[i]) for z in y]) +
 "\n" for i in range(len(y[0]))]) +
  "\n" )
print table

-- 
Denis McMahon, denismfmcma...@gmail.com
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Dynamically swapping between two algorithms

2014-09-23 Thread C Smith
Once the runtime of SHORT starts to increase by a certain threshold,
Such as 2x, 4x, or 16x its last runtime? The other ideas already
proposed sound better, but I am wondering if it would work.

On Tue, Sep 23, 2014 at 12:21 PM, Terry Reedy  wrote:
> On 9/23/2014 10:48 AM, Steven D'Aprano wrote:
>>
>> I have a certain calculation which can be performed two radically
>> different
>> ways. With the first algorithm, let's call it SHORT, performance is very
>> fast for small values of the argument, but terrible for large values. For
>> the second algorithm, LARGE, performance is quite poor for small values,
>> but excellent for large values.
>>
>> To add to the complexity, I perform this calculation repeatedly, in a
>> loop:
>>
>> value = 1
>> while True:
>>  x = SHORT(value)  # Or should I use LARGE? Decisions, decisions...
>>  process(x)
>>  value += some_increment()
>>  if condition: break
>>
>> Luckily, the value never gets smaller. So if I could somehow determine a
>> cut-over point, CUTOFF, I might write my loop like this:
>>
>> value = 1
>> while True:
>>  f = SHORT if value < CUTOFF else LARGE
>>  x = f(value)
>>  process(x)
>>  value += some_increment()
>>  if condition: break
>>
>> alas, the CUTOVER point is likely to be machine-dependent. Take it as a
>> given that inserting a fixed CUTOVER point into the source code (say,
>> ``CUTOVER = 123456``) is not likely to be very effective, and dynamically
>> calculating it at import time is impractical.
>>
>> *If* Python was a different language, I would spawn two threads, one using
>> SHORT and the other using LARGE, then which ever completes first, I'd just
>> kill the other. Alas, this won't work because (1) the GIL and (2) you
>> cannot forcibly kill threads, only ask them to die and hope they listen.
>>
>> I am seeking other ideas for dynamically swapping between the two
>> algorithms, based on runtime information. Any thoughts?
>>
>>
>> (1) I can't tell in advance how many loops I will make.
>>
>> (2) Both SHORT and LARGE get slower as the size of their argument
>> increases.
>> This is unavoidable due to the nature of the problem.
>>
>> (3) SHORT starts off relatively speedy, significantly faster than LARGE
>> for
>> the first few tens of thousands of loops. I'm not talking about trivial
>> micro-optimizations here, I'm talking about the difference between 0.1
>> second for SHORT versus 10 seconds for LARGE.
>>
>> (4) But as the size of the argument increases, SHORT suffers catastrophic
>> quadratic slowdown, while LARGE slows down only linearly. (Give or take.)
>
>
> One possibility is to apply both algorithms to a few values below any
> plausible cutoff value, fit curves (line and quadratic), and find
> intersection of extrapolated cutoff.  Possible calculate a few more values
> to verify and refine extrapolation.
>
>
>> (5) Consequently, by the time I reach a few million loops, the difference
>> is
>> now between (say) 5 minutes for LARGE versus 15 hours for SHORT.
>>
>> (6) There is no single algorithm which performs acceptably across the
>> entire
>> range of values I'm expecting to process in practice.
>>
>> (7) Leaving the choice up to the caller is not an option. I am the caller.
>>
>>
>>
>>
>
>
> --
> Terry Jan Reedy
>
> --
> https://mail.python.org/mailman/listinfo/python-list
-- 
https://mail.python.org/mailman/listinfo/python-list


Flask and Python 3

2014-09-23 Thread Juan Christian
I'm following a tutorial about Flask using Python 3.4.1, but I'm getting an
error with a dead simple example:

generator.py:

from flask import Flask, render_template


app = Flask(__name__)

@app.route('/')
def index():
return 'Hello World'


@app.route('/blog/post/')
def post():
return render_template('post.html', post_content = "Hello, World (from a
template)")


if __name__ == '__main__':
app.run(port = 8000)



base.html:



{% block head %}
Test
{% endlbock head %}



{% block content %}{% endlbock content %}






post.html:

{% extends "base.html" %}

{% block content %}


Blog post title
Subtitle
date




{{ post_content }}

{% endblock content %}



I typed everything correct,acessing http://localhost:8000 works, but
http://localhost:8000/blog/post/ gives me ' 500 Internal Server Error '.
Why?

Python 3.4.1

Flask (0.10.1)
itsdangerous (0.24)
Jinja2 (2.7.3)
MarkupSafe (0.23)
pip (1.5.6)
setuptools (5.8)
Werkzeug (0.9.6)
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 18:55, Stefan Behnel wrote:
> blindanagram schrieb am 23.09.2014 um 19:43:
>> On 23/09/2014 18:26, Stefan Behnel wrote:
>>> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
 While at first I thought this to be a rather irrelevant debate over module
 private vs public naming conventions, I now think the OP is probably right
 and renaming fractions.gcd to fractions._gcd may be a good idea.
>>> For negative numbers, the "expected" behaviour seems to be unclear, so the
>>> current behaviour is just as good as any, so backwards compatibility
>>> concerns clearly win this fight.
>>
>> The expected behaviour is not unclear for anyone who takes the
>> mathematical properties of the GCD seriously.  It's a shame that Python
>> doesn't.
> 
> May I ask how you get from one little function in the well-defined scope of
> a data type module (which is not named "math" or "integers" or "natural" or
> anything like it) to the extrapolation that Python doesn't take
> mathematical properties serious?

Firstly I have to choose between two possibilities:

(a) that the name of the function has been deliberately chosen to imply
that it calculates the mathematical function known as the 'greatest
commmon divisor'; or

(b) that the initials 'gcd' have been chosen by pure chance and the
association between this function and the 'greatest commmon divisor' has
arisen from pure coincidence.

Of these, I find (a) overwhelmingly more likely.

Seccondly (as others here have pointed out), the mathematical properties
of the greatest common divisor are well defined for both positive and
negative integers.  But the Python function called gcd doesn't have some
of these properties.

I hence conclude that Python doesn't take the mathematical properties of
the greatest common divisor seriously since it doesn't ensure that its
version of this function has these properties.

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


Re: GCD in Fractions

2014-09-23 Thread blindanagram
On 23/09/2014 20:30, Mark Lawrence wrote:
> On 23/09/2014 18:43, blindanagram wrote:
>> On 23/09/2014 18:26, Stefan Behnel wrote:
>>> Wolfgang Maier schrieb am 23.09.2014 um 18:38:
 While at first I thought this to be a rather irrelevant debate over
 module
 private vs public naming conventions, I now think the OP is probably
 right
 and renaming fractions.gcd to fractions._gcd may be a good idea.
>>> For negative numbers, the "expected" behaviour seems to be unclear,
>>> so the
>>> current behaviour is just as good as any, so backwards compatibility
>>> concerns clearly win this fight.
>>
>> The expected behaviour is not unclear for anyone who takes the
>> mathematical properties of the GCD seriously.  It's a shame that Python
>> doesn't.
>>
> All you need do is raise an issue on the bug tracker, provide a patch to
> code, test and docs and the job is done.

Thank you for your helpful comment.  I will happily do this if after
discussion here there is a reasonable level of support and encouragement
for such an action.

However, there is at least one person here who takes the view that
backward compatibility outranks mathematical correctness and I don't
want to find that 'I am banging my head against a brick wall' if this is
likely to be the stance that Python developers take.

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


Re: Flask and Python 3

2014-09-23 Thread John Gordon
In  Juan Christian 
 writes:

> @app.route('/')
> def index():
> return 'Hello World'

As posted, your code is not indented.  Is this literally how your code
looks?

> {% block content %}{% endlbock content %}

"endlbock" is certainly a typo.

> I typed everything correct,acessing http://localhost:8000 works, but
> http://localhost:8000/blog/post/ gives me ' 500 Internal Server Error '.
> Why?

Have you looked in the http server error log for an explanatory error
message?

-- 
John Gordon Imagine what it must be like for a real medical doctor to
gor...@panix.comwatch 'House', or a real serial killer to watch 'Dexter'.

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


Re: Flask and Python 3

2014-09-23 Thread Juan Christian
On Tue, Sep 23, 2014 at 6:48 PM, John Gordon  wrote:
>
> > @app.route('/')
> > def index():
> > return 'Hello World'
>
> As posted, your code is not indented.  Is this literally how your code
> looks?
>
>
The mail screwed the indentation, it's indented in the file.


> > {% block content %}{% endlbock content %}
>
> "endlbock" is certainly a typo.


Oh my Godd... Yes, that's it, working 100% now. Thanks!
-- 
https://mail.python.org/mailman/listinfo/python-list


Best way to deal with different data types in a list comprehension

2014-09-23 Thread Larry Martell
I have some code that I inherited:

' '.join([self.get_abbrev()] +
   [str(f['value')
for f in self.filters
if f.has_key('value')]).strip()


This broke today when it encountered some non-ascii data.

I changed the str(f['value']) line to f['value'].encode('utf-8'),
which works fine, except when f['value'] is not a string (it could be
anything).

Without rewriting this without the list comprehension, how can I write
this to deal with both strings and non-strings?
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best way to deal with different data types in a list comprehension

2014-09-23 Thread Rock Neurotiko
Maybe there are a different way, but you can do this:

' '.join([self.get_abbrev()] +
   [str(f['value').encode('utf-8') if type(f['value']) is str else
str(f['value']
for f in self.filters
if f.has_key('value')]).strip()

2014-09-24 0:01 GMT+02:00 Larry Martell :

> I have some code that I inherited:
>
> ' '.join([self.get_abbrev()] +
>[str(f['value')
> for f in self.filters
> if f.has_key('value')]).strip()
>
>
> This broke today when it encountered some non-ascii data.
>
> I changed the str(f['value']) line to f['value'].encode('utf-8'),
> which works fine, except when f['value'] is not a string (it could be
> anything).
>
> Without rewriting this without the list comprehension, how can I write
> this to deal with both strings and non-strings?
> --
> https://mail.python.org/mailman/listinfo/python-list
>



-- 
Miguel García Lafuente - Rock Neurotiko

Do it, the devil is in the details.
The quieter you are, the more you are able to hear.
Happy Coding. Code with Passion, Decode with Patience.
If we make consistent effort, based on proper education, we can change the
world.

El contenido de este e-mail es privado, no se permite la revelacion del
contenido de este e-mail a gente ajena a él.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Best way to deal with different data types in a list comprehension

2014-09-23 Thread Chris Kaynor
On Tue, Sep 23, 2014 at 3:01 PM, Larry Martell 
wrote:

> I have some code that I inherited:
>
> ' '.join([self.get_abbrev()] +
>[str(f['value')
> for f in self.filters
> if f.has_key('value')]).strip()
>

> This broke today when it encountered some non-ascii data.
>

One option would be to do the processing in unicode, and convert to utf-8
only when needed:

u' '.join([self.get_abbrev()] +
   [unicode(f['value')
for f in self.filters
if f.has_key('value')]).strip()

If needed, add a .encode('utf-8') to the end.


>
> I changed the str(f['value']) line to f['value'].encode('utf-8'),
> which works fine, except when f['value'] is not a string (it could be
> anything).
>
> Without rewriting this without the list comprehension, how can I write
> this to deal with both strings and non-strings?
> --
> https://mail.python.org/mailman/listinfo/python-list
>
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Pyrolite, lightweight pickle and pyro client library, seeking a bit of testing help

2014-09-23 Thread Irmen de Jong
On 22-9-2014 20:28, Chris Angelico wrote:
> On Tue, Sep 23, 2014 at 4:23 AM, Irmen de Jong  wrote:
>> This is why Pyro has been using a different (and safe) serializer by default 
>> for a while
>> now. You have to plow through the usual security warnings in the docs and 
>> make a
>> conscious effort in your code to enable the pickle serializer if you really 
>> want/need it.
> 
> Is the safe serializer affected by byte order? If not, you could just
> mark this off as a known bug, and say "if anyone has a big-endian
> system to test this on, please help out". It would be another
> incentive to use the safe serializer rather than pickle. And it'd save
> you a lot of trouble. :)

The safe serializer is this one: https://github.com/irmen/serpent and it is a 
text based
protocol, so no, it is not affected by byte order. It uses Python literal 
expressions as
understood by ast.literal_eval().

Note that the endianness bug in my pickle implementation was fixed by the pull 
request
so it is no longer a known bug. But I still would like to be able to run the 
test suite
on both endianness platforms (or let someone else try it for me :-) )


> 
> I would have offered one of my systems for the test, except ...
> they're all little-endian. I'm all PC-based hardware here (mainly
> Linux running on Intel CPUs, though there are some variations).

Heh, yes; I used to have a PowerPC G4 mac mini (a big endian platform), but 
that machine
got replaced by an Intel based one (little endian, as all the other computers I 
have
access to). Ah well.

Irmen



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


Re: Best way to deal with different data types in a list comprehension

2014-09-23 Thread Larry Martell
On Tue, Sep 23, 2014 at 6:05 PM, Rock Neurotiko
 wrote:
> 2014-09-24 0:01 GMT+02:00 Larry Martell :
>>
>> I have some code that I inherited:
>>
>> ' '.join([self.get_abbrev()] +
>>[str(f['value')
>> for f in self.filters
>> if f.has_key('value')]).strip()
>>
>>
>> This broke today when it encountered some non-ascii data.
>>
>> I changed the str(f['value']) line to f['value'].encode('utf-8'),
>> which works fine, except when f['value'] is not a string (it could be
>> anything).
>>
>> Without rewriting this without the list comprehension, how can I write
>> this to deal with both strings and non-strings?

> Maybe there are a different way, but you can do this:
>
> ' '.join([self.get_abbrev()] +
>[str(f['value').encode('utf-8') if type(f['value']) is str else
> str(f['value']
> for f in self.filters
> if f.has_key('value')]).strip()

Thanks for the reply, but please don't top post.

This worked for me:

'.join([self.get_abbrev()] +
 [f['value'].encode('utf-8') if type(f['value']) is unicode
else str(f['value'])
  for f in self.filters
  if f.has_key('value')]).strip()
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: GCD in Fractions

2014-09-23 Thread Mark Lawrence

On 23/09/2014 22:48, blindanagram wrote:

On 23/09/2014 20:30, Mark Lawrence wrote:

On 23/09/2014 18:43, blindanagram wrote:

On 23/09/2014 18:26, Stefan Behnel wrote:

Wolfgang Maier schrieb am 23.09.2014 um 18:38:

While at first I thought this to be a rather irrelevant debate over
module
private vs public naming conventions, I now think the OP is probably
right
and renaming fractions.gcd to fractions._gcd may be a good idea.

For negative numbers, the "expected" behaviour seems to be unclear,
so the
current behaviour is just as good as any, so backwards compatibility
concerns clearly win this fight.


The expected behaviour is not unclear for anyone who takes the
mathematical properties of the GCD seriously.  It's a shame that Python
doesn't.


All you need do is raise an issue on the bug tracker, provide a patch to
code, test and docs and the job is done.


Thank you for your helpful comment.  I will happily do this if after
discussion here there is a reasonable level of support and encouragement
for such an action.

However, there is at least one person here who takes the view that
backward compatibility outranks mathematical correctness and I don't
want to find that 'I am banging my head against a brick wall' if this is
likely to be the stance that Python developers take.



From https://docs.python.org/devguide/experts.html Mark Dickinson and 
Raymond Hettinger are listed as the maintainers of the fractions module. 
 If they're not lurking here I'd guess the simplest way to contact them 
is via the bug tracker.  That also gives the official mechanism as to 
whether or not an enhancement request such as this is accepted or 
rejected and the rationale behind the decision.  For example it is 
feasible that the current behaviour would be deprecated in Python 3.5 
and changed in 3.6 to match your needs.  I don't have enough knowledge 
of the maths to say one way or another, but I'm certain that others will 
chip in with their comments.  Best of luck anyway :)


--
My fellow Pythonistas, ask not what our language can do for you, ask
what you can do for our language.

Mark Lawrence

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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread luofeiyu

how can i  create the proper html file with /Jinjia/2 or other temple?

Joel Goldstick wrote:
Generally, you would use a framework like django or others.

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


Re: Flask and Python 3

2014-09-23 Thread Terry Reedy

On 9/23/2014 5:57 PM, Juan Christian wrote:

On Tue, Sep 23, 2014 at 6:48 PM, John Gordon mailto:gor...@panix.com>> wrote:

> @app.route('/')
> def index():
> return 'Hello World'

As posted, your code is not indented.  Is this literally how your code
looks?

The mail screwed the indentation, it's indented in the file.


Did you use tabs? They are more likely to disappear than spaces.


--
Terry Jan Reedy

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


Re: how to write a html to automatically display the dictionary?

2014-09-23 Thread Ned Batchelder

On 9/23/14 4:53 PM, Denis McMahon wrote:

from string import *


You aren't using any names from string, so you can skip this line.



x={'f1':1,'f2':2,'f3':3}
y = [ (a,x[a]) for a in x.keys() ]
y.sort( cmp=lambda a,b: cmp(a[0],b[0]) )


This is more easily done as:

y = sorted(x.items())

.items() returns a sequence of (key, value) pairs, and tuples are sorted 
lexicographically, so the first elements are compared first, then the 
second, etc.


--
Ned Batchelder, http://nedbatchelder.com

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


Re: Flask and Python 3

2014-09-23 Thread Jon Ribbens
On 2014-09-23, Juan Christian  wrote:
> if __name__ == '__main__':
> app.run(port = 8000)

app.run(port=8000, debug=True) might've made the problem easier to find.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: Flask and Python 3

2014-09-23 Thread Juan Christian
On Tue, Sep 23, 2014 at 8:46 PM, Terry Reedy  wrote:
>
> Did you use tabs? They are more likely to disappear than spaces.


Yes, I use tabs.

On Tue, Sep 23, 2014 at 9:33 PM, Jon Ribbens 
wrote:
>
> app.run(port=8000, debug=True) might've made the problem easier to find.
>

I didn't learn debug with Flask yet. Only in the next videos.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: SOAPpy: Expected to find node type 'Element' with name 'CountriesFetchingRequest'; Found node type 'Element' with name 'FetchCountries'

2014-09-23 Thread Veek M
dieter wrote:
> I have no experience with "SOAPpy", but with "suds" (another Python
> SAOP client). A "suds" client exposes two attributes "factory"
*miaows happily*
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Fuzzy" Counter?

2014-09-23 Thread Miki Tebeka
On Tuesday, September 23, 2014 4:37:10 PM UTC+3, Peter Otten wrote:
> x eq y 
> y eq z
> not (x eq z)
> 
> where eq is the test given above -- should x, y, and z land in the same bin?
Yeah, I know the counting depends on the order of items. But I'm OK with that.
-- 
https://mail.python.org/mailman/listinfo/python-list


Re: "Fuzzy" Counter?

2014-09-23 Thread Miki Tebeka
On Tuesday, September 23, 2014 7:33:06 PM UTC+3, Rob Gaddi wrote:

> While you're at it, think
> long and hard about that definition of fuzziness.  If you can make it
> closer to the concept of histogram "bins" you'll get much better
> performance.  
The problem for me here is that I can't determine the number of bins in 
advance. I'd like to get frequencies. I guess every "new" (don't have any 
previous equal item) can be a bin.

> TL;DR you need to think very hard about your problem definition and
> what you want to happen before you actually try to implement this.
Always a good advice :) I'm actually implementing algorithm for someone else 
(in the bio world where I know very little about).
-- 
https://mail.python.org/mailman/listinfo/python-list