本文整理汇总了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)
示例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
示例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)
示例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
示例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()
示例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)
示例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)
示例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]
示例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
示例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))
示例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
示例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)
示例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)
示例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
示例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')