python类copy()的实例源码

io_helpers.py 文件源码 项目:core-framework 作者: RedhawkSDR 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def sri(self):
        if self._sri != None:
            return _copy.copy(self._sri)
        else:
            # make a default sri from the current state
            keywords = []
            try:
                for key in self._SRIKeywords:
                    keywords.append(_CF.DataType(key._name, _getAnyValue(key)))
            except:
                pass
            candidateSri = _BULKIO.StreamSRI(1, 0.0, 1, 0, self._subsize, 0.0, 0, 0, 0,
                                             "defaultStreamID", self._blocking, keywords)
            if self._sampleRate > 0.0:
                candidateSri.xdelta = 1.0/float(self._sampleRate)

            if self._complexData and self._complexData == True:
                candidateSri.mode = 1

            if self._startTime >= 0.0:
                candidateSri.xstart = self._startTime
            return candidateSri
tf_util.py 文件源码 项目:distributional_perspective_on_RL 作者: Kiwoo 项目源码 文件源码 阅读 30 收藏 0 点赞 0 评论 0
def switch(condition, then_expression, else_expression):
    '''Switches between two operations depending on a scalar value (int or bool).
    Note that both `then_expression` and `else_expression`
    should be symbolic tensors of the *same shape*.

    # Arguments
        condition: scalar tensor.
        then_expression: TensorFlow operation.
        else_expression: TensorFlow operation.
    '''
    x_shape = copy.copy(then_expression.get_shape())
    x = tf.cond(tf.cast(condition, 'bool'),
                lambda: then_expression,
                lambda: else_expression)
    x.set_shape(x_shape)
    return x

# Extras
algorithm.py 文件源码 项目:zipline-chinese 作者: zhanghan1990 项目源码 文件源码 阅读 35 收藏 0 点赞 0 评论 0
def __repr__(self):
        """
        N.B. this does not yet represent a string that can be used
        to instantiate an exact copy of an algorithm.

        However, it is getting close, and provides some value as something
        that can be inspected interactively.
        """
        return """
{class_name}(
    capital_base={capital_base}
    sim_params={sim_params},
    initialized={initialized},
    slippage={slippage},
    commission={commission},
    blotter={blotter},
    recorded_vars={recorded_vars})
""".strip().format(class_name=self.__class__.__name__,
                   capital_base=self.capital_base,
                   sim_params=repr(self.sim_params),
                   initialized=self.initialized,
                   slippage=repr(self.slippage),
                   commission=repr(self.commission),
                   blotter=repr(self.blotter),
                   recorded_vars=repr(self.recorded_vars))
tarfile.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 27 收藏 0 点赞 0 评论 0
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
tarfile.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 25 收藏 0 点赞 0 评论 0
def _apply_pax_info(self, pax_headers, encoding, errors):
        """Replace fields with supplemental information from a previous
           pax extended or global header.
        """
        for keyword, value in pax_headers.iteritems():
            if keyword not in PAX_FIELDS:
                continue

            if keyword == "path":
                value = value.rstrip("/")

            if keyword in PAX_NUMBER_FIELDS:
                try:
                    value = PAX_NUMBER_FIELDS[keyword](value)
                except ValueError:
                    value = 0
            else:
                value = uts(value, encoding, errors)

            setattr(self, keyword, value)

        self.pax_headers = pax_headers.copy()
tarfile.py 文件源码 项目:kinect-2-libras 作者: inessadl 项目源码 文件源码 阅读 28 收藏 0 点赞 0 评论 0
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")
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 31 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this RTI is running.
        """
        return copy.copy(self._location)
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def get_peers():
        _Peer._lock.acquire()
        peers = [copy.copy(peer.location) for peer in _Peer.peers.itervalues()]
        _Peer._lock.release()
        return peers
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this task is running.

        Can also be used on remotely running tasks.
        """
        if self._location:
            return copy.copy(self._location)
        return self._scheduler.location
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 21 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this channel is located.

        Can also be used on remote channels.
        """
        if self._location:
            return copy.copy(self._location)
        return self._scheduler.location
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this Pycos is running.
        """
        return copy.copy(self._location)
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 33 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this RTI is running.
        """
        return copy.copy(self._location)
netpycos.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 32 收藏 0 点赞 0 评论 0
def get_peers():
        _Peer._lock.acquire()
        peers = [copy.copy(peer.location) for peer in _Peer.peers.values()]
        _Peer._lock.release()
        return peers
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this task is running.

        Can also be used on remotely running tasks.
        """
        if self._location:
            return copy.copy(self._location)
        return self._scheduler.location
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this channel is located.

        Can also be used on remote channels.
        """
        if self._location:
            return copy.copy(self._location)
        return self._scheduler.location
__init__.py 文件源码 项目:pycos 作者: pgiri 项目源码 文件源码 阅读 19 收藏 0 点赞 0 评论 0
def location(self):
        """Get Location instance where this Pycos is running.
        """
        return copy.copy(self._location)
models.py 文件源码 项目:AutoML5 作者: djajetic 项目源码 文件源码 阅读 22 收藏 0 点赞 0 评论 0
def fit(self, X, Y):
        if len(Y.shape)==1: 
            Y = np.array([Y]).transpose() # Transform vector into column matrix
            # This is NOT what we want: Y = Y.reshape( -1, 1 ), because Y.shape[1] out of range
        self.n_target = Y.shape[1]                 # Num target values = num col of Y
        self.n_label = len(set(Y.ravel()))         # Num labels = num classes (categories of categorical var if n_target=1 or n_target if labels are binary )
        # Create the right number of copies of the predictor instance
        if len(self.predictors)!=self.n_target:
            predictorInstance = self.predictors[0]
            self.predictors = [predictorInstance]
            for i in range(1,self.n_target):
                self.predictors.append(copy.copy(predictorInstance))
        # Fit all predictors
        for i in range(self.n_target):
            # Update the number of desired prodictos
            if hasattr(self.predictors[i], 'n_estimators'):
                self.predictors[i].n_estimators=self.n_estimators
            # Subsample if desired
            if self.balance:
                pos = Y[:,i]>0
                neg = Y[:,i]<=0
                if sum(pos)<sum(neg): 
                    chosen = pos
                    not_chosen = neg
                else: 
                    chosen = neg
                    not_chosen = pos
                num = sum(chosen)
                idx=filter(lambda(x): x[1]==True, enumerate(not_chosen))
                idx=np.array(zip(*idx)[0])
                np.random.shuffle(idx)
                chosen[idx[0:min(num, len(idx))]]=True
                # Train with chosen samples            
                self.predictors[i].fit(X[chosen,:],Y[chosen,i])
            else:
                self.predictors[i].fit(X,Y[:,i])
        return
bleu_scorer.py 文件源码 项目:deep-summarization 作者: harpribot 项目源码 文件源码 阅读 23 收藏 0 点赞 0 评论 0
def copy(self):
        """
        copy the refs.
        :return:
        """
        new = BleuScorer(n=self.n)
        new.ctest = copy.copy(self.ctest)
        new.crefs = copy.copy(self.crefs)
        new._score = None
        return new
myhdlpeek.py 文件源码 项目:myhdlpeek 作者: xesscorp 项目源码 文件源码 阅读 29 收藏 0 点赞 0 评论 0
def store_sample(self, value):
        '''Store a value and the current time into the trace.'''
        self.append(Sample(now(), copy(value)))
gen.py 文件源码 项目:tree-gen 作者: friggog 项目源码 文件源码 阅读 24 收藏 0 点赞 0 评论 0
def calc_helix_points(turtle, rad, pitch):
    """ calculates required points to produce helix bezier curve with given radius and pitch in direction of turtle"""
    # alpha = radians(90)
    # pit = pitch/(2*pi)
    # a_x = rad*cos(alpha)
    # a_y = rad*sin(alpha)
    # a = pit*alpha*(rad - a_x)*(3*rad - a_x)/(a_y*(4*rad - a_x)*tan(alpha))
    # b_0 = Vector([a_x, -a_y, -alpha*pit])
    # b_1 = Vector([(4*rad - a_x)/3, -(rad - a_x)*(3*rad - a_x)/(3*a_y), -a])
    # b_2 = Vector([(4*rad - a_x)/3, (rad - a_x)*(3*rad - a_x)/(3*a_y), a])
    # b_3 = Vector([a_x, a_y, alpha*pit])
    # axis = Vector([0, 0, 1])

    # simplifies greatly for case inc_angle = 90
    points = [Vector([0, -rad, -pitch / 4]),
              Vector([(4 * rad) / 3, -rad, 0]),
              Vector([(4 * rad) / 3, rad, 0]),
              Vector([0, rad, pitch / 4])]

    # align helix points to turtle direction and randomize rotation around axis
    trf = turtle.dir.to_track_quat('Z', 'Y')
    spin_ang = rand_in_range(0, 2 * pi)
    for p in points:
        p.rotate(Quaternion(Vector([0, 0, 1]), spin_ang))
        p.rotate(trf)

    return points[1] - points[0], points[2] - points[0], points[3] - points[0], turtle.dir.copy()


问题


面经


文章

微信
公众号

扫码关注公众号