Python copy.copy() Examples

The following are code examples for showing how to use copy.copy(). They are from open source Python projects. You can vote up the examples you like or vote down the ones you don't like.

Example 1
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 6 votes vote down vote up
def add_border(self, val, img_shape=None):
        if val == 0:
            return self.copy()
        else:
            if isinstance(val, int):
                rect = Rectangle(x1=self.x1-val, x2=self.x2+val, y1=self.y1-val, y2=self.y2+val)
            elif isinstance(val, float):
                rect = Rectangle(x1=int(self.x1 - self.width*val), x2=int(self.x2 + self.width*val), y1=int(self.y1 - self.height*val), y2=int(self.y2 + self.height*val))
            elif isinstance(val, tuple):
                assert len(val) == 4, str(len(val))

                if all([isinstance(subval, int) for subval in val]):
                    rect = Rectangle(x1=self.x1-val[3], x2=self.x2+val[1], y1=self.y1-val[0], y2=self.y2+val[2])
                elif all([isinstance(subval, float) or subval == 0 for subval in val]): # "or subval==0" da sonst zB (0.1, 0, 0.1, 0) einen fehler erzeugt (0 ist int)
                    rect = Rectangle(x1=int(self.x1 - self.width*val[3]), x2=int(self.x2 + self.width*val[1]), y1=int(self.y1 - self.height*val[0]), y2=int(self.y2 + self.height*val[2]))
                else:
                    raise Exception("Tuple of all ints or tuple of all floats expected, got %s" % (str([type(v) for v in val]),))
            else:
                raise Exception("int or float or tuple of ints/floats expected, got %s" % (type(val),))

            if img_shape is not None:
                rect.fix_by_image_dimensions(height=img_shape[0], width=img_shape[1])

            return rect 
Example 2
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 6 votes vote down vote up
def draw_on_image(self, img, color=[0, 255, 0], alpha=1.0, copy=True, from_img=None):
        if copy:
            img = np.copy(img)

        orig_dtype = img.dtype
        if alpha != 1.0 and img.dtype != np.float32:
            img = img.astype(np.float32, copy=False)

        for rect in self:
            if from_img is not None:
                rect.resize(from_img, img).draw_on_image(img, color=color, alpha=alpha, copy=False)
            else:
                rect.draw_on_image(img, color=color, alpha=alpha, copy=False)

        if orig_dtype != img.dtype:
            img = img.astype(orig_dtype, copy=False)

        return img 
Example 3
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def revert(self, filename=None,
               ignore_discard=False, ignore_expires=False):
        """Clear all cookies and reload cookies from a saved file.

        Raises LoadError (or IOError) if reversion is not successful; the
        object's state will not be altered if this happens.

        """
        if filename is None:
            if self.filename is not None: filename = self.filename
            else: raise ValueError(MISSING_FILENAME_TEXT)

        self._cookies_lock.acquire()
        try:

            old_state = copy.deepcopy(self._cookies)
            self._cookies = {}
            try:
                self.load(filename, ignore_discard, ignore_expires)
            except (LoadError, IOError):
                self._cookies = old_state
                raise

        finally:
            self._cookies_lock.release() 
Example 4
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def makelink(self, tarinfo, targetpath):
        """Make a (symbolic) link called targetpath. If it cannot be created
          (platform limitation), we try to make a copy of the referenced file
          instead of a link.
        """
        if hasattr(os, "symlink") and hasattr(os, "link"):
            # For systems that support symbolic and hard links.
            if tarinfo.issym():
                if os.path.lexists(targetpath):
                    os.unlink(targetpath)
                os.symlink(tarinfo.linkname, targetpath)
            else:
                # See extract().
                if os.path.exists(tarinfo._link_target):
                    if os.path.lexists(targetpath):
                        os.unlink(targetpath)
                    os.link(tarinfo._link_target, targetpath)
                else:
                    self._extract_member(self._find_link_target(tarinfo), targetpath)
        else:
            try:
                self._extract_member(self._find_link_target(tarinfo), targetpath)
            except KeyError:
                raise ExtractError("unable to resolve link inside archive") 
Example 5
Project: pyblish-win   Author: pyblish   File: test_sysconfig.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def setUp(self):
        """Make a copy of sys.path"""
        super(TestSysConfig, self).setUp()
        self.sys_path = sys.path[:]
        self.makefile = None
        # patching os.uname
        if hasattr(os, 'uname'):
            self.uname = os.uname
            self._uname = os.uname()
        else:
            self.uname = None
            self._uname = None
        os.uname = self._get_uname
        # saving the environment
        self.name = os.name
        self.platform = sys.platform
        self.version = sys.version
        self.sep = os.sep
        self.join = os.path.join
        self.isabs = os.path.isabs
        self.splitdrive = os.path.splitdrive
        self._config_vars = copy(sysconfig._CONFIG_VARS)
        self.old_environ = deepcopy(os.environ) 
Example 6
Project: pyblish-win   Author: pyblish   File: test_bytes.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_returns_new_copy(self):
        val = self.marshal(b'1234')
        # On immutable types these MAY return a reference to themselves
        # but on mutable types like bytearray they MUST return a new copy.
        for methname in ('zfill', 'rjust', 'ljust', 'center'):
            method = getattr(val, methname)
            newval = method(3)
            self.assertEqual(val, newval)
            self.assertTrue(val is not newval,
                            methname+' returned self on a mutable object')
        for expr in ('val.split()[0]', 'val.rsplit()[0]',
                     'val.partition(".")[0]', 'val.rpartition(".")[2]',
                     'val.splitlines()[0]', 'val.replace("", "")'):
            newval = eval(expr)
            self.assertEqual(val, newval)
            self.assertTrue(val is not newval,
                            expr+' returned val on a mutable object') 
Example 7
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_copying(self):
        # Check that ordered dicts are copyable, deepcopyable, picklable,
        # and have a repr/eval round-trip
        pairs = [('c', 1), ('b', 2), ('a', 3), ('d', 4), ('e', 5), ('f', 6)]
        od = OrderedDict(pairs)
        update_test = OrderedDict()
        update_test.update(od)
        for i, dup in enumerate([
                    od.copy(),
                    copy.copy(od),
                    copy.deepcopy(od),
                    pickle.loads(pickle.dumps(od, 0)),
                    pickle.loads(pickle.dumps(od, 1)),
                    pickle.loads(pickle.dumps(od, 2)),
                    pickle.loads(pickle.dumps(od, -1)),
                    eval(repr(od)),
                    update_test,
                    OrderedDict(od),
                    ]):
            self.assertTrue(dup is not od)
            self.assertEqual(dup, od)
            self.assertEqual(list(dup.items()), list(od.items()))
            self.assertEqual(len(dup), len(od))
            self.assertEqual(type(dup), type(od)) 
Example 8
Project: pyblish-win   Author: pyblish   File: test_defaultdict.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def test_copy(self):
        d1 = defaultdict()
        d2 = d1.copy()
        self.assertEqual(type(d2), defaultdict)
        self.assertEqual(d2.default_factory, None)
        self.assertEqual(d2, {})
        d1.default_factory = list
        d3 = d1.copy()
        self.assertEqual(type(d3), defaultdict)
        self.assertEqual(d3.default_factory, list)
        self.assertEqual(d3, {})
        d1[42]
        d4 = d1.copy()
        self.assertEqual(type(d4), defaultdict)
        self.assertEqual(d4.default_factory, list)
        self.assertEqual(d4, {42: []})
        d4[12]
        self.assertEqual(d4, {42: [], 12: []})

        # Issue 6637: Copy fails for empty default dict
        d = defaultdict()
        d['a'] = 42
        e = d.copy()
        self.assertEqual(e['a'], 42) 
Example 9
Project: pyblish-win   Author: pyblish   File: test_weakref.py    GNU Lesser General Public License v3.0 6 votes vote down vote up
def check_weak_destroy_and_mutate_while_iterating(self, dict, testcontext):
        # Check that we can explicitly mutate the weak dict without
        # interfering with delayed removal.
        # `testcontext` should create an iterator, destroy one of the
        # weakref'ed objects and then return a new key/value pair corresponding
        # to the destroyed object.
        with testcontext() as (k, v):
            self.assertFalse(k in dict)
        with testcontext() as (k, v):
            self.assertRaises(KeyError, dict.__delitem__, k)
        self.assertFalse(k in dict)
        with testcontext() as (k, v):
            self.assertRaises(KeyError, dict.pop, k)
        self.assertFalse(k in dict)
        with testcontext() as (k, v):
            dict[k] = v
        self.assertEqual(dict[k], v)
        ddict = copy.copy(dict)
        with testcontext() as (k, v):
            dict.update(ddict)
        self.assertEqual(dict, ddict)
        with testcontext() as (k, v):
            dict.clear()
        self.assertEqual(len(dict), 0) 
Example 10
Project: fs_image   Author: facebookincubator   File: test_extent.py    MIT License 5 votes vote down vote up
def test_copy(self):
        e = Extent.empty().write(offset=5, length=5)
        self.assertIs(e, copy.deepcopy(e))
        self.assertIs(e, copy.copy(e)) 
Example 11
Project: projection-methods   Author: akshayka   File: cartesian_product.py    GNU General Public License v3.0 5 votes vote down vote up
def dual(self, x):
        # TODO(akshayka): assert that x is of the correct size
        cones = []
        for s, slx in zip(self.sets, self.slices):
            cones.append(s.dual(x[slx]))
        return CartesianProduct(x, cones, copy.copy(self.slices)) 
Example 12
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def copy(self, x1=None, x2=None, y1=None, y2=None):
        rect = copy.deepcopy(self)
        if x1 is not None:
            rect.x1 = x1
        if x2 is not None:
            rect.x2 = x2
        if y1 is not None:
            rect.y1 = y1
        if y2 is not None:
            rect.y2 = y2
        return rect 
Example 13
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def draw_on_image(self, img, color=[0, 255, 0], alpha=1.0, thickness=1, copy=copy):
        assert img.dtype in [np.uint8, np.float32, np.int32, np.int64]

        result = np.copy(img) if copy else img
        for i in range(thickness):
            y = [self.y1-i, self.y1-i, self.y2+i, self.y2+i]
            x = [self.x1-i, self.x2+i, self.x2+i, self.x1-i]
            rr, cc = draw.polygon_perimeter(y, x, shape=img.shape)
            if alpha >= 0.99:
                result[rr, cc, 0] = color[0]
                result[rr, cc, 1] = color[1]
                result[rr, cc, 2] = color[2]
            else:
                if result.dtype == np.float32:
                    result[rr, cc, 0] = (1 - alpha) * result[rr, cc, 0] + alpha * color[0]
                    result[rr, cc, 1] = (1 - alpha) * result[rr, cc, 1] + alpha * color[1]
                    result[rr, cc, 2] = (1 - alpha) * result[rr, cc, 2] + alpha * color[2]
                    result = np.clip(result, 0, 255)
                else:
                    result = result.astype(np.float32)
                    result[rr, cc, 0] = (1 - alpha) * result[rr, cc, 0] + alpha * color[0]
                    result[rr, cc, 1] = (1 - alpha) * result[rr, cc, 1] + alpha * color[1]
                    result[rr, cc, 2] = (1 - alpha) * result[rr, cc, 2] + alpha * color[2]
                    result = np.clip(result, 0, 255).astype(np.uint8)

        return result 
Example 14
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def draw_on_image_filled_binary(self, img, copy=True):
        if copy:
            img = np.copy(img)
        h, w = img.shape[0], img.shape[1]
        x1 = np.clip(self.x1, 0, w-1)
        x2 = np.clip(self.x2, 0, w-1)
        y1 = np.clip(self.y1, 0, h-1)
        y2 = np.clip(self.y2, 0, h-1)
        if x1 < x2 and y1 < y2:
            img[self.y1:self.y2, self.x1:self.x2] = 1
        return img 
Example 15
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def copy(self):
        return Rectangle(x1=self.x1, x2=self.x2, y1=self.y1, y2=self.y2)
        #return copy.copy(self) 
Example 16
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def on(self, img):
        shape_new = img if isinstance(img, tuple) else img.shape
        if shape_new == self.shape:
            return self
        else:
            rect_rs = self.rect.resize(self.shape, shape_new)
            return self.copy(rect=rect_rs, shape=shape_new) 
Example 17
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def draw_on_image(self, img, color=[0, 255, 0], alpha=1.0, thickness=1, copy=True, project=True):
        if project:
            return self.on(img).rect.draw_on_image(img, color=color, alpha=alpha, thickness=thickness, copy=copy)
        else:
            return self.rect.draw_on_image(img, color=color, alpha=alpha, thickness=thickness, copy=copy) 
Example 18
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 5 votes vote down vote up
def draw_on_image_filled_binary(self, img, copy=True, project=True):
        if project:
            return self.on(img).rect.draw_on_image_filled_binary(img, copy=copy)
        else:
            return self.rect.draw_on_image_filled_binary(img, copy=copy) 
Example 19
Project: pyblish-win   Author: pyblish   File: cookielib.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __init__(self, version, name, value,
                 port, port_specified,
                 domain, domain_specified, domain_initial_dot,
                 path, path_specified,
                 secure,
                 expires,
                 discard,
                 comment,
                 comment_url,
                 rest,
                 rfc2109=False,
                 ):

        if version is not None: version = int(version)
        if expires is not None: expires = int(expires)
        if port is None and port_specified is True:
            raise ValueError("if port is None, port_specified must be false")

        self.version = version
        self.name = name
        self.value = value
        self.port = port
        self.port_specified = port_specified
        # normalise case, as per RFC 2965 section 3.3.3
        self.domain = domain.lower()
        self.domain_specified = domain_specified
        # Sigh.  We need to know whether the domain given in the
        # cookie-attribute had an initial dot, in order to follow RFC 2965
        # (as clarified in draft errata).  Needed for the returned $Domain
        # value.
        self.domain_initial_dot = domain_initial_dot
        self.path = path
        self.path_specified = path_specified
        self.secure = secure
        self.expires = expires
        self.discard = discard
        self.comment = comment
        self.comment_url = comment_url
        self.rfc2109 = rfc2109

        self._rest = copy.copy(rest) 
Example 20
Project: pyblish-win   Author: pyblish   File: gettext.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def translation(domain, localedir=None, languages=None,
                class_=None, fallback=False, codeset=None):
    if class_ is None:
        class_ = GNUTranslations
    mofiles = find(domain, localedir, languages, all=1)
    if not mofiles:
        if fallback:
            return NullTranslations()
        raise IOError(ENOENT, 'No translation file found for domain', domain)
    # Avoid opening, reading, and parsing the .mo file after it's been done
    # once.
    result = None
    for mofile in mofiles:
        key = (class_, os.path.abspath(mofile))
        t = _translations.get(key)
        if t is None:
            with open(mofile, 'rb') as fp:
                t = _translations.setdefault(key, class_(fp))
        # Copy the translation object to allow setting fallbacks and
        # output charset. All other instance data is shared with the
        # cached object.
        t = copy.copy(t)
        if codeset:
            t.set_output_charset(codeset)
        if result is None:
            result = t
        else:
            result.add_fallback(t)
    return result 
Example 21
Project: pyblish-win   Author: pyblish   File: copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def copy(x):
    """Shallow copy operation on arbitrary Python objects.

    See the module's __doc__ string for more info.
    """

    cls = type(x)

    copier = _copy_dispatch.get(cls)
    if copier:
        return copier(x)

    copier = getattr(cls, "__copy__", None)
    if copier:
        return copier(x)

    reductor = dispatch_table.get(cls)
    if reductor:
        rv = reductor(x)
    else:
        reductor = getattr(x, "__reduce_ex__", None)
        if reductor:
            rv = reductor(2)
        else:
            reductor = getattr(x, "__reduce__", None)
            if reductor:
                rv = reductor()
            else:
                raise Error("un(shallow)copyable object of type %s" % cls)

    return _reconstruct(x, rv, 0) 
Example 22
Project: pyblish-win   Author: pyblish   File: copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _copy_with_copy_method(x):
    return x.copy() 
Example 23
Project: pyblish-win   Author: pyblish   File: argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
        items.append(values)
        setattr(namespace, self.dest, items) 
Example 24
Project: pyblish-win   Author: pyblish   File: argparse.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def __call__(self, parser, namespace, values, option_string=None):
        items = _copy.copy(_ensure_value(namespace, self.dest, []))
        items.append(self.const)
        setattr(namespace, self.dest, items) 
Example 25
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def copyfileobj(src, dst, length=None):
    """Copy length bytes from fileobj src to fileobj dst.
       If length is None, copy the entire content.
    """
    if length == 0:
        return
    if length is None:
        shutil.copyfileobj(src, dst)
        return

    BUFSIZE = 16 * 1024
    blocks, remainder = divmod(length, BUFSIZE)
    for b in xrange(blocks):
        buf = src.read(BUFSIZE)
        if len(buf) < BUFSIZE:
            raise IOError("end of file reached")
        dst.write(buf)

    if remainder != 0:
        buf = src.read(remainder)
        if len(buf) < remainder:
            raise IOError("end of file reached")
        dst.write(buf)
    return 
Example 26
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def addfile(self, tarinfo, fileobj=None):
        """Add the TarInfo object `tarinfo' to the archive. If `fileobj' is
           given, tarinfo.size bytes are read from it and added to the archive.
           You can create TarInfo objects using gettarinfo().
           On Windows platforms, `fileobj' should always be opened with mode
           'rb' to avoid irritation about the file size.
        """
        self._check("aw")

        tarinfo = copy.copy(tarinfo)

        buf = tarinfo.tobuf(self.format, self.encoding, self.errors)
        self.fileobj.write(buf)
        self.offset += len(buf)

        # If there's data to follow, append it.
        if fileobj is not None:
            copyfileobj(fileobj, self.fileobj, tarinfo.size)
            blocks, remainder = divmod(tarinfo.size, BLOCKSIZE)
            if remainder > 0:
                self.fileobj.write(NUL * (BLOCKSIZE - remainder))
                blocks += 1
            self.offset += blocks * BLOCKSIZE

        self.members.append(tarinfo) 
Example 27
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def extractall(self, path=".", members=None):
        """Extract all members from the archive to the current working
           directory and set owner, modification time and permissions on
           directories afterwards. `path' specifies a different directory
           to extract to. `members' is optional and must be a subset of the
           list returned by getmembers().
        """
        directories = []

        if members is None:
            members = self

        for tarinfo in members:
            if tarinfo.isdir():
                # Extract directories with a safe mode.
                directories.append(tarinfo)
                tarinfo = copy.copy(tarinfo)
                tarinfo.mode = 0700
            self.extract(tarinfo, path)

        # Reverse sort directories.
        directories.sort(key=operator.attrgetter('name'))
        directories.reverse()

        # Set correct owner, mtime and filemode on directories.
        for tarinfo in directories:
            dirpath = os.path.join(path, tarinfo.name)
            try:
                self.chown(tarinfo, dirpath)
                self.utime(tarinfo, dirpath)
                self.chmod(tarinfo, dirpath)
            except ExtractError, e:
                if self.errorlevel > 1:
                    raise
                else:
                    self._dbg(1, "tarfile: %s" % e) 
Example 28
Project: pyblish-win   Author: pyblish   File: UserDict.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def copy(self):
        if self.__class__ is UserDict:
            return UserDict(self.data.copy())
        import copy
        data = self.data
        try:
            self.data = {}
            c = copy.copy(self)
        finally:
            self.data = data
        c.update(self)
        return c 
Example 29
Project: pyblish-win   Author: pyblish   File: xmlbuilder.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def parse(self, input):
        options = copy.copy(self._options)
        options.filter = self.filter
        options.errorHandler = self.errorHandler
        fp = input.byteStream
        if fp is None and options.systemId:
            import urllib2
            fp = urllib2.urlopen(input.systemId)
        return self._parse_bytestream(fp, options) 
Example 30
Project: pyblish-win   Author: pyblish   File: webbrowser.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _synthesize(browser, update_tryorder=1):
    """Attempt to synthesize a controller base on existing controllers.

    This is useful to create a controller when a user specifies a path to
    an entry in the BROWSER environment variable -- we can copy a general
    controller to operate using a specific installation of the desired
    browser in this way.

    If we can't create a controller in this way, or if there is no
    executable for the requested browser, return [None, None].

    """
    cmd = browser.split()[0]
    if not _iscommand(cmd):
        return [None, None]
    name = os.path.basename(cmd)
    try:
        command = _browsers[name.lower()]
    except KeyError:
        return [None, None]
    # now attempt to clone to fit the new name:
    controller = command[1]
    if controller and name.lower() == controller.basename:
        import copy
        controller = copy.copy(controller)
        controller.name = browser
        controller.basename = os.path.basename(browser)
        register(browser, None, controller, update_tryorder)
        return [None, controller]
    return [None, None] 
Example 31
Project: pyblish-win   Author: pyblish   File: test_fractions.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_deepcopy_pickle(self):
        r = F(13, 7)
        dr = DummyFraction(13, 7)
        self.assertEqual(r, loads(dumps(r)))
        self.assertEqual(id(r), id(copy(r)))
        self.assertEqual(id(r), id(deepcopy(r)))
        self.assertNotEqual(id(dr), id(copy(dr)))
        self.assertNotEqual(id(dr), id(deepcopy(dr)))
        self.assertTypedEquals(dr, copy(dr))
        self.assertTypedEquals(dr, deepcopy(dr)) 
Example 32
Project: pyblish-win   Author: pyblish   File: test_coercion.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_infix_binops(self):
        for ia, a in enumerate(candidates):
            for ib, b in enumerate(candidates):
                results = infix_results[(ia, ib)]
                for op, res, ires in zip(infix_binops, results[0], results[1]):
                    if res is TE:
                        self.assertRaises(TypeError, eval,
                                          'a %s b' % op, {'a': a, 'b': b})
                    else:
                        self.assertEqual(format_result(res),
                                         format_result(eval('a %s b' % op)),
                                         '%s %s %s == %s failed' % (a, op, b, res))
                    try:
                        z = copy.copy(a)
                    except copy.Error:
                        z = a # assume it has no inplace ops
                    if ires is TE:
                        try:
                            exec 'z %s= b' % op
                        except TypeError:
                            pass
                        else:
                            self.fail("TypeError not raised")
                    else:
                        exec('z %s= b' % op)
                        self.assertEqual(ires, z) 
Example 33
Project: pyblish-win   Author: pyblish   File: test_bytes.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copied(self):
        # Issue 4348.  Make sure that operations that don't mutate the array
        # copy the bytes.
        b = bytearray(b'abc')
        self.assertFalse(b is b.replace(b'abc', b'cde', 0))

        t = bytearray([i for i in range(256)])
        x = bytearray(b'')
        self.assertFalse(x is x.translate(t)) 
Example 34
Project: pyblish-win   Author: pyblish   File: test_bytes.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy(self):
        a = ByteArraySubclass(b"abcd")
        a.x = 10
        a.y = ByteArraySubclass(b"efgh")
        for copy_method in (copy.copy, copy.deepcopy):
            b = copy_method(a)
            self.assertNotEqual(id(a), id(b))
            self.assertEqual(a, b)
            self.assertEqual(a.x, b.x)
            self.assertEqual(a.y, b.y)
            self.assertEqual(type(a), type(b))
            self.assertEqual(type(a.y), type(b.y)) 
Example 35
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy(self):
        p = TestNT(x=10, y=20, z=30)
        for copier in copy.copy, copy.deepcopy:
            q = copier(p)
            self.assertEqual(p, q)
            self.assertEqual(p._fields, q._fields) 
Example 36
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copying(self):
        # Check that counters are copyable, deepcopyable, picklable, and
        #have a repr/eval round-trip
        words = Counter('which witch had which witches wrist watch'.split())
        update_test = Counter()
        update_test.update(words)
        for i, dup in enumerate([
                    words.copy(),
                    copy.copy(words),
                    copy.deepcopy(words),
                    pickle.loads(pickle.dumps(words, 0)),
                    pickle.loads(pickle.dumps(words, 1)),
                    pickle.loads(pickle.dumps(words, 2)),
                    pickle.loads(pickle.dumps(words, -1)),
                    cPickle.loads(cPickle.dumps(words, 0)),
                    cPickle.loads(cPickle.dumps(words, 1)),
                    cPickle.loads(cPickle.dumps(words, 2)),
                    cPickle.loads(cPickle.dumps(words, -1)),
                    eval(repr(words)),
                    update_test,
                    Counter(words),
                    ]):
            msg = (i, dup, words)
            self.assertTrue(dup is not words)
            self.assertEqual(dup, words)
            self.assertEqual(len(dup), len(words))
            self.assertEqual(type(dup), type(words)) 
Example 37
Project: pyblish-win   Author: pyblish   File: test_collections.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_subclass(self):
        class MyCounter(Counter):
            pass
        c = MyCounter('slartibartfast')
        d = c.copy()
        self.assertEqual(d, c)
        self.assertEqual(len(d), len(c))
        self.assertEqual(type(d), type(c)) 
Example 38
Project: pyblish-win   Author: pyblish   File: test_defaultdict.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_shallow_copy(self):
        d1 = defaultdict(foobar, {1: 1})
        d2 = copy.copy(d1)
        self.assertEqual(d2.default_factory, foobar)
        self.assertEqual(d2, d1)
        d1.default_factory = list
        d2 = copy.copy(d1)
        self.assertEqual(d2.default_factory, list)
        self.assertEqual(d2, d1) 
Example 39
Project: pyblish-win   Author: pyblish   File: test_defaultdict.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deep_copy(self):
        d1 = defaultdict(foobar, {1: [1]})
        d2 = copy.deepcopy(d1)
        self.assertEqual(d2.default_factory, foobar)
        self.assertEqual(d2, d1)
        self.assertTrue(d1[1] is not d2[1])
        d1.default_factory = list
        d2 = copy.deepcopy(d1)
        self.assertEqual(d2.default_factory, list)
        self.assertEqual(d2, d1) 
Example 40
Project: pyblish-win   Author: pyblish   File: test_itertools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_count(self):
        self.assertEqual(zip('abc',count()), [('a', 0), ('b', 1), ('c', 2)])
        self.assertEqual(zip('abc',count(3)), [('a', 3), ('b', 4), ('c', 5)])
        self.assertEqual(take(2, zip('abc',count(3))), [('a', 3), ('b', 4)])
        self.assertEqual(take(2, zip('abc',count(-1))), [('a', -1), ('b', 0)])
        self.assertEqual(take(2, zip('abc',count(-3))), [('a', -3), ('b', -2)])
        self.assertRaises(TypeError, count, 2, 3, 4)
        self.assertRaises(TypeError, count, 'a')
        self.assertEqual(list(islice(count(maxsize-5), 10)), range(maxsize-5, maxsize+5))
        self.assertEqual(list(islice(count(-maxsize-5), 10)), range(-maxsize-5, -maxsize+5))
        c = count(3)
        self.assertEqual(repr(c), 'count(3)')
        c.next()
        self.assertEqual(repr(c), 'count(4)')
        c = count(-9)
        self.assertEqual(repr(c), 'count(-9)')
        c.next()
        self.assertEqual(repr(count(10.25)), 'count(10.25)')
        self.assertEqual(c.next(), -8)
        for i in (-sys.maxint-5, -sys.maxint+5 ,-10, -1, 0, 10, sys.maxint-5, sys.maxint+5):
            # Test repr (ignoring the L in longs)
            r1 = repr(count(i)).replace('L', '')
            r2 = 'count(%r)'.__mod__(i).replace('L', '')
            self.assertEqual(r1, r2)

        # check copy, deepcopy, pickle
        for value in -3, 3, sys.maxint-5, sys.maxint+5:
            c = count(value)
            self.assertEqual(next(copy.copy(c)), value)
            self.assertEqual(next(copy.deepcopy(c)), value)
            self.assertEqual(next(pickle.loads(pickle.dumps(c))), value) 
Example 41
Project: pyblish-win   Author: pyblish   File: test_itertools.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_sf_793826(self):
        # Fix Armin Rigo's successful efforts to wreak havoc

        def mutatingtuple(tuple1, f, tuple2):
            # this builds a tuple t which is a copy of tuple1,
            # then calls f(t), then mutates t to be equal to tuple2
            # (needs len(tuple1) == len(tuple2)).
            def g(value, first=[1]):
                if first:
                    del first[:]
                    f(z.next())
                return value
            items = list(tuple2)
            items[1:1] = list(tuple1)
            gen = imap(g, items)
            z = izip(*[gen]*len(tuple1))
            z.next()

        def f(t):
            global T
            T = t
            first[:] = list(T)

        first = []
        mutatingtuple((1,2,3), f, (4,5,6))
        second = list(T)
        self.assertEqual(first, second) 
Example 42
Project: pyblish-win   Author: pyblish   File: test_weakref.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_weak_keys(self):
        #
        #  This exercises d.copy(), d.items(), d[] = v, d[], del d[],
        #  len(d), in d.
        #
        dict, objects = self.make_weak_keyed_dict()
        for o in objects:
            self.assertEqual(weakref.getweakrefcount(o), 1,
                         "wrong number of weak references to %r!" % o)
            self.assertIs(o.arg, dict[o],
                         "wrong object returned by weak dict!")
        items1 = dict.items()
        items2 = dict.copy().items()
        self.assertEqual(set(items1), set(items2),
                     "cloning of weak-keyed dictionary did not work!")
        del items1, items2
        self.assertEqual(len(dict), self.COUNT)
        del objects[0]
        self.assertEqual(len(dict), (self.COUNT - 1),
                     "deleting object did not cause dictionary update")
        del objects, o
        self.assertEqual(len(dict), 0,
                     "deleting the keys did not clear the dictionary")
        o = Object(42)
        dict[o] = "What is the meaning of the universe?"
        self.assertIn(o, dict)
        self.assertNotIn(34, dict) 
Example 43
Project: pyblish-win   Author: pyblish   File: test_weakref.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _reference(self):
        return self.__ref.copy() 
Example 44
Project: pyblish-win   Author: pyblish   File: test_weakref.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def _reference(self):
        return self.__ref.copy() 
Example 45
Project: pyblish-win   Author: pyblish   File: test_deque.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy(self):
        mut = [10]
        d = deque([mut])
        e = copy.deepcopy(d)
        self.assertEqual(list(d), list(e))
        mut[0] = 11
        self.assertNotEqual(id(d), id(e))
        self.assertNotEqual(list(d), list(e)) 
Example 46
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy(self):
        import copy
        a = array.array(self.typecode, self.example)
        b = copy.copy(a)
        self.assertNotEqual(id(a), id(b))
        self.assertEqual(a, b) 
Example 47
Project: pyblish-win   Author: pyblish   File: test_array.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy(self):
        import copy
        a = array.array(self.typecode, self.example)
        b = copy.deepcopy(a)
        self.assertNotEqual(id(a), id(b))
        self.assertEqual(a, b) 
Example 48
Project: pyblish-win   Author: pyblish   File: test_copy_reg.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_bool(self):
        import copy
        self.assertEqual(True, copy.copy(True)) 
Example 49
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def init():
    global ORIGINAL_CONTEXT
    ORIGINAL_CONTEXT = getcontext().copy()
    DefaultTestContext = Context(
        prec = 9,
        rounding = ROUND_HALF_EVEN,
        traps = dict.fromkeys(Signals, 0)
        )
    setcontext(DefaultTestContext)

# decorator for skipping tests on non-IEEE 754 platforms 
Example 50
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy(self):
        # All copies should be deep
        c = Context()
        d = c.copy()
        self.assertNotEqual(id(c), id(d))
        self.assertNotEqual(id(c.flags), id(d.flags))
        self.assertNotEqual(id(c.traps), id(d.traps)) 
Example 51
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_localcontext(self):
        # Use a copy of the current context in the block
        orig_ctx = getcontext()
        with localcontext() as enter_ctx:
            set_ctx = getcontext()
        final_ctx = getcontext()
        self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly')
        self.assertIsNot(orig_ctx, set_ctx, 'did not copy the context')
        self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context') 
Example 52
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_localcontextarg(self):
        # Use a copy of the supplied context in the block
        orig_ctx = getcontext()
        new_ctx = Context(prec=42)
        with localcontext(new_ctx) as enter_ctx:
            set_ctx = getcontext()
        final_ctx = getcontext()
        self.assertIs(orig_ctx, final_ctx, 'did not restore context correctly')
        self.assertEqual(set_ctx.prec, new_ctx.prec, 'did not set correct context')
        self.assertIsNot(new_ctx, set_ctx, 'did not copy the context')
        self.assertIs(set_ctx, enter_ctx, '__enter__ returned wrong context') 
Example 53
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_exceptions(self):
        self.assertTrue(copy.Error is copy.error)
        self.assertTrue(issubclass(copy.Error, Exception))

    # The copy() method 
Example 54
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_basic(self):
        x = 42
        y = copy.copy(x)
        self.assertEqual(x, y) 
Example 55
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_registry(self):
        class C(object):
            def __new__(cls, foo):
                obj = object.__new__(cls)
                obj.foo = foo
                return obj
        def pickle_C(obj):
            return (C, (obj.foo,))
        x = C(42)
        self.assertRaises(TypeError, copy.copy, x)
        copy_reg.pickle(C, pickle_C, C)
        y = copy.copy(x) 
Example 56
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_reduce_ex(self):
        class C(object):
            def __reduce_ex__(self, proto):
                return ""
            def __reduce__(self):
                raise test_support.TestFailed, "shouldn't call this"
        x = C()
        y = copy.copy(x)
        self.assertTrue(y is x) 
Example 57
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_reduce(self):
        class C(object):
            def __reduce__(self):
                return ""
        x = C()
        y = copy.copy(x)
        self.assertTrue(y is x) 
Example 58
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_cant(self):
        class C(object):
            def __getattribute__(self, name):
                if name.startswith("__reduce"):
                    raise AttributeError, name
                return object.__getattribute__(self, name)
        x = C()
        self.assertRaises(copy.Error, copy.copy, x)

    # Type-specific _copy_xxx() methods 
Example 59
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_atomic(self):
        class Classic:
            pass
        class NewStyle(object):
            pass
        def f():
            pass
        tests = [None, 42, 2L**100, 3.14, True, False, 1j,
                 "hello", u"hello\u1234", f.func_code,
                 NewStyle, xrange(10), Classic, max]
        for x in tests:
            self.assertTrue(copy.copy(x) is x, repr(x)) 
Example 60
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_tuple(self):
        x = (1, 2, 3)
        self.assertEqual(copy.copy(x), x) 
Example 61
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_dict(self):
        x = {"foo": 1, "bar": 2}
        self.assertEqual(copy.copy(x), x) 
Example 62
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_inst_vanilla(self):
        class C:
            def __init__(self, foo):
                self.foo = foo
            def __cmp__(self, other):
                return cmp(self.foo, other.foo)
        x = C(42)
        self.assertEqual(copy.copy(x), x) 
Example 63
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_inst_copy(self):
        class C:
            def __init__(self, foo):
                self.foo = foo
            def __copy__(self):
                return C(self.foo)
            def __cmp__(self, other):
                return cmp(self.foo, other.foo)
        x = C(42)
        self.assertEqual(copy.copy(x), x) 
Example 64
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_inst_getinitargs(self):
        class C:
            def __init__(self, foo):
                self.foo = foo
            def __getinitargs__(self):
                return (self.foo,)
            def __cmp__(self, other):
                return cmp(self.foo, other.foo)
        x = C(42)
        self.assertEqual(copy.copy(x), x) 
Example 65
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_inst_setstate(self):
        class C:
            def __init__(self, foo):
                self.foo = foo
            def __setstate__(self, state):
                self.foo = state["foo"]
            def __cmp__(self, other):
                return cmp(self.foo, other.foo)
        x = C(42)
        self.assertEqual(copy.copy(x), x) 
Example 66
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_copy_inst_getstate_setstate(self):
        class C:
            def __init__(self, foo):
                self.foo = foo
            def __getstate__(self):
                return self.foo
            def __setstate__(self, state):
                self.foo = state
            def __cmp__(self, other):
                return cmp(self.foo, other.foo)
        x = C(42)
        self.assertEqual(copy.copy(x), x)

    # The deepcopy() method 
Example 67
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_basic(self):
        x = 42
        y = copy.deepcopy(x)
        self.assertEqual(y, x) 
Example 68
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_memo(self):
        # Tests of reflexive objects are under type-specific sections below.
        # This tests only repetitions of objects.
        x = []
        x = [x, x]
        y = copy.deepcopy(x)
        self.assertEqual(y, x)
        self.assertTrue(y is not x)
        self.assertTrue(y[0] is not x[0])
        self.assertTrue(y[0] is y[1]) 
Example 69
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_issubclass(self):
        # XXX Note: there's no way to test the TypeError coming out of
        # issubclass() -- this can only happen when an extension
        # module defines a "type" that doesn't formally inherit from
        # type.
        class Meta(type):
            pass
        class C:
            __metaclass__ = Meta
        self.assertEqual(copy.deepcopy(C), C) 
Example 70
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_registry(self):
        class C(object):
            def __new__(cls, foo):
                obj = object.__new__(cls)
                obj.foo = foo
                return obj
        def pickle_C(obj):
            return (C, (obj.foo,))
        x = C(42)
        self.assertRaises(TypeError, copy.deepcopy, x)
        copy_reg.pickle(C, pickle_C, C)
        y = copy.deepcopy(x) 
Example 71
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_reduce_ex(self):
        class C(object):
            def __reduce_ex__(self, proto):
                return ""
            def __reduce__(self):
                raise test_support.TestFailed, "shouldn't call this"
        x = C()
        y = copy.deepcopy(x)
        self.assertTrue(y is x) 
Example 72
Project: pyblish-win   Author: pyblish   File: test_copy.py    GNU Lesser General Public License v3.0 5 votes vote down vote up
def test_deepcopy_reduce(self):
        class C(object):
            def __reduce__(self):
                return ""
        x = C()
        y = copy.deepcopy(x)
        self.assertTrue(y is x) 
Example 73
Project: cat-bbs   Author: aleju   File: bbs.py    MIT License 4 votes vote down vote up
def copy(self, rect=None, x1=None, x2=None, y1=None, y2=None, shape=None, class_label=None, score=None):
        """
        rectimg = copy.deepcopy(self)
        if rect is not None:
            rectimg.rect = rect
        if x1 is not None:
            rectimg.x1 = x1
        if x2 is not None:
            rectimg.x2 = x2
        if y1 is not None:
            rectimg.y1 = y1
        if y2 is not None:
            rectimg.y2 = y2
        if shape is not None:
            assert isinstance(shape, tuple)
            rectimg.shape = shape
        if class_label is not None:
            rectimg.class_label = class_label
        if score is not None:
            rectimg.score = score
        #return self.copy_with_new_rect(self.rect.copy())
        """

        # neue variante hier weil deepcopy wohl sehr langsam ist(?)
        if rect is None:
            rectimg = RectangleOnImage(
                x1=self.rect.x1 if x1 is None else x1,
                x2=self.rect.x2 if x2 is None else x2,
                y1=self.rect.y1 if y1 is None else y1,
                y2=self.rect.y2 if y2 is None else y2,
                shape=tuple(self.shape) if shape is None else shape,
                class_label=self.class_label if class_label is None else class_label,
                score=self.score if score is None else score
            )
        else:
            assert x1 is None
            assert x2 is None
            assert y1 is None
            assert y2 is None
            rectimg = RectangleOnImage(
                x1=rect.x1,
                x2=rect.x2,
                y1=rect.y1,
                y2=rect.y2,
                shape=tuple(self.shape) if shape is None else shape,
                class_label=self.class_label if class_label is None else class_label,
                score=self.score if score is None else score
            )

        return rectimg 
Example 74
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def create_pax_header(self, info, encoding, errors):
        """Return the object as a ustar header block. If it cannot be
           represented this way, prepend a pax extended header sequence
           with supplement information.
        """
        info["magic"] = POSIX_MAGIC
        pax_headers = self.pax_headers.copy()

        # Test string fields for values that exceed the field length or cannot
        # be represented in ASCII encoding.
        for name, hname, length in (
                ("name", "path", LENGTH_NAME), ("linkname", "linkpath", LENGTH_LINK),
                ("uname", "uname", 32), ("gname", "gname", 32)):

            if hname in pax_headers:
                # The pax header has priority.
                continue

            val = info[name].decode(encoding, errors)

            # Try to encode the string as ASCII.
            try:
                val.encode("ascii")
            except UnicodeEncodeError:
                pax_headers[hname] = val
                continue

            if len(info[name]) > length:
                pax_headers[hname] = val

        # Test number fields for values that exceed the field limit or values
        # that like to be stored as float.
        for name, digits in (("uid", 8), ("gid", 8), ("size", 12), ("mtime", 12)):
            if name in pax_headers:
                # The pax header has priority. Avoid overflow.
                info[name] = 0
                continue

            val = info[name]
            if not 0 <= val < 8 ** (digits - 1) or isinstance(val, float):
                pax_headers[name] = unicode(val)
                info[name] = 0

        # Create a pax extended header if necessary.
        if pax_headers:
            buf = self._create_pax_generic_header(pax_headers)
        else:
            buf = ""

        return buf + self._create_header(info, USTAR_FORMAT) 
Example 75
Project: pyblish-win   Author: pyblish   File: tarfile.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def _proc_pax(self, tarfile):
        """Process an extended or global header as described in
           POSIX.1-2001.
        """
        # Read the header information.
        buf = tarfile.fileobj.read(self._block(self.size))

        # A pax header stores supplemental information for either
        # the following file (extended) or all following files
        # (global).
        if self.type == XGLTYPE:
            pax_headers = tarfile.pax_headers
        else:
            pax_headers = tarfile.pax_headers.copy()

        # Parse pax header information. A record looks like that:
        # "%d %s=%s\n" % (length, keyword, value). length is the size
        # of the complete record including the length field itself and
        # the newline. keyword and value are both UTF-8 encoded strings.
        regex = re.compile(r"(\d+) ([^=]+)=", re.U)
        pos = 0
        while True:
            match = regex.match(buf, pos)
            if not match:
                break

            length, keyword = match.groups()
            length = int(length)
            value = buf[match.end(2) + 1:match.start(1) + length - 1]

            keyword = keyword.decode("utf8")
            value = value.decode("utf8")

            pax_headers[keyword] = value
            pos += length

        # Fetch the next header.
        try:
            next = self.fromtarfile(tarfile)
        except HeaderError:
            raise SubsequentHeaderError("missing or bad subsequent header")

        if self.type in (XHDTYPE, SOLARIS_XHDTYPE):
            # Patch the TarInfo object with the extended header info.
            next._apply_pax_info(pax_headers, tarfile.encoding, tarfile.errors)
            next.offset = self.offset

            if "size" in pax_headers:
                # If the extended header replaces the size field,
                # we need to recalculate the offset where the next
                # header starts.
                offset = next.offset_data
                if next.isreg() or next.type not in SUPPORTED_TYPES:
                    offset += next._block(next.size)
                tarfile.offset = offset

        return next 
Example 76
Project: pyblish-win   Author: pyblish   File: dbtables.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def CreateOrExtendTable(self, table, columns):
        """CreateOrExtendTable(table, columns)

        Create a new table in the database.

        If a table of this name already exists, extend it to have any
        additional columns present in the given list as well as
        all of its current columns.
        """
        assert isinstance(columns, list)

        try:
            self.CreateTable(table, columns)
        except TableAlreadyExists:
            # the table already existed, add any new columns
            txn = None
            try:
                columnlist_key = _columns_key(table)
                txn = self.env.txn_begin()

                # load the current column list
                oldcolumnlist = pickle.loads(
                    getattr(self.db, "get_bytes",
                        self.db.get)(columnlist_key, txn=txn, flags=db.DB_RMW))
                # create a hash table for fast lookups of column names in the
                # loop below
                oldcolumnhash = {}
                for c in oldcolumnlist:
                    oldcolumnhash[c] = c

                # create a new column list containing both the old and new
                # column names
                newcolumnlist = copy.copy(oldcolumnlist)
                for c in columns:
                    if not c in oldcolumnhash:
                        newcolumnlist.append(c)

                # store the table's new extended column list
                if newcolumnlist != oldcolumnlist :
                    # delete the old one first since we opened with DB_DUP
                    self.db.delete(columnlist_key, txn=txn)
                    getattr(self.db, "put_bytes", self.db.put)(columnlist_key,
                                pickle.dumps(newcolumnlist, 1),
                                txn=txn)

                txn.commit()
                txn = None

                self.__load_column_info(table)
            except db.DBError, dberror:
                if txn:
                    txn.abort()
                if sys.version_info < (2, 6) :
                    raise TableDBError, dberror[1]
                else :
                    raise TableDBError, dberror.args[1] 
Example 77
Project: pyblish-win   Author: pyblish   File: test_sysconfig.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_platform_in_subprocess(self):
        my_platform = sysconfig.get_platform()

        # Test without MACOSX_DEPLOYMENT_TARGET in the environment

        env = os.environ.copy()
        if 'MACOSX_DEPLOYMENT_TARGET' in env:
            del env['MACOSX_DEPLOYMENT_TARGET']

        with open('/dev/null', 'w') as devnull_fp:
            p = subprocess.Popen([
                    sys.executable, '-c',
                   'import sysconfig; print(sysconfig.get_platform())',
                ],
                stdout=subprocess.PIPE,
                stderr=devnull_fp,
                env=env)
        test_platform = p.communicate()[0].strip()
        test_platform = test_platform.decode('utf-8')
        status = p.wait()

        self.assertEqual(status, 0)
        self.assertEqual(my_platform, test_platform)


        # Test with MACOSX_DEPLOYMENT_TARGET in the environment, and
        # using a value that is unlikely to be the default one.
        env = os.environ.copy()
        env['MACOSX_DEPLOYMENT_TARGET'] = '10.1'

        p = subprocess.Popen([
                sys.executable, '-c',
                'import sysconfig; print(sysconfig.get_platform())',
            ],
            stdout=subprocess.PIPE,
            stderr=open('/dev/null'),
            env=env)
        test_platform = p.communicate()[0].strip()
        test_platform = test_platform.decode('utf-8')
        status = p.wait()

        self.assertEqual(status, 0)
        self.assertEqual(my_platform, test_platform) 
Example 78
Project: pyblish-win   Author: pyblish   File: test_descr.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_spam_lists(self):
        # Testing spamlist operations...
        import copy, xxsubtype as spam

        def spamlist(l, memo=None):
            import xxsubtype as spam
            return spam.spamlist(l)

        # This is an ugly hack:
        copy._deepcopy_dispatch[spam.spamlist] = spamlist

        self.binop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+b",
                       "__add__")
        self.binop_test(spamlist([1,2,3]), 2, 1, "b in a", "__contains__")
        self.binop_test(spamlist([1,2,3]), 4, 0, "b in a", "__contains__")
        self.binop_test(spamlist([1,2,3]), 1, 2, "a[b]", "__getitem__")
        self.ternop_test(spamlist([1,2,3]), 0, 2, spamlist([1,2]), "a[b:c]",
                        "__getslice__")
        self.setop_test(spamlist([1]), spamlist([2]), spamlist([1,2]), "a+=b",
                       "__iadd__")
        self.setop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*=b",
                       "__imul__")
        self.unop_test(spamlist([1,2,3]), 3, "len(a)", "__len__")
        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "a*b",
                       "__mul__")
        self.binop_test(spamlist([1,2]), 3, spamlist([1,2,1,2,1,2]), "b*a",
                       "__rmul__")
        self.set2op_test(spamlist([1,2]), 1, 3, spamlist([1,3]), "a[b]=c",
                        "__setitem__")
        self.set3op_test(spamlist([1,2,3,4]), 1, 3, spamlist([5,6]),
                   spamlist([1,5,6,4]), "a[b:c]=d", "__setslice__")
        # Test subclassing
        class C(spam.spamlist):
            def foo(self): return 1
        a = C()
        self.assertEqual(a, [])
        self.assertEqual(a.foo(), 1)
        a.append(100)
        self.assertEqual(a, [100])
        self.assertEqual(a.getstate(), 0)
        a.setstate(42)
        self.assertEqual(a.getstate(), 42) 
Example 79
Project: pyblish-win   Author: pyblish   File: test_descr.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_spam_dicts(self):
        # Testing spamdict operations...
        import copy, xxsubtype as spam
        def spamdict(d, memo=None):
            import xxsubtype as spam
            sd = spam.spamdict()
            for k, v in d.items():
                sd[k] = v
            return sd
        # This is an ugly hack:
        copy._deepcopy_dispatch[spam.spamdict] = spamdict

        self.binop_test(spamdict({1:2}), spamdict({2:1}), -1, "cmp(a,b)",
                       "__cmp__")
        self.binop_test(spamdict({1:2,3:4}), 1, 1, "b in a", "__contains__")
        self.binop_test(spamdict({1:2,3:4}), 2, 0, "b in a", "__contains__")
        self.binop_test(spamdict({1:2,3:4}), 1, 2, "a[b]", "__getitem__")
        d = spamdict({1:2,3:4})
        l1 = []
        for i in d.keys():
            l1.append(i)
        l = []
        for i in iter(d):
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in d.__iter__():
            l.append(i)
        self.assertEqual(l, l1)
        l = []
        for i in type(spamdict({})).__iter__(d):
            l.append(i)
        self.assertEqual(l, l1)
        straightd = {1:2, 3:4}
        spamd = spamdict(straightd)
        self.unop_test(spamd, 2, "len(a)", "__len__")
        self.unop_test(spamd, repr(straightd), "repr(a)", "__repr__")
        self.set2op_test(spamdict({1:2,3:4}), 2, 3, spamdict({1:2,2:3,3:4}),
                   "a[b]=c", "__setitem__")
        # Test subclassing
        class C(spam.spamdict):
            def foo(self): return 1
        a = C()
        self.assertEqual(a.items(), [])
        self.assertEqual(a.foo(), 1)
        a['foo'] = 'bar'
        self.assertEqual(a.items(), [('foo', 'bar')])
        self.assertEqual(a.getstate(), 0)
        a.setstate(100)
        self.assertEqual(a.getstate(), 100) 
Example 80
Project: pyblish-win   Author: pyblish   File: test_decimal.py    GNU Lesser General Public License v3.0 4 votes vote down vote up
def test_explicit_context_create_decimal(self):

        nc = copy.copy(getcontext())
        nc.prec = 3

        # empty
        d = Decimal()
        self.assertEqual(str(d), '0')
        d = nc.create_decimal()
        self.assertEqual(str(d), '0')

        # from None
        self.assertRaises(TypeError, nc.create_decimal, None)

        # from int
        d = nc.create_decimal(456)
        self.assertIsInstance(d, Decimal)
        self.assertEqual(nc.create_decimal(45678),
                         nc.create_decimal('457E+2'))

        # from string
        d = Decimal('456789')
        self.assertEqual(str(d), '456789')
        d = nc.create_decimal('456789')
        self.assertEqual(str(d), '4.57E+5')
        # leading and trailing whitespace should result in a NaN;
        # spaces are already checked in Cowlishaw's test-suite, so
        # here we just check that a trailing newline results in a NaN
        self.assertEqual(str(nc.create_decimal('3.14\n')), 'NaN')

        # from tuples
        d = Decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
        self.assertEqual(str(d), '-4.34913534E-17')
        d = nc.create_decimal( (1, (4, 3, 4, 9, 1, 3, 5, 3, 4), -25) )
        self.assertEqual(str(d), '-4.35E-17')

        # from Decimal
        prevdec = Decimal(500000123)
        d = Decimal(prevdec)
        self.assertEqual(str(d), '500000123')
        d = nc.create_decimal(prevdec)
        self.assertEqual(str(d), '5.00E+8')