Commits

Alex Gaynor committed f49b248 Merge

merged default

Comments (0)

Files changed (6)

lib_pypy/datetime.py

         return result
     fromtimestamp = classmethod(fromtimestamp)
 
+    @classmethod
     def utcfromtimestamp(cls, t):
         "Construct a UTC datetime from a POSIX timestamp (like time.time())."
-        if 1 - (t % 1.0) < 0.0000005:
-            t = float(int(t)) + 1
-        if t < 0:
-            t -= 1
+        t, frac = divmod(t, 1.0)
+        us = round(frac * 1e6)
+
+        # If timestamp is less than one microsecond smaller than a
+        # full second, us can be rounded up to 1000000.  In this case,
+        # roll over to seconds, otherwise, ValueError is raised
+        # by the constructor.
+        if us == 1000000:
+            t += 1
+            us = 0
         y, m, d, hh, mm, ss, weekday, jday, dst = _time.gmtime(t)
-        us = int((t % 1.0) * 1000000)
         ss = min(ss, 59)    # clamp out leap seconds if the platform has them
         return cls(y, m, d, hh, mm, ss, us)
-    utcfromtimestamp = classmethod(utcfromtimestamp)
 
     # XXX This is supposed to do better than we *can* do by using time.time(),
     # XXX if the platform supports a more accurate way.  The C implementation

pypy/module/micronumpy/interp_numarray.py

     def descr_copy(self, space):
         return self.copy(space)
 
+    def descr_flatten(self, space):
+        return self.flatten(space)
+
     def copy(self, space):
         return self.get_concrete().copy(space)
 
+    def flatten(self, space):
+        return self.get_concrete().flatten(space)
+
     def descr_len(self, space):
         if len(self.shape):
             return space.wrap(self.shape[0])
     def copy(self, space):
         return Scalar(self.dtype, self.value)
 
+    def flatten(self, space):
+        array = W_NDimArray(self.size, [self.size], self.dtype)
+        array.setitem(0, self.value)
+        return array
+
     def fill(self, space, w_value):
         self.value = self.dtype.coerce(space, w_value)
 
                                self.left.create_sig(), self.right.create_sig())
 
 class SliceArray(Call2):
-    def __init__(self, shape, dtype, left, right):
+    def __init__(self, shape, dtype, left, right, no_broadcast=False):
+        self.no_broadcast = no_broadcast
         Call2.__init__(self, None, 'sliceloop', shape, dtype, dtype, left,
                        right)
 
     def create_sig(self):
         lsig = self.left.create_sig()
         rsig = self.right.create_sig()
-        if self.shape != self.right.shape:
+        if not self.no_broadcast and self.shape != self.right.shape:
             return signature.SliceloopBroadcastSignature(self.ufunc,
                                                          self.name,
                                                          self.calc_dtype,
         array.setslice(space, self)
         return array
 
+    def flatten(self, space):
+        array = W_NDimArray(self.size, [self.size], self.dtype, self.order)
+        if self.supports_fast_slicing():
+            array._fast_setslice(space, self)
+        else:
+            arr = SliceArray(array.shape, array.dtype, array, self, no_broadcast=True)
+            array._sliceloop(arr)
+        return array
+
     def fill(self, space, w_value):
         self.setslice(space, scalar_w(space, self.dtype, w_value))
 
     fill = interp2app(BaseArray.descr_fill),
 
     copy = interp2app(BaseArray.descr_copy),
+    flatten = interp2app(BaseArray.descr_flatten),
     reshape = interp2app(BaseArray.descr_reshape),
     tolist = interp2app(BaseArray.descr_tolist),
 )

pypy/module/micronumpy/test/test_numarray.py

         a = array([5.0])
         assert a.std() == 0.0
 
+    def test_flatten(self):
+        from _numpypy import array
+
+        a = array([[1, 2, 3], [4, 5, 6]])
+        assert (a.flatten() == [1, 2, 3, 4, 5, 6]).all()
+        a = array([[[1, 2], [3, 4]], [[5, 6], [7, 8]]])
+        assert (a.flatten() == [1, 2, 3, 4, 5, 6, 7, 8]).all()
+        a = array([1, 2, 3, 4, 5, 6, 7, 8])
+        assert (a[::2].flatten() == [1, 3, 5, 7]).all()
+        a = array([1, 2, 3])
+        assert ((a + a).flatten() == [2, 4, 6]).all()
+        a = array(2)
+        assert (a.flatten() == [2]).all()
+        a = array([[1, 2], [3, 4]])
+        assert (a.T.flatten() == [1, 3, 2, 4]).all()
+
 
 class AppTestMultiDim(BaseNumpyAppTest):
     def test_init(self):

pypy/module/test_lib_pypy/test_datetime.py

+"""Additional tests for datetime."""
+
+import time
+import datetime
+import os
+
+def test_utcfromtimestamp():
+    """Confirm that utcfromtimestamp and fromtimestamp give consistent results.
+
+    Based on danchr's test script in https://bugs.pypy.org/issue986
+    """
+    try:
+        prev_tz = os.environ.get("TZ")
+        os.environ["TZ"] = "GMT"
+        for unused in xrange(100):
+            now = time.time()
+            delta = (datetime.datetime.utcfromtimestamp(now) -
+                     datetime.datetime.fromtimestamp(now))
+            assert delta.days * 86400 + delta.seconds == 0
+    finally:
+        if prev_tz is None:
+            del os.environ["TZ"]
+        else:
+            os.environ["TZ"] = prev_tz

pypy/objspace/std/complexobject.py

 from pypy.rlib.rbigint import rbigint
 from pypy.rlib.rfloat import (
     formatd, DTSF_STR_PRECISION, isinf, isnan, copysign)
+from pypy.rlib import jit
 
 import math
 
             ir = len * math.sin(phase)
         return W_ComplexObject(rr, ir)
 
-    def pow_int(self, n):
-        if n > 100 or n < -100:
-            return self.pow(W_ComplexObject(1.0 * n, 0.0))
-        elif n > 0:
+    def pow_small_int(self, n):
+        if n >= 0:
+            if jit.isconstant(n) and n == 2:
+                return self.mul(self)
             return self.pow_positive_int(n)
         else:
             return w_one.div(self.pow_positive_int(-n))
 def pow__Complex_Complex_ANY(space, w_complex, w_exponent, thirdArg):
     if not space.is_w(thirdArg, space.w_None):
         raise OperationError(space.w_ValueError, space.wrap('complex modulo'))
-    int_exponent = int(w_exponent.realval)
     try:
-        if w_exponent.imagval == 0.0 and w_exponent.realval == int_exponent:
-            w_p = w_complex.pow_int(int_exponent)
+        r = w_exponent.realval
+        if w_exponent.imagval == 0.0 and -100.0 <= r <= 100.0 and r == int(r):
+            w_p = w_complex.pow_small_int(int(r))
         else:
             w_p = w_complex.pow(w_exponent)
     except ZeroDivisionError:

pypy/objspace/std/test/test_complexobject.py

         assert _powu((0.0,1.0),2) == (-1.0,0.0)
 
         def _powi((r1, i1), n):
-            w_res = W_ComplexObject(r1, i1).pow_int(n)
+            w_res = W_ComplexObject(r1, i1).pow_small_int(n)
             return w_res.realval, w_res.imagval
         assert _powi((0.0,2.0),0) == (1.0,0.0)
         assert _powi((0.0,0.0),2) == (0.0,0.0)
         assert a ** 105 == a ** 105
         assert a ** -105 == a ** -105
         assert a ** -30 == a ** -30
+        assert a ** 2 == a * a
 
         assert 0.0j ** 0 == 1