code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def read_index(fn): index = None with open(fn, 'rb') as i_file: if (i_file.read(len(_CHECK_STRING)) != _CHECK_STRING): raise ValueError('{}: not a valid index file'.format(fn)) index = pd.read_csv(io.StringIO(zlib.decompress(i_file.read()).decode(encoding='utf-8'))) return index
Reads index from file. Args: fn (str): the name of the file containing the index. Returns: pandas.DataFrame: the index of the file. Before reading the index, we check the first couple of bytes to see if it is a valid index file.
codesearchnet
def remove_padding_from_sc(value_in_checkpoint: tensor.Tensor, variable_shape: tuple[int, int]) -> tensor.Tensor: checkpoint_value_shape = value_in_checkpoint.shape.as_list() is_init_value_padded = all([i >= j for i, j in zip(checkpoint_value_shape, variable_shape)]) if not is_init_value_padded: return value_in_checkpoint begin = [0] * len(checkpoint_value_shape) return array_ops.slice(value_in_checkpoint, begin=begin, size=variable_shape)
Removes padding, if any, from sparsecore checkpoint. Args: value_in_checkpoint: input tensor value, usually from checkpoint. variable_shape: Expected shape of tensor after removing padding. Returns: A slice of the input tensor to match the variable_shape if the variable shape is a valid slice if the input tensor.
github-repos
def chglog(amend: bool = False, stage: bool = False, next_version: str = None, auto_next_version: bool = False): changed_files = CTX.repo.changed_files() changelog_file_path: Path = config.CHANGELOG_FILE_PATH() changelog_file_name = changelog_file_path.name if changelog_file_name in changed_files: LOGGER.error('changelog has changed; cannot update it') exit(-1) _chglog(amend, stage, next_version, auto_next_version)
Writes the changelog Args: amend: amend last commit with changes stage: stage changes next_version: indicates next version auto_next_version: infer next version from VCS
juraj-google-style
def from_dict(cls, video_processor_dict: Dict[str, Any], **kwargs): video_processor_dict = video_processor_dict.copy() return_unused_kwargs = kwargs.pop('return_unused_kwargs', False) if 'size' in kwargs and 'size' in video_processor_dict: video_processor_dict['size'] = kwargs.pop('size') if 'crop_size' in kwargs and 'crop_size' in video_processor_dict: video_processor_dict['crop_size'] = kwargs.pop('crop_size') video_processor = cls(**video_processor_dict) to_remove = [] for key, value in kwargs.items(): if hasattr(video_processor, key): setattr(video_processor, key, value) to_remove.append(key) for key in to_remove: kwargs.pop(key, None) logger.info(f'Video processor {video_processor}') if return_unused_kwargs: return (video_processor, kwargs) else: return video_processor
Instantiates a type of [`~video_processing_utils.VideoProcessorBase`] from a Python dictionary of parameters. Args: video_processor_dict (`Dict[str, Any]`): Dictionary that will be used to instantiate the video processor object. Such a dictionary can be retrieved from a pretrained checkpoint by leveraging the [`~video_processing_utils.VideoProcessorBase.to_dict`] method. kwargs (`Dict[str, Any]`): Additional parameters from which to initialize the video processor object. Returns: [`~video_processing_utils.VideoProcessorBase`]: The video processor object instantiated from those parameters.
github-repos
def IsSynced(self): if (Blockchain.Default().Height == 0): return False if (int(((100 * self._current_height) / Blockchain.Default().Height)) < 100): return False else: return True
Check if wallet is synced. Returns: bool: True if wallet is synced.
codesearchnet
def change_password(username, new_password): assert (username in passwd_reader.load_users()), ("Username '%s' not found!" % username) sh.ftpasswd('--change-password', passwd=True, name=username, stdin=True, file=settings.LOGIN_FILE, _in=new_password) reload_configuration()
Change password for given `username`. Args: username (str): User's name. new_password (str): User's new password.
codesearchnet
def format(self, record): if ((not FLAGS['showprefixforinfo'].value) and (FLAGS['verbosity'].value == converter.ABSL_INFO) and (record.levelno == logging.INFO) and (_absl_handler.python_handler.stream == sys.stderr)): prefix = '' else: prefix = get_absl_log_prefix(record) return (prefix + super(PythonFormatter, self).format(record))
Appends the message from the record to the results of the prefix. Args: record: logging.LogRecord, the record to be formatted. Returns: The formatted string representing the record.
codesearchnet
def command_factory(command): def communicate(body={}, root_dir=None): 'Communicate with the daemon.\n\n This function sends a payload to the daemon and returns the unpickled\n object sent by the daemon.\n\n Args:\n body (dir): Any other arguments that should be put into the payload.\n root_dir (str): The root directory in which we expect the daemon.\n We need this to connect to the daemons socket.\n Returns:\n function: The returned payload.\n ' client = connect_socket(root_dir) body['mode'] = command if ('func' in body): del body['func'] data_string = pickle.dumps(body, (- 1)) client.send(data_string) response = receive_data(client) return response return communicate
A factory which returns functions for direct daemon communication. This factory will create a function which sends a payload to the daemon and returns the unpickled object which is returned by the daemon. Args: command (string): The type of payload this should be. This determines as what kind of instruction this will be interpreted by the daemon. Returns: function: The created function.
codesearchnet
def read_until(self, s, echo=None): s_len = len(s) buf = self.read(s_len, echo) while buf[-s_len:] != s: buf += self.read(1, echo) return buf
Read until a certain string is encountered.. Args: s(bytes): The string to wait for. echo(bool): Whether to write the read data to stdout. Returns: bytes: The data up to and including *s*. Raises: EOFError: If the channel was closed.
juraj-google-style
def assign(self, variable, value): variable.assign(value)
Assign a value to a variable. This should be used in optimizers instead of `variable.assign(value)` to support backend specific optimizations. Note that the variable can be a model variable or an optimizer variable; it can be a backend native variable or a Keras variable. Args: variable: The variable to update. value: The value to add to the variable.
github-repos
def add_cell_argument(self, name, help, required=False): for action in self._actions: if action.dest == name: raise ValueError('Arg "%s" was added by add_argument already.' % name) self._cell_args[name] = {'required': required, 'help': help}
Add a cell only argument. Args: name: name of the argument. No need to start with "-" or "--". help: the help string of the argument. required: Whether it is required in cell content.
juraj-google-style
def silu(x): if any_symbolic_tensors((x,)): return Silu().symbolic_call(x) return backend.nn.silu(x)
Sigmoid Linear Unit (SiLU) activation function, also known as Swish. The SiLU activation function is computed by the sigmoid function multiplied by its input. It is defined as `f(x) = x * sigmoid(x)`. Args: x: Input tensor. Returns: A tensor with the same shape as `x`. Example: >>> x = keras.ops.convert_to_tensor([-6.0, 1.0, 0.0, 1.0, 6.0]) >>> keras.ops.sigmoid(x) array([0.00247262, 0.7310586, 0.5, 0.7310586, 0.9975274], dtype=float32) >>> keras.ops.silu(x) array([-0.0148357, 0.7310586, 0.0, 0.7310586, 5.9851646], dtype=float32)
github-repos
def to_dict(self, drop_null=True, camel=False): def to_dict(obj, drop_null, camel): 'Recursively constructs the dict.' if isinstance(obj, (Body, BodyChild)): obj = obj.__dict__ if isinstance(obj, dict): data = {} for (attr, val) in six.iteritems(obj): if camel: attr = _snake_to_camel(attr) valid_null = (isinstance(val, bool) or (val == 0) or (val and to_dict(val, drop_null, camel))) if ((not drop_null) or (drop_null and valid_null)): data[attr] = to_dict(val, drop_null, camel) return data elif isinstance(obj, list): data = [] for val in obj: valid_null = (isinstance(val, bool) or (val == 0) or (val and to_dict(val, drop_null, camel))) if ((not drop_null) or (drop_null and valid_null)): data.append(to_dict(val, drop_null, camel)) return data else: return obj return to_dict(self, drop_null, camel)
Serialize self as dict. Args: drop_null: bool, default True. Remove 'empty' attributes. camel: bool, default True. Convert keys to camelCase. Return: dict: object params.
codesearchnet
def count_star(session: Union[Session, Engine, Connection], tablename: str, *criteria: Any) -> int: query = select([func.count()]).select_from(table(tablename)) for criterion in criteria: query = query.where(criterion) return session.execute(query).scalar()
Returns the result of ``COUNT(*)`` from the specified table (with additional ``WHERE`` criteria if desired). Args: session: SQLAlchemy :class:`Session`, :class:`Engine`, or :class:`Connection` object tablename: name of the table criteria: optional SQLAlchemy "where" criteria Returns: a scalar
juraj-google-style
def ConvertToWireFormat(self, value): output = _SerializeEntries(((python_format, wire_format, value.type_descriptor) for (python_format, wire_format) in value.wrapped_list)) return (b'', b'', output)
Convert to the wire format. Args: value: is of type RepeatedFieldHelper. Returns: A wire format representation of the value.
codesearchnet
def decode(self, ids, strip_extraneous=False): if strip_extraneous: ids = strip_ids(ids, list(range(self._num_reserved_ids or 0))) return " ".join(self.decode_list(ids))
Transform a sequence of int ids into a human-readable string. EOS is not expected in ids. Args: ids: list of integers to be converted. strip_extraneous: bool, whether to strip off extraneous tokens (EOS and PAD). Returns: s: human-readable string.
juraj-google-style
def groups(self, group_type=None, filters=None, params=None): group = self._tcex.ti.group(group_type) for g in self.tc_requests.groups_from_tag(group, self.name, filters=filters, params=params): (yield g)
Gets all groups from a tag. Args: filters: params: group_type:
codesearchnet
def Execute(self, http): self._Execute(http) for key in self.__request_response_handlers: response = self.__request_response_handlers[key].response callback = self.__request_response_handlers[key].handler exception = None if (response.status_code >= 300): exception = exceptions.HttpError.FromResponse(response) if (callback is not None): callback(response, exception) if (self.__callback is not None): self.__callback(response, exception)
Execute all the requests as a single batched HTTP request. Args: http: A httplib2.Http object to be used with the request. Returns: None Raises: BatchError if the response is the wrong format.
codesearchnet
def add_error(self, error, critical=False): self.errors.append((error, critical))
Adds an error to the state. Args: error: The text that will be added to the error list. critical: If set to True and the error is checked with check_errors, will dfTimewolf will abort.
juraj-google-style
def tf_loss(self, states, internals, actions, terminal, reward, next_states, next_internals, update, reference=None): loss_per_instance = self.fn_loss_per_instance(states=states, internals=internals, actions=actions, terminal=terminal, reward=reward, next_states=next_states, next_internals=next_internals, update=update, reference=reference) updated = self.memory.update_batch(loss_per_instance=loss_per_instance) with tf.control_dependencies(control_inputs=(updated,)): loss = tf.reduce_mean(input_tensor=loss_per_instance, axis=0) if ('losses' in self.summary_labels): tf.contrib.summary.scalar(name='loss-without-regularization', tensor=loss) losses = self.fn_regularization_losses(states=states, internals=internals, update=update) if (len(losses) > 0): loss += tf.add_n(inputs=[losses[name] for name in sorted(losses)]) if ('regularization' in self.summary_labels): for name in sorted(losses): tf.contrib.summary.scalar(name=('regularization/' + name), tensor=losses[name]) if (('losses' in self.summary_labels) or ('total-loss' in self.summary_labels)): tf.contrib.summary.scalar(name='total-loss', tensor=loss) return loss
Creates the TensorFlow operations for calculating the full loss of a batch. Args: states: Dict of state tensors. internals: List of prior internal state tensors. actions: Dict of action tensors. terminal: Terminal boolean tensor. reward: Reward tensor. next_states: Dict of successor state tensors. next_internals: List of posterior internal state tensors. update: Boolean tensor indicating whether this call happens during an update. reference: Optional reference tensor(s), in case of a comparative loss. Returns: Loss tensor.
codesearchnet
def ReadClientMetadata(self, client_id): result = self.MultiReadClientMetadata([client_id]) try: return result[client_id] except KeyError: raise UnknownClientError(client_id)
Reads the ClientMetadata record for a single client. Args: client_id: A GRR client id string, e.g. "C.ea3b2b71840d6fa7". Returns: An rdfvalues.object.ClientMetadata object. Raises: UnknownClientError: if no client with corresponding id was found.
juraj-google-style
def get_tensor_from_tensor_info(tensor_info, graph=None, import_scope=None): graph = graph or ops.get_default_graph() def _get_tensor(name): return graph.get_tensor_by_name(ops.prepend_name_scope(name, import_scope=import_scope)) encoding = tensor_info.WhichOneof('encoding') if encoding == 'name': return _get_tensor(tensor_info.name) elif encoding == 'coo_sparse': return sparse_tensor.SparseTensor(_get_tensor(tensor_info.coo_sparse.indices_tensor_name), _get_tensor(tensor_info.coo_sparse.values_tensor_name), _get_tensor(tensor_info.coo_sparse.dense_shape_tensor_name)) elif encoding == 'composite_tensor': spec_proto = struct_pb2.StructuredValue(type_spec_value=tensor_info.composite_tensor.type_spec) spec = nested_structure_coder.decode_proto(spec_proto) components = [_get_tensor(component.name) for component in tensor_info.composite_tensor.components] return nest.pack_sequence_as(spec, components, expand_composites=True) else: raise ValueError(f'Invalid TensorInfo.encoding: {encoding}. Expected `coo_sparse`, `composite_tensor`, or `name` for a dense tensor.')
Returns the Tensor or CompositeTensor described by a TensorInfo proto. Args: tensor_info: A TensorInfo proto describing a Tensor or SparseTensor or CompositeTensor. graph: The tf.Graph in which tensors are looked up. If None, the current default graph is used. import_scope: If not None, names in `tensor_info` are prefixed with this string before lookup. Returns: The Tensor or SparseTensor or CompositeTensor in `graph` described by `tensor_info`. Raises: KeyError: If `tensor_info` does not correspond to a tensor in `graph`. ValueError: If `tensor_info` is malformed.
github-repos
def write_bashrc(_path): cfg_mounts = CFG["container"]["mounts"].value cfg_prefix = CFG["container"]["prefixes"].value path.mkfile_uchroot("/etc/portage/bashrc") mounts = uchroot.mounts("mnt", cfg_mounts) p_paths, p_libs = uchroot.env(cfg_prefix) paths, libs = uchroot.env(mounts) paths = paths + p_paths libs = libs + p_libs with open(_path, 'w') as bashrc: lines = .format(path.list_to_path(paths), path.list_to_path(libs)) bashrc.write(lines)
Write a valid gentoo bashrc file to :path:. Args: path - The output path of the make.conf
juraj-google-style
def read(self, x): access_logits = self._address_content(x) weights = tf.nn.softmax(access_logits) retrieved_mem = tf.reduce_sum(tf.multiply(tf.expand_dims(weights, 3), tf.expand_dims(self.mem_vals, axis=1)), axis=2) return (access_logits, retrieved_mem)
Read from the memory. An external component can use the results via a simple MLP, e.g., fn(x W_x + retrieved_mem W_m). Args: x: a tensor in the shape of [batch_size, length, depth]. Returns: access_logits: the logits for accessing the memory in shape of [batch_size, length, memory_size]. retrieved_mem: the retrieved results in the shape of [batch_size, length, val_depth].
codesearchnet
def is20(msg): if allzeros(msg): return False d = hex2bin(data(msg)) if d[0:8] != '00100000': return False cs = cs20(msg) if ' return False return True
Check if a message is likely to be BDS code 2,0 Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
juraj-google-style
def read_tree_nexus(nexus): if not isinstance(nexus, str): raise TypeError("nexus must be a str") if nexus.lower().endswith('.gz'): f = gopen(expanduser(nexus)) elif isfile(expanduser(nexus)): f = open(expanduser(nexus)) else: f = nexus.splitlines() trees = dict() for line in f: if isinstance(line,bytes): l = line.decode().strip() else: l = line.strip() if l.lower().startswith('tree '): i = l.index('='); left = l[:i].strip(); right = l[i+1:].strip() name = ' '.join(left.split(' ')[1:]) trees[name] = read_tree_newick(right) if hasattr(f,'close'): f.close() return trees
Read a tree from a Nexus string or file Args: ``nexus`` (``str``): Either a Nexus string or the path to a Nexus file (plain-text or gzipped) Returns: ``dict`` of ``Tree``: A dictionary of the trees represented by ``nexus``, where keys are tree names (``str``) and values are ``Tree`` objects
juraj-google-style
def parse_line(self, line): line = line.lstrip() toks = shlex.split(line) cmd = toks[0] arg = line[len(cmd):] return (cmd, [arg])
Parser for the debugging shell. Treat everything after the first token as one literal entity. Whitespace characters between the first token and the next first non-whitespace character are preserved. For example, ' foo dicj didiw ' is parsed as ( 'foo', ' dicj didiw ' ) Returns: A tuple (cmd, args), where the args is a list that consists of one and only one string containing everything after the cmd as is.
codesearchnet
def stop_gradient(input_layer): if input_layer.is_sequence(): result = [tf.stop_gradient(t) for t in input_layer.sequence] return input_layer.with_sequence(result) else: return tf.stop_gradient(input_layer)
Cuts off the gradient at this point. This works on both sequence and regular Pretty Tensors. Args: input_layer: The input. Returns: A new Pretty Tensor of the same type with stop_gradient applied.
juraj-google-style
def get(url, params={}): request_url = url if len(params): request_url = '{}?{}'.format(url, urlencode(params)) try: req = Request(request_url, headers={'User-Agent': 'Mozilla/5.0'}) response = json.loads(urlopen(req).read().decode('utf-8')) return response except HTTPError as err: raise MtgException(err.read())
Invoke an HTTP GET request on a url Args: url (string): URL endpoint to request params (dict): Dictionary of url parameters Returns: dict: JSON response as a dictionary
codesearchnet
def _pull_out_unaffected_blocks_lhs(lhs, rest, out_port, in_port): (_, block_index) = lhs.index_in_block(out_port) bs = lhs.block_structure (nbefore, nblock, nafter) = (sum(bs[:block_index]), bs[block_index], sum(bs[(block_index + 1):])) (before, block, after) = lhs.get_blocks((nbefore, nblock, nafter)) if ((before != cid(nbefore)) or (after != cid(nafter))): outer_lhs = ((before + cid((nblock - 1))) + after) inner_lhs = ((cid(nbefore) + block) + cid(nafter)) return (outer_lhs << Feedback.create(SeriesProduct.create(inner_lhs, *rest), out_port=out_port, in_port=in_port)) elif (block == cid(nblock)): outer_lhs = ((before + cid((nblock - 1))) + after) return (outer_lhs << Feedback.create(SeriesProduct.create(*rest), out_port=out_port, in_port=in_port)) raise CannotSimplify()
In a self-Feedback of a series product, where the left-most operand is reducible, pull all non-trivial blocks outside of the feedback. Args: lhs (Circuit): The reducible circuit rest (tuple): The other SeriesProduct operands out_port (int): The feedback output port index in_port (int): The feedback input port index Returns: Circuit: The simplified circuit
codesearchnet
def __init__(self, fail_on_unset: bool = False, default: str = 'none'): self.fail_on_unset = bool(fail_on_unset) self.default = str(default)
Initializer. Args: fail_on_unset (bool): If set to True an exception will be raised when the environment variable is unset; otherwise the default value (see next) will be used instead. default (str): If a environment variable is unset, it will get this value instead.
juraj-google-style
def addStreamHandler(self,lvl=20): sh = logging.StreamHandler(sys.stdout) sh.setLevel(lvl) sFrmt = logging.Formatter('%(message)s') if False: sFrmt = logging.Formatter('%(name)s - %(levelname)s - %(message)s') sh.setFormatter(sFrmt) self.addHandler(sh)
This function will add a stream handler to a log with the provided level. Args: lvl (int): The severity level of messages printed to the screen with the stream handler, default = 20.
juraj-google-style
def search(cls, session, queries): return super(Customers, cls).search(session, queries, SearchCustomer)
Search for a customer given a domain. Args: session (requests.sessions.Session): Authenticated session. queries (helpscout.models.Domain or iter): The queries for the domain. If a ``Domain`` object is provided, it will simply be returned. Otherwise, a ``Domain`` object will be generated from the complex queries. In this case, the queries should conform to the interface in :func:`helpscout.domain.Domain.from_tuple`. Returns: RequestPaginator(output_type=helpscout.models.SearchCustomer): SearchCustomer iterator.
codesearchnet
def codify(combination): if (isinstance(combination, int) and ((combination < 0) or (combination >= LIMIT))): raise errors.FlagError('Out-of-range flag-combination!') codes = [] for enum in (Style, Color, Fill): for flag in enum: if (combination & flag): codes.append(str(flag)) return ';'.join(codes)
Gets escape-codes for flag combinations. Arguments: combination (int): Either a single integer-convertible flag or an OR'd flag-combination. Returns: A semi-colon-delimited string of appropriate escape sequences. Raises: errors.FlagError if the combination is out-of-range.
codesearchnet
def _match_instance_against_type(self, left, other_type, subst, view): if isinstance(other_type, abstract.LiteralClass): other_value = other_type.value if isinstance(left, abstract.ConcreteValue) and isinstance(other_value, abstract.ConcreteValue): return subst if left.pyval == other_value.pyval else None elif isinstance(left, abstract.Instance) and left.cls.is_enum and isinstance(other_value, abstract.Instance) and other_value.cls.is_enum: names_match = left.name == other_value.name clses_match = left.cls == other_value.cls return subst if names_match and clses_match else None else: return None elif isinstance(other_type, typed_dict.TypedDictClass): if not self._match_dict_against_typed_dict(left, other_type): return None return subst elif isinstance(other_type, abstract.ParameterizedClass) and isinstance(other_type.base_cls, typed_dict.TypedDictClass): if not self._match_dict_against_typed_dict(left, other_type.base_cls): return None return self._match_instance_parameters(left.cls, left, other_type, subst, view) elif isinstance(left.cls, typed_dict.TypedDictClass): return self._match_typed_dict_against_dict(left, other_type, subst, view) elif isinstance(other_type, (fiddle_overlay.BuildableBuilder, fiddle_overlay.BuildableType)): return self._match_fiddle_instance(left.cls, left, other_type, subst, view) elif isinstance(other_type, abstract.PyTDClass) and fiddle_overlay.is_fiddle_buildable_pytd(other_type.pytd_cls) and isinstance(left, fiddle_overlay.Buildable): return self._match_fiddle_instance_against_bare_type(left.cls, left, other_type, subst, view) elif isinstance(other_type, abstract.Class): if not self._satisfies_noniterable_str(left.cls, other_type): self._noniterable_str_error = error_types.NonIterableStrError(left.cls, other_type) return None base = self.match_from_mro(left.cls, other_type) if base is None: if other_type.is_protocol: with self._track_partially_matched_protocols(): return self._match_against_protocol(left, other_type, subst, view) elif other_type.has_protocol_base(): return subst return None elif isinstance(base, abstract.AMBIGUOUS_OR_EMPTY): return self._match_maybe_parameterized_instance(base, left, other_type, subst, view) else: return self._match_instance(base, left, other_type, subst, view) elif isinstance(other_type, abstract.Empty): return None else: raise NotImplementedError(f"Can't match {left!r} against {other_type!r}")
Checks whether an instance of a type is compatible with a (formal) type. Args: left: An instance of a type. other_type: A formal type. E.g. abstract.Class or abstract.Union. subst: The current type parameter assignment. view: The current mapping of Variable to Value. Returns: A new type parameter assignment if the matching succeeded, None otherwise.
github-repos
def decode(self, decoder_input_ids, encoder_outputs, encoder_attention_mask: Optional[jnp.ndarray]=None, decoder_attention_mask: Optional[jnp.ndarray]=None, decoder_position_ids: Optional[jnp.ndarray]=None, past_key_values: Optional[dict]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None): output_attentions = output_attentions if output_attentions is not None else self.config.output_attentions output_hidden_states = output_hidden_states if output_hidden_states is not None else self.config.output_hidden_states return_dict = return_dict if return_dict is not None else self.config.return_dict encoder_hidden_states = encoder_outputs[0] if encoder_attention_mask is None: batch_size, sequence_length = encoder_hidden_states.shape[:2] encoder_attention_mask = jnp.ones((batch_size, sequence_length)) batch_size, sequence_length = decoder_input_ids.shape if decoder_attention_mask is None: decoder_attention_mask = jnp.ones((batch_size, sequence_length)) if decoder_position_ids is None: if past_key_values is not None: raise ValueError('Make sure to provide `decoder_position_ids` when passing `past_key_values`.') decoder_position_ids = jnp.broadcast_to(jnp.arange(sequence_length)[None, :], (batch_size, sequence_length)) rngs = {} if dropout_rng is not None: rngs['dropout'] = dropout_rng inputs = {'params': params or self.params} if past_key_values: inputs['cache'] = past_key_values mutable = ['cache'] else: mutable = False def _decoder_forward(module, decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs): decoder_module = module._get_decoder_module() outputs = decoder_module(decoder_input_ids, decoder_attention_mask, decoder_position_ids, **kwargs) hidden_states = outputs[0] if self.config.tie_word_embeddings: shared_embedding = module.model.variables['params']['shared']['embedding'] lm_logits = module.lm_head.apply({'params': {'kernel': shared_embedding.T}}, hidden_states) else: lm_logits = module.lm_head(hidden_states) lm_logits += module.final_logits_bias.astype(self.dtype) return (lm_logits, outputs) outputs = self.module.apply(inputs, decoder_input_ids=jnp.array(decoder_input_ids, dtype='i4'), decoder_attention_mask=jnp.array(decoder_attention_mask, dtype='i4'), decoder_position_ids=jnp.array(decoder_position_ids, dtype='i4'), encoder_hidden_states=encoder_hidden_states, encoder_attention_mask=jnp.array(encoder_attention_mask, dtype='i4'), output_attentions=output_attentions, output_hidden_states=output_hidden_states, return_dict=return_dict, deterministic=not train, rngs=rngs, mutable=mutable, method=_decoder_forward) if past_key_values is None: lm_logits, decoder_outputs = outputs else: (lm_logits, decoder_outputs), past = outputs if return_dict: outputs = FlaxCausalLMOutputWithCrossAttentions(logits=lm_logits, hidden_states=decoder_outputs.hidden_states, attentions=decoder_outputs.attentions, cross_attentions=decoder_outputs.cross_attentions) else: outputs = (lm_logits,) + decoder_outputs[1:] if past_key_values is not None and return_dict: outputs['past_key_values'] = unfreeze(past['cache']) return outputs elif past_key_values is not None and (not return_dict): outputs = outputs[:1] + (unfreeze(past['cache']),) + outputs[1:] return outputs
Returns: Example: ```python >>> import jax.numpy as jnp >>> from transformers import AutoTokenizer, FlaxMarianMTModel >>> model = FlaxMarianMTModel.from_pretrained("Helsinki-NLP/opus-mt-en-de") >>> tokenizer = AutoTokenizer.from_pretrained("Helsinki-NLP/opus-mt-en-de") >>> text = "My friends are cool but they eat too many carbs." >>> inputs = tokenizer(text, max_length=64, return_tensors="jax") >>> encoder_outputs = model.encode(**inputs) >>> decoder_start_token_id = model.config.decoder_start_token_id >>> decoder_input_ids = jnp.ones((inputs.input_ids.shape[0], 1), dtype="i4") * decoder_start_token_id >>> outputs = model.decode(decoder_input_ids, encoder_outputs) >>> logits = outputs.logits ```
github-repos
def shift_by_n_processors(self, x, mesh_axis, offset, wrap): n = self.shape[mesh_axis].size source_pcoord = [] for i in xrange(n): c = (i - offset) if (c != (c % n)): if wrap: c = (c % n) else: c = None source_pcoord.append(c) return self.receive(x, mesh_axis, source_pcoord)
Receive the slice from processor pcoord - offset. Args: x: a LaidOutTensor mesh_axis: an integer offset: an integer wrap: a boolean. If True, then wrap around. Otherwise, pad with zeros.
codesearchnet
def _wrap_usage_section(source, width): if not any(len(line) > width for line in source.splitlines()): return source section_header = source[:source.index(':') + 1].strip() lines = [section_header] for commands, args in parse_commands(source): command = ' {} '.format(' '.join(commands)) max_len = width - len(command) sep = '\n' + ' ' * len(command) wrapped_args = sep.join(textwrap.wrap(' '.join(args), max_len)) full_command = command + wrapped_args lines += full_command.splitlines() return '\n'.join(lines)
Wrap the given usage section string to the current terminal size. Note: Commands arguments are wrapped to the column that the arguments began on the first line of the command. Args: source: The section string to wrap. Returns: The wrapped section string.
juraj-google-style
def _find_all_hints_in_nodes(nodes): func_calls = _collections.defaultdict(_LiteFuncCall) for node in nodes: attr = node.attr if OpHint.FUNCTION_UUID_ATTR not in attr or not attr[OpHint.FUNCTION_UUID_ATTR].s: continue uuid = attr[OpHint.FUNCTION_UUID_ATTR].s call_def = func_calls[uuid] call_def.uuid = uuid call_def.function_name = attr[OpHint.FUNCTION_NAME_ATTR].s call_def.level = attr[OpHint.FUNCTION_LEVEL_ATTR].i sort = attr[OpHint.FUNCTION_SORT_INDEX_ATTR].i if OpHint.FUNCTION_SORT_INDEX_ATTR in attr else None if sort == -1: sort = None aggregation = None if OpHint.FUNCTION_AGGREGATE_ATTR in attr: aggregation = _compat.as_text(attr[OpHint.FUNCTION_AGGREGATE_ATTR].s) if OpHint.CHILDREN_INPUTS_MAPPINGS in attr: call_def.children_inputs_mappings = _json.loads(_compat.as_text(attr[OpHint.CHILDREN_INPUTS_MAPPINGS].s)) def put_operand(stuff, index, sort, operand, aggregation): if sort is None: stuff[index] = _LiteSingleOperand(operand) else: if index not in stuff: stuff[index] = _LiteAggregateOperand(aggregation) stuff[index].add(sort, operand) if OpHint.FUNCTION_INPUT_INDEX_ATTR in attr: put_operand(call_def.inputs, attr[OpHint.FUNCTION_INPUT_INDEX_ATTR].i, sort, node, aggregation) if OpHint.FUNCTION_OUTPUT_INDEX_ATTR in attr: put_operand(call_def.outputs, attr[OpHint.FUNCTION_OUTPUT_INDEX_ATTR].i, sort, node, aggregation) for a in attr: if a.startswith('_tflite_attr_'): call_def.params[a.replace('_tflite_attr_,', '')] = attr[a].tensor return func_calls
Look at the all the input nodes and return a list of LiteFuncCall objs. Args: nodes: A TensorFlow graph_def to look for LiteFuncCalls. Returns: a list of `LifeFuncCall` objects in the form
github-repos
def verify(self, byts, sign): try: chosen_hash = c_hashes.SHA256() hasher = c_hashes.Hash(chosen_hash, default_backend()) hasher.update(byts) digest = hasher.finalize() self.publ.verify(sign, digest, c_ec.ECDSA(c_utils.Prehashed(chosen_hash))) return True except InvalidSignature: logger.exception('Error in publ.verify') return False
Verify the signature for the given bytes using the ECC public key. Args: byts (bytes): The data bytes. sign (bytes): The signature bytes. Returns: bool: True if the data was verified, False otherwise.
codesearchnet
def _count_and_gen_subtokens(token_counts, alphabet, subtoken_dict, max_subtoken_length): subtoken_counts = collections.defaultdict(int) for (token, count) in six.iteritems(token_counts): token = _escape_token(token, alphabet) subtokens = _split_token_to_subtokens(token, subtoken_dict, max_subtoken_length) start = 0 for subtoken in subtokens: for end in xrange((start + 1), (len(token) + 1)): new_subtoken = token[start:end] subtoken_counts[new_subtoken] += count start += len(subtoken) return subtoken_counts
Count number of times subtokens appear, and generate new subtokens. Args: token_counts: dict mapping tokens to the number of times they appear in the original files. alphabet: list of allowed characters. Used to escape the tokens, which guarantees that all tokens can be split into subtokens. subtoken_dict: dict mapping subtokens to ids. max_subtoken_length: maximum length of subtoken in subtoken_dict. Returns: A defaultdict mapping subtokens to the number of times they appear in the tokens. The dict may contain new subtokens.
codesearchnet
def print_variant(variant_line, outfile=None, silent=False): variant_line = variant_line.rstrip() if not variant_line.startswith(' if outfile: outfile.write(variant_line+'\n') else: if not silent: print(variant_line) return
Print a variant. If a result file is provided the variante will be appended to the file, otherwise they are printed to stdout. Args: variants_file (str): A string with the path to a file outfile (FileHandle): An opened file_handle silent (bool): Bool. If nothing should be printed.
juraj-google-style
def id_to_int(cls, _id: Union[int, ObjectId]) -> int: if isinstance(_id, int): return _id ints = struct.unpack('>III', _id.binary) return (ints[0] << 64) + (ints[1] << 32) + ints[2]
Args: _id: ObjectId required for each MongoDB document _id field. Returns: Converted integer value of ObjectId's 12 bytes binary value.
github-repos
def drop_dimension(self, dimensions): dimensions = [dimensions] if np.isscalar(dimensions) else dimensions dims = [d for d in self.kdims if d not in dimensions] dim_inds = [self.get_dimension_index(d) for d in dims] key_getter = itemgetter(*dim_inds) return self.clone([(key_getter(k), v) for k, v in self.data.items()], kdims=dims)
Drops dimension(s) from keys Args: dimensions: Dimension(s) to drop Returns: Clone of object with with dropped dimension(s)
juraj-google-style
def normalize(x, axis=-1, order=2, epsilon=None): if any_symbolic_tensors((x,)): return Normalize(axis=axis, order=order, epsilon=epsilon).symbolic_call(x) return _normalize(x, axis=axis, order=order, epsilon=epsilon)
Normalizes `x` over the specified axis. It is defined as: `normalize(x) = x / max(norm(x), epsilon)`. Args: x: Input tensor. axis: The axis or axes along which to perform normalization. Default to -1. order: The exponent value in the norm formulation. Defaults to 2. epsilon: A lower bound value for the norm. Defaults to `backend.epsilon()`. Returns: The normalized array. Example: >>> x = keras.ops.convert_to_tensor([[1, 2, 3], [4, 5, 6]]) >>> x_norm = keras.ops.math.normalize(x) >>> print(x_norm) array([[0.26726124 0.5345225 0.8017837 ] [0.45584232 0.5698029 0.68376344]], shape=(2, 3), dtype=float32)
github-repos
def bundle_apps(self, bundle_name, bundle_apps): bundle_file = os.path.join( self.app_path, self.args.outdir, '{}-bundle.zip'.format(bundle_name) ) z = zipfile.ZipFile(bundle_file, 'w') for app in bundle_apps: self.package_data['bundle'].append( {'action': 'Adding App:', 'output': os.path.basename(app)} ) z.write(app, os.path.basename(app)) self.package_data['bundle'].append( {'action': 'Created Bundle:', 'output': os.path.basename(bundle_file)} ) z.close()
Bundle multiple Job or Playbook Apps (.tcx files) into a single zip file. Args: bundle_name (str): The output name of the bundle zip file. bundle_apps (list): A list of Apps to include in the bundle.
juraj-google-style
def get_numpy_to_framework_fn(arr) -> Callable: if isinstance(arr, np.ndarray): return np.array if is_tf_available() and is_tf_tensor(arr): import tensorflow as tf return tf.convert_to_tensor if is_torch_available() and is_torch_tensor(arr): import torch return torch.tensor if is_flax_available() and is_jax_tensor(arr): import jax.numpy as jnp return jnp.array raise ValueError(f'Cannot convert arrays of type {type(arr)}')
Returns a function that converts a numpy array to the framework of the input array. Args: arr (`np.ndarray`): The array to convert.
github-repos
def _jvp_helper_wrapper(op_name, attr_tuple, inputs, outputs, tangents, use_batch): if use_batch: for primal, tangent in zip(inputs, tangents): if not tangent.shape.is_compatible_with([None] + primal.shape): raise ValueError('Tangent {} was expected to be of shape {} but is instead of shape {}'.format(tangent, [None] + primal.shape, tangent.shape)) return control_flow_ops.vectorized_map(functools.partial(_jvp_helper, op_name, attr_tuple, inputs, outputs), tangents) return _jvp_helper(op_name, attr_tuple, inputs, outputs, tangents)
Computes a batch of Jacobian-vector product for an op. Args: op_name: A string, the type of operation being executed. attr_tuple: Attributes of the operation. inputs: A flat list of input Tensors to the operation. outputs: A flat list of output Tensors from the operation. tangents: A flat list of Tensors, compatible with shape `[None] + input_shape`. use_batch: A bool, True to vetorize over batch of tangents of shape `[None] + input_shape`. Returns: A flat list of tangents compatible with `outputs` or `[None] + output_shape`. Raises: ValueError: if tangent shapes are not compatible with input shapes.
github-repos
def full_like(x, fill_value, dtype=None): if any_symbolic_tensors((x, fill_value)): return FullLike(dtype=dtype).symbolic_call(x, fill_value) return backend.numpy.full_like(x, fill_value, dtype=dtype)
Return a full tensor with the same shape and type as the given tensor. Args: x: Input tensor. fill_value: Fill value. dtype: Overrides data type of the result. Returns: Tensor of `fill_value` with the same shape and type as `x`.
github-repos
def _view_options(self): return {'window_mapping_fn': self._window_mapping_fn, 'coder': self._windowed_coder()}
Internal options corresponding to specific view. Intended for internal use by runner implementations. Returns: Tuple of options for the given view.
github-repos
def merge_sites(self, tol=0.01, mode="sum"): mode = mode.lower()[0] from scipy.spatial.distance import squareform from scipy.cluster.hierarchy import fcluster, linkage d = self.distance_matrix np.fill_diagonal(d, 0) clusters = fcluster(linkage(squareform((d + d.T) / 2)), tol, 'distance') sites = [] for c in np.unique(clusters): inds = np.where(clusters == c)[0] species = self[inds[0]].species coords = self[inds[0]].frac_coords props = self[inds[0]].properties for n, i in enumerate(inds[1:]): sp = self[i].species if mode == "s": species += sp offset = self[i].frac_coords - coords coords = coords + ((offset - np.round(offset)) / (n + 2)).astype( coords.dtype) for key in props.keys(): if props[key] is not None and self[i].properties[key] != props[key]: if mode == 'a' and isinstance(props[key], float): props[key] = props[key]*(n+1)/(n+2) + self[i].properties[key]/(n+2) else: props[key] = None warnings.warn("Sites with different site property %s are merged. " "So property is set to none" % key) sites.append(PeriodicSite(species, coords, self.lattice, properties=props)) self._sites = sites
Merges sites (adding occupancies) within tol of each other. Removes site properties. Args: tol (float): Tolerance for distance to merge sites. mode (str): Three modes supported. "delete" means duplicate sites are deleted. "sum" means the occupancies are summed for the sites. "average" means that the site is deleted but the properties are averaged Only first letter is considered.
juraj-google-style
def buckets_delete(self, bucket): url = Api._ENDPOINT + (Api._BUCKET_PATH % bucket) google.datalab.utils.Http.request(url, method='DELETE', credentials=self._credentials, raw_response=True)
Issues a request to delete a bucket. Args: bucket: the name of the bucket. Raises: Exception if there is an error performing the operation.
juraj-google-style
def _get_validation_labels(val_path): labels_path = tfds.core.get_tfds_path(_VALIDATION_LABELS_FNAME) with tf.io.gfile.GFile(labels_path) as labels_f: labels = labels_f.read().strip().split('\n') with tf.io.gfile.GFile(val_path, 'rb') as tar_f_obj: tar = tarfile.open(mode='r:', fileobj=tar_f_obj) images = sorted(tar.getnames()) return dict(zip(images, labels))
Returns labels for validation. Args: val_path: path to TAR file containing validation images. It is used to retrieve the name of pictures and associate them to labels. Returns: dict, mapping from image name (str) to label (str).
codesearchnet
def apply_grad_processors(opt, gradprocs): assert isinstance(gradprocs, (list, tuple)), gradprocs for gp in gradprocs: assert isinstance(gp, GradientProcessor), gp class _ApplyGradientProcessor(ProxyOptimizer): def __init__(self, opt, gradprocs): self._gradprocs = gradprocs[:] super(_ApplyGradientProcessor, self).__init__(opt) def apply_gradients(self, grads_and_vars, global_step=None, name=None): g = self._apply(grads_and_vars) return self._opt.apply_gradients(g, global_step, name) def _apply(self, g): for proc in self._gradprocs: g = proc.process(g) return g return _ApplyGradientProcessor(opt, gradprocs)
Wrapper around optimizers to apply gradient processors. Args: opt (tf.train.Optimizer): gradprocs (list[GradientProcessor]): gradient processors to add to the optimizer. Returns: a :class:`tf.train.Optimizer` instance which runs the gradient processors before updating the variables.
juraj-google-style
def get_intersection(self, range_): result = [] for entry in self.entries: package, value = entry if value is None: continue if package.version not in range_: continue if isinstance(value, list): variants = value entry_ = _PackageEntry(package, variants, self.solver) result.append(entry_) continue if self.solver.package_filter: rule = self.solver.package_filter.excludes(package) if rule: if config.debug_package_exclusions: print_debug("Package '%s' was excluded by rule '%s'" % (package.qualified_name, str(rule))) entry[1] = None continue if self.solver.package_load_callback: self.solver.package_load_callback(package) variants_ = [] for var in package.iter_variants(): variant = PackageVariant(var, self.solver.building) variants_.append(variant) entry[1] = variants_ entry_ = _PackageEntry(package, variants_, self.solver) result.append(entry_) return result or None
Get a list of variants that intersect with the given range. Args: range_ (`VersionRange`): Package version range. Returns: List of `_PackageEntry` objects.
juraj-google-style
def convert_adaptive_max_pool2d(params, w_name, scope_name, inputs, layers, weights, names): print('Converting adaptive_avg_pool2d...') if names == 'short': tf_name = 'APOL' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) global_pool = keras.layers.GlobalMaxPooling2D(data_format='channels_first', name=tf_name) layers[scope_name] = global_pool(layers[inputs[0]]) def target_layer(x): import keras return keras.backend.expand_dims(x) lambda_layer = keras.layers.Lambda(target_layer, name=tf_name + 'E') layers[scope_name] = lambda_layer(layers[scope_name]) layers[scope_name] = lambda_layer(layers[scope_name])
Convert convert_adaptive_max_pool2d layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def get_optimizer_group(self, param: Optional[Union[str, torch.nn.parameter.Parameter]]=None): if self.optimizer is None: raise ValueError('Trainer optimizer is None, please make sure you have setup the optimizer before.') if param is not None: for group in self.optimizer.param_groups: if param in group['params']: return group return [group['params'] for group in self.optimizer.param_groups]
Returns optimizer group for a parameter if given, else returns all optimizer groups for params. Args: param (`str` or `torch.nn.parameter.Parameter`, *optional*): The parameter for which optimizer group needs to be returned.
github-repos
def __init__(self, api, path, options): self._init(api, path, options)
Initialize. Args: api: storage_api instance. path: bucket path of form '/bucket'. options: a dict of listbucket options. Please see listbucket doc.
juraj-google-style
def _MultipleModulesFoundError(path, candidates): assert len(candidates) > 1 params = [path] + _StripCommonPathPrefix(candidates[:2]) if len(candidates) == 2: fmt = ERROR_LOCATION_MULTIPLE_MODULES_3 else: fmt = ERROR_LOCATION_MULTIPLE_MODULES_4 params.append(str(len(candidates) - 2)) return fmt, params
Generates an error message to be used when multiple matches are found. Args: path: The breakpoint location path that the user provided. candidates: List of paths that match the user provided path. Must contain at least 2 entries (throws AssertionError otherwise). Returns: A (format, parameters) tuple that should be used in the description field of the breakpoint error status.
juraj-google-style
def save_aggregate_reports_to_kafka(self, aggregate_reports, aggregate_topic): if (type(aggregate_reports) == dict or type(aggregate_reports) == OrderedDict): aggregate_reports = [aggregate_reports] if len(aggregate_reports) < 1: return for report in aggregate_reports: report['date_range'] = self.generate_daterange(report) report = self.strip_metadata(report) for slice in report['records']: slice['date_range'] = report['date_range'] slice['org_name'] = report['org_name'] slice['org_email'] = report['org_email'] slice['policy_published'] = report['policy_published'] slice['report_id'] = report['report_id'] logger.debug("Sending slice.") try: logger.debug("Saving aggregate report to Kafka") self.producer.send(aggregate_topic, slice) except UnknownTopicOrPartitionError: raise KafkaError( "Kafka error: Unknown topic or partition on broker") except Exception as e: raise KafkaError( "Kafka error: {0}".format(e.__str__())) try: self.producer.flush() except Exception as e: raise KafkaError( "Kafka error: {0}".format(e.__str__()))
Saves aggregate DMARC reports to Kafka Args: aggregate_reports (list): A list of aggregate report dictionaries to save to Kafka aggregate_topic (str): The name of the Kafka topic
juraj-google-style
def _isbn_pairing(items): NameWrapper = namedtuple('NameWrapper', ['name', 'obj']) metas = map((lambda x: NameWrapper(_just_name(x.filename), x)), filter((lambda x: isinstance(x, MetadataFile)), items)) ebooks = map((lambda x: NameWrapper(_just_name(x.filename), x)), filter((lambda x: isinstance(x, EbookFile)), items)) metas = sorted(metas, key=(lambda x: x.name)) ebooks = sorted(ebooks, key=(lambda x: x.name), reverse=True) while metas: meta = metas.pop() if (not isbn_validator.is_valid_isbn(meta.name)): continue if (not ebooks): break ebook_index = _index(ebooks, meta.name, key=(lambda x: x.name)) if (ebook_index >= 0): logger.debug(("Pairing '%s' and '%s'." % (meta.obj.filename, ebooks[ebook_index].obj.filename))) items.append(DataPair(metadata_file=meta.obj, ebook_file=ebooks[ebook_index].obj)) items.remove(meta.obj) items.remove(ebooks[ebook_index].obj) ebooks = ebooks[(ebook_index + 1):] return items
Pair `items` with same ISBN into `DataPair` objects. Args: items (list): list of items, which will be searched. Returns: list: list with paired items. Paired items are removed, `DataPair` is \ added instead.
codesearchnet
def main(args=None): parser = get_parser() args = parser.parse_args(args=args) if not (args.matrix or args.dependencies or args.treemap or args.graph): args.matrix = True packages = [] for arg in args.packages: if ',' in arg: for package in arg.split(','): if package not in packages: packages.append(package) elif arg not in packages: packages.append(arg) depth = args.depth if depth is None: depth = guess_depth(packages) output = args.output if isinstance(output, str): output = open(output, 'w') dsm = DSM(*packages, build_tree=True, build_dependencies=True, enforce_init=not args.greedy) if dsm.empty: return 1 indent = args.indent if indent is None: if args.format == CSV: indent = 0 else: indent = 2 elif indent < 0 and args.format == JSON: indent = None try: if args.dependencies: dsm.print(format=args.format, output=output, indent=indent) elif args.matrix: dsm.print_matrix(format=args.format, output=output, depth=depth, indent=indent) elif args.treemap: dsm.print_treemap(format=args.format, output=output) elif args.graph: dsm.print_graph(format=args.format, output=output, depth=depth, indent=indent) except BrokenPipeError: return 2 return 0
Main function. This function is the command line entry point. Args: args (list of str): the arguments passed to the program. Returns: int: return code being 0 (OK), 1 (dsm empty) or 2 (error).
juraj-google-style
def authenticate(self, request, username=None, password=None): if not isinstance(username, str): return None username = re.sub(r'\W', '', username) krb_ticket = self.get_kerberos_ticket(username, password) if krb_ticket == "reset": user, status = User.objects.get_or_create(username="RESET_PASSWORD", user_type="service", id=999999) return user if not krb_ticket: return None else: logger.debug("Authentication successful") try: user = User.objects.get(username__iexact=username) except User.DoesNotExist: return None return user
Authenticate a username-password pair. Creates a new user if one is not already in the database. Args: username The username of the `User` to authenticate. password The password of the `User` to authenticate. Returns: `User`
juraj-google-style
def graphviz_imshow(self, ax=None, figsize=None, dpi=300, fmt="png", **kwargs): graph = self.get_graphviz(**kwargs) graph.format = fmt graph.attr(dpi=str(dpi)) _, tmpname = tempfile.mkstemp() path = graph.render(tmpname, view=False, cleanup=True) ax, fig, _ = get_ax_fig_plt(ax=ax, figsize=figsize, dpi=dpi) import matplotlib.image as mpimg ax.imshow(mpimg.imread(path, format="png")) ax.axis("off") return fig
Generate flow graph in the DOT language and plot it with matplotlib. Args: ax: matplotlib :class:`Axes` or None if a new figure should be created. figsize: matplotlib figure size (None to use default) dpi: DPI value. fmt: Select format for output image Return: matplotlib Figure
juraj-google-style
def start_after(self, document_fields): query = query_mod.Query(self) return query.start_after(document_fields)
Start query after a cursor with this collection as parent. See :meth:`~.firestore_v1beta1.query.Query.start_after` for more information on this method. Args: document_fields (Union[~.firestore_v1beta1.\ document.DocumentSnapshot, dict, list, tuple]): a document snapshot or a dictionary/list/tuple of fields representing a query results cursor. A cursor is a collection of values that represent a position in a query result set. Returns: ~.firestore_v1beta1.query.Query: A query with cursor.
codesearchnet
def _AddCampaignsToGroup(client, campaign_group_id, campaign_ids): campaign_service = client.GetService('CampaignService', version='v201809') operations = [{ 'operator': 'SET', 'operand': { 'id': campaign_id, 'campaignGroupId': campaign_group_id } } for campaign_id in campaign_ids] campaign_service.mutate(operations) print ('The following campaign IDs were added to the campaign group with ID ' '"%d":\n\t%s' % (campaign_group_id, campaign_ids))
Adds multiple campaigns to a campaign group. Args: client: an AdWordsClient instance. campaign_group_id: an integer ID for the campaign group. campaign_ids: a list of integer IDs for campaigns.
juraj-google-style
def auto_plot_array(*, video_min_num_frames: int=15, height: None | int | tuple[int, int]=(100, 250), show_images_kwargs: Optional[dict[str, Any]]=None, show_videos_kwargs: Optional[dict[str, Any]]=None) -> None: ipython = IPython.get_ipython() if ipython is None: return array_repr_html_fn = functools.partial(array_repr_html, video_min_num_frames=video_min_num_frames, height=height, show_images_kwargs=show_images_kwargs, show_videos_kwargs=show_videos_kwargs) print('Display big np/tf/jax arrays as image for nicer IPython display') formatter = ipython.display_formatter.formatters['text/html'] try: jnp = enp.lazy.jnp except ImportError: pass else: jax_array_cls = type(jnp.zeros(shape=())) formatter.for_type(jax_array_cls, array_repr_html_fn) try: tf = enp.lazy.tf except ImportError: pass else: formatter.for_type(tf.Tensor, array_repr_html_fn) try: torch = enp.lazy.torch except ImportError: pass else: formatter.for_type(torch.Tensor, array_repr_html_fn) formatter.for_type(enp.lazy.np.ndarray, array_repr_html_fn)
If called, 2d/3d imgage arrays will be plotted as images in colab/jupyter. Usage: >>> ecolab.auto_plot_array() >>> np.zeros((28, 28, 3)) # Displayed as image Args: video_min_num_frames: Video `(num_frames, h, w, c)` with less than this number of frames will be displayed as individual images height: `(min, max)` image height in pixels. Images smaller/larger will be reshaped. `None` to disable. If a single number, assume `min == max`. show_images_kwargs: Kwargs forwarded to `mediapy.show_images` show_videos_kwargs: Kwargs forwarded to `mediapy.show_videos`
github-repos
def from_key(cls, *args): key = (args if (len(args) > 1) else args[0]) return cls._instances.get(key, None)
Return flyweight object with specified key, if it has already been created. Returns: cls or None: Previously constructed flyweight object with given key or None if key not found
codesearchnet
def fix_variables(self, fixed): for (v, val) in fixed.items(): self.fix_variable(v, val)
Fix the value of the variables and remove it from a binary quadratic model. Args: fixed (dict): A dictionary of variable assignments. Examples: >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN) >>> bqm.fix_variables({'a': -1, 'b': +1})
codesearchnet
def resolve_type(arg): arg_type = type(arg) if (arg_type == list): assert isinstance(arg, list) sample = arg[:min(4, len(arg))] tentative_type = TentativeType() for sample_item in sample: tentative_type.add(resolve_type(sample_item)) return ListType(tentative_type) elif (arg_type == set): assert isinstance(arg, set) sample = [] iterator = iter(arg) for i in range(0, min(4, len(arg))): sample.append(next(iterator)) tentative_type = TentativeType() for sample_item in sample: tentative_type.add(resolve_type(sample_item)) return SetType(tentative_type) elif (arg_type == FakeIterator): assert isinstance(arg, FakeIterator) sample = [] iterator = iter(arg) for i in range(0, min(4, len(arg))): sample.append(next(iterator)) tentative_type = TentativeType() for sample_item in sample: tentative_type.add(resolve_type(sample_item)) return IteratorType(tentative_type) elif (arg_type == tuple): assert isinstance(arg, tuple) sample = list(arg[:min(10, len(arg))]) return TupleType([resolve_type(sample_item) for sample_item in sample]) elif (arg_type == dict): assert isinstance(arg, dict) key_tt = TentativeType() val_tt = TentativeType() for (i, (k, v)) in enumerate(iteritems(arg)): if (i > 4): break key_tt.add(resolve_type(k)) val_tt.add(resolve_type(v)) return DictType(key_tt, val_tt) else: return type(arg)
Resolve object to one of our internal collection types or generic built-in type. Args: arg: object to resolve
codesearchnet
def to_obj(self, wd=False, pack=False, relpath=None): obj = CommentedMap() if pack: obj['run'] = self.orig elif (relpath is not None): if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.relpath(self.run, relpath) elif wd: if self.from_url: obj['run'] = self.run else: obj['run'] = os.path.basename(self.run) else: obj['run'] = self.run obj['in'] = self.step_inputs obj['out'] = self.output_names if self.is_scattered: obj['scatter'] = self.scattered_inputs if (self.scatter_method is not None): obj['scatterMethod'] = self.scatter_method return obj
Return the step as an dict that can be written to a yaml file. Returns: dict: yaml representation of the step.
codesearchnet
def artifact_bundles(self): if (not self.__artifact_bundles): self.__artifact_bundles = ArtifactBundles(self.__connection) return self.__artifact_bundles
Gets the Artifact Bundles API client. Returns: ArtifactBundles:
codesearchnet
def enclosure_groups(self): if (not self.__enclosure_groups): self.__enclosure_groups = EnclosureGroups(self.__connection) return self.__enclosure_groups
Gets the EnclosureGroups API client. Returns: EnclosureGroups:
codesearchnet
def step(self, action): observ, reward, done, info = self._env.step(action) observ = self._convert_observ(observ) reward = self._convert_reward(reward) return observ, reward, done, info
Forward action to the wrapped environment. Args: action: Action to apply to the environment. Raises: ValueError: Invalid action. Returns: Converted observation, converted reward, done flag, and info object.
juraj-google-style
def set_weight_collections(self, weight_collections): self._weight_collections = weight_collections
Sets the weight collections for the layer. Args: weight_collections: A list of collection names to which the Variable will be added.
github-repos
def find_all(container): if isinstance(container, dict): names = container.keys() else: names = dir(container) built_context = BasicContext() for name in names: if name.startswith('_'): continue if isinstance(container, dict): obj = container[name] else: obj = getattr(container, name) if (isinstance(container, dict) and isinstance(obj, str)): built_context[name] = obj elif (hasattr(obj, 'metadata') and isinstance(getattr(obj, 'metadata'), AnnotatedMetadata)): built_context[name] = obj return built_context
Find all annotated function inside of a container. Annotated functions are identified as those that: - do not start with a _ character - are either annotated with metadata - or strings that point to lazily loaded modules Args: container (object): The container to search for annotated functions. Returns: dict: A dict with all of the found functions in it.
codesearchnet
def complete(command_line, current_token, position, shell: arg(choices=('bash', 'fish'))): position = int(position) tokens = shlex.split(command_line[:position]) (all_argv, run_argv, command_argv) = run.partition_argv(tokens[1:]) run_args = run.parse_args(run_argv) module = run_args.get('commands_module') module = (module or DEFAULT_COMMANDS_MODULE) module = normalize_path(module) try: collection = Collection.load_from_module(module) except Exception: collection = {} found_command = (find_command(collection, tokens) or run) if current_token: if current_token.startswith('-'): if (current_token not in found_command.option_map): print_command_options(found_command, current_token) else: print_commands(collection, shell) path = os.path.expanduser(current_token) path = os.path.expandvars(path) paths = glob.glob(('%s*' % path)) if paths: for entry in paths: if os.path.isdir(entry): print(('%s/' % entry)) else: print(entry) else: option = found_command.option_map.get(tokens[(- 1)]) if (option and option.takes_value): if option.choices: for choice in option.choices: print(choice) else: for entry in os.listdir(): if os.path.isdir(entry): print(('%s/' % entry)) else: print(entry) else: print_command_options(found_command) print_commands(collection, shell)
Find completions for current command. This assumes that we'll handle all completion logic here and that the shell's automatic file name completion is disabled. Args: command_line: Command line current_token: Token at cursor position: Current cursor position shell: Name of shell
codesearchnet
def check_against_mro(ctx: 'context.Context', target: '_base.BaseValue', class_spec: '_instance_base.SimpleValue') -> bool | None: classes = [] ambiguous = flatten(class_spec, classes) for c in classes: if ctx.matcher(None).match_from_mro(target, c, allow_compat_builtins=False): return True return None if ambiguous else False
Check if any of the classes are in the target's MRO. Args: ctx: The abstract context. target: A BaseValue whose MRO will be checked. class_spec: A Class or PythonConstant tuple of classes (i.e. the second argument to isinstance or issubclass). Returns: True if any class in classes is found in the target's MRO, False if no match is found and None if it's ambiguous.
github-repos
def GetNewSessionID(self, **_): return rdfvalue.SessionID(base='aff4:/hunts', queue=self.runner_args.queue)
Returns a random integer session ID for this hunt. All hunts are created under the aff4:/hunts namespace. Returns: a formatted session id string.
codesearchnet
def set(self, context_id, address_value_list): if (context_id not in self._contexts): LOGGER.warning('Context_id not in contexts, %s', context_id) return False context = self._contexts.get(context_id) add_value_dict = {} for d in address_value_list: for (add, val) in d.items(): if (not self.address_is_valid(address=add)): raise AuthorizationException(address=add) add_value_dict[add] = val context.set_direct(add_value_dict) return True
Within a context, sets addresses to a value. Args: context_id (str): the context id returned by create_context address_value_list (list): list of {address: value} dicts Returns: (bool): True if the operation is successful, False if the context_id doesn't reference a known context. Raises: AuthorizationException if an address is given in the address_value_list that was not in the original transaction's outputs, or was under a namespace but the characters after the namespace are not valid address characters.
codesearchnet
def __parse_tonodes(self, text, **kwargs): n = self.options.get('nbest', 1) try: if self._KW_BOUNDARY in kwargs: patt = kwargs.get(self._KW_BOUNDARY, '.') tokens = list(self.__split_pattern(text, patt)) text = ''.join([t[0] for t in tokens]) btext = self.__str2bytes(text) self.__mecab.mecab_lattice_set_sentence(self.lattice, btext) bpos = 0 self.__mecab.mecab_lattice_set_boundary_constraint( self.lattice, bpos, self.MECAB_TOKEN_BOUNDARY) for (token, match) in tokens: bpos += 1 if match: mark = self.MECAB_INSIDE_TOKEN else: mark = self.MECAB_ANY_BOUNDARY for _ in range(1, len(self.__str2bytes(token))): self.__mecab.mecab_lattice_set_boundary_constraint( self.lattice, bpos, mark) bpos += 1 self.__mecab.mecab_lattice_set_boundary_constraint( self.lattice, bpos, self.MECAB_TOKEN_BOUNDARY) elif self._KW_FEATURE in kwargs: features = kwargs.get(self._KW_FEATURE, ()) fd = {morph: self.__str2bytes(feat) for morph, feat in features} tokens = self.__split_features(text, [e[0] for e in features]) text = ''.join([t[0] for t in tokens]) btext = self.__str2bytes(text) self.__mecab.mecab_lattice_set_sentence(self.lattice, btext) bpos = 0 for chunk, match in tokens: c = len(self.__str2bytes(chunk)) if match: self.__mecab.mecab_lattice_set_feature_constraint( self.lattice, bpos, bpos+c, fd[chunk]) bpos += c else: btext = self.__str2bytes(text) self.__mecab.mecab_lattice_set_sentence(self.lattice, btext) self.__mecab.mecab_parse_lattice(self.tagger, self.lattice) for _ in range(n): check = self.__mecab.mecab_lattice_next(self.lattice) if n == 1 or check: nptr = self.__mecab.mecab_lattice_get_bos_node(self.lattice) while nptr != self.__ffi.NULL: if nptr.stat != MeCabNode.BOS_NODE: raws = self.__ffi.string( nptr.surface[0:nptr.length]) surf = self.__bytes2str(raws).strip() if 'output_format_type' in self.options or \ 'node_format' in self.options: sp = self.__mecab.mecab_format_node( self.tagger, nptr) if sp != self.__ffi.NULL: rawf = self.__ffi.string(sp) else: err = self.__mecab.mecab_strerror( self.tagger) err = self.__bytes2str( self.__ffi.string(err)) msg = self._ERROR_NODEFORMAT.format( surf, err) raise MeCabError(msg) else: rawf = self.__ffi.string(nptr.feature) feat = self.__bytes2str(rawf).strip() mnode = MeCabNode(nptr, surf, feat) yield mnode nptr = getattr(nptr, 'next') except GeneratorExit: logger.debug('close invoked on generator') except MeCabError: raise except: err = self.__mecab.mecab_lattice_strerror(self.lattice) logger.error(self.__bytes2str(self.__ffi.string(err))) raise MeCabError(self.__bytes2str(self.__ffi.string(err)))
Builds and returns the MeCab function for parsing to nodes using morpheme boundary constraints. Args: format_feature: flag indicating whether or not to format the feature value for each node yielded. Returns: A function which returns a Generator, tailored to using boundary constraints and parsing as nodes, using either the default or N-best behavior.
juraj-google-style
def parse(self, stream, parser=None): (force, parsers) = self._get_parsers(parser) try: stream.seek(0) lookup = stream.read(1024) stream.seek(0) except (io.UnsupportedOperation, AttributeError): lookup = None for p in parsers: if p.hook(path=self.path, force=force, lookup=lookup): (self.meta, self.terms, self.imports, self.typedefs) = p.parse(stream) self._parsed_by = p.__name__ break
Parse the given file using available `BaseParser` instances. Raises: TypeError: when the parser argument is not a string or None. ValueError: when the parser argument is a string that does not name a `BaseParser`.
codesearchnet
def run(self, data): result_type = namedtuple('Result', 'code messages') if self.passes is True: result = result_type(Checker.Code.PASSED, '') elif self.passes is False: if self.allow_failure: result = result_type(Checker.Code.IGNORED, '') else: result = result_type(Checker.Code.FAILED, '') else: try: result = self.check(data, **self.arguments) messages = '' if isinstance(result, tuple): result, messages = result if result not in Checker.Code: result = Checker.Code.PASSED if bool(result) else Checker.Code.FAILED if result == Checker.Code.FAILED and self.allow_failure: result = Checker.Code.IGNORED result = result_type(result, messages) except NotImplementedError: result = result_type(Checker.Code.NOT_IMPLEMENTED, '') self.result = result
Run the check method and format the result for analysis. Args: data (DSM/DMM/MDM): DSM/DMM/MDM instance to check. Returns: tuple (int, str): status constant from Checker class and messages.
juraj-google-style
def get_data_for_sensors(macs=[], search_duratio_sec=5, bt_device=''): log.info('Get latest data for sensors. Stop with Ctrl+C.') log.info('Stops automatically in %ss', search_duratio_sec) log.info('MACs: %s', macs) datas = dict() for new_data in RuuviTagSensor._get_ruuvitag_datas(macs, search_duratio_sec, bt_device=bt_device): datas[new_data[0]] = new_data[1] return datas
Get lates data for sensors in the MAC's list. Args: macs (array): MAC addresses search_duratio_sec (int): Search duration in seconds. Default 5 bt_device (string): Bluetooth device id Returns: dict: MAC and state of found sensors
codesearchnet
def log_run_info(self, model_name): run_info = { "model_name": model_name, "machine_config": {}, "run_date": datetime.datetime.now().strftime(_DATE_TIME_FORMAT_PATTERN)} _collect_tensorflow_info(run_info) _collect_tensorflow_environment_variables(run_info) _collect_cpu_info(run_info) _collect_gpu_info(run_info) _collect_memory_info(run_info) with tf.gfile.GFile(os.path.join( self._logging_dir, BENCHMARK_RUN_LOG_FILE_NAME), "w") as f: try: json.dump(run_info, f) f.write("\n") except (TypeError, ValueError) as e: tf.logging.warning("Failed to dump benchmark run info to log file: %s", e)
Collect most of the TF runtime information for the local env. The schema of the run info follows official/benchmark/datastore/schema. Args: model_name: string, the name of the model.
juraj-google-style
def flatten_zip_dataset(*args): flattened = tf.data.Dataset.from_tensors(args[0]) for ex in args[1:]: flattened = flattened.concatenate(tf.data.Dataset.from_tensors(ex)) return flattened
A list of examples to a dataset containing mixed examples. Given a list of `n` dataset examples, flatten them by converting each element into a dataset and concatenating them to convert into a single dataset. Args: *args: A list containing one example each from `n` different datasets. Returns: flattened: A new dataset containing the examples from the list as part of a single dataset.
juraj-google-style
def determine_drift(self): try: response = self._cloud_formation.detect_stack_drift(StackName=self._stack_name) drift_request_id = response.get('StackDriftDetectionId', None) if drift_request_id: logging.info('drift_request_id: %s - polling', drift_request_id) drift_calc_done = False while (not drift_calc_done): time.sleep(self.nap_time) response = self._cloud_formation.describe_stack_drift_detection_status(StackDriftDetectionId=drift_request_id) current_state = response.get('DetectionStatus', None) logging.info('describe_stack_drift_detection_status(): {}'.format(current_state)) drift_calc_done = (current_state in CALC_DONE_STATES) drift_answer = response.get('StackDriftStatus', 'UNKNOWN') logging.info('drift of {}: {}'.format(self._stack_name, drift_answer)) if (drift_answer == 'DRIFTED'): if self._verbose: self._print_drift_report() return False else: return True else: logging.warning('drift_request_id is None') return False except Exception as wtf: logging.error(wtf, exc_info=True) return False
Determine the drift of the stack. Args: None Returns: Good or Bad; True or False
codesearchnet
def delete_jobs(self, user_ids, job_ids, task_ids, labels, create_time_min=None, create_time_max=None): tasks = list(self.lookup_job_tasks({'RUNNING'}, user_ids=user_ids, job_ids=job_ids, task_ids=task_ids, labels=labels, create_time_min=create_time_min, create_time_max=create_time_max)) print(('Found %d tasks to delete.' % len(tasks))) return google_base.cancel(self._service.new_batch_http_request, self._service.operations().cancel, tasks)
Kills the operations associated with the specified job or job.task. Args: user_ids: List of user ids who "own" the job(s) to cancel. job_ids: List of job_ids to cancel. task_ids: List of task-ids to cancel. labels: List of LabelParam, each must match the job(s) to be canceled. create_time_min: a timezone-aware datetime value for the earliest create time of a task, inclusive. create_time_max: a timezone-aware datetime value for the most recent create time of a task, inclusive. Returns: A list of tasks canceled and a list of error messages.
codesearchnet
def ShlexSplit(string): precondition.AssertType(string, Text) if PY2: string = string.encode("utf-8") parts = shlex.split(string) if PY2: parts = [part.decode("utf-8") for part in parts] return parts
A wrapper for `shlex.split` that works with unicode objects. Args: string: A unicode string to split. Returns: A list of unicode strings representing parts of the input string.
juraj-google-style
class ThresholdedReLU(Layer): def __init__(self, theta=1.0, **kwargs): super(ThresholdedReLU, self).__init__(**kwargs) if theta is None: raise ValueError('Theta of a Thresholded ReLU layer cannot be None, requires a float. Got %s' % theta) if theta < 0: raise ValueError('The theta value of a Thresholded ReLU layer should be >=0, got %s' % theta) self.supports_masking = True self.theta = backend.cast_to_floatx(theta) def call(self, inputs): theta = math_ops.cast(self.theta, inputs.dtype) return inputs * math_ops.cast(math_ops.greater(inputs, theta), inputs.dtype) def get_config(self): config = {'theta': float(self.theta)} base_config = super(ThresholdedReLU, self).get_config() return dict(list(base_config.items()) + list(config.items())) @tf_utils.shape_type_conversion def compute_output_shape(self, input_shape): return input_shape
Thresholded Rectified Linear Unit. It follows: ``` f(x) = x for x > theta f(x) = 0 otherwise` ``` Input shape: Arbitrary. Use the keyword argument `input_shape` (tuple of integers, does not include the samples axis) when using this layer as the first layer in a model. Output shape: Same shape as the input. Args: theta: Float >= 0. Threshold location of activation.
github-repos
def resize(self, image: np.ndarray, size: Dict[str, int], resample: PILImageResampling=PILImageResampling.BICUBIC, data_format: Optional[Union[str, ChannelDimension]]=None, input_data_format: Optional[Union[str, ChannelDimension]]=None, **kwargs) -> np.ndarray: size = get_size_dict(size, default_to_square=False) output_size = get_resize_output_image_size(image, size=(size['height'], size['width']), default_to_square=False, input_data_format=input_data_format) return resize(image, size=output_size, resample=resample, data_format=data_format, input_data_format=input_data_format, **kwargs)
Resize an image. The shortest edge of the image is resized to size["shortest_edge"], with the longest edge resized to keep the input aspect ratio. Args: image (`np.ndarray`): Image to resize. size (`Dict[str, int]`): Size of the output image. resample (`PILImageResampling`, *optional*, defaults to `PILImageResampling.BICUBIC`): Resampling filter to use when resiizing the image. data_format (`str` or `ChannelDimension`, *optional*): The channel dimension format of the image. If not provided, it will be the same as the input image. input_data_format (`ChannelDimension` or `str`, *optional*): The channel dimension format of the input image. If not provided, it will be inferred from the input image.
github-repos
def event(self, **kwargs): if (self.callback.noargs and (self.streams == [])): self.param.warning('No streams declared. To update a DynamicMaps using generators (or callables without arguments) use streams=[Next()]') return if (self.streams == []): self.param.warning('No streams on DynamicMap, calling event will have no effect') return stream_params = set(util.stream_parameters(self.streams)) invalid = [k for k in kwargs.keys() if (k not in stream_params)] if invalid: msg = 'Key(s) {invalid} do not correspond to stream parameters' raise KeyError(msg.format(invalid=', '.join((('%r' % i) for i in invalid)))) streams = [] for stream in self.streams: contents = stream.contents applicable_kws = {k: v for (k, v) in kwargs.items() if (k in set(contents.keys()))} if ((not applicable_kws) and contents): continue streams.append(stream) rkwargs = util.rename_stream_kwargs(stream, applicable_kws, reverse=True) stream.update(**rkwargs) Stream.trigger(streams)
Updates attached streams and triggers events Automatically find streams matching the supplied kwargs to update and trigger events on them. Args: **kwargs: Events to update streams with
codesearchnet
def _build_url(self, path): if (path.startswith('http: return path else: return ('%s%s' % (self._url, path))
Returns the full url from path. If path is already a url, return it unchanged. If it's a path, append it to the stored url. Returns: str: The full URL
codesearchnet
def ReadDataAtOffset(self, file_offset, size): self._file_object.seek(file_offset, os.SEEK_SET) return self._file_object.read(size)
Reads a byte string from the file-like object at a specific offset. Args: file_offset (int): file offset. size (int): number of bytes to read. Returns: bytes: data read. Raises: IOError: if the read failed. OSError: if the read failed.
codesearchnet
def solve(a, b): if any_symbolic_tensors((a, b)): return Solve().symbolic_call(a, b) return _solve(a, b)
Solves a linear system of equations given by `a x = b`. Args: a: A tensor of shape `(..., M, M)` representing the coefficients matrix. b: A tensor of shape `(..., M)` or `(..., M, N)` representing the right-hand side or "dependent variable" matrix. Returns: A tensor of shape `(..., M)` or `(..., M, N)` representing the solution of the linear system. Returned shape is identical to `b`.
github-repos
def minmax(self, minimum=None, maximum=None): if minimum is None and maximum is None: return {"minimum": self._minimum, "maximum": self._maximum}; if minimum != None: if self._type in ['base64', 'date', 'datetime', 'ip', 'time']: if not isinstance(minimum, basestring) \ or not _typeToRegex[self._type].match(minimum): raise ValueError('__minimum__') elif self._type in ['int', 'string', 'timestamp', 'uint']: if not isinstance(minimum, (int, long)): if isinstance(minimum, basestring) \ and _typeToRegex['int'].match(minimum): minimum = int(minimum, 0) else: raise ValueError('__minimum__') if self._type in ['base64', 'string', 'timestamp', 'uint']: if minimum < 0: raise ValueError('__minimum__') elif self._type == 'decimal': try: minimum = Decimal(minimum) except ValueError: raise ValueError('__minimum__') elif self._type == 'float': try: minimum = float(minimum) except ValueError: raise ValueError('__minimum__') elif self._type == 'price': if not isinstance(minimum, basestring) or not _typeToRegex['price'].match(minimum): raise ValueError('__minimum__') minimum = Decimal(minimum) else: raise TypeError('can not set __minimum__ for ' + self._type) self._minimum = minimum if maximum != None: if self._type in ['date', 'datetime', 'ip', 'time']: if not isinstance(maximum, basestring) \ or not _typeToRegex[self._type].match(maximum): raise ValueError('__maximum__') elif self._type in ['int', 'string', 'timestamp', 'uint']: if not isinstance(maximum, (int, long)): if isinstance(maximum, basestring) \ and _typeToRegex['int'].match(maximum): maximum = int(maximum, 0) else: raise ValueError('__minimum__') if self._type in ['string', 'timestamp', 'uint']: if maximum < 0: raise ValueError('__maximum__') elif self._type == 'decimal': try: maximum = Decimal(maximum) except ValueError: raise ValueError('__maximum__') elif self._type == 'float': try: minimum = float(minimum) except ValueError: raise ValueError('__maximum__') elif self._type == 'price': if not isinstance(maximum, basestring) or not _typeToRegex['price'].match(maximum): raise ValueError('__maximum__') maximum = Decimal(maximum) else: raise TypeError('can not set __maximum__ for ' + self._type) if self._minimum is not None: if self._type == 'ip': if self.__compare_ips(self._minimum, maximum) == 1: raise ValueError('__maximum__') else: if self._minimum > maximum: raise ValueError('__maximum__') self._maximum = maximum
Min/Max Sets or gets the minimum and/or maximum values for the Node. For getting, returns {"minimum":mixed,"maximum":mixed} Arguments: minimum {mixed} -- The minimum value maximum {mixed} -- The maximum value Raises: TypeError, ValueError Returns: None | dict
juraj-google-style
def _restart(self, downtime_secs, job): self._cluster.kill_task(job, 0) time.sleep(downtime_secs) self.assertFalse(context.check_alive('/job:%s/replica:0/task:0' % job)) self._cluster.start_task(job, 0) while not context.check_alive('/job:%s/replica:0/task:0' % job): time.sleep(1)
Kills `job` (index: 0) and restarts it after `downtime_secs`. Args: downtime_secs: secs before restarting the job. job: a string specifying the job to restart.
github-repos
def eval_from_json(json): closes = poloniex.get_attribute(json, 'close') volumes = poloniex.get_attribute(json, 'volume') obv = 0 for date in range(1, len(json)): curr = {'close': closes[date], 'volume': volumes[date]} prev = {'close': closes[date - 1], 'obv': obv} obv = OBV.eval_algorithm(curr, prev) return obv
Evaluates OBV from JSON (typically Poloniex API response) Args: json: List of dates where each entry is a dict of raw market data. Returns: Float of OBV
juraj-google-style
def _Execute(self, funcname, *args, **kwargs): wait_for_completion = kwargs.get('wait_for_completion', False) rpc_dict = {'func': funcname, 'args': args} self._Send(json.dumps(rpc_dict)) timeout = (TIMEOUT_FOREVER if wait_for_completion else TIMEOUT_DEFAULT) result_string = self._Recv(timeout) try: result = json.loads(result_string, object_hook=self._JsonDecodeDict) if isinstance(result, unicode): result = self._TryStr(result) elif isinstance(result, list): result = self._JsonDecodeList(result) except ValueError: raise ValueError(('Response JSON invalid: ' + str(result_string))) except TypeError: raise ValueError(('Response JSON invalid: ' + str(result_string))) return result
Send an RPC request to the gdb-internal python. Blocks for 3 seconds by default and returns any results. Args: funcname: the name of the function to call. *args: the function's arguments. **kwargs: Only the key 'wait_for_completion' is inspected, which decides whether to wait forever for completion or just 3 seconds. Returns: The result of the function call.
codesearchnet
def route(cls, route, config=None): def decorator(wrapped_class, **kwds): cls._routes.append(dict(url=route, request_handler=wrapped_class)) return wrapped_class return decorator
This method provides a decorator for adding endpoints to the http server. Args: route (str): The url to be handled by the RequestHandled config (dict): Configuration for the request handler Example: .. code-block:: python import nautilus from nauilus.network.http import RequestHandler class MyService(nautilus.Service): # ... @MyService.route('/') class HelloWorld(RequestHandler): def get(self): return self.finish('hello world')
codesearchnet