本文整理汇总了Python中jsonpickle.decode方法的典型用法代码示例。如果您正苦于以下问题:Python jsonpickle.decode方法的具体用法?Python jsonpickle.decode怎么用?Python jsonpickle.decode使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类jsonpickle
的用法示例。
在下文中一共展示了jsonpickle.decode方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: decode
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def decode(self, feature_vec, input_features, ndigits=8):
"""Reverse operation to binary_encoded_features
:param feature_vec: binary feature vector
:param input_features: list of all features
:param ndigits: ignored
:return: dictionary of active features
"""
reversed_features = []
for bf in feature_vec:
if np.sum(np.where(bf == 1)) > 0:
feature_tuples = []
feat_names = list(np.array(input_features)[np.where(bf == 1)])
for feat_name in feat_names:
feature_tuples.append((feat_name, 1))
reversed_features.append(feature_tuples)
else:
reversed_features.append(None)
return reversed_features
示例2: __init__
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def __init__(self, file, error_on_decode=False, ctx=None):
proscli.utils.debug('Opening {} ({})'.format(file, self.__class__.__name__), ctx=ctx)
self.save_file = file # type: str
self.__ignored = ['save_file', '_Config__ignored'] # type: list(str)
if file:
if os.path.isfile(file):
with open(file, 'r') as f:
try:
self.__dict__.update(jsonpickle.decode(f.read()).__dict__)
except (json.decoder.JSONDecodeError, AttributeError):
if error_on_decode:
raise
else:
pass
elif os.path.isdir(file):
raise ValueError('{} must be a file, not a directory'.format(file))
else:
try:
self.save()
except Exception:
pass
示例3: read_dictionary
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def read_dictionary(self, providers=None):
config_dir = user_config_dir()
filename = os.path.join(config_dir, 'QTable.json')
if not os.path.exists(filename):
# TODO: check if it will not affect anything
self.self_state = VPSState(provider="blueangelhost", option="Basic Plan")
self.init_qtable_and_environment(providers)
self.create_initial_tree()
self.write_dictionary()
else:
with open(filename) as json_file:
data_encoded = json.load(json_file)
data = jsonpickle.decode(data_encoded)
self.environment = data['environment']
self.qtable = data['qtable']
self.providers_offers = data['providers_offers']
self.self_state = data['self_state']
self.tree = data['tree']
示例4: _load
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def _load():
def load_stock_weapons():
with open('dueutil/game/configs/defaultweapons.json') as defaults_file:
defaults = json.load(defaults_file)
for weapon_name, weapon_data in defaults.items():
stock_weapons.append(weapon_name)
Weapon(weapon_data["name"],
weapon_data["useText"],
weapon_data["damage"],
weapon_data["accy"],
icon=weapon_data["icon"],
image_url=weapon_data["image"],
melee=weapon_data["melee"],
no_save=True)
load_stock_weapons()
# Load from db
for weapon in dbconn.get_collection_for_object(Weapon).find():
loaded_weapon = jsonpickle.decode(weapon['data'])
weapons[loaded_weapon.id] = util.load_and_update(NO_WEAPON, loaded_weapon)
util.logger.info("Loaded %s weapons", len(weapons))
示例5: _load
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def _load():
def load_default_quests():
with open('dueutil/game/configs/defaultquests.json') as defaults_file:
defaults = json.load(defaults_file)
for quest_data in defaults.values():
Quest(quest_data["name"],
quest_data["baseAttack"],
quest_data["baseStrg"],
quest_data["baseAccy"],
quest_data["baseHP"],
task=quest_data["task"],
weapon_id=weapons.stock_weapon(quest_data["weapon"]),
image_url=quest_data["image"],
spawn_chance=quest_data["spawnChance"],
no_save=True)
load_default_quests()
for quest in dbconn.get_collection_for_object(Quest).find():
loaded_quest = jsonpickle.decode(quest['data'])
quest_map[loaded_quest.id] = util.load_and_update(REFERENCE_QUEST, loaded_quest)
util.logger.info("Loaded %s quests", len(quest_map))
示例6: check_queue
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def check_queue():
await bot.wait_until_ready()
while not bot.is_closed:
queue = await get_queue()
if len(queue) == 0:
await asyncio.sleep(1)
else:
for s in queue:
message_id = int(s)
channel_id = str(queue[s][0])
message = str(queue[s][1])
embed = True if int(queue[s][3]) else False
try:
target = bot.get_channel(channel_id)
if embed:
await bot.send_message(target, embed=jsonpickle.decode(message))
else:
await truncate(target, message)
except Exception as e:
print(e)
pass
delete_request = await delete_queue(message_id)
await asyncio.sleep(0.21)
示例7: load_chain
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def load_chain(current_port, nodes=None):
all_blocks = []
from requests.exceptions import ConnectionError
import jsonpickle
for node in nodes:
try:
# kendi kendisine chain sormaması için.
if node != current_port:
http_response = requests.get(
'http://localhost:{0}/chain'.format(node))
serialized = http_response.json()['blocks']
thawed = jsonpickle.decode(serialized)
all_blocks.append((node, thawed))
except ConnectionError as conerr:
_log('info', '{0} porta sahip node offline olabilir'.format(node))
active_node.load_chain(all_blocks)
示例8: load
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def load(self, cfgf, prefix=None):
if self.dataLoaded:
return
if prefix != None:
self.certsDir = prefix + '/etc/ca/certs'
if not os.path.exists(self.certsDir):
log.L.error('Certs directory does not exist or is unreadable (%s)!' % self.certsDir)
log.L.error('Make sure you ran `make install` without errors.')
self.certsDir = None
if (self.configFile is None):
self.configFile = cfgf
try:
if (self.configFile != None):
f = open(self.configFile, 'r')
jsonStr = f.read()
f.close()
self.data = jsonpickle.decode(jsonStr)
self.dataLoaded = True
except IOError:
log.L.error("Cannot read SDP file %s" % (self.configFile))
示例9: call_method_post
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def call_method_post(self, method, json_scheme, debug=False):
url = '{}/{}'.format(self.wcf_baseurl, method)
headers = {'Content-Type': 'application/json', 'Content-Length': str(len(json_scheme))}
response = Http.post(url=url, data=json_scheme, headers=headers)
parsed_response = json.loads(response.content.decode('utf-8'))
if response.status_code != 200:
from ArubaCloud.base.Errors import MalformedJsonRequest
raise MalformedJsonRequest("Request: {}, Status Code: {}".format(json_scheme, response.status_code))
if parsed_response['Success'] is False:
from ArubaCloud.base.Errors import RequestFailed
raise RequestFailed("Request: {}, Response: {}".format(json_scheme, parsed_response))
if debug is True:
msg = "Response Message: {}\nHTTP Status Code: {}".format(parsed_response, response.status_code)
self.logger.debug(msg)
print(msg)
return parsed_response
示例10: _commit
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def _commit(self):
"""
:return: (dict) Response object content
"""
assert self.uri is not None, Exception("BadArgument: uri property cannot be None")
url = '{}/{}'.format(self.uri, self.__class__.__name__)
serialized_json = jsonpickle.encode(self, unpicklable=False, )
headers = {'Content-Type': 'application/json', 'Content-Length': str(len(serialized_json))}
response = Http.post(url=url, data=serialized_json, headers=headers)
if response.status_code != 200:
from ArubaCloud.base.Errors import MalformedJsonRequest
raise MalformedJsonRequest("Request: {}, Status Code: {}".format(serialized_json, response.status_code))
content = jsonpickle.decode(response.content.decode("utf-8"))
if content['ResultCode'] == 17:
from ArubaCloud.base.Errors import OperationAlreadyEnqueued
raise OperationAlreadyEnqueued("{} already enqueued".format(self.__class__.__name__))
if content['Success'] is False:
from ArubaCloud.base.Errors import RequestFailed
raise RequestFailed("Request: {}, Response: {}".format(serialized_json, response.content))
return content
示例11: __init__
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def __init__(self):
configureLogging()
self.logger = getLogger(with_console=True)
get_packet_logger(with_console=True)
self.logger.info("mq operator is starting")
with open("settings.json", "r") as stream:
lines = stream.read()
txt = ""
for line in lines:
txt = txt + line
self.configuration = jsonpickle.decode(txt)
self.client = mqtt.Client(client_id=self.configuration.mqtt_clientid, protocol=mqtt.MQTTv311)
self.client.on_connect = self.on_connect
self.client.on_disconnect = self.on_disconnect
self.client.on_message = self.on_message
self.client.tls_set(ca_certs="/etc/ssl/certs/DST_Root_CA_X3.pem")
self.i_pdm = None
self.i_pod = None
self.g_pdm = None
self.g_pod = None
self.rate_requested = None
self.rate_request_lock = Lock()
self.rate_check_lock = Lock()
self.rate_check_event = Event()
示例12: get_automatic_additional
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def get_automatic_additional(self):
if self.additional:
clf = jsonpickle.decode(self.additional)
a = list([a for l in clf.corrections.values() for a in l]) + \
list([a for l in clf.additions.values() for a in l]) + \
list([a for l in clf.resolutions.values() for a in l])
if len(a) != 0 and type(a[0]) is not StressCorrection:
self.__compatibility_stress_correction(clf.corrections)
self.__compatibility_stress_correction(clf.resolutions)
self.__compatibility_stress_correction(clf.additions)
return clf
else:
return ""
示例13: load
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def load(path):
featurizer_file = os.path.join(path, "featurizer.json")
if os.path.isfile(featurizer_file):
with io.open(featurizer_file, 'r') as f:
_json = f.read()
return jsonpickle.decode(_json)
else:
logger.info("Couldn't load featurizer for policy. "
"File '{}' doesn't exist. ".format(featurizer_file))
return None
示例14: setup_schedule
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def setup_schedule(self):
# init entries
self.merge_inplace(self.app.conf.CELERYBEAT_SCHEDULE)
tasks = [jsonpickle.decode(entry) for entry in self.rdb.zrange(self.key, 0, -1)]
linfo('Current schedule:\n' + '\n'.join(
str('task: ' + entry.task + '; each: ' + repr(entry.schedule))
for entry in tasks))
示例15: merge_inplace
# 需要导入模块: import jsonpickle [as 别名]
# 或者: from jsonpickle import decode [as 别名]
def merge_inplace(self, tasks):
old_entries = self.rdb.zrangebyscore(self.key, 0, MAXINT, withscores=True)
old_entries_dict = dict({})
for task, score in old_entries:
if not task:
break
debug("ready to loads old entry: ", str(task))
entry = jsonpickle.decode(task)
old_entries_dict[entry.name] = (entry, score)
debug("old_entries: {}".format(old_entries_dict))
self.rdb.delete(self.key)
for key in tasks:
last_run_at = 0
e = self.Entry(**dict(tasks[key], name=key, app=self.app))
if key in old_entries_dict:
# replace entry and remain old score
last_run_at = old_entries_dict[key][1]
del old_entries_dict[key]
self.rdb.zadd(self.key, {jsonpickle.encode(e): min(last_run_at, self._when(e, e.is_due()[1]) or 0)})
debug("old_entries: {}".format(old_entries_dict))
for key, tasks in old_entries_dict.items():
debug("key: {}".format(key))
debug("tasks: {}".format(tasks))
debug("zadd: {}".format(self.rdb.zadd(self.key, {jsonpickle.encode(tasks[0]): tasks[1]})))
debug(self.rdb.zrange(self.key, 0, -1))