code
string
signature
string
docstring
string
loss_without_docstring
float64
loss_with_docstring
float64
factor
float64
# Match ISO 8601? match = _RE_ISO8601_DATE.search(string) if not match: raise ValueError('Expected ISO 8601 date') # Extract ISO 8601 components year = int(match.group('year')) month = int(match.group('month')) day = int(match.group('day')) return date(year, month, day)
def parse_iso8601_date(string)
Parse an ISO 8601 date string
2.512586
2.477232
1.014271
# Match ISO 8601? match = _RE_ISO8601_DATETIME.search(string) if not match: raise ValueError('Expected ISO 8601 date/time') # Extract ISO 8601 components year = int(match.group('year')) month = int(match.group('month')) day = int(match.group('day')) hour = int(match.group(...
def parse_iso8601_datetime(string)
Parse an ISO 8601 date/time string
1.879817
1.862299
1.009407
exclude_submodules_dot = [x + '.' for x in exclude_submodules] if exclude_submodules else exclude_submodules package = importlib.import_module(package, parent_package) for _, name, _ in pkgutil.walk_packages(package.__path__, package.__name__ + '.'): if exclude_submodules and (name in exclude_...
def import_submodules(package, parent_package=None, exclude_submodules=None)
Generator which imports all submodules of a module, recursively, including subpackages :param package: package name (e.g 'chisel.util'); may be relative if parent_package is provided :type package: str :param parent_package: parent package name (e.g 'chisel') :type package: str :rtype: iterator of ...
2.21722
2.457782
0.902123
'''Returns a tuple of tensors representing the initial state fluents. Args: batch_size (Optional[int]): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors. ''' with self.graph.as_default(): with tf.name_scope('initial_state'): ...
def compile_initial_state(self, batch_size: Optional[int] = None) -> Sequence[tf.Tensor]
Returns a tuple of tensors representing the initial state fluents. Args: batch_size (Optional[int]): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors.
2.828017
2.173695
1.301018
'''Returns a tuple of tensors representing the default action fluents. Args: batch_size (int): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors. ''' with self.graph.as_default(): with tf.name_scope('default_action'): ...
def compile_default_action(self, batch_size: Optional[int] = None) -> Sequence[tf.Tensor]
Returns a tuple of tensors representing the default action fluents. Args: batch_size (int): The batch size. Returns: Sequence[tf.Tensor]: A tuple of tensors.
2.823814
2.141771
1.318448
'''Compiles the intermediate and next state fluent CPFs given the current `state` and `action`. Args: state (Sequence[tf.Tensor]): A tuple of state tensors. action (Sequence[tf.Tensor]): A tuple of action tensors. Returns: Tuple[List[TensorFluent], L...
def cpfs(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], noise: Optional[Noise] = None) -> Tuple[List[TensorFluent], List[TensorFluent]]
Compiles the intermediate and next state fluent CPFs given the current `state` and `action`. Args: state (Sequence[tf.Tensor]): A tuple of state tensors. action (Sequence[tf.Tensor]): A tuple of action tensors. Returns: Tuple[List[TensorFluent], List[TensorF...
3.295287
2.048511
1.608626
'''Compiles the reward function given the current `state`, `action` and `next_state`. Args: state (Sequence[tf.Tensor]): A tuple of current state tensors. action (Sequence[tf.Tensor]): A tuple of action tensors. next_state (Sequence[tf.Tensor]): A tuple of ne...
def reward(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], next_state: Sequence[tf.Tensor]) -> tf.Tensor
Compiles the reward function given the current `state`, `action` and `next_state`. Args: state (Sequence[tf.Tensor]): A tuple of current state tensors. action (Sequence[tf.Tensor]): A tuple of action tensors. next_state (Sequence[tf.Tensor]): A tuple of next state te...
3.046342
2.016402
1.510781
'''Compiles the intermediate and next state fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: Tuple...
def compile_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> Tuple[List[CPFPair], List[CPFPair]]
Compiles the intermediate and next state fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: Tuple[List[CPFPa...
3.960243
1.641624
2.412393
'''Compiles the intermediate fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: A list of intermedia...
def compile_intermediate_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> List[CPFPair]
Compiles the intermediate fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: A list of intermediate fluent C...
3.760037
2.1522
1.747067
'''Compiles the next state fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: A list of state fluent...
def compile_state_cpfs(self, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[Noise] = None) -> List[CPFPair]
Compiles the next state fluent CPFs given the current `state` and `action` scope. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for CPF evaluation. batch_size (Optional[int]): The batch size. Returns: A list of state fluent CPFs compi...
3.523178
2.139627
1.646632
'''Compiles the reward function given the fluent `scope`. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for reward evaluation. Returns: A :obj:`rddl2tf.fluent.TensorFluent` representing the reward function. ''' reward_expr...
def compile_reward(self, scope: Dict[str, TensorFluent]) -> TensorFluent
Compiles the reward function given the fluent `scope`. Args: scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): The fluent scope for reward evaluation. Returns: A :obj:`rddl2tf.fluent.TensorFluent` representing the reward function.
4.192551
2.137866
1.961091
'''Compiles the state-action constraints given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`. ...
def compile_state_action_constraints(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]
Compiles the state-action constraints given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`.
3.632796
2.472378
1.469353
'''Compiles the action preconditions given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`. ''...
def compile_action_preconditions(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> List[TensorFluent]
Compiles the action preconditions given current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`.
3.330644
2.369344
1.405724
'''Compiles the state invarints given current `state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`. ''' scope = self.state_invariant_scope(state) invariants = [] ...
def compile_state_invariants(self, state: Sequence[tf.Tensor]) -> List[TensorFluent]
Compiles the state invarints given current `state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A list of :obj:`rddl2tf.fluent.TensorFluent`.
4.425709
2.638096
1.677615
'''Combines the action preconditions into an applicability checking op. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A boolean tensor for checking if `action` is application in `stat...
def compile_action_preconditions_checking(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> tf.Tensor
Combines the action preconditions into an applicability checking op. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A boolean tensor for checking if `action` is application in `state`.
3.661904
2.009823
1.822003
'''Compiles all actions bounds for the given `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from action names to a pair of :obj:`rddl2tf.fluent.TensorFluent` representing its lower and upper bounds. ...
def compile_action_bound_constraints(self, state: Sequence[tf.Tensor]) -> Dict[str, Bounds]
Compiles all actions bounds for the given `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from action names to a pair of :obj:`rddl2tf.fluent.TensorFluent` representing its lower and upper bounds.
2.993476
1.997069
1.498934
'''Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' if self.__dict__.get('non_fluents') is None: self._initialize_non_fluents() return dict(self.non_fluents)
def non_fluents_scope(self) -> Dict[str, TensorFluent]
Returns a partial scope with non-fluents. Returns: A mapping from non-fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
5.505784
2.366759
2.326297
'''Returns a partial scope with current state-fluents. Args: state_fluents (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' return dict(zip(self.rddl.domain.state_flue...
def state_scope(self, state_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]
Returns a partial scope with current state-fluents. Args: state_fluents (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from state fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
5.90108
2.301119
2.564439
'''Returns a partial scope with current action-fluents. Args: action_fluents (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from action fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' return dict(zip(self.rddl.domain.action_fluent_...
def action_scope(self, action_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]
Returns a partial scope with current action-fluents. Args: action_fluents (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from action fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
6.088499
2.342812
2.5988
'''Returns a partial scope with current next state-fluents. Args: next_state_fluents (Sequence[tf.Tensor]): The next state fluents. Returns: A mapping from next state fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' return dict(zip(self.rddl.domai...
def next_state_scope(self, next_state_fluents: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]
Returns a partial scope with current next state-fluents. Args: next_state_fluents (Sequence[tf.Tensor]): The next state fluents. Returns: A mapping from next state fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
5.67893
2.227663
2.549278
'''Returns the complete transition fluent scope for the current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from fluent names to :obj...
def transition_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]
Returns the complete transition fluent scope for the current `state` and `action` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.f...
3.424594
1.669556
2.051201
'''Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. next_state (Sequence[tf.Tensor]): ...
def reward_scope(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], next_state: Sequence[tf.Tensor]) -> Dict[str, TensorFluent]
Returns the complete reward fluent scope for the current `state`, `action` fluents, and `next_state` fluents. Args: state (Sequence[tf.Tensor]): The current state fluents. action (Sequence[tf.Tensor]): The action fluents. next_state (Sequence[tf.Tensor]): The next st...
2.703722
1.488779
1.816067
'''Returns the state invariant fluent scope for the current `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`. ''' scope = {} scope.update(self.non_fl...
def state_invariant_scope(self, state: Sequence[tf.Tensor])
Returns the state invariant fluent scope for the current `state`. Args: state (Sequence[tf.Tensor]): The current state fluents. Returns: A mapping from fluent names to :obj:`rddl2tf.fluent.TensorFluent`.
7.177778
2.039079
3.520107
'''Instantiates `pvariables` given an initialization list and returns a list of TensorFluents in the given `ordering`. Returns: List[Tuple[str, TensorFluent]]: A list of pairs of fluent name and fluent tensor. ''' if initializer is not None: init = dict()...
def _initialize_pvariables(self, pvariables: Dict[str, PVariable], ordering: List[str], initializer: Optional[InitializerList] = None) -> List[Tuple[str, TensorFluent]]
Instantiates `pvariables` given an initialization list and returns a list of TensorFluents in the given `ordering`. Returns: List[Tuple[str, TensorFluent]]: A list of pairs of fluent name and fluent tensor.
3.662492
3.007358
1.217844
'''Returns the non-fluents instantiated.''' non_fluents = self.rddl.domain.non_fluents initializer = self.rddl.non_fluents.init_non_fluent self.non_fluents = self._initialize_pvariables( non_fluents, self.rddl.domain.non_fluent_ordering, initializer) ...
def _initialize_non_fluents(self)
Returns the non-fluents instantiated.
5.006557
4.363306
1.147423
'''Returns the initial state-fluents instantiated.''' state_fluents = self.rddl.domain.state_fluents initializer = self.rddl.instance.init_state self.initial_state_fluents = self._initialize_pvariables( state_fluents, self.rddl.domain.state_fluent_ordering, ...
def _initialize_initial_state_fluents(self)
Returns the initial state-fluents instantiated.
5.477772
4.4618
1.227705
'''Returns the default action-fluents instantiated.''' action_fluents = self.rddl.domain.action_fluents self.default_action_fluents = self._initialize_pvariables( action_fluents, self.rddl.domain.action_fluent_ordering) return self.default_action_fluents
def _initialize_default_action_fluents(self)
Returns the default action-fluents instantiated.
5.159938
3.974154
1.298374
'''Compiles `fluents` into tensors with given `batch_size`. Returns: Sequence[tf.Tensor]: A tuple of tensors with first dimension corresponding to the batch size. ''' batch_fluents = [] with self.graph.as_default(): for name, fluent in fluents...
def _compile_batch_fluents(self, fluents: List[Tuple[str, TensorFluent]], batch_size: int) -> Sequence[tf.Tensor]
Compiles `fluents` into tensors with given `batch_size`. Returns: Sequence[tf.Tensor]: A tuple of tensors with first dimension corresponding to the batch size.
3.295164
2.468352
1.334965
'''Compile the expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[siz...
def _compile_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> TensorFluent
Compile the expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optional[size]): The ba...
2.796546
1.928423
1.450173
'''Compile a constant expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_si...
def _compile_constant_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> Tenso...
Compile a constant expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL constant expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optiona...
4.407116
1.996174
2.207781
'''Compile a pvariable expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_...
def _compile_pvariable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> ...
Compile a pvariable expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL pvariable expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optio...
3.819356
2.325925
1.642081
'''Compile a random variable expression `expr` into a TensorFluent in the given `scope` with optional batch size. If `reparam` tensor is given, then it conditionally stops gradient backpropagation at the batch level where `reparam` is False. Args: expr (:obj:`rddl2t...
def _compile_random_variable_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optiona...
Compile a random variable expression `expr` into a TensorFluent in the given `scope` with optional batch size. If `reparam` tensor is given, then it conditionally stops gradient backpropagation at the batch level where `reparam` is False. Args: expr (:obj:`rddl2tf.expr.Expr...
2.193633
1.573699
1.393934
'''Compile an arithmetic expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. bat...
def _compile_arithmetic_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None...
Compile an arithmetic expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL arithmetic expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Op...
2.188509
1.590491
1.375996
'''Compile a function expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL function expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_si...
def _compile_function_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] = None) -> Tenso...
Compile a function expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL function expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (Optiona...
1.980733
1.556633
1.272447
'''Compile a control flow expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL control flow expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. ...
def _compile_control_flow_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tenso...
Compile a control flow expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL control flow expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size ...
2.72992
1.676534
1.628312
'''Compile an aggregation expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL aggregation expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. b...
def _compile_aggregation_expression(self, expr: Expression, scope: Dict[str, TensorFluent], batch_size: Optional[int] = None, noise: Optional[List[tf.Tensor]] =...
Compile an aggregation expression `expr` into a TensorFluent in the given `scope` with optional batch size. Args: expr (:obj:`rddl2tf.expr.Expression`): A RDDL aggregation expression. scope (Dict[str, :obj:`rddl2tf.fluent.TensorFluent`]): A fluent scope. batch_size (...
3.618683
2.379794
1.520587
if self._operator is None: if self._operands is None: return np.ones(self._get_table_len(table), dtype=np.bool) else: return self._create_mask(table, self._operands) if self._operator == 'NOT': return ~self._operands.mask(tabl...
def mask(self, table)
Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- mask : numpy bool array
2.269698
2.371082
0.957242
if self._operator is None and self._operands is None: return table if column_slice is None else self._get_table_column(table, column_slice) if self._operator == 'AND' and column_slice is None: for op in self._operands: table = op.filter(table) ...
def filter(self, table, column_slice=None)
Use the current Query object to create a mask (a boolean array) for `table`. Parameters ---------- table : NumPy structured array, astropy Table, etc. column_slice : Column to return. Default is None (return all columns). Returns ------- table : filtered...
3.12985
3.54579
0.882695
if self._operator is None and self._operands is None: return self._get_table_len(table) return np.count_nonzero(self.mask(table))
def count(self, table)
Use the current Query object to count the number of entries in `table` that satisfy `queries`. Parameters ---------- table : NumPy structured array, astropy Table, etc. Returns ------- count : int
7.112816
8.739307
0.813888
if self._variable_names is None: if self._operator is None: if self._operands is None: self._variable_names = tuple() else: self._variable_names = self._get_variable_names(self._operands) elif self._operat...
def variable_names(self)
Get all variable names required for this query
2.440269
2.223577
1.097452
try: return self._user except AttributeError: self._user = MatrixUser(self.mxid, self.Api(identity=self.mxid)) return self._user
def user(self)
Creates a User object when requested.
6.67977
6.334664
1.054479
try: return self._room except AttributeError: room_id = self.json["room_id"] self._room = MatrixRoom(room_id, self.Api) return self._room
def room(self)
Creates a Room object when requested.
4.096479
3.769012
1.086884
response = self.user_api.join_room(room_str) return self._mkroom(response["room_id"])
def join(self, room_str)
Joins room id or alias even if it must first be created.
6.46088
5.370766
1.202972
for room_id in self.user_api.get_joined_rooms()["joined_rooms"]: self._rooms[room_id] = MatrixRoom(room_id, self.user_api)
def refresh_rooms(self)
Calls GET /joined_rooms to refresh rooms list.
4.548762
3.7901
1.200169
if is_callable(_object): _validator = _object @wraps(_validator) @instance_of() def decorated(value): ensure(value, "%s is empty" % safe_repr(value)) return _validator(value) return decorated try: ensure(len(_object), "%s is empty" % ...
def not_empty(_object)
Validates the given input (has to be a valid data structure) is empty. Input *has* to be one of: `list`, `dict`, or `string`. It is specially useful when most of the validators being created are dealing with data structures that should not be empty.
4.930114
5.113682
0.964103
if is_callable(_object): validator = _object @wraps(validator) def decorated(value): if value: return validator(value) return return decorated else: def optional(*args): return _object optional.is_optional...
def optional(_object)
This decorator has a double functionality, it can wrap validators and make them optional or it can wrap keys and make that entry optional. **Optional Validator:** Allows to have validators work only when there is a value that contains some data, otherwise it will just not pass the information to the ac...
3.821474
6.166582
0.619707
if not isinstance(walltime, timedelta): raise TypeError( 'walltime must be an instance of datetime.timedelta. %s given' % type(walltime) ) self._options['walltime'] = walltime return self
def set_walltime(self, walltime)
Setting a walltime for the job >>> job.set_walltime(datetime.timedelta(hours=2, minutes=30)) :param walltime: Walltime of the job (an instance of timedelta) :returns: self :rtype: self
3.309524
3.638901
0.909484
url = request.quote(url, safe=':/?=&') logger.debug('URL: %s', url) req = request.Request(url, headers={'User-Agent': 'foobar'}) try: response = request.urlopen(req) except HTTPError: raise except (ssl.SSLError, URLError): # Some websites (like metal-archives) use ol...
def get_url(url, parser='html')
Requests the specified url and returns a BeautifulSoup object with its contents.
3.926253
4.055386
0.968158
if not lastfm_key: if 'lastfm_key' not in CONFIG or not CONFIG['lastfm_key']: logger.warning('No lastfm key configured') return '' else: lastfm_key = CONFIG['lastfm_key'] url = 'http://ws.audioscrobbler.com/2.0/?method={}&api_key={}&format=json' url ...
def get_lastfm(method, lastfm_key='', **kwargs)
Request the specified method from the lastfm api.
2.172876
2.193611
0.990548
ret = string.translate(str.maketrans({ 'á': 'a', 'ä': 'a', 'æ': 'ae', 'é': 'e', 'í': 'i', 'ó': 'o', 'ö': 'o', 'ú': 'u', 'ü': 'u', 'ñ': 'n', })) if isinstance(chars_to_remove, dict): for chars, replace in chars_to_r...
def normalize(string, chars_to_remove=None, replacement='')
Remove accented characters and such. The argument chars_to_remove is a dictionary that maps a string of chars to a single character. Every occurrence of every character in the first string will be replaced by that second character passed as value. If only one mapping is desired, chars_to_remove may be ...
1.8655
1.873502
0.995729
translate = {URLESCAPE: '', ' ': '-'} title = song.title.lower() title = normalize(title, translate) title = re.sub(r'\-{2,}', '-', title) artist = song.artist.lower() artist = normalize(artist, translate) artist = re.sub(r'\-{2,}', '-', artist) url = 'http://www.metrolyrics.com/{}...
def metrolyrics(song)
Returns the lyrics found in metrolyrics for the specified mp3 file or an empty string if not found.
2.800846
2.819489
0.993388
# Darklyrics relies on the album name if not hasattr(song, 'album') or not song.album: song.fetch_album_name() if not hasattr(song, 'album') or not song.album: # If we don't have the name of the album, there's nothing we can do # on darklyrics return '' ...
def darklyrics(song)
Returns the lyrics found in darklyrics for the specified mp3 file or an empty string if not found.
2.96508
2.919629
1.015568
artist = song.artist.lower() if artist[0:2] == 'a ': artist = artist[2:] artist = normalize(artist, URLESCAPES, '') title = song.title.lower() title = normalize(title, URLESCAPES, '') url = 'https://www.azlyrics.com/lyrics/{}/{}.html'.format(artist, title) soup = get_url(url) ...
def azlyrics(song)
Returns the lyrics found in azlyrics for the specified mp3 file or an empty string if not found.
3.094374
3.157607
0.979974
translate = { '@': 'at', '&': 'and', URLESCAPE: '', ' ': '-' } artist = song.artist.capitalize() artist = normalize(artist, translate) title = song.title.capitalize() title = normalize(title, translate) url = 'https://www.genius.com/{}-{}-lyrics'.format(...
def genius(song)
Returns the lyrics found in genius.com for the specified mp3 file or an empty string if not found.
3.531026
3.570777
0.988868
artist = normalize(song.artist) title = normalize(song.title) url = 'https://www.metal-archives.com/search/ajax-advanced/searching/songs' url += f'/?songTitle={title}&bandName={artist}&ExactBandMatch=1' soup = get_url(url, parser='json') if not soup: return '' song_id_re = re....
def metalarchives(song)
Returns the lyrics found in MetalArchives for the specified mp3 file or an empty string if not found.
3.660903
3.602087
1.016328
artist = song.artist.title() artist = normalize(artist, ' ', '_') title = song.title title = normalize(title, ' ', '_') url = 'https://lyrics.wikia.com/wiki/{}:{}'.format(artist, title) soup = get_url(url) text = '' content = soup.find('div', class_='lyricbox') if not content: ...
def lyricswikia(song)
Returns the lyrics found in lyrics.wikia.com for the specified mp3 file or an empty string if not found.
2.911863
2.917594
0.998036
escape = re.sub("'-¡¿", '', URLESCAPE) translate = { escape: '', ' ': '-' } artist = song.artist.title() artist = re.sub(r"( '|' )", '', artist) artist = re.sub(r"'", '-', artist) title = song.title title = re.sub(r"( '|' )", '', title) title = re.sub(r"'", '-', ...
def musixmatch(song)
Returns the lyrics found in musixmatch for the specified mp3 file or an empty string if not found.
3.131834
3.168931
0.988294
translate = { URLESCAPE: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) artist = re.sub(r'\-{2,}', '-', artist) title = re.sub(r'\-{2,}', '-', title) url = 'http:/...
def songlyrics(song)
Returns the lyrics found in songlyrics.com for the specified mp3 file or an empty string if not found.
3.360411
3.236092
1.038416
artist = song.artist.lower() artist = normalize(artist, ' ', '+') title = song.title url = 'https://www.lyrics.com/artist/{}'.format(artist) soup = get_url(url) location = '' for a in soup.select('tr a'): if a.string.lower() == title.lower(): location = a['href'] ...
def lyricscom(song)
Returns the lyrics found in lyrics.com for the specified mp3 file or an empty string if not found.
2.782792
2.75479
1.010165
translate = { '@': 'a', URLESCAPE: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) artist = re.sub(r'\-{2,}', '-', artist) title = song.title.lower() title = normalize(title, translate) title = re.sub(r'\-{2,}', '-', title) ...
def vagalume(song)
Returns the lyrics found in vagalume.com.br for the specified mp3 file or an empty string if not found.
3.057685
3.01207
1.015144
translate = { URLESCAPE: '', ' ': '_' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) artist = re.sub(r'\_{2,}', '_', artist) title = re.sub(r'\_{2,}', '_', title) if artist[0:4...
def lyricsmode(song)
Returns the lyrics found in lyricsmode.com for the specified mp3 file or an empty string if not found.
3.012846
2.902477
1.038026
translate = { '&': 'a', URLESCAPE: '', ' ': '-' } artist = song.artist.lower() artist = normalize(artist, translate) title = song.title.lower() title = normalize(title, translate) url = 'https://www.letras.com/{}/{}/'.format(artist, title) soup = get_url(url...
def letras(song)
Returns the lyrics found in letras.com for the specified mp3 file or an empty string if not found.
3.155633
3.005644
1.049903
if source not in source_ids: return '' if full: return source_ids[source][1] else: return source_ids[source][0]
def id_source(source, full=False)
Returns the name of a website-scrapping function.
3.005207
2.999002
1.002069
gitlab_api = gitlab.Gitlab(url=params['url'], private_token=params['token'], api_version=4) while True: try: metrics = update_gitlab_runners(gitlab_api) update_metrics(metrics) except Exception: update_metrics({}) log.exception('During loop') ...
async def update_gitlab_loop(update_metrics, params)
app = Sanic() mserver = MetricsServer(app) mserver.add_task(update_gitlab_loop, params={'url': GITLAB_URL, 'token': token})
3.803018
3.53905
1.074587
if new_probe_position is not None: # convert the probe position to a FloatPoint and limit it to the 0.0 to 1.0 range in both axes. new_probe_position = Geometry.FloatPoint.make(new_probe_position) new_probe_position = Geometry.FloatPoint(y=max(min(new_probe_position....
def set_probe_position(self, new_probe_position)
Set the probe position, in normalized coordinates with origin at top left.
3.852352
3.775286
1.020413
pass
def apply_metadata_groups(self, properties: typing.Dict, metatdata_groups: typing.Tuple[typing.List[str], str]) -> None
Apply metadata groups to properties. Metadata groups is a tuple with two elements. The first is a list of strings representing a dict-path in which to add the controls. The second is a control group from which to read a list of controls to be added as name value pairs to the dict-path.
130,510.03125
13,793.988281
9.46137
backend = settings.get('backend') if isinstance(backend, basestring): backend = import_string(backend) elif backend: backend = backend else: raise KeyError('backend') return backend(settings.get("settings", {}))
def create_analytic_backend(settings)
Creates a new Analytics backend from the settings :param settings: Dictionary of settings for the analytics backend :returns: A backend object implementing the analytics api >>> >>> analytics = create_analytic({ >>> 'backend': 'analytics.backends.redis.Redis', >>> 'settings': { >>>...
4.134825
4.582372
0.902333
if self.__scan_hardware_source: self.__profile_changed_event_listener = self.__scan_hardware_source.profile_changed_event.listen(self.__update_profile_index) self.__frame_parameters_changed_event_listener = self.__scan_hardware_source.frame_parameters_changed_event.listen(self._...
def initialize_state(self)
Call this to initialize the state of the UI after everything has been connected.
2.078582
2.058427
1.009791
if self.__scan_hardware_source: if self.is_playing: self.__scan_hardware_source.stop_playing() else: self.__scan_hardware_source.start_playing()
def handle_play_pause_clicked(self)
Call this when the user clicks the play/pause button.
4.468911
4.120182
1.084639
assert callable(callback_fn) if self.__scan_hardware_source: def finish_record(data_and_metadata_list): record_index = self.__scan_hardware_source.record_index for data_and_metadata in data_and_metadata_list: data_item = DataItem....
def handle_record_clicked(self, callback_fn)
Call this when the user clicks the record button.
3.177906
3.16259
1.004843
if horizontal_padding is None: horizontal_padding = 0 if vertical_padding is None: vertical_padding = 0 self.sizing.set_fixed_size(Geometry.IntSize(18 + 2 * horizontal_padding, 18 + 2 * vertical_padding))
def size_to_content(self, horizontal_padding=None, vertical_padding=None)
Size the canvas item to the text content.
3.188141
3.133904
1.017307
round_start = None rounds_completed = 0 for item in cycled_iterable: if round_start is None: round_start = item elif item == round_start: rounds_completed += 1 if rounds_completed == rounds: return yield item
def round_controlled(cycled_iterable, rounds=1)
Return after <rounds> passes through a cycled iterable.
2.458102
2.353984
1.044231
if self.successes + self.fails == 0: success_rate = 0 else: total_attempts = self.successes + self.fails success_rate = (self.successes * 100 / total_attempts) return success_rate
def success_rate(self)
Returns a float with the rate of success from all the logged results.
2.767169
2.52777
1.094707
self.source_stats[source.__name__].add_runtime(runtime) if found: self.source_stats[source.__name__].successes += 1 else: self.source_stats[source.__name__].fails += 1
def add_result(self, source, found, runtime)
Adds a new record to the statistics 'database'. This function is intended to be called after a website has been scraped. The arguments indicate the function that was called, the time taken to scrap the website and a boolean indicating if the lyrics were found or not.
2.868402
2.982165
0.961852
if source is None: runtimes = [] for rec in self.source_stats.values(): runtimes.extend([r for r in rec.runtimes if r != 0]) return avg(runtimes) else: if callable(source): return avg(self.source_stats[source.__name...
def avg_time(self, source=None)
Returns the average time taken to scrape lyrics. If a string or a function is passed as source, return the average time taken to scrape lyrics from that source, otherwise return the total average.
2.82396
2.590611
1.090075
best, worst, fastest, slowest = (), (), (), () found = notfound = total_time = 0 for source, rec in self.source_stats.items(): if not best or rec.successes > best[1]: best = (source, rec.successes, rec.success_rate()) if not worst or rec.successes...
def calculate(self)
Calculate the overall counts of best, worst, fastest, slowest, total found, total not found and total runtime Results are returned in a dictionary with the above parameters as keys.
2.438927
2.149158
1.134829
stats = self.calculate() total_time = '%d:%02d:%02d' % (stats['total_time'] / 3600, (stats['total_time'] / 3600) / 60, (stats['total_time'] % 3600) % 60) output = output = output.format(total_time=tot...
def print_stats(self)
Print a series of relevant stats about a full execution. This function is meant to be called at the end of the program.
2.564969
2.515347
1.019728
'''It broadcasts the smaller scope over the larger scope. It handles scope intersection as well as differences in scopes in order to output a resulting scope so that input scopes are contained within it (i.e., input scopes are subscopes of the output scope). Also, if necessary, ...
def broadcast(cls, s1: ParamsList, s2: ParamsList) -> BroadcastTuple
It broadcasts the smaller scope over the larger scope. It handles scope intersection as well as differences in scopes in order to output a resulting scope so that input scopes are contained within it (i.e., input scopes are subscopes of the output scope). Also, if necessary, it outputs ...
2.591497
1.435466
1.805335
columns = "chrom\tpos\tref\tcov\tA\tC\tG\tT\t*\t-\t+".split() if bp_lines is None: return None # change baseparser output to get most common maf per indel bpdf = pd.DataFrame([[sample] + l.rstrip('\n').split("\t") for l in bp_lines if len(l) > 0], columns=["sample"]...
def get_baseparser_extended_df(sample, bp_lines, ref, alt)
Turn baseParser results into a dataframe
2.832927
2.790618
1.015161
df = tumordf.merge(normaldf, on=["chrom", "pos"], suffixes=("_T", "_N")) # filters common_al = (df.most_common_al_count_T == df.most_common_count_T) & (df.most_common_al_T == df.most_common_al_N) common_indel = (df.most_common_indel_count_T == df.most_common_count_T) & \ (df.most_common_in...
def filter_out_mutations_in_normal(tumordf, normaldf, most_common_maf_min=0.2, most_common_count_maf_threshold=20, most_common_count_min=1)
Remove mutations that are in normal
2.431603
2.416573
1.006219
if sum([bool(snv), bool(ins), bool(dlt)]) != 1: raise(Exception("Should be either snv, ins or del".format(snv))) if snv: if snv not in ["A", "C", "G", "T"]: raise(Exception("snv {} should be A, C, G or T".format(snv))) return bpdf[(bpdf.most_common_al == snv) & (bpdf.mo...
def select_only_revertant_mutations(bpdf, snv=None, ins=None, dlt=None)
Selects only mutations that revert the given mutations in a single event.
1.881402
1.881366
1.000019
for pool_id, client in enumerate(clients): # Tag it with an id we'll use to identify it in the pool if hasattr(client, "pool_id"): raise ValueError("%r is already part of a pool.", client) setattr(client, "pool_id", pool_id) # Wrap all pub...
def _prep_clients(self, clients)
Prep a client by tagging it with and id and wrapping methods. Methods are wrapper to catch ConnectionError so that we can remove it from the pool until the instance comes back up. :returns: patched clients
6.531621
5.192815
1.257819
def wrap(fn): def wrapper(*args, **kwargs): try: return fn(*args, **kwargs) except (ConnectionError, TimeoutError): # TO THE PENALTY BOX! self._penalize_client(client) raise ...
def _wrap_functions(self, client)
Wrap public functions to catch ConnectionError. When an error happens, it puts the client in the penalty box so that it won't be retried again for a little while.
3.964874
3.268218
1.213161
added = False for client in self.penalty_box.get(): log.info("Client %r is back up.", client) self.active_clients.append(client) added = True if added: self._sort_clients()
def _prune_penalty_box(self)
Restores clients that have reconnected. This function should be called first for every public method.
8.185754
6.605315
1.239268
self._prune_penalty_box() if len(self.active_clients) == 0: raise ClusterEmptyError("All clients are down.") # So that hashing is consistent when a node is down, check against # the initial client list. Only use the active client list when # the desired nod...
def get_client(self, shard_key)
Get the client for a given shard, based on what's available. If the proper client isn't available, the next available client is returned. If no clients are available, an exception is raised.
6.966093
6.855079
1.016194
if client in self.active_clients: # hasn't been removed yet log.warning("%r marked down.", client) self.active_clients.remove(client) self.penalty_box.add(client) else: log.info("%r not in active client list.")
def _penalize_client(self, client)
Place client in the penalty box. :param client: Client object
6.749594
6.270931
1.07633
self._prune_penalty_box() if len(self.active_clients) == 0: raise ClusterEmptyError("All clients are down.") element__score = defaultdict(int) for client in self.active_clients: revrange = client.zrevrangebyscore( key, max_score, min_sco...
def zrevrange_with_int_score(self, key, max_score, min_score)
Get the zrevrangebyscore across the cluster. Highest score for duplicate element is returned. A faster method should be written if scores are not needed.
4.675441
4.225106
1.106585
prepend_negation = kwargs.get('prepend_negation', True) return Linker(regexes, prepend_negation=prepend_negation)
def chain(*regexes, **kwargs)
A helper function to interact with the regular expression engine that compiles and applies partial matches to a string. It expects key value tuples as arguments (any number of them) where the first pair is the regex to compile and the latter is the message to display when the regular expression does no...
6.313928
6.896523
0.915523
if files: vault = g.client.Vault.get_personal_vault() files = json.loads(files) objects = [] for i in xrange(len(files)): obj = g.client.Object.create( vault_id=vault.id, object_type='file', filename=files[i].get('filen...
def generate_s3_url(files)
Takes files from React side, creates SolveBio Object containing signed S3 URL.
2.831671
2.776275
1.019953
if uploaded_files: uploaded_files = json.loads(uploaded_files)[0] _id = uploaded_files.get('id') # Strip extension from filename _filename = os.path.splitext(uploaded_files.get('filename'))[0] # Create a dataset dataset = g.client.Dataset.get_or_create_by_full_p...
def handle_uploaded_files(uploaded_files)
Handles downstream processes using metadata about the uploaded files from React side.
4.172952
4.210367
0.991114
camera_panel_type = properties.get("camera_panel_type") for component in Registry.get_components_by_type("camera_panel"): if component.camera_panel_type == camera_panel_type: hardware_source_id = properties["hardware_source_id"] hardware_source = HardwareSource.HardwareSourc...
def create_camera_panel(document_controller, panel_id, properties)
Create a custom camera panel. The camera panel type is specified in the 'camera_panel_type' key in the properties dict. The camera panel type must match a the 'camera_panel_type' of a camera panel factory in the Registry. The matching camera panel factory must return a ui_handler for the panel which is u...
3.367476
3.121874
1.078671
if self.__hardware_source: self.__profile_changed_event_listener = self.__hardware_source.profile_changed_event.listen(self.__update_profile_index) self.__frame_parameters_changed_event_listener = self.__hardware_source.frame_parameters_changed_event.listen(self.__update_frame_p...
def initialize_state(self)
Call this to initialize the state of the UI after everything has been connected.
2.376006
2.321724
1.02338
if self.__hardware_source: if self.is_playing: self.__hardware_source.stop_playing() else: self.__hardware_source.start_playing()
def handle_play_pause_clicked(self)
Call this when the user clicks the play/pause button.
3.999088
3.606176
1.108955
c = self.copy() c.is_summary = summarize c.for_save = for_save final_points = [] for i, p in enumerate(self.params): try: float(p) except: _, source, _, join_list, last = query.setup_joins( s...
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
Setup any data here, this method will be called before final SQL is generated
4.696915
4.60213
1.020596
c = self.copy() c.is_summary = summarize c.for_save = for_save for pos, expression in enumerate(self.expressions): c.expressions[pos] = expression.resolve_expression(query, allow_joins, reuse, summarize) return c
def resolve_expression(self, query=None, allow_joins=True, reuse=None, summarize=False, for_save=False)
Prepare SQL from inner funcions (ll_to_earth or any other)
3.04578
2.957086
1.029994
clone = self._clone() return clone.annotate( **{annotate: EarthDistance([ LlToEarth(fields), LlToEarth(points)]) }).filter(**{'{0}__lte'.format(annotate): distance})
def in_distance(self, distance, fields, points, annotate='_ed_distance')
Filter rows inside a circunference of radius distance `distance` :param distance: max distance to allow :param fields: `tuple` with the fields to filter (latitude, longitude) :param points: center of the circunference (latitude, longitude) :param annotate: name where the...
9.427401
11.738289
0.803132
value = self._source steps_taken = [] try: # walk through the values dictionary for step in path.split(self._separator): steps_taken.append(step) value = value[step] if as_type: return as_type(value) ...
def get(self, path, default=_NoDefault, as_type=None, resolve_references=True)
Gets a value for the specified path. :param path: the configuration key to fetch a value for, steps separated by the separator supplied to the constructor (default ``.``) :param default: a value to return if no value is found for the supplied path (``None`` is allowe...
5.544891
5.780542
0.959234
if action_callback is None: return lambda fn: action(fn, **kwargs) else: return Action(action_callback, **kwargs).decorate_module(action_callback)
def action(action_callback=None, **kwargs)
Chisel action decorator
5.132513
4.418656
1.161555
assert callable(callback_fn) def record_thread(): current_frame_time = self.get_current_frame_time() def handle_finished(xdatas): callback_fn(xdatas) self.start_recording(current_frame_time, finished_callback_fn=handle_finished) se...
def record_async(self, callback_fn)
Call this when the user clicks the record button.
4.079614
3.932605
1.037382
if hasattr(self.__device, "get_buffer_data"): buffer_data = self.__device.get_buffer_data(start, count) enabled_channel_states = list() for channel_index in range(self.channel_count): channel_state = self.get_channel_state(channel_index) ...
def get_buffer_data(self, start: int, count: int) -> typing.Optional[typing.List[typing.List[typing.Dict]]]
Get recently acquired (buffered) data. The start parameter can be negative to index backwards from the end. If start refers to a buffer item that doesn't exist or if count requests too many buffer items given the start value, the returned list may have fewer elements than count. Retur...
3.38868
3.448732
0.982587