本文整理汇总了Python中state.load函数的典型用法代码示例。如果您正苦于以下问题:Python load函数的具体用法?Python load怎么用?Python load使用的例子?那么恭喜您, 这里精选的函数代码示例或许可以为您提供帮助。
在下文中一共展示了load函数的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: update
def update(self, events):
'''
Updates the screen when an event happens
@param - list of game events
'''
for event in events:
if not hasattr(event, 'key'):
continue
if event.type == KEYDOWN:
if event.key == K_RETURN:
if self.currLine == GameMenuScreenLine.NewGame:
gui = EnterSaveNameGUI()
save_name = gui.saveName
if len(save_name) <= 0:
continue
load(NEW_GAME_DIR)
State.save_name = save_name
State.push_screen(gameScreen.GameScreen(CURRENT_GAME_DIR))
elif self.currLine == GameMenuScreenLine.LoadGame:
State.push_screen(loadGameScreen.LoadGameScreen())
elif self.currLine == GameMenuScreenLine.Exit:
sys.exit(0)
else:
super(GameMenuScreen, self).interact(event)
示例2: test_load_save_state
def test_load_save_state(self):
filename = "test_logs/state.dat"
my_id = tc.CLIENT_ID
# TODO: change state
state.save(my_id, [], filename)
# TODO:check file
state.load(filename)
示例3: play
def play():
if state.canload():
state.load()
scene.pop()
scene.push(gamescene)
scene.push(buildscene)
else:
state.reset()
scene.pop()
scene.push(gamescene)
scene.push(cutscene)
示例4: predict
def predict():
saved = state.load('model')
#saved = None
if debug_mode:
saved = None
if saved == None:
train, y, test, _ = data.get()
ftrain, ftest, _ = fea_1.get()
ftrain2, ftest2, _ = fea_2.get()
train = pd.concat([train, ftrain, ftrain2], axis=1)
test = pd.concat([test, ftest, ftest2], axis=1)
print(train.shape, test.shape)
z = pd.DataFrame()
z['id'] = test.id
z['y'] = 0
v = pd.DataFrame()
v['id'] = train.id
v['y'] = y
cv, _ = run(train, y, test, v, z)
state.save('model', (v, z, cv, None))
else:
v, z, cv, _ = saved
return v, z, cv, _
示例5: __init__
def __init__(self, dht_addr, state_filename,
routing_m_mod, lookup_m_mod,
experimental_m_mod,
private_dht_name):
#TODO: don't do this evil stuff!!!
message.private_dht_name = private_dht_name
if size_estimation:
self._size_estimation_file = open('size_estimation.dat', 'w')
self.state_filename = state_filename
saved_id, saved_bootstrap_nodes = state.load(self.state_filename)
if saved_id:
self._my_id = saved_id
else:
self._my_id = identifier.RandomId()
self._my_node = Node(dht_addr, self._my_id)
self._tracker = tracker.Tracker()
self._token_m = token_manager.TokenManager()
self._querier = Querier()
self._routing_m = routing_m_mod.RoutingManager(self._my_node,
saved_bootstrap_nodes)
self._lookup_m = lookup_m_mod.LookupManager(self._my_id)
self._experimental_m = experimental_m_mod.ExperimentalManager(self._my_node.id)
current_ts = time.time()
self._next_save_state_ts = current_ts + SAVE_STATE_DELAY
self._next_maintenance_ts = current_ts
self._next_timeout_ts = current_ts
self._next_main_loop_call_ts = current_ts
self._pending_lookups = []
示例6: __init__
def __init__( self ):
"""
Initialise a ScrambleSuitTransport object.
"""
log.error("\n\n################################################\n"
"Do NOT rely on ScrambleSuit for strong security!\n"
"################################################\n")
log.debug("Initialising %s." % const.TRANSPORT_NAME)
super(ScrambleSuitTransport, self).__init__()
# Load the server's persistent state from file.
if self.weAreServer:
self.srvState = state.load()
# Initialise the protocol's state machine.
log.debug("Switching to state ST_WAIT_FOR_AUTH.")
self.protoState = const.ST_WAIT_FOR_AUTH
# Buffer for outgoing data.
self.sendBuf = ""
# Buffer for inter-arrival time obfuscation.
self.choppingBuf = fifobuf.Buffer()
# AES instances to decrypt incoming and encrypt outgoing data.
self.sendCrypter = mycrypto.PayloadCrypter()
self.recvCrypter = mycrypto.PayloadCrypter()
# Packet morpher to modify the protocol's packet length distribution.
self.pktMorpher = packetmorpher.new(self.srvState.pktDist
if self.weAreServer else None)
# Inter-arrival time morpher to obfuscate inter arrival times.
self.iatMorpher = self.srvState.iatDist if self.weAreServer else \
probdist.new(lambda: random.random() %
const.MAX_PACKET_DELAY)
# Used to extract protocol messages from encrypted data.
self.protoMsg = message.MessageExtractor()
# Used by the server-side: `True' if the ticket is already
# decrypted but not yet authenticated.
self.decryptedTicket = False
# If we are in external mode we should already have a shared
# secret set up because of validate_external_mode_cli().
if self.weAreExternal:
assert(self.uniformDHSecret)
if self.weAreClient and not self.weAreExternal:
# As a client in managed mode, we get the shared secret
# from callback `handle_socks_args()' per-connection. Set
# the shared secret to None for now.
self.uniformDHSecret = None
self.uniformdh = uniformdh.new(self.uniformDHSecret, self.weAreServer)
示例7: main
def main():
pygame.init()
pygame.mixer.init()
sound.setvolume(0)
pygame.font.init()
graphics.setmode()
graphics.init()
if settings.playback:
state0, record = cPickle.load(open(data.filepath("record.pkl"), "rb"))
state.loadobj(state0)
scene.push(scenes.game if settings.skipmenu else scenes.menu)
elif settings.restart:
state.init()
scene.push(scenes.game if settings.skipmenu else scenes.menu)
else:
scene.push(scenes.menu)
if state.load():
scene.push(scenes.game)
clock = pygame.time.Clock()
if settings.playback:
for rstate, dt, events, kpress, mpos in record:
clock.tick(settings.fps)
s = scene.top()
random.setstate(rstate)
if settings.vidcap:
vidcap._mpos = mpos
s.think(dt, events, kpress, mpos)
s.draw(mpos)
pygame.display.flip()
return
if settings.getrecord:
record = []
state0 = cPickle.loads(cPickle.dumps(state.saveobj()))
while scene.top():
dt = min(0.001 * clock.tick(settings.fps), 0.5)
if settings.fixfps:
dt = 1.0 / settings.fps
s = scene.top()
while dt > 0:
tdt = min(dt, 0.1)
events = map(EventProxy, pygame.event.get())
kpress = pygame.key.get_pressed()
mpos = pygame.mouse.get_pos()
if settings.getrecord:
record.append((random.getstate(), tdt, events, kpress, mpos))
s.think(tdt, events, kpress, mpos)
dt -= tdt
s.draw(mpos)
pygame.display.flip()
graphics.quit()
if settings.getrecord:
cPickle.dump([state0, record], open(data.filepath("record.pkl"), "wb"))
示例8: __enter__
def __enter__(self):
""" Resume or start the session. """
if self.resume and state.load():
state.basic_state.session.resume()
else:
state.basic_state.session = Session(self.show_greeting, self.prog)
self.thread = threading.Thread(target=state.basic_state.session.run,
args=(self.cmd, self.run, self.quit, self.wait))
self.thread.start()
示例9: update
def update(self, events):
'''
Updates the screen when an event happens
@param - list of game events
'''
for event in events:
if not hasattr(event, 'key'):
continue
if event.type == KEYDOWN:
if event.key == K_RETURN:
if self.currLine == LoadGameScreenLine.ReturnToMainMenu:
State.pop_screen()
continue
save_name = self.lines[self.currLine]
load(USER_SAVES_DIR + save_name)
State.save_name = save_name
State.pop_screen()
State.push_screen(gameScreen.GameScreen(CURRENT_GAME_DIR))
else:
super(LoadGameScreen, self).interact(event)
示例10: setup
def setup(cls, transportConfig):
"""
Called once when obfsproxy starts.
"""
log.error(
"\n\n################################################\n"
"Do NOT rely on ScrambleSuit for strong security!\n"
"################################################\n"
)
util.setStateLocation(transportConfig.getStateLocation())
cls.weAreClient = transportConfig.weAreClient
cls.weAreServer = not cls.weAreClient
cls.weAreExternal = transportConfig.weAreExternal
# If we are server and in managed mode, we should get the
# shared secret from the server transport options.
if cls.weAreServer and not cls.weAreExternal:
cfg = transportConfig.getServerTransportOptions()
if cfg and "password" in cfg:
try:
cls.uniformDHSecret = base64.b32decode(util.sanitiseBase32(cfg["password"]))
except (TypeError, AttributeError) as error:
raise base.TransportSetupFailed("Password could not be base32 decoded (%s)" % error)
cls.uniformDHSecret = cls.uniformDHSecret.strip()
if cls.weAreServer:
if not hasattr(cls, "uniformDHSecret"):
log.debug("Using fallback password for descriptor file.")
srv = state.load()
cls.uniformDHSecret = srv.fallbackPassword
if len(cls.uniformDHSecret) != const.SHARED_SECRET_LENGTH:
raise base.TransportSetupFailed(
"Wrong password length (%d instead of %d)" % len(cls.uniformDHSecret), const.SHARED_SECRET_LENGTH
)
if not const.STATE_LOCATION:
raise base.TransportSetupFailed(
"No state location set. If you are using external mode, "
"please set it using the --data-dir switch."
)
state.writeServerPassword(cls.uniformDHSecret)
示例11: predict
def predict():
saved = state.load('model')
#saved = None
if saved == None:
train, y, test, _ = data.get()
z = pd.DataFrame()
z['id'] = test.id
z['y'] = 0
v = pd.DataFrame()
v['id'] = train.id
v['y'] = y
cv, _ = run(train, y, test, v, z)
state.save('model', (v, z, cv, None))
else:
v, z, cv, _ = saved
return v, z, cv, _
示例12: predict
def predict():
saved = state.load('model')
if saved == None:
import l1_1_ho_xgb_1
import l1_1_ho_xgb_2
import l1_3_ho_xgb_1
import l1_3_ho_xgb_2
import l1_3_ho_xgb_3
#import l1_1_keras_1
import l1_1_keras_2
import l1_3_keras_1
import l1_3_keras_2
vs, zs, cvs = [], [], []
for module in [l1_1_ho_xgb_1, l1_1_ho_xgb_2, l1_3_ho_xgb_1, l1_3_ho_xgb_2,
l1_1_keras_2, l1_3_keras_1, l1_3_ho_xgb_3, l1_3_keras_2 ]:
v, z, cv, _ = module.predict()
vs.append(v)
zs.append(z)
cvs.append(cv)
z = pd.DataFrame()
z['id'] = zs[-1].id
z['y'] = 0
v = pd.DataFrame()
v['id'] = vs[-1].id
v['y'] = vs[-1].y
for s in vs + zs:
s.drop(['id', 'y'], axis=1, inplace=True)
train = pd.concat(vs, axis=1)
test = pd.concat(zs, axis=1)
y = v.y
cv, _ = run(train, y, test, v, z)
#state.save('model', (v, z, cv, None))
else:
v, z, cv, _ = saved
return v, z, cv, _
示例13: get_public_server_options
def get_public_server_options( cls, transportOptions ):
"""
Return ScrambleSuit's BridgeDB parameters, i.e., the shared secret.
As a fallback mechanism, we return an automatically generated password
if the bridge operator did not use `ServerTransportOptions'.
"""
log.debug("Tor's transport options: %s" % str(transportOptions))
if not "password" in transportOptions:
log.warning("No password found in transport options (use Tor's " \
"`ServerTransportOptions' to set your own password)." \
" Using automatically generated password instead.")
srv = state.load()
transportOptions = {"password":
base64.b32encode(srv.fallbackPassword)}
cls.uniformDHSecret = srv.fallbackPassword
return transportOptions
示例14: __init__
def __init__(self, version_label,
my_node, state_filename,
routing_m_mod, lookup_m_mod,
experimental_m_mod,
private_dht_name,
bootstrap_mode):
if size_estimation:
self._size_estimation_file = open('size_estimation.dat', 'w')
self.state_filename = state_filename
saved_id, saved_bootstrap_nodes = state.load(self.state_filename)
my_addr = my_node.addr
self._my_id = my_node.id # id indicated by user
if not self._my_id:
self._my_id = saved_id # id loaded from file
if not self._my_id:
self._my_id = self._my_id = identifier.RandomId() # random id
self._my_node = Node(my_addr, self._my_id, version=version_label)
self.msg_f = message.MsgFactory(version_label, self._my_id,
private_dht_name)
self._querier = Querier()
self._routing_m = routing_m_mod.RoutingManager(
self._my_node, saved_bootstrap_nodes, self.msg_f)
self._responder = responder.Responder(self._my_id, self._routing_m,
self.msg_f, bootstrap_mode)
self._tracker = self._responder._tracker
self._lookup_m = lookup_m_mod.LookupManager(self._my_id, self.msg_f)
self._experimental_m = experimental_m_mod.ExperimentalManager(
self._my_node.id, self.msg_f)
current_ts = time.time()
self._next_save_state_ts = current_ts + SAVE_STATE_DELAY
self._next_maintenance_ts = current_ts
self._next_timeout_ts = current_ts
self._next_main_loop_call_ts = current_ts
self._pending_lookups = []
self._cached_lookups = []
示例15: setup
def setup( cls, transportConfig ):
"""
Called once when obfsproxy starts.
"""
util.setStateLocation(transportConfig.getStateLocation())
cls.weAreClient = transportConfig.weAreClient
cls.weAreServer = not cls.weAreClient
cls.weAreExternal = transportConfig.weAreExternal
# If we are server and in managed mode, we should get the
# shared secret from the server transport options.
if cls.weAreServer and not cls.weAreExternal:
cfg = transportConfig.getServerTransportOptions()
if cfg and "password" in cfg:
try:
cls.uniformDHSecret = base64.b32decode(util.sanitiseBase32(
cfg["password"]))
except TypeError as error:
log.error(error.message)
raise base.PluggableTransportError("Given password '%s' " \
"is not valid Base32! Run " \
"'generate_password.py' to generate a good " \
"password." % cfg["password"])
cls.uniformDHSecret = cls.uniformDHSecret.strip()
if cls.weAreServer:
if not hasattr(cls, "uniformDHSecret"):
log.debug("Using fallback password for descriptor file.")
srv = state.load()
cls.uniformDHSecret = srv.fallbackPassword
state.writeServerDescriptor(cls.uniformDHSecret,
transportConfig.getBindAddr(),
cls.weAreExternal)