当前位置: 首页>>代码示例>>Python>>正文


Python copy函数代码示例

本文整理汇总了Python中copy函数的典型用法代码示例。如果您正苦于以下问题:Python copy函数的具体用法?Python copy怎么用?Python copy使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。


在下文中一共展示了copy函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。

示例1: contour_plot

	def contour_plot(self, box, nc=10, z_max=-2e20, z_min=2e20,
					 color='k', labels=True, precision=5, ptype="sig_figs",
					 contours=[], neg_ls="dashed", pos_ls="solid", lw=1.0):
		"""plot the field as a contour"""
		# adapted to work with a cpdn_box
		# have to copy LON and LAT so they can be manipulated
		LON = copy(box.get_dimension("X").get_values())
		LAT = copy(box.get_dimension("Y").get_values())
		Z = numpy.array(box.get_values().squeeze())
		# translate the LON, LAT and Z to the coordinate system
		LON, LAT, Z = self.prepare_data(LON, LAT, Z)
		# create the contour values to draw
		if contours != []:
			V = contours
		elif z_max != -2e20 and z_min != 2e20:
			V = numpy.linspace(z_min, z_max, nc)
		else:
			V = nc
		# get the line styles for the contours
		ls = []
		for v in V:
			if v < 0.0:
				ls.append(neg_ls)
			else:
				ls.append(pos_ls)
		# draw the contours - all in the same color
		CS = self.sp.contour(LON, LAT, Z, V, colors=color, linewidths=lw, linestyles=ls)
		# do the labels
		format = self.get_format_string(precision, ptype)
		self.sp.clabel(CS, fontsize=8, inline=True, inline_spacing=-2, 
					   fmt=format)
开发者ID:nrmassey,项目名称:cpdn_analysis,代码行数:31,代码来源:map_plot.py

示例2: dfs

def dfs(depth, prev):
    global state, path
    if state.MD == 0:
        return True
    # 現在の深さにヒューリスティックを足して制限を超えたら枝を刈る
    if depth + state.MD > limit:
        return False

    sx = state.space / N
    sy = state.sapce % N
    tmp = Puzzle()

    for r in xrange(4):
        tx = sx + dx[r]
        ty = sy + dy[r]
        if tx < 0 or ty < 0 or tx >= N or ty >= N:
            continue
        if max(prev, r) - min(prev, r) == 2:
            continue
        tmp = copy(state)
        # マンハッタン距離の差分を計算しつつ、ピースをスワップ
        txy = tx * N + ty
        sxy = sx * N + sy
        state.MD -= MDT[txy][state.f[txy] - 1]
        state.MD += MDT[sxy][state.f[txy] - 1]
        state.f[txy], state.f[sxy] = state.f[sxy], state.f[txy]
        state.space = txy
        if dfs(depth + 1, r):
            path[depth] = r
            return True
        state = copy(tmp)

    return False
开发者ID:issy-kn,项目名称:ALDS1,代码行数:33,代码来源:c.py

示例3: send_mail_mime

def send_mail_mime(request, to, frm, subject, msg, cc=None, extra=None, toUser=False, bcc=None):
    """Send MIME message with content already filled in."""
    
    condition_message(to, frm, subject, msg, cc, extra)

    # start debug server with python -m smtpd -n -c DebuggingServer localhost:2025
    # then put USING_DEBUG_EMAIL_SERVER=True and EMAIL_HOST='localhost'
    # and EMAIL_PORT=2025 in settings_local.py
    debugging = getattr(settings, "USING_DEBUG_EMAIL_SERVER", False) and settings.EMAIL_HOST == 'localhost' and settings.EMAIL_PORT == 2025

    if test_mode or debugging or settings.SERVER_MODE == 'production':
        with smtp_error_logging(send_smtp) as logging_send:
            with smtp_error_user_warning(logging_send,request) as send:
                send(msg, bcc)
    elif settings.SERVER_MODE == 'test':
	if toUser:
	    copy_email(msg, to, toUser=True, originalBcc=bcc)
	elif request and request.COOKIES.has_key( 'testmailcc' ):
	    copy_email(msg, request.COOKIES[ 'testmailcc' ],originalBcc=bcc)
    try:
	copy_to = settings.EMAIL_COPY_TO
    except AttributeError:
        copy_to = "ietf.tracker.archive+%[email protected]" % settings.SERVER_MODE
    if copy_to and not test_mode and not debugging: # if we're running automated tests, this copy is just annoying
        if bcc:
            msg['X-Tracker-Bcc']=bcc
        with smtp_error_logging(copy_email) as logging_copy:
            with smtp_error_user_warning(logging_copy,request) as copy:
                copy(msg, copy_to,originalBcc=bcc)
开发者ID:algby,项目名称:ietfdb,代码行数:29,代码来源:mail.py

示例4: extendRow

def extendRow(list,fig) :

    if len(list) > 5 :
        return

    l = copy(list)
    f = copy(fig)

    f[numbers2[l[-1]]] = 1


    s34 = str(l[-1])[-2:]
    matches = numbers2contains(s34)

    for match in matches :
        index = -1
        try :
            index = l.index(match)
        except:
            pass

        if f.has_key(numbers2[match]) == False and index == -1:
            extendRow(l + [match], f)



            if len(l) == 5 and str(l[0])[:2] == str(match)[-2:] :
                print str(l + [match]) + str(f) + "!!!!!!!!"
    return
开发者ID:deronda,项目名称:project-euler,代码行数:29,代码来源:61.py

示例5: state_push

 def state_push(self):
     """
     Save the current state of the output function to an internal stack.
     """
    
     self.__current_state_stack.append((copy(self.t), copy(self.y_avg), copy(self.first_call)))
     super(SimpleHomeoLinear, self).state_push()
开发者ID:jesuscript,项目名称:TopographicaSVN,代码行数:7,代码来源:jacommands.py

示例6: backup

def backup(src, prefix='.'):
    """Backup (copy) `src` to <src><prefix><num>, where <num> is an integer
    starting at 0 which is incremented until there is no destination with that
    name.
    
    Symlinks are handled by shutil.copy() for files and shutil.copytree() for
    dirs. In both cases, the content of the file/dir pointed to by the link is
    copied.

    Parameters
    ----------
    src : str
        name of file/dir to be copied
    prefix : str, optional
    """
    if os.path.isfile(src):
        copy = shutil.copy 
    elif os.path.isdir(src):
        copy = shutil.copytree
    else:
        raise StandardError("source '%s' is not file or dir" %src)
    idx = 0
    dst = src + '%s%s' %(prefix,idx)
    while os.path.exists(dst):
        idx += 1
        dst = src + '%s%s' %(prefix,idx)
    # sanity check
    if os.path.exists(dst):
        raise StandardError("destination '%s' exists" %dst)
    else:        
        copy(src, dst)
开发者ID:elcorto,项目名称:pwtools,代码行数:31,代码来源:common.py

示例7: parse

    def parse(self, reader):
        for line in reader.readlines():
            line = line.strip()
            if len(line) == 0: 
                continue

            # List<TaggedWord>
            sentence = copy(self.startMarkers)
            # String[]
            lineParts = re.split("\\s+", line)
            for i in xrange(0, len(lineParts)): 
                # String
                wordTag = lineParts[i]
                # int
                sepIndex = wordTag.rfind('/')
                if sepIndex == -1: 
                    raise CorpusReaderException("Tag is missing in '" + wordTag + "'", CorpusReaderException.CorpusReadError.MISSING_TAG)

                # String
                word = wordTag[:sepIndex]
                # String
                tag = wordTag[sepIndex + 1:]
                if len(word) == 0: 
                    raise CorpusReaderException("Zero-length word in '" + wordTag + "'", CorpusReaderException.CorpusReadError.ZERO_LENGTH_WORD)

                if i == 0: 
                    word = replaceCharAt(word, 0, word[0].lower());

                sentence.append(TaggedWord(word, tag))

            sentence += copy(self.endMarkers)
            self.sentenceHandler.handleSentence(sentence)
开发者ID:IrfanWahyudin,项目名称:RiskCluster,代码行数:32,代码来源:training.py

示例8: AnIPsolver

def AnIPsolver(constraints, obj,Qorbit): #objective function must contain integer terms (adjust it so that is the case)
    #we make a copy of the constraints so as to not lose them
    A1 = copy(constraints)
    A2 = copy(constraints)
    #we generate temporary maxes and mins
    cmax = probGenerate(A1, obj, 'Max') #get the current max
    cmin = probGenerate(A2, obj, 'Min') #get the current min
    currentmax = cmax[2]
    currentmin = cmin[2]

    #proper bounding would create a tighter space 
    currentsolution = 0
    while True:
        if (currentmax- currentmin) < 1 or currentmin > currentmax: #if these two planes get within distance 1 of each other, then there really won't be an integer point 
            return [currentsolution,temptarg]
        temptarg = (currentmax + currentmin)/2
        #we make a shallow copy of the constraints
        tconstraint = copy(constraints)
        #we then slice the set by adding in the expected performance we desire
        tconstraint += [obj + [-1]+[temptarg]] #add on the bound obj >= thisvalue
        tconstraint += [obj + [1] + [currentmax]] #make sure it is less than the current maximum (so we don't repeat work)
        #now we check for an integer solution
        endresult = autoSolver(tconstraint,Qorbit)
        if endresult[0] == 'No Integer Solution': #this is too tight of a bound
            currentmax = temptarg-1 #there is nothing with a max greater than this so we can set it to the middle

        if endresult[0] == 'Integer Solution Discovered':
            
            currentmin = temptarg+1 #we expect at least this much performance so something slightly tighter is given
            currentsolution = endresult[1:] #grab the value array along with objective value
            print [currentsolution,temptarg]
开发者ID:frogeyedpeas,项目名称:TreeSlicer,代码行数:31,代码来源:IntegerProgramming3.py

示例9: shuffle_function

def shuffle_function(*list_object):
    if len(list_object) == 1 and is_tuple_or_list(list_object[0]):
        result_list = list(copy(list_object[0]))
    else:
        result_list = list(copy(list_object))
    shuffle(result_list)
    return result_list
开发者ID:salasgar,项目名称:Ecosystems,代码行数:7,代码来源:Basic_tools.py

示例10: build

    def build(self):
        try:
            # Find home dir
            if platform == "android":
                _home = "/storage/emulated/0/Android/data/"
            else:
                _home = os.path.expanduser("~")
            # Check if there is a settings file there
            _config_path = os.path.join(_home, "se.optimalbpm.optimal_file_sync/config.txt")
            # Raise error if non existing config
            if not os.path.exists(_config_path):
                if not os.path.exists(os.path.join(_home, "se.optimalbpm.optimal_file_sync")):
                    os.mkdir(os.path.join(_home, "se.optimalbpm.optimal_file_sync"))
                if platform == "android":
                    copy("default_config_android.txt", _config_path)
                else:
                    copy("default_config_linux.txt", _config_path)

                notification.notify("Optimal File Sync Service", "First time, using default config.")

            self.settingsframe = SettingsFrame()
            self.settingsframe.init(_cfg_file=_config_path)
            return self.settingsframe
        except Exception as e:
            notification.notify("Optimal File Sync Service", "Error finding config :" + str(e))
开发者ID:OptimalBPM,项目名称:optimal_file_sync,代码行数:25,代码来源:main.py

示例11: Evaluate

 def Evaluate( self ,queueD, queueCodeN , queueN, ifile ,Population ):
     i = 0
     self.X = []
     self.ListNonDominated = []
     self.lockList.acquire()
     self.ListCodedNonDominated =[]# copy(queueCodeN)
     self.ListDominated = copy(queueD)
     self.lockList.release()
     while i < 20:   #????
             self.RealisableSpace( Population )
             j = len(self.X)-1
             self.Dominate(queueD,j);
             i = i +1
     self.RealisableSpace( Population )
     j = len(self.X)-1
     self.Dominate(queueD,j);
     self.lock.acquire()
     self.Tofile('data',self.X,ifile , 1)
     self.lock.release()
     fonction1 = eval(self.fonctionObject[0])
     fonction2 = eval(self.fonctionObject[1])
     i = 0
     while i < len(self.X):
         if self.X[i] not in self.ListDominated:
             self.ListNonDominated.append(copy(self.X[i]))
             self.ListCodedNonDominated.append(copy(self.CodedX[i]))
             self.lockList.acquire()
             queueCodeN.append(copy(self.CodedX[i]))
             queueN.append(copy(self.X[i]))                
             self.lockList.release()
         i = i +1
开发者ID:ahcheriet,项目名称:qemoo,代码行数:31,代码来源:AllFunctions.py

示例12: prevision

	def prevision(self, gravite, tick, iterations):
		if not self.previsions:
			self.previsions = [copy(self)]
		for i in range(len(self.previsions), iterations):
			prevision = copy(self.previsions[-1])
			prevision.sim(gravite, tick)
			self.previsions.append(prevision)
开发者ID:ChartrandEtienne,项目名称:Orbit,代码行数:7,代码来源:pom.py

示例13: test_COPY_verb_with_storlets

    def test_COPY_verb_with_storlets(self):
        source = '/v1/AUTH_a/c/so'
        target = '/v1/AUTH_a/c/to'
        destination = 'c/to'
        self.app.register('GET', source, HTTPOk, body='source body')
        self.app.register('PUT', target, HTTPCreated)
        storlet = '/v1/AUTH_a/storlet/Storlet-1.0.jar'
        self.app.register('GET', storlet, HTTPOk, body='jar binary')

        def copy(target, source, destination):
            req = Request.blank(source, environ={'REQUEST_METHOD': 'COPY'},
                                headers={'Destination': destination,
                                         'X-Run-Storlet': 'Storlet-1.0.jar',
                                         'X-Backend-Storage-Policy-Index': 0})
            app = self.get_app(self.app, self.conf)
            app(req.environ, self.start_response)
            self.assertEqual('201 Created', self.got_statuses[-1])
            get_calls = self.app.get_calls('GET', source)
            self.assertEqual(len(get_calls), 1)
            self.assertEqual(get_calls[-1][3], '')
            self.assertEqual(get_calls[-1][1], source)
            put_calls = self.app.get_calls('PUT', target)
            self.assertEqual(len(put_calls), 1)
            self.assertEqual(put_calls[-1][3], 'source body')
        with storlet_enabled():
            copy(target, source, destination)
开发者ID:Nicolepcx,项目名称:storlets,代码行数:26,代码来源:test_storlet_handler.py

示例14: __deepcopy__

 def __deepcopy__(self, memo):
     res = self.__class__()
     res.module = self.module
     res.names = copy(self.names)
     res.last_name = self.last_name
     res.attrs = copy(self.attrs)
     return res
开发者ID:sataloger,项目名称:python-static-analysis,代码行数:7,代码来源:type_callable.py

示例15: test01_init

    def test01_init(self):
        "Testing LayerMapping initialization."

        # Model field that does not exist.
        bad1 = copy(city_mapping)
        bad1['foobar'] = 'FooField'

        # Shapefile field that does not exist.
        bad2 = copy(city_mapping)
        bad2['name'] = 'Nombre'

        # Nonexistent geographic field type.
        bad3 = copy(city_mapping)
        bad3['point'] = 'CURVE'

        # Incrementing through the bad mapping dictionaries and
        # ensuring that a LayerMapError is raised.
        for bad_map in (bad1, bad2, bad3):
            try:
                lm = LayerMapping(City, city_shp, bad_map)
            except LayerMapError:
                pass
            else:
                self.fail('Expected a LayerMapError.')

        # A LookupError should be thrown for bogus encodings.
        try:
            lm = LayerMapping(City, city_shp, city_mapping, encoding='foobar')
        except LookupError:
            pass
        else:
            self.fail('Expected a LookupError')
开发者ID:farstarinc,项目名称:django,代码行数:32,代码来源:tests.py


注:本文中的copy函数示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。