本文整理汇总了Python中six.viewitems方法的典型用法代码示例。如果您正苦于以下问题:Python six.viewitems方法的具体用法?Python six.viewitems怎么用?Python six.viewitems使用的例子?那么, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在类six
的用法示例。
在下文中一共展示了six.viewitems方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Python代码示例。
示例1: plot_avg_regret
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def plot_avg_regret(policy):
"""Plot average regret with respect to time.
Parameters
----------
policy: bandit object
The bandit algorithm you want to evaluate.
"""
avg_reward = calculate_avg_reward(policy)
points = sorted(six.viewitems(avg_reward), key=lambda x: x[0])
x, y = zip(*points)
plt.plot(x, [1 - reward for reward in y], 'r-', label="average regret")
plt.xlabel('time')
plt.ylabel('avg regret')
plt.legend()
plt.title("Average Regret with respect to Time")
示例2: form_valid
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def form_valid(self, form):
"""
Main functionality, creates :class:`Service` and calls
:meth:`execute` with proper parameters. If everything
is successful, calls Base :meth:`form_valid`. If error
is throw, adds it to the form and calls :meth:`form_invalid`
"""
try:
cls = self.get_service_class()
cls.execute(
self.get_service_input(form),
self.get_service_files(),
**self.get_service_kwargs()
)
return super(ServiceViewMixin, self).form_valid(form)
except InvalidInputsError as e:
for k, v in viewitems(e.errors):
form.add_error(k, v)
return self.form_invalid(form)
except ValidationError as e:
form.add_error(None, e)
return self.form_invalid(form)
示例3: dump
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def dump(self):
cls = self.__class__
# FIXME: doesn't support recursion
def stringify(layer, indent=0, tab=' '):
data = (k for k, v in six.viewitems(layer) if not isinstance(v, node))
result = []
for k in data:
result.append("{:s}{!r} -> {!r}".format(tab * indent, k, layer[k]))
branches = [k for k, v in six.viewitems(layer) if isinstance(v, node)]
for k in branches:
result.append("{:s}{!r}".format(tab * indent, k))
branch_data = stringify(layer[k], indent+1, tab=tab)
result.extend(branch_data)
return result
return '\n'.join(("{!r}({:d})".format(cls, self.id), '\n'.join(stringify(self))))
### cache for looking up encoder/decoder types
示例4: CaptureFrameLocals
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def CaptureFrameLocals(self, frame):
"""Captures local variables and arguments of the specified frame.
Args:
frame: frame to capture locals and arguments.
Returns:
(arguments, locals) tuple.
"""
# Capture all local variables (including method arguments).
variables = {n: self.CaptureNamedVariable(n, v, 1,
self.default_capture_limits)
for n, v in six.viewitems(frame.f_locals)}
# Split between locals and arguments (keeping arguments in the right order).
nargs = frame.f_code.co_argcount
if frame.f_code.co_flags & inspect.CO_VARARGS: nargs += 1
if frame.f_code.co_flags & inspect.CO_VARKEYWORDS: nargs += 1
frame_arguments = []
for argname in frame.f_code.co_varnames[:nargs]:
if argname in variables: frame_arguments.append(variables.pop(argname))
return (frame_arguments, list(six.viewvalues(variables)))
示例5: get_data_keys_from_structure
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def get_data_keys_from_structure(structure):
data_keys = []
def _get_data_keys_from_structure(structure):
if isinstance(structure, basestring):
data_keys.append(structure)
elif isinstance(structure, list):
data_keys.extend(structure)
elif isinstance(structure, dict):
for _, val in six.viewitems(structure):
_get_data_keys_from_structure(val)
else:
raise TypeError("The bundle structure only support "
"dict, list and str.")
_get_data_keys_from_structure(structure)
return data_keys
示例6: match_node
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def match_node(self, key):
found_node = None
for regex_key, node in six.viewitems(self._key_node_dict):
match_object = re.match("(?:%s)\Z" % regex_key, key)
if match_object is not None:
if found_node is None:
found_node = node
found_regex_key = regex_key
found_match_object = match_object
else:
raise ValueError("The data key '{}' matches multiple keys: "
"'{}' for {} and '{}' for {}.".format(
key, found_regex_key, found_node,
regex_key, node))
if found_node is None:
raise KeyError(key)
return found_regex_key, found_node, found_match_object
示例7: viewflatitems
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def viewflatitems(self):
''' Return view of flattened items '''
return six.viewitems(self.flattened())
示例8: get_advice
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def get_advice(context, action_ids, experts):
advice = {}
for t, context_t in six.viewitems(context):
advice[t] = {}
for exp_i, expert in enumerate(experts):
prob = expert.predict_proba(context_t[np.newaxis, :])[0]
advice[t][exp_i] = {}
for action_id, action_prob in zip(action_ids, prob):
advice[t][exp_i][action_id] = action_prob
return advice
示例9: reward
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def reward(self, history_id, rewards):
"""Reward the previous action with reward.
Parameters
----------
history_id : int
The history id of the action to reward.
rewards : dictionary
The dictionary {action_id, reward}, where reward is a float.
"""
context = (self._history_storage
.get_unrewarded_history(history_id)
.context)
# Update the model
model = self._model_storage.get_model()
B = model['B'] # pylint: disable=invalid-name
f = model['f']
for action_id, reward in six.viewitems(rewards):
context_t = np.reshape(context[action_id], (-1, 1))
B += context_t.dot(context_t.T) # pylint: disable=invalid-name
f += reward * context_t
mu_hat = np.linalg.inv(B).dot(f)
self._model_storage.save_model({'B': B, 'mu_hat': mu_hat, 'f': f})
# Update the history
self._history_storage.add_reward(history_id, rewards)
示例10: reward
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def reward(self, history_id, rewards):
"""Reward the previous action with reward.
Parameters
----------
history_id : int
The history id of the action to reward.
rewards : dictionary
The dictionary {action_id, reward}, where reward is a float.
"""
context = (self._history_storage
.get_unrewarded_history(history_id)
.context)
# Update the model
model = self._model_storage.get_model()
A = model['A'] # pylint: disable=invalid-name
A_inv = model['A_inv'] # pylint: disable=invalid-name
b = model['b']
theta = model['theta']
for action_id, reward in six.viewitems(rewards):
action_context = np.reshape(context[action_id], (-1, 1))
A[action_id] += action_context.dot(action_context.T)
A_inv[action_id] = np.linalg.inv(A[action_id])
b[action_id] += reward * action_context
theta[action_id] = A_inv[action_id].dot(b[action_id])
self._model_storage.save_model({
'A': A,
'A_inv': A_inv,
'b': b,
'theta': theta,
})
# Update the history
self._history_storage.add_reward(history_id, rewards)
示例11: reward
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def reward(self, history_id, rewards):
"""Reward the previous action with reward.
Parameters
----------
history_id : int
The history id of the action to reward.
rewards : dictionary
The dictionary {action_id, reward}, where reward is a float.
"""
context = (self._historystorage
.get_unrewarded_history(history_id)
.context)
model = self._modelstorage.get_model()
w = model['w']
action_probs = model['action_probs']
action_ids = list(six.viewkeys(six.next(six.itervalues(context))))
# Update the model
for action_id, reward in six.viewitems(rewards):
y_hat = {}
v_hat = {}
for i in six.viewkeys(context):
y_hat[i] = (context[i][action_id] * reward
/ action_probs[action_id])
v_hat[i] = sum(
[context[i][k] / action_probs[k] for k in action_ids])
w[i] = w[i] * np.exp(
self.p_min / 2
* (y_hat[i] + v_hat[i]
* np.sqrt(np.log(len(context) / self.delta)
/ (len(action_ids) * self.max_rounds))))
self._modelstorage.save_model({
'action_probs': action_probs, 'w': w})
# Update the history
self._historystorage.add_reward(history_id, rewards)
示例12: get_format_str
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def get_format_str(data):
for format_str, format_class in six.viewitems(FORMAT_DICT):
if isinstance(data, format_class):
return format_str
raise ValueError("Data type {} is not supported.".format(type(data)))
示例13: hashable_lru
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def hashable_lru(maxsize=16):
def hashable_cache_internal(func):
cache = lru_cache(maxsize=maxsize)
def deserialize(value):
if isinstance(value, Serialized):
return json.loads(value.json)
else:
return value
def func_with_serialized_params(*args, **kwargs):
_args = tuple([deserialize(arg) for arg in args])
_kwargs = {k: deserialize(v) for k, v in six.viewitems(kwargs)}
return func(*_args, **_kwargs)
cached_func = cache(func_with_serialized_params)
@wraps(func)
def hashable_cached_func(*args, **kwargs):
_args = tuple([
Serialized(json.dumps(arg, sort_keys=True))
if type(arg) in (list, dict) else arg
for arg in args
])
_kwargs = {
k: Serialized(json.dumps(v, sort_keys=True))
if type(v) in (list, dict) else v
for k, v in kwargs.items()
}
return copy.deepcopy(cached_func(*_args, **_kwargs))
hashable_cached_func.cache_info = cached_func.cache_info
hashable_cached_func.cache_clear = cached_func.cache_clear
return hashable_cached_func
return hashable_cache_internal
示例14: globals
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def globals(Globals, **tagmap):
'''Apply the tags in `Globals` back into the database.'''
global apply
cls, tagmap_output = apply.__class__, u", {:s}".format(u', '.join(u"{:s}={:s}".format(internal.utils.string.escape(oldtag), internal.utils.string.escape(newtag)) for oldtag, newtag in six.iteritems(tagmap))) if tagmap else ''
count = 0
for ea, res in Globals:
ns = func if func.within(ea) else db
# grab the current (old) tag state
state = ns.tag(ea)
# transform the new tag state using the tagmap
new = { tagmap.get(name, name) : value for name, value in six.viewitems(res) }
# check if the tag mapping resulted in the deletion of a tag
if len(new) != len(res):
for name in six.viewkeys(res) - six.viewkeys(new):
logging.warn(u"{:s}.globals(...{:s}) : Refusing requested tag mapping as it results in the tag \"{:s}\" overwriting the tag \"{:s}\" in the global {:#x}. The value {!s} would be replaced with {!s}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.escape(name, '"'), internal.utils.string.escape(tagmap[name], '"'), ea, internal.utils.string.repr(res[name]), internal.utils.string.repr(res[tagmap[name]])))
pass
# check what's going to be overwritten with different values prior to doing it
for name in six.viewkeys(state) & six.viewkeys(new):
if state[name] == new[name]: continue
logging.warn(u"{:s}.globals(...{:s}) : Overwriting tag \"{:s}\" for global at {:#x} with new value {!s}. Old value was {!s}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.escape(name, '"'), ea, internal.utils.string.repr(new[name]), internal.utils.string.repr(state[name])))
# now we can apply the tags to the global address
try:
[ ns.tag(ea, name, value) for name, value in six.iteritems(new) if state.get(name, dummy) != value ]
except:
logging.warn(u"{:s}.globals(...{:s}) : Unable to apply tags ({!s}) to global {:#x}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.repr(new), ea), exc_info=True)
# increase our counter
count += 1
return count
## applying contents tags to all the functions
示例15: contents
# 需要导入模块: import six [as 别名]
# 或者: from six import viewitems [as 别名]
def contents(Contents, **tagmap):
'''Apply the tags in `Contents` back into each function within the database.'''
global apply
cls, tagmap_output = apply.__class__, u", {:s}".format(u', '.join(u"{:s}={:s}".format(internal.utils.string.escape(oldtag), internal.utils.string.escape(newtag)) for oldtag, newtag in six.iteritems(tagmap))) if tagmap else ''
count = 0
for loc, res in Contents:
ea = locationToAddress(loc)
# warn the user if this address is not within a function
if not func.within(ea):
logging.warn(u"{:s}.contents(...{:s}) : Address {:#x} is not within a function. Using a global tag.".format('.'.join((__name__, cls.__name__)), tagmap_output, ea))
# grab the current (old) tag state
state = db.tag(ea)
# transform the new tag state using the tagmap
new = { tagmap.get(name, name) : value for name, value in six.viewitems(res) }
# check if the tag mapping resulted in the deletion of a tag
if len(new) != len(res):
for name in six.viewkeys(res) - six.viewkeys(new):
logging.warn(u"{:s}.contents(...{:s}) : Refusing requested tag mapping as it results in the tag \"{:s}\" overwriting tag \"{:s}\" for the contents at {:#x}. The value {!s} would be overwritten by {!s}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.escape(name, '"'), internal.utils.string.escape(tagmap[name], '"'), ea, internal.utils.string.repr(res[name]), internal.utils.string.repr(res[tagmap[name]])))
pass
# inform the user if any tags are being overwritten with different values
for name in six.viewkeys(state) & six.viewkeys(new):
if state[name] == new[name]: continue
logging.warn(u"{:s}.contents(...{:s}) : Overwriting contents tag \"{:s}\" for address {:#x} with new value {!s}. Old value was {!s}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.escape(name, '"'), ea, internal.utils.string.repr(new[name]), internal.utils.string.repr(state[name])))
# write the tags to the contents address
try:
[ db.tag(ea, name, value) for name, value in six.iteritems(new) if state.get(name, dummy) != value ]
except:
logging.warn(u"{:s}.contents(...{:s}) : Unable to apply tags {!s} to location {:#x}.".format('.'.join((__name__, cls.__name__)), tagmap_output, internal.utils.string.repr(new), ea), exc_info=True)
# increase our counter
count += 1
return count
## applying frames to all the functions