Search is not available for this dataset
text stringlengths 75 104k |
|---|
def group(self, *args):
"""Returns one or more subgroups of the match. Each argument is either a
group index or a group name."""
if len(args) == 0:
args = (0,)
grouplist = []
for group in args:
grouplist.append(self._get_slice(self._get_index(group), None)... |
def fast_search(self, pattern_codes):
"""Skips forward in a string as fast as possible using information from
an optimization info block."""
# pattern starts with a known prefix
# <5=length> <6=skip> <7=prefix data> <overlap data>
flags = pattern_codes[2]
prefix_len = pat... |
def push_new_context(self, pattern_offset):
"""Creates a new child context of this context and pushes it on the
stack. pattern_offset is the offset off the current code position to
start interpreting from."""
child_context = _MatchContext(self.state,
self.pattern_codes[self.c... |
def match(self, context):
"""Returns True if the current context matches, False if it doesn't and
None if matching is not finished, ie must be resumed after child
contexts have been matched."""
while context.remaining_codes() > 0 and context.has_matched is None:
opcode = cont... |
def dispatch(self, opcode, context):
"""Dispatches a context on a given opcode. Returns True if the context
is done matching, False if it must be resumed when next encountered."""
if id(context) in self.executing_contexts:
generator = self.executing_contexts[id(context)]
... |
def check_charset(self, ctx, char):
"""Checks whether a character matches set of arbitrary length. Assumes
the code pointer is at the first member of the set."""
self.set_dispatcher.reset(char)
save_position = ctx.code_position
result = None
while result is None:
... |
def count_repetitions(self, ctx, maxcount):
"""Returns the number of repetitions of a single item, starting from the
current string position. The code pointer is expected to point to a
REPEAT_ONE operation (with the repeated 4 ahead)."""
count = 0
real_maxcount = ctx.state.end - ... |
def extract(s):
"""Return (sign, intpart, fraction, expo) or raise an exception:
sign is '+' or '-'
intpart is 0 or more digits beginning with a nonzero
fraction is 0 or more digits
expo is an integer"""
res = decoder.match(s)
if res is None: raise NotANumber, s
sign, intpart, fraction, ... |
def unexpo(intpart, fraction, expo):
"""Remove the exponent by changing intpart and fraction."""
if expo > 0: # Move the point left
f = len(fraction)
intpart, fraction = intpart + fraction[:expo], fraction[expo:]
if expo > f:
intpart = intpart + '0'*(expo-f)
elif expo < 0... |
def roundfrac(intpart, fraction, digs):
"""Round or extend the fraction to size digs."""
f = len(fraction)
if f <= digs:
return intpart, fraction + '0'*(digs-f)
i = len(intpart)
if i+digs < 0:
return '0'*-digs, ''
total = intpart + fraction
nextdigit = total[i+digs]
if ne... |
def fix(x, digs):
"""Format x as [-]ddd.ddd with 'digs' digits after the point
and at least one digit before.
If digs <= 0, the point is suppressed."""
if type(x) != type(''): x = repr(x)
try:
sign, intpart, fraction, expo = extract(x)
except NotANumber:
return x
intpart, fra... |
def sci(x, digs):
"""Format x as [-]d.dddE[+-]ddd with 'digs' digits after the point
and exactly one digit before.
If digs is <= 0, one digit is kept and the point is suppressed."""
if type(x) != type(''): x = repr(x)
sign, intpart, fraction, expo = extract(x)
if not intpart:
while fract... |
def getrandbits(self, k):
"""getrandbits(k) -> x. Generates an int with k random bits."""
if k <= 0:
raise ValueError('number of bits must be greater than zero')
if k != int(k):
raise TypeError('number of bits should be an integer')
numbytes = (k + 7) // 8 # bits / 8 a... |
def _randbelow(self, n):
"""Return a random int in the range [0,n)."""
# TODO
# change once int.bit_length is implemented.
# k = n.bit_length()
k = _int_bit_length(n)
r = self.getrandbits(k)
while r >= n:
r = self.getrandbits(k)
return r |
def getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
Parses command line options and parameter list. args is the
argument list to be parsed, without the leading reference to the
running program. Typically, this means "sys.argv[1:]". shortopts
is the ... |
def gnu_getopt(args, shortopts, longopts = []):
"""getopt(args, options[, long_options]) -> opts, args
This function works like getopt(), except that GNU style scanning
mode is used by default. This means that option and non-option
arguments may be intermixed. The getopt() function stops
processing... |
def filter(names, pat):
"""Return the subset of the list NAMES that match PAT"""
import os
# import posixpath
result=[]
# pat=os.path.normcase(pat)
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if len(_cache) >= _MAXCACHE:
# _cache.clear(... |
def fnmatchcase(name, pat):
"""Test whether FILENAME matches PATTERN, including case.
This is a version of fnmatch() which doesn't case-normalize
its arguments.
"""
try:
re_pat = _cache[pat]
except KeyError:
res = translate(pat)
if len(_cache) >= _MAXCACHE:
... |
def translate(pat):
"""Translate a shell PATTERN to a regular expression.
There is no way to quote meta-characters.
"""
i, n = 0, len(pat)
res = ''
while i < n:
c = pat[i]
i = i+1
if c == '*':
res = res + '.*'
elif c == '?':
res = res + '... |
def task_done(self):
"""Indicate that a formerly enqueued task is complete.
Used by Queue consumer threads. For each get() used to fetch a task,
a subsequent call to task_done() tells the queue that the processing
on the task is complete.
If a join() is currently blocking, it ... |
def qsize(self):
"""Return the approximate size of the queue (not reliable!)."""
self.mutex.acquire()
n = self._qsize()
self.mutex.release()
return n |
def empty(self):
"""Return True if the queue is empty, False otherwise (not reliable!)."""
self.mutex.acquire()
n = not self._qsize()
self.mutex.release()
return n |
def full(self):
"""Return True if the queue is full, False otherwise (not reliable!)."""
self.mutex.acquire()
n = 0 < self.maxsize == self._qsize()
self.mutex.release()
return n |
def put(self, item, block=True, timeout=None):
"""Put an item into the queue.
If optional args 'block' is true and 'timeout' is None (the default),
block if necessary until a free slot is available. If 'timeout' is
a non-negative number, it blocks at most 'timeout' seconds and raises
... |
def calculate_transitive_deps(modname, script, gopath):
"""Determines all modules that script transitively depends upon."""
deps = set()
def calc(modname, script):
if modname in deps:
return
deps.add(modname)
for imp in collect_imports(modname, script, gopath):
if imp.is_native:
de... |
def _make_future_features(node):
"""Processes a future import statement, returning set of flags it defines."""
assert isinstance(node, ast.ImportFrom)
assert node.module == '__future__'
features = FutureFeatures()
for alias in node.names:
name = alias.name
if name in _FUTURE_FEATURES:
if name no... |
def parse_future_features(mod):
"""Accumulates a set of flags for the compiler __future__ imports."""
assert isinstance(mod, ast.Module)
found_docstring = False
for node in mod.body:
if isinstance(node, ast.ImportFrom):
if node.module == '__future__':
return node, _make_future_features(node)
... |
def contextmanager(func):
"""@contextmanager decorator.
Typical usage:
@contextmanager
def some_generator(<arguments>):
<setup>
try:
yield <value>
finally:
<cleanup>
This makes this:
with some_generator(<argument... |
def nested(*managers):
"""Combine multiple context managers into a single nested context manager.
This function has been deprecated in favour of the multiple manager form
of the with statement.
The one advantage of this function over the multiple manager form of the
with statement is that argument unp... |
def decode(self, s, _w=WHITESPACE.match):
"""Return the Python representation of ``s`` (a ``str`` or ``unicode``
instance containing a JSON document)
"""
obj, end = self.raw_decode(s, idx=_w(s, 0).end())
end = _w(s, end).end()
if end != len(s):
raise ValueErr... |
def tf_loss(self, states, internals, reward, update, reference=None):
"""
Creates the TensorFlow operations for calculating the L2 loss between predicted
state values and actual rewards.
Args:
states: Dict of state tensors.
internals: List of prior internal state... |
def get_variables(self, include_nontrainable=False):
"""
Returns the TensorFlow variables used by the baseline.
Returns:
List of variables
"""
if include_nontrainable:
return [self.all_variables[key] for key in sorted(self.all_variables)]
else:
... |
def from_spec(spec, kwargs=None):
"""
Creates a baseline from a specification dict.
"""
baseline = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.baselines.baselines,
kwargs=kwargs
)
assert isinstance(baseline, Baseline)... |
def reset(self):
"""
same as step (no kwargs to pass), but needs to block and return observation_dict
- stores the received observation in self.last_observation
"""
# Send command.
self.protocol.send({"cmd": "reset"}, self.socket)
# Wait for response.
resp... |
def execute(self, action):
"""
Executes a single step in the UE4 game. This step may be comprised of one or more actual game ticks for all of
which the same given
action- and axis-inputs (or action number in case of discretized actions) are repeated.
UE4 distinguishes between act... |
def translate_abstract_actions_to_keys(self, abstract):
"""
Translates a list of tuples ([pretty mapping], [value]) to a list of tuples ([some key], [translated value])
each single item in abstract will undergo the following translation:
Example1:
we want: "MoveRight": 5.0
... |
def discretize_action_space_desc(self):
"""
Creates a list of discrete action(-combinations) in case we want to learn with a discrete set of actions,
but only have action-combinations (maybe even continuous) available from the env.
E.g. the UE4 game has the following action/axis-mappings... |
def reset(self):
"""
Resets the environment to its initialization state. This method needs to be called to start a
new episode after the last episode ended.
:return: initial state
"""
self.level.reset() # optional: episode=-1, seed=None
return self.level.observa... |
def execute(self, action):
"""
Pass action to universe environment, return reward, next step, terminal state and
additional info.
:param action: action to execute as numpy array, should have dtype np.intc and should adhere to
the specification given in DeepMindLabEnvironment... |
def tf_solve(self, fn_x, x_init, b):
"""
Iteratively solves the system of linear equations $A x = b$.
Args:
fn_x: A callable returning the left-hand side $A x$ of the system of linear equations.
x_init: Initial solution guess $x_0$, zero vector if None.
b: Th... |
def tf_initialize(self, x_init, b):
"""
Initialization step preparing the arguments for the first iteration of the loop body:
$x_0, 0, p_0, r_0, r_0^2$.
Args:
x_init: Initial solution guess $x_0$, zero vector if None.
b: The right-hand side $b$ of the system of... |
def tf_step(self, x, iteration, conjugate, residual, squared_residual):
"""
Iteration loop body of the conjugate gradient algorithm.
Args:
x: Current solution estimate $x_t$.
iteration: Current iteration counter $t$.
conjugate: Current conjugate $c_t$.
... |
def tf_next_step(self, x, iteration, conjugate, residual, squared_residual):
"""
Termination condition: max number of iterations, or residual sufficiently small.
Args:
x: Current solution estimate $x_t$.
iteration: Current iteration counter $t$.
conjugate: Cu... |
def tf_step(self, time, variables, **kwargs):
"""
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional arguments passed on to the internal optimizer.
... |
def from_spec(spec, kwargs=None):
"""
Creates a layer from a specification dict.
"""
layer = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.networks.layers,
kwargs=kwargs
)
assert isinstance(layer, Layer)
return ... |
def tf_q_delta(self, q_value, next_q_value, terminal, reward):
"""
Creates the deltas (or advantage) of the Q values.
:return: A list of deltas per action
"""
for _ in range(util.rank(q_value) - 1):
terminal = tf.expand_dims(input=terminal, axis=1)
reward... |
def target_optimizer_arguments(self):
"""
Returns the target optimizer arguments including the time, the list of variables to
optimize, and various functions which the optimizer might require to perform an update
step.
Returns:
Target optimizer arguments as dict.... |
def from_spec(spec, kwargs):
"""
Creates an environment from a specification dict.
"""
env = tensorforce.util.get_object(
obj=spec,
predefined_objects=tensorforce.environments.environments,
kwargs=kwargs
)
assert isinstance(env, Environ... |
def setup(app):
"""When used for spinx extension."""
global _is_sphinx
_is_sphinx = True
app.add_config_value('no_underscore_emphasis', False, 'env')
app.add_source_parser('.md', M2RParser)
app.add_directive('mdinclude', MdInclude) |
def output_image_link(self, m):
"""Pass through rest role."""
return self.renderer.image_link(
m.group('url'), m.group('target'), m.group('alt')) |
def output_eol_literal_marker(self, m):
"""Pass through rest link."""
marker = ':' if m.group(1) is None else ''
return self.renderer.eol_literal_marker(marker) |
def header(self, text, level, raw=None):
"""Rendering header/heading tags like ``<h1>`` ``<h2>``.
:param text: rendered text content for the header.
:param level: a number for the header level, for example: 1.
:param raw: raw text content of the header.
"""
return '\n{0}... |
def list(self, body, ordered=True):
"""Rendering list tags like ``<ul>`` and ``<ol>``.
:param body: body contents of the list.
:param ordered: whether this list is ordered or not.
"""
mark = '#. ' if ordered else '* '
lines = body.splitlines()
for i, line in enum... |
def table(self, header, body):
"""Rendering table element. Wrap header and body in it.
:param header: header part of the table.
:param body: body part of the table.
"""
table = '\n.. list-table::\n'
if header and not header.isspace():
table = (table + self.in... |
def table_row(self, content):
"""Rendering a table row. Like ``<tr>``.
:param content: content of current table row.
"""
contents = content.splitlines()
if not contents:
return ''
clist = ['* ' + contents[0]]
if len(contents) > 1:
for c in... |
def codespan(self, text):
"""Rendering inline `code` text.
:param text: text content for inline code.
"""
if '``' not in text:
return '\ ``{}``\ '.format(text)
else:
# actually, docutils split spaces in literal
return self._raw_html(
... |
def link(self, link, title, text):
"""Rendering a given link with content and title.
:param link: href link for ``<a>`` tag.
:param title: title content for `title` attribute.
:param text: text content for description.
"""
if title:
raise NotImplementedError(... |
def image(self, src, title, text):
"""Rendering a image with title and text.
:param src: source link of the image.
:param title: title text of the image.
:param text: alt text of the image.
"""
# rst does not support title option
# and I couldn't find title attri... |
def run(self):
"""Most of this method is from ``docutils.parser.rst.Directive``.
docutils version: 0.12
"""
if not self.state.document.settings.file_insertion_enabled:
raise self.warning('"%s" directive disabled.' % self.name)
source = self.state_machine.input_lines.... |
def WorkerAgentGenerator(agent_class):
"""
Worker Agent generator, receives an Agent class and creates a Worker Agent class that inherits from that Agent.
"""
# Support special case where class is given as type-string (AgentsDictionary) or class-name-string.
if isinstance(agent_class, str):
... |
def clone_worker_agent(agent, factor, environment, network, agent_config):
"""
Clones a given Agent (`factor` times) and returns a list of the cloned Agents with the original Agent
in the first slot.
Args:
agent (Agent): The Agent object to clone.
factor (int): The length of the final l... |
def run(
self,
num_episodes=-1,
max_episode_timesteps=-1,
episode_finished=None,
summary_report=None,
summary_interval=0,
num_timesteps=None,
deterministic=False,
episodes=None,
max_timesteps=None,
testing=False,
sleep=None
... |
def _run_single(self, thread_id, agent, environment, deterministic=False,
max_episode_timesteps=-1, episode_finished=None, testing=False, sleep=None):
"""
The target function for a thread, runs an agent and environment until signaled to stop.
Adds rewards to shared episode re... |
def _int_to_pos(self, flat_position):
"""Returns x, y from flat_position integer.
Args:
flat_position: flattened position integer
Returns: x, y
"""
return flat_position % self.env.action_space.screen_shape[0],\
flat_position % self.env.action_space.scre... |
def _wait_state(self, state, reward, terminal):
"""
Wait until there is a state.
"""
while state == [None] or not state:
state, terminal, reward = self._execute(dict(key=0))
return state, terminal, reward |
def apply_step(self, variables, deltas):
"""
Applies the given (and already calculated) step deltas to the variable values.
Args:
variables: List of variables.
deltas: List of deltas of same length.
Returns:
The step-applied operation. A tf.group of ... |
def minimize(self, time, variables, **kwargs):
"""
Performs an optimization step.
Args:
time: Time tensor.
variables: List of variables to optimize.
**kwargs: Additional optimizer-specific arguments. The following arguments are used
by some op... |
def from_spec(spec, kwargs=None):
"""
Creates an optimizer from a specification dict.
"""
optimizer = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.optimizers.optimizers,
kwargs=kwargs
)
assert isinstance(optimizer, Opt... |
def np_dtype(dtype):
"""Translates dtype specifications in configurations to numpy data types.
Args:
dtype: String describing a numerical type (e.g. 'float') or numerical type primitive.
Returns: Numpy data type
"""
if dtype == 'float' or dtype == float or dtype == np.float32 or dtype == t... |
def get_tensor_dependencies(tensor):
"""
Utility method to get all dependencies (including placeholders) of a tensor (backwards through the graph).
Args:
tensor (tf.Tensor): The input tensor.
Returns: Set of all dependencies (including needed placeholders) for the input tensor.
"""
dep... |
def get_object(obj, predefined_objects=None, default_object=None, kwargs=None):
"""
Utility method to map some kind of object specification to its content,
e.g. optimizer or baseline specifications to the respective classes.
Args:
obj: A specification dict (value for key 'type' optionally speci... |
def prepare_kwargs(raw, string_parameter='name'):
"""
Utility method to convert raw string/diction input into a dictionary to pass
into a function. Always returns a dictionary.
Args:
raw: string or dictionary, string is assumed to be the name of the activation
activation functi... |
def register_saver_ops(self):
"""
Registers the saver operations to the graph in context.
"""
variables = self.get_savable_variables()
if variables is None or len(variables) == 0:
self._saver = None
return
base_scope = self._get_base_variable_sco... |
def save(self, sess, save_path, timestep=None):
"""
Saves this component's managed variables.
Args:
sess: The session for which to save the managed variables.
save_path: The path to save data to.
timestep: Optional, the timestep to append to the file name.
... |
def restore(self, sess, save_path):
"""
Restores the values of the managed variables from disk location.
Args:
sess: The session for which to save the managed variables.
save_path: The path used to save the data to.
"""
if self._saver is None:
... |
def reset(self):
"""
Calls `reset` on all our Preprocessor objects.
Returns:
A list of tensors to be fetched.
"""
fetches = []
for processor in self.preprocessors:
fetches.extend(processor.reset() or [])
return fetches |
def process(self, tensor):
"""
Process state.
Args:
tensor: tensor to process
Returns: processed state
"""
for processor in self.preprocessors:
tensor = processor.process(tensor=tensor)
return tensor |
def processed_shape(self, shape):
"""
Shape of preprocessed state given original shape.
Args:
shape: original state shape
Returns: processed state shape
"""
for processor in self.preprocessors:
shape = processor.processed_shape(shape=shape)
... |
def from_spec(spec, kwargs=None):
"""
Creates a preprocessing stack from a specification dict.
"""
if isinstance(spec, dict):
spec = [spec]
stack = PreprocessorStack()
for preprocessor_spec in spec:
# need to deep copy, otherwise will add first pr... |
def tf_solve(self, fn_x, x_init, *args):
"""
Iteratively solves an equation/optimization for $x$ involving an expression $f(x)$.
Args:
fn_x: A callable returning an expression $f(x)$ given $x$.
x_init: Initial solution guess $x_0$.
*args: Additional solver-sp... |
def execute(self, action):
"""
Executes action, observes next state and reward.
Args:
actions: Actions to execute.
Returns:
Tuple of (next state, bool indicating terminal, reward)
"""
next_state, rew, done, _ = self.env.step(action)
retur... |
def as_local_model(self):
"""
Makes sure our optimizer is wrapped into the global_optimizer meta. This is only relevant for distributed RL.
"""
super(MemoryModel, self).as_local_model()
self.optimizer_spec = dict(
type='global_optimizer',
optimizer=self.op... |
def setup_components_and_tf_funcs(self, custom_getter=None):
"""
Constructs the memory and the optimizer objects.
Generates and stores all template functions.
"""
custom_getter = super(MemoryModel, self).setup_components_and_tf_funcs(custom_getter)
# Memory
self.... |
def tf_discounted_cumulative_reward(self, terminal, reward, discount=None, final_reward=0.0, horizon=0):
"""
Creates and returns the TensorFlow operations for calculating the sequence of discounted cumulative rewards
for a given sequence of single rewards.
Example:
single reward... |
def tf_reference(self, states, internals, actions, terminal, reward, next_states, next_internals, update):
"""
Creates the TensorFlow operations for obtaining the reference tensor(s), in case of a
comparative loss.
Args:
states: Dict of state tensors.
internals: ... |
def tf_loss_per_instance(self, states, internals, actions, terminal, reward,
next_states, next_internals, update, reference=None):
"""
Creates the TensorFlow operations for calculating the loss per batch instance.
Args:
states: Dict of state tensors.
... |
def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None):
"""
Creates the TensorFlow operations for calculating the full loss of a batch.
Args:
states: Dict of state tensors.
internals: List of prior internal st... |
def optimizer_arguments(self, states, internals, actions, terminal, reward, next_states, next_internals):
"""
Returns the optimizer arguments including the time, the list of variables to optimize,
and various functions which the optimizer might require to perform an update step.
Args:
... |
def tf_optimization(self, states, internals, actions, terminal, reward, next_states=None, next_internals=None):
"""
Creates the TensorFlow operations for performing an optimization update step based
on the given input states and actions batch.
Args:
states: Dict of state ten... |
def tf_observe_timestep(self, states, internals, actions, terminal, reward):
"""
Creates and returns the op that - if frequency condition is hit - pulls a batch from the memory
and does one optimization step.
"""
# Store timestep in memory
stored = self.memory.store(
... |
def tf_import_experience(self, states, internals, actions, terminal, reward):
"""
Imports experiences into the TensorFlow memory structure. Can be used to import
off-policy data.
:param states: Dict of state values to import with keys as state names and values as values to set.
... |
def import_experience(self, states, internals, actions, terminal, reward):
"""
Stores experiences.
"""
fetches = self.import_experience_output
feed_dict = self.get_feed_dict(
states=states,
internals=internals,
actions=actions,
ter... |
def tf_step(
self,
time,
variables,
arguments,
fn_loss,
fn_reference,
**kwargs
):
"""
Creates the TensorFlow operations for performing an optimization step.
Args:
time: Time tensor.
variables: List of variables ... |
def from_spec(spec, kwargs=None):
"""
Creates a distribution from a specification dict.
"""
distribution = util.get_object(
obj=spec,
predefined_objects=tensorforce.core.distributions.distributions,
kwargs=kwargs
)
assert isinstance(dis... |
def reset(self):
"""
Resets the agent to its initial state (e.g. on experiment start). Updates the Model's internal episode and
time step counter, internal states, and resets preprocessors.
"""
self.episode, self.timestep, self.next_internals = self.model.reset()
self.cur... |
def act(self, states, deterministic=False, independent=False, fetch_tensors=None, buffered=True, index=0):
"""
Return action(s) for given state(s). States preprocessing and exploration are applied if
configured accordingly.
Args:
states (any): One state (usually a value tupl... |
def observe(self, terminal, reward, index=0):
"""
Observe experience from the environment to learn from. Optionally pre-processes rewards
Child classes should call super to get the processed reward
EX: terminal, reward = super()...
Args:
terminal (bool): boolean indi... |
def atomic_observe(self, states, actions, internals, reward, terminal):
"""
Utility method for unbuffered observing where each tuple is inserted into TensorFlow via
a single session call, thus avoiding race conditions in multi-threaded mode.
Observe full experience tuplefrom the enviro... |
def save_model(self, directory=None, append_timestep=True):
"""
Save TensorFlow model. If no checkpoint directory is given, the model's default saver
directory is used. Optionally appends current timestep to prevent overwriting previous
checkpoint files. Turn off to be able to load model... |
def restore_model(self, directory=None, file=None):
"""
Restore TensorFlow model. If no checkpoint file is given, the latest checkpoint is
restored. If no checkpoint directory is given, the model's default saver directory is
used (unless file specifies the entire path).
Args:
... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.