本文整理汇总了Python中random.setstate函数的典型用法代码示例。如果您正苦于以下问题:Python setstate函数的具体用法?Python setstate怎么用?Python setstate使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了setstate函数的20个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于我们的系统推荐出更棒的Python代码示例。
示例1: internal_rng
def internal_rng(self):
# Swap to the internal RNG state if necessary, then return random
if self.rng_for_agent:
self.agent_state = random.getstate()
random.setstate(self.internal_state)
self.rng_for_agent = False
return random
开发者ID:wmayner,项目名称:wumpus,代码行数:7,代码来源:wumpus_world.py
示例2: __makeResistanceToon
def __makeResistanceToon(self):
if self.resistanceToon:
return
npc = Toon.Toon()
npc.setName(TTLocalizer.ResistanceToonName)
npc.setPickable(0)
npc.setPlayerType(NametagGroup.CCNonPlayer)
dna = ToonDNA.ToonDNA()
dna.newToonRandom(11237, 'f', 1)
dna.head = 'pls'
npc.setDNAString(dna.makeNetString())
npc.animFSM.request('neutral')
self.resistanceToon = npc
self.resistanceToon.setPosHpr(*ToontownGlobals.CashbotRTBattleOneStartPosHpr)
state = random.getstate()
random.seed(self.doId)
self.resistanceToon.suitType = SuitDNA.getRandomSuitByDept('m')
random.setstate(state)
self.fakeGoons = []
for i in range(self.numFakeGoons):
goon = DistributedCashbotBossGoon.DistributedCashbotBossGoon(base.cr)
goon.doId = -1 - i
goon.setBossCogId(self.doId)
goon.generate()
goon.announceGenerate()
self.fakeGoons.append(goon)
self.__hideFakeGoons()
开发者ID:BmanGames,项目名称:Toontown-Level-Editor,代码行数:28,代码来源:DistributedCashbotBoss.py
示例3: lorem
def lorem(randseed=None, count=1, method=None):
u"""
Creates Lorem Ipsum text.
Usage format:
{% lorem [randseed] [count] [method] %}
``randseed`` is any hashable object used to initialize the random numbers generator.
If ``randseed`` is not given the common "Lorem ipsum dolor sit..." text is used.
``count`` is a number of paragraphs or sentences to generate (default is 1).
``method`` is either ``p`` for HTML paragraphs enclosed in ``<p>`` tags, or ``b`` for
plain-text paragraph blocks (default is ``b``).
Notice: This filter is rewrited ``lorem`` filter from ``webdesign`` modul from default Django
package ``django.contrib.webdesign``. The original ``lorem`` filter does not give stable random
text, thus its generated paragraphs change on every page refresh. We stabilize the generated
text by setting a fixed randseed before generating the paragraph.
"""
state = random.getstate()
random.seed(randseed)
res = paragraphs(count, common=(randseed is None))
random.setstate(state)
if method == u'p':
res = [u'<p>{}</p>'.format(p) for p in res]
return u'\n'.join(res)
开发者ID:gitter-badger,项目名称:chcemvediet,代码行数:30,代码来源:utils.py
示例4: simplified_data
def simplified_data(num_train, num_dev, num_test):
rndstate = random.getstate()
random.seed(0)
trees = loadTrees('train') + loadTrees('dev') + loadTrees('test')
#filter extreme trees
pos_trees = [t for t in trees if t.root.label==4]
neg_trees = [t for t in trees if t.root.label==0]
#binarize labels
binarize_labels(pos_trees)
binarize_labels(neg_trees)
#split into train, dev, test
print len(pos_trees), len(neg_trees)
pos_trees = sorted(pos_trees, key=lambda t: len(t.get_words()))
neg_trees = sorted(neg_trees, key=lambda t: len(t.get_words()))
num_train/=2
num_dev/=2
num_test/=2
train = pos_trees[:num_train] + neg_trees[:num_train]
dev = pos_trees[num_train : num_train+num_dev] + neg_trees[num_train : num_train+num_dev]
test = pos_trees[num_train+num_dev : num_train+num_dev+num_test] + neg_trees[num_train+num_dev : num_train+num_dev+num_test]
random.shuffle(train)
random.shuffle(dev)
random.shuffle(test)
random.setstate(rndstate)
return train, dev, test
开发者ID:yihui-he,项目名称:recursive-neural-network,代码行数:30,代码来源:tree.py
示例5: sgd
def sgd(f, x0, step, iterations, useSaved = False, PRINT_EVERY=10):
# possibly more arguments for postprocessing, save trained variables,
# print status lines
# Anneal learning rate every several iterations
ANNEAL_EVERY = 20000
if useSaved:
start_iter, oldx, state = load_saved_params()
if start_iter > 0:
x0 = oldx
step *= 0.5 ** (start_iter / ANNEAL_EVERY)
if state:
random.setstate(state)
else:
start_iter = 0
x = x0
for iter in xrange(1, iterations + 1):
cost, grad = f(x)
x -= step * grad
if iter % PRINT_EVERY == 0:
print "iter %d: %f" % (iter, cost)
if iter % SAVE_PARAMS_EVERY == 0 and useSaved:
save_params(iter, x)
if iter % ANNEAL_EVERY == 0:
step *= 0.5
return x
开发者ID:romanegloo,项目名称:primer,代码行数:32,代码来源:sgd.py
示例6: movement_phase
def movement_phase(process):
repeat = process.current_actions
Action.set_process(process)
rand_state = random.getstate()
random.shuffle(repeat)
random.setstate(rand_state)
repeat.sort()
sorted_moves = []
repeat = [Movement(a, find_shortest_path(process.map, a.pos, a.dest)) for a in repeat]
occupied, que = set(), []
while len(repeat) != len(que):
que, repeat = repeat, []
for turn in que:
if turn.path and turn.path[0] not in occupied:
occupied.add(turn.path[0])
sorted_moves.append(turn.action)
else:
repeat.append(turn)
for turn in repeat:
for node in turn.path:
if node not in occupied:
occupied.add(node)
sorted_moves.append(Action(turn.action.pos, node.pos, turn.action.attack))
break
else:
sorted_moves.append(Action(turn.action.pos, turn.action.pos, turn.action.attack))
return sorted_moves
开发者ID:B-Rich,项目名称:ttb-game,代码行数:27,代码来源:logics.py
示例7: load
def load(self, filename):
data = Data.load(filename)
random.setstate(data['random'])
self.tiles = data['tiles']
self.initindexes()
self.popcache = {}
开发者ID:tps12,项目名称:Tec-Nine,代码行数:7,代码来源:populationsimulation.py
示例8: use_internal_state
def use_internal_state(self):
"""Use a specific RNG state."""
old_state = random.getstate()
random.setstate(self._random_state)
yield
self._random_state = random.getstate()
random.setstate(old_state)
开发者ID:AhlamMD,项目名称:decaNLP,代码行数:7,代码来源:iterator.py
示例9: randomOpening
def randomOpening(size, seed):
oldstate = random.getstate()
random.seed(seed)
r = random.randint(0, (size*size - 1))
random.setstate(oldstate)
move = str(chr(ord('a') + (r / size))) + str((r % size) + 1)
return move
开发者ID:kenjyoung,项目名称:benzene-vanilla,代码行数:7,代码来源:MoHexScript.py
示例10: random_seed
def random_seed(seed):
"""Context manager to set random.seed() temporarily
"""
state = random.getstate()
random.seed(seed)
yield
random.setstate(state)
开发者ID:openstack,项目名称:designate,代码行数:7,代码来源:fixtures.py
示例11: penis
async def penis(self, ctx, *users: discord.Member):
"""Detects user's penis length
This is 100% accurate.
Enter multiple users for an accurate comparison!"""
if not users:
await self.bot.send_cmd_help(ctx)
return
dongs = {}
msg = ""
state = random.getstate()
for user in users:
random.seed(user.id)
dongs[user] = "8{}D".format("=" * random.randint(0, 30))
random.setstate(state)
dongs = sorted(dongs.items(), key=lambda x: x[1])
for user, dong in dongs:
msg += "**{}'s size:**\n{}\n".format(user.display_name, dong)
for page in pagify(msg):
await self.bot.say(page)
开发者ID:Redjumpman,项目名称:26-Cogs,代码行数:25,代码来源:penis.py
示例12: testAgainstRandom
def testAgainstRandom(p):
state = random.getstate()
score = 0
#random.seed(0)
for iter in range(100):
population = []
nIndividuals = 3
for n in range(nIndividuals):
newIndividual = {}
for i in ['PE', 'LB', 'PK', 'OE', 'RD', 'YW', 'GN', 'DB', 'RR', 'UY',
'PE_up', 'LB_up', 'PK_up', 'OE_up', 'RD_up', 'YW_up', 'GN_up', 'DB_up', 'RR_up', 'UY_up']:
#newIndividual[i] = random.random()
#newIndividual[i] = 1.0
if random.random() > .5:
newIndividual[i] = random.random()
else:
newIndividual[i] = random.random()
population.append(newIndividual)
points = playGame(p, population[0], population[1], population[2])
score += points[0]
random.setstate(state)
return score
开发者ID:shreerajshrestha,项目名称:Monopoly_Mega_Edition_Evolutionary_Optimization,代码行数:30,代码来源:optimize_monopoly_groups.py
示例13: _numpy_do_teardown
def _numpy_do_teardown():
global _old_python_random_state
global _old_numpy_random_state
random.setstate(_old_python_random_state)
numpy.random.set_state(_old_numpy_random_state)
_old_python_random_state = None
_old_numpy_random_state = None
开发者ID:asi1024,项目名称:chainer,代码行数:7,代码来源:random.py
示例14: spatial_graph_variable_spatial_scale
def spatial_graph_variable_spatial_scale(cell_positions,
spatial_scale=1.,
connection_probability=connection_probability_vervaeke_2010,
synaptic_weight=synaptic_weight_vervaeke_2010):
state = random.getstate()
g_2010 = spatial_graph_2010(cell_positions)
weights_2010 = [e[2]['weight'] for e in g_2010.edges(data=True)]
total_weight_2010 = sum(weights_2010)
# reset RNG to make sure we will rescale strengths fairly
random.setstate(state)
# generate spatial network with 2010 rules but scaling all distances
n_cells = len(cell_positions)
edges = []
for i, p in enumerate(cell_positions):
for j, q in enumerate(cell_positions[i+1:]):
d = distance(p, q) / spatial_scale
if random.random() < connection_probability(d):
edges.append((i, i+1+j, {'weight': synaptic_weight(d)}))
# rescale weights to keep the same total value across the network
weights = [e[2]['weight'] for e in edges]
total_weight = sum(weights)
for e in edges:
e[2]['weight'] *= total_weight_2010 / total_weight
# create graph object
g = nx.Graph()
g.add_nodes_from(range(n_cells))
for node in g.nodes():
g.node[node]['x'] = cell_positions[node][0]
g.node[node]['y'] = cell_positions[node][1]
g.node[node]['z'] = cell_positions[node][2]
g.add_edges_from(edges)
return g
开发者ID:RokasSt,项目名称:GJGolgi_ReducedMorph,代码行数:35,代码来源:utils.py
示例15: optimize
def optimize(p, k, distances, mode='clusters', seed=12345, granularity=1.):
if k == 1:
return [p]
random_state = random.getstate()
try:
# we want the same output on every call on the same data, so we use
# a fixed random seed at this point.
random.seed(seed)
clusterer = _Clusterer(
len(p), tuple(range(len(p))), None, [], p, distances.distance)
if isinstance(k, tuple) and len(k) == 2:
criterion = k[0](**k[1])
assert isinstance(criterion, SplitCriterion)
clusters = clusterer.without_k(criterion)
elif isinstance(k, int):
clusters = [c.members for c in clusterer.with_k(k)]
else:
raise ValueError('illegal parameter k "%s"' % str(k))
# sort clusters by order of their first element in the original list.
clusters = sorted(clusters, key=lambda c: c[0])
if mode == 'clusters':
return list(map(lambda c: map(lambda i: p[i], c), clusters))
elif mode == 'components':
return _components(clusters, len(p))
else:
raise ValueError('illegal mode %s' % mode)
finally:
random.setstate(random_state)
开发者ID:Piruzzolo,项目名称:Mathics,代码行数:33,代码来源:clusters.py
示例16: __call__
def __call__(self, raw_bytes, avoid, pcreg=None):
icache_flush = 1
# If randomization is disabled, ensure that the seed
# is always the same for the builder.
state = random.getstate()
if not context.randomize:
random.seed(1)
try:
b = builder.builder()
enc_data = b.enc_data_builder(raw_bytes)
dec_loop = b.DecoderLoopBuilder(icache_flush)
enc_dec_loop = b.encDecoderLoopBuilder(dec_loop)
dec = b.DecoderBuilder(dec_loop, icache_flush)
output, dec = b.buildInit(dec)
output += dec
output += enc_dec_loop
output += enc_data
finally:
random.setstate(state)
return output
开发者ID:arthaud,项目名称:python3-pwntools,代码行数:26,代码来源:__init__.py
示例17: gradcheck_naive
def gradcheck_naive(f, x):
"""
Gradient check for a function f
- f should be a function that takes a single argument and outputs the cost and its gradients
- x is the point (numpy array) to check the gradient at
"""
rndstate = random.getstate()
random.setstate(rndstate)
fx, grad = f(x) # Evaluate function value at original point
h = 1e-4
# Iterate over all indexes in x
it = np.nditer(x, flags=['multi_index'], op_flags=['readwrite'])
while not it.finished:
ix = it.multi_index
### try modifying x[ix] with h defined above to compute numerical gradients
### make sure you call random.setstate(rndstate) before calling f(x) each time, this will make it
### possible to test cost functions with built in randomness later
### YOUR CODE HERE:
raise NotImplementedError
### END YOUR CODE
# Compare gradients
reldiff = abs(numgrad - grad[ix]) / max(1, abs(numgrad), abs(grad[ix]))
if reldiff > 1e-5:
print "Gradient check failed."
print "First gradient error found at index %s" % str(ix)
print "Your gradient: %f \t Numerical gradient: %f" % (grad[ix], numgrad)
return
it.iternext() # Step to next dimension
print "Gradient check passed!"
开发者ID:Darktex,项目名称:CS224d,代码行数:35,代码来源:q2_gradcheck.py
示例18: get_random_condition
def get_random_condition(conn):
# hits can be in one of three states:
# jobs that are finished
# jobs that are started but not finished
# jobs that are never going to finish (user decided not to do it)
# our count should be based on the first two so, lets stay anything finished or anything not finished that was started in the last 45 minutes should be counted
starttime = datetime.datetime.now() + datetime.timedelta(minutes=-30)
s = select([participantsdb.c.cond], and_(participantsdb.c.codeversion==CODE_VERSION, or_(participantsdb.c.endhit!=null, participantsdb.c.beginhit>starttime)), from_obj=[participantsdb])
result = conn.execute(s)
counts = [0]*NUMCONDS
# Excluding less interesting conditions:
counts[2] = 5000
counts[4] = 5000
for row in result:
counts[row[0]]+=1
# choose randomly from the ones that have the least in them (so will tend to fill in evenly)
indicies = [i for i, x in enumerate(counts) if x == min(counts)]
rstate = getstate()
seed()
if TESTINGPROBLEMSIX:
#subj_cond = choice([5,11])
subj_cond = 5
else:
subj_cond = choice(indicies)
setstate(rstate)
return subj_cond
开发者ID:NYUCCL,项目名称:CrumpMcDonnellGureckis2013,代码行数:28,代码来源:app.py
示例19: determine_action
def determine_action(state, dict, random_state, score, max_score):
#print state
random.setstate(random_state[1])
state_click = dict.get((state, True), 0)
state_nothing = dict.get((state, False), 0)
print state
print state_click
print state_nothing
value = random.randint(1,10)
random_state[1] = random.getstate()
if value < 3 and score >= max_score:
value = random.randint(0,1)
random_state[1] = random.getstate()
if value == 1:
print "RNG VALUE OF 1"
return True
else:
print "RNG VALUE OF 0"
return False
elif state_click > state_nothing:
print "state_click greater than state_nothing"
return True
print "state_nothing greater than state_click"
return False
开发者ID:Sindalf,项目名称:Flappy-Bird-Q-learning-Rev.1,代码行数:27,代码来源:flappybird.py
示例20: shuffle
def shuffle(self, i, seed=None):
if seed is not None:
rand_state = random.getstate()
random.seed(seed)
move_list = []
last_face = None
for _ in range(i):
face = last_face
while face == last_face:
face = Face.random()
turn_type = TurnType.random()
move_list.append((face, turn_type))
last_face = face
shuffle_algorithm = Algorithm(reversed(move_list))
self.apply_algorithm(shuffle_algorithm)
if seed is not None:
random.setstate(rand_state)
return shuffle_algorithm
开发者ID:abau171,项目名称:cubetree,代码行数:28,代码来源:model.py
注:本文中的random.setstate函数示例由纯净天空整理自Github/MSDocs等源码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。 |
请发表评论