code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def reverse(self, transfer_id, data={}, **kwargs): url = "{}/{}/reversals".format(self.base_url, transfer_id) return self.post_url(url, data, **kwargs)
Reverse Transfer from given id Args: transfer_id : Id for which transfer object has to be reversed Returns: Transfer Dict which was reversed
juraj-google-style
def coverage_score(gold, pred, ignore_in_gold=[], ignore_in_pred=[]): gold, pred = _preprocess(gold, pred, ignore_in_gold, ignore_in_pred) return np.sum(pred != 0) / len(pred)
Calculate (global) coverage. Args: gold: A 1d array-like of gold labels pred: A 1d array-like of predicted labels (assuming abstain = 0) ignore_in_gold: A list of labels for which elements having that gold label will be ignored. ignore_in_pred: A list of labels for which elements having that pred label will be ignored....
juraj-google-style
def _environment_variables(**kwargs): hdx_key = os.getenv('HDX_KEY') if hdx_key is not None: kwargs['hdx_key'] = hdx_key hdx_url = os.getenv('HDX_URL') if hdx_url is not None: kwargs['hdx_url'] = hdx_url else: hdx_site = os.g...
Overwrite keyword arguments with environment variables Args: **kwargs: See below hdx_url (str): HDX url to use. Overrides hdx_site. hdx_site (str): HDX site to use eg. prod, test. Defaults to test. hdx_key (str): Your HDX key. Ignored if hdx_read_only = True. Returns: kwargs: Changed keyword arguments
juraj-google-style
def concat(self,array_like): arr = list(array_like) if len(set([x.microns_per_pixel for x in arr])) != 1: raise ValueError("Multiple microns per pixel set") cdf = CellDataFrame(pd.concat([pd.DataFrame(x) for x in arr])) cdf.microns_per_pixel = arr[0].microns_per_pixe...
Concatonate multiple CellDataFrames throws an error if the microns_per_pixel is not uniform across the frames Args: array_like (list): a list of CellDataFrames with 1 or more CellDataFrames Returns: CellDataFrame
juraj-google-style
def ParseFileObject(self, parser_mediator, file_object): filename = parser_mediator.GetFilename() if (not filename.startswith('INFO2')): return file_header_map = self._GetDataTypeMap('recycler_info2_file_header') try: (file_header, _) = self._ReadStructureFromFileObject(file_object, 0, f...
Parses a Windows Recycler INFO2 file-like object. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object. Raises: UnableToParseFile: when the file cannot be parsed.
codesearchnet
def detect_changepoints(points, min_time, data_processor=acc_difference): data = data_processor(points) changepoints = pelt(normal_mean(data, np.std(data)), len(data)) changepoints.append((len(points) - 1)) result = [] for (start, end) in pairwise(changepoints): time_diff = points[end].time_...
Detects changepoints on points that have at least a specific duration Args: points (:obj:`Point`) min_time (float): Min time that a sub-segmented, bounded by two changepoints, must have data_processor (function): Function to extract data to feed to the changepoint algorithm. Defaults to `speed_difference` Returns: :ob...
codesearchnet
def sample(self, bqm, beta_range=None, num_reads=10, num_sweeps=1000): if (not isinstance(num_reads, int)): raise TypeError("'samples' should be a positive integer") if (num_reads < 1): raise ValueError("'samples' should be a positive integer") (h, J, offset) = bqm.to_ising() samples = [...
Sample from low-energy spin states using simulated annealing. Args: bqm (:obj:`.BinaryQuadraticModel`): Binary quadratic model to be sampled from. beta_range (tuple, optional): Beginning and end of the beta schedule (beta is the inverse temperature) as a 2-tuple. The schedule is applied linearly in beta. Default is c...
codesearchnet
def maybe_append_oov_vectors(embeddings, num_oov_buckets): num_embeddings = np.shape(embeddings)[0] embedding_dim = np.shape(embeddings)[1] embeddings.resize([(num_embeddings + num_oov_buckets), embedding_dim], refcheck=False)
Adds zero vectors for oov buckets if num_oov_buckets > 0. Since we are assigning zero vectors, adding more that one oov bucket is only meaningful if we perform fine-tuning. Args: embeddings: Embeddings to extend. num_oov_buckets: Number of OOV buckets in the extended embedding.
codesearchnet
def cmAccuracy(cm): cm = cm.type(torch.float64) return cm.diag().sum() / (cm.sum() + 1e-15)
Calculates accuracy using :class:`~ignite.metrics.ConfusionMatrix` metric. Args: cm (ConfusionMatrix): instance of confusion matrix metric Returns: MetricsLambda
juraj-google-style
def trace_sync(self, data, timeout=5.0): done = AwaitableResponse() self.trace(data, callback=done.set_result) return done.wait(timeout)
Send tracing data and wait for it to finish. This awaitable coroutine wraps VirtualIOTileDevice.trace() and turns the callback into an awaitable object. The appropriate usage of this method is by calling it inside the event loop as: await device.trace_sync(data) Args: data (bytes): The raw data that should be trace...
codesearchnet
def pandas_dataframe(self, start, stop, ncol, **kwargs): try: int(start) int(stop) except TypeError: print('start and stop must be ints') try: ncol = int(ncol) return pd.read_csv(six.StringIO('\n'.join(self[start:stop])), delim...
Returns the result of tab-separated pandas.read_csv on a subset of the file. Args: start (int): line number where structured data starts stop (int): line number where structured data stops ncol (int or list): the number of columns in the structured data or a list of that length with column names Returns: pd.DataFrame...
juraj-google-style
def write(self, fb): print('[{}.{}]'.format(fb.module, fb.func.__name__), file=self.file) print('class = {}'.format(fb.func_ins.name), file=self.file) print('inspecs = {}'.format(repr(fb.inspecs)), file=self.file) print('func_args = {}'.format(repr(fb.func_args)), file=self.file...
Write a single function benchmark. Args: fb (FunctionBenchmark): FunctionBenchmark class instance. Before passing to this, you should call ``fb.benchmark()``.
juraj-google-style
def ReportStatus(self, request, global_params=None): config = self.GetMethodConfig('ReportStatus') return self._RunMethod(config, request, global_params=global_params)
Reports the status of dataflow WorkItems leased by a worker. Args: request: (DataflowProjectsLocationsJobsWorkItemsReportStatusRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (ReportWorkItemStatusResponse) The response message.
github-repos
def render_parse_load(raw_config, environment=None, validate=True): pre_rendered = render(raw_config, environment) rendered = process_remote_sources(pre_rendered, environment) config = parse(rendered) if config.namespace is None: namespace = environment.get("namespace") ...
Encapsulates the render -> parse -> validate -> load process. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config validate (bool): if provided, the config is validated before being loaded. Returns: :class:`Config`: the ...
juraj-google-style
def interpret_obj( self, obj, v_level_indexes, h_level_indexes, v_level_visibility, h_level_visibility, v_level_sort_keys, h_level_sort_keys, v_level_titles, h_level_titles, ): if not isinstance(obj, NonStringIterable):...
Interpret the given Python object as a table. Args: obj: A sequence (later a mapping, too) Returns: A list of lists represents rows of cells. Raises: TypeError: If the type couldn't be interpreted as a table.
juraj-google-style
def _ParseEntryObject(self, file_object, file_offset): entry_object_map = self._GetDataTypeMap('systemd_journal_entry_object') try: (entry_object, _) = self._ReadStructureFromFileObject(file_object, file_offset, entry_object_map) except (ValueError, errors.ParseError) as exception: raise err...
Parses an entry object. Args: file_object (dfvfs.FileIO): a file-like object. file_offset (int): offset of the entry object relative to the start of the file-like object. Returns: systemd_journal_entry_object: entry object. Raises: ParseError: if the entry object cannot be parsed.
codesearchnet
def __init__(self, input_energy: energy.BernoulliEnergy, num_expectation_samples: int, initial_seed: Union[None, tf.Tensor]=None, name: Union[None, str]=None): super().__init__(input_energy, num_expectation_samples, initial_seed, name) self._logits_variable = tf.Variable(input_energy.logits, trainable=False) ...
Initializes a BernoulliEnergyInference. Args: input_energy: The parameterized energy function which defines this distribution via the equations of an energy based model. This class assumes that all parameters of `energy` are `tf.Variable`s and that they are all returned by `energy.variables`. num_expectation_samples:...
github-repos
def __init__(self, msg, url, headers, status_code, writer=None): self.msg = msg self.url = url self.http_headers = headers self.status_code = status_code self._init_writer(writer)
Set the main attributes and instantiate the writer if given. Args: msg(pandasdmx.model.Message): the SDMX message url(str): the URL, if any, that had been sent to the SDMX server headers(dict): http headers status_code(int): the status code returned by the server writer(str): the module path for the writer class
juraj-google-style
def ffn_self_attention_layer(x, filter_depth, output_depth, num_parts, dropout_rate, share_kv=False, name=None): with tf.variable_scope(name, default_name='feedforward_self_attention', values=[x]): x_shape = common_layers.shape_list(x) part_depth = (filter_depth if (not share_kv): ...
Self-attention feedforward layer. We use self-attention to do feedforward computations. We apply this function positionwise where for each position, we linearly transform the output to have depth filter_depth, and break up the result depth-wise into num_parts contiguous parts. The parts self-attend, we concatenate the...
codesearchnet
def calibrate(self, dataset_gen): self._feed_tensors(dataset_gen, resize_input=True) return self._calibrator.Calibrate()
Calibrates the model with specified generator. Returns: A model with min and max calibration stats. Args: dataset_gen: A generator that generates calibration samples.
github-repos
def quoted_tweet(self): quote_tweet = tweet_embeds.get_quoted_tweet(self) if (quote_tweet is not None): try: return Tweet(quote_tweet) except NotATweetError as nate: raise NotATweetError(('The quote-tweet payload appears malformed.' + " Failed with '{}'".format(nate))) ...
The quoted Tweet as a Tweet object If the Tweet is not a quote Tweet, return None If the quoted Tweet payload cannot be loaded as a Tweet, this will raise a "NotATweetError" Returns: Tweet: A Tweet representing the quoted status (or None) (see tweet_embeds.get_quote_tweet, this is that value as a Tweet) Raises: NotAT...
codesearchnet
def get_privkey(self, address: AddressHex, password: str) -> PrivateKey: address = add_0x_prefix(address).lower() if not self.address_in_keystore(address): raise ValueError('Keystore file not found for %s' % address) with open(self.accounts[address]) as data_file: ...
Find the keystore file for an account, unlock it and get the private key Args: address: The Ethereum address for which to find the keyfile in the system password: Mostly for testing purposes. A password can be provided as the function argument here. If it's not then the user is interactively queried for one. Returns T...
juraj-google-style
def atoms_string_from_file(filename): with zopen(filename, "rt") as fobject: f = fobject.readlines() coords = 0 atoms_str = [] for line in f: if coords == 0: find_atoms = line.find("ATOMS") if find_...
Reads atomic shells from file such as feff.inp or ATOMS file The lines are arranged as follows: x y z ipot Atom Symbol Distance Number with distance being the shell radius and ipot an integer identifying the potential used. Args: filename: File name containing atomic coord data. Returns: Atoms string.
juraj-google-style
def download_archive(self, name, file_path): uri = self.URI + "/archive/" + name return self._client.download(uri, file_path)
Download archived logs of the OS Volume. Args: name: Name of the OS Volume. file_path (str): Destination file path. Returns: bool: Indicates if the resource was successfully downloaded.
juraj-google-style
def _log_band_edge_information(bs, edge_data): if bs.is_spin_polarized: spins = edge_data['band_index'].keys() b_indices = [', '.join([str(i+1) for i in edge_data['band_index'][spin]]) + '({})'.format(spin.name.capitalize()) for spin in spins...
Log data about the valence band maximum or conduction band minimum. Args: bs (:obj:`~pymatgen.electronic_structure.bandstructure.BandStructureSymmLine`): The band structure. edge_data (dict): The :obj:`dict` from ``bs.get_vbm()`` or ``bs.get_cbm()``
juraj-google-style
def get_panel_info(panel_lines=None, panel_id=None, institute=None, version=None, date=None, display_name=None): panel_info = { 'panel_id': panel_id, 'institute': institute, 'version': version, 'date': date, 'display_name': display_name, } if ...
Parse metadata for a gene panel For historical reasons it is possible to include all information about a gene panel in the header of a panel file. This function parses the header. Args: panel_lines(iterable(str)) Returns: panel_info(dict): Dictionary with panel information
juraj-google-style
def download(self, chunk_size=1024): stream = BytesIO() response = self._swimlane.request( 'get', 'attachment/download/{}'.format(self.file_id), stream=True ) for chunk in response.iter_content(chunk_size): stream.write(chunk) ...
Download attachment Args: chunk_size (int): Byte-size of chunked download request stream Returns: BytesIO: Stream ready for reading containing the attachment file contents
juraj-google-style
def nr_genes(self, build=None): if build: LOG.info('Fetching all genes from build %s', build) else: LOG.info('Fetching all genes') return self.hgnc_collection.find({'build': build}).count()
Return the number of hgnc genes in collection If build is used, return the number of genes of a certain build Returns: result()
codesearchnet
def find_signature(self, signature_id=None, signer_email_address=None): if self.signatures: for signature in self.signatures: if signature.signature_id == signature_id or signature.signer_email_address == signer_email_address: return signature
Return a signature for the given parameters Args: signature_id (str): Id of the signature to retrieve. signer_email_address (str): Email address of the associated signer for the signature to retrieve. Returns: A Signature object or None
juraj-google-style
def verify_repo_matches_url(repo, url): repo_parts = urlparse(repo) url_parts = urlparse(url) errors = [] repo_path_parts = repo_parts.path.split('/') url_path_parts = url_parts.path.split('/') if repo_parts.hostname != url_parts.hostname: errors.append("verify_repo_matches_url: Hos...
Verify ``url`` is a part of ``repo``. We were using ``startswith()`` for a while, which isn't a good comparison. This function allows us to ``urlparse`` and compare host and path. Args: repo (str): the repo url url (str): the url to verify is part of the repo Returns: bool: ``True`` if the repo matches the url.
juraj-google-style
def _check_currency_format(self, format=None): defaults = self.settings['currency']['format'] if hasattr(format, '__call__'): format = format() if is_str(format) and re.match('%v', format): return { 'pos': format, 'ne...
Summary. Args: format (TYPE, optional): Description Returns: name (TYPE): Description
juraj-google-style
def _get_source_chunks(self, input_text, language=None): chunks = ChunkList() seek = 0 result = self._get_annotations(input_text, language=language) tokens = result['tokens'] language = result['language'] for i, token in enumerate(tokens): word = token['text']['content'] begin_o...
Returns a chunk list retrieved from Syntax Analysis results. Args: input_text (str): Text to annotate. language (:obj:`str`, optional): Language of the text. Returns: A chunk list. (:obj:`budou.chunk.ChunkList`)
juraj-google-style
def validate(self): errors = [] for cls in self.OPTIONS: if 'validate' in cls.__dict__ and callable(cls.__dict__['validate']): errors.extend(self.options.view_as(cls).validate(self)) return errors
Calls validate on subclassess and returns a list of errors. validate will call validate method on subclasses, accumulate the returned list of errors, and returns the aggregate list. Returns: Aggregate list of errors after all calling all possible validate methods.
github-repos
def set_memory_growth(device, enable): context.context().set_memory_growth(device, enable)
Set if memory growth should be enabled for a `PhysicalDevice`. If memory growth is enabled for a `PhysicalDevice`, the runtime initialization will not allocate all memory on the device. Memory growth cannot be configured on a `PhysicalDevice` with virtual devices configured. For example: >>> physical_devices = tf.co...
github-repos
def ProcessAst(serializable_ast, module_map): serializable_ast = _LookupClassReferences(serializable_ast, module_map, serializable_ast.ast.name) serializable_ast = serializable_ast.Replace(class_type_nodes=None) serializable_ast = FillLocalReferences(serializable_ast, {'': serializable_ast.ast, serializable...
Postprocess a pickled ast. Postprocessing will either just fill the ClassType references from module_map or if module_name changed between pickling and loading rename the module internal references to the new module_name. Renaming is more expensive than filling references, as the whole AST needs to be rebuild. Args: ...
github-repos
def merge_input_csv_forecast_json(input_csv_file, forecast_json_path, condition_models, dist_models): try: run_date = input_csv_file[:(- 4)].split('_')[(- 1)] print(run_date) ens_member = '_'.join(input_csv_file.split('/')[(- 1)][:(- 4)].split('_')[3:(- 1)]) ens_name = input_csv_file...
Reads forecasts from json files and merges them with the input data from the step csv files. Args: input_csv_file: Name of the input data csv file being processed forecast_json_path: Path to the forecast json files toplevel directory condition_models: List of models used to forecast hail or no hail dist_models: List o...
codesearchnet
def add_slab(self, height, n_background=1., position='top'): assert position in ('top', 'bottom') name = str(self.slab_count) if not callable(n_background): n_back = lambda wl: n_background else: n_back = n_background height_discretised = self....
Creates and adds a :class:`Slab` object. Args: height (float): Height of the slab. n_background (float): The nominal refractive index of the slab. Default is 1 (air). Returns: str: The name of the slab.
juraj-google-style
def __call__(self, shardable_tensors: Sequence[sharding_util.ShardableTensor]) -> Sequence[sharding_util.Shard]: tensors_by_task = {} for shardable_tensor in shardable_tensors: tensor = shardable_tensor.tensor checkpoint_key = shardable_tensor.checkpoint_key slice_spec = shardable_tensor...
Callback to split tensors into shards based on their device spec task. Args: shardable_tensors: A list of ShardableTensors. Returns: List of shard dicts containing tensors. [ {checkpoint key: {slice_spec: tensor} } ]
github-repos
def __init__(self, logger=logging, instance_config_metadata=None): self.logger = logger self.instance_config_metadata = instance_config_metadata self.instance_config_header %= ( self.instance_config_script, self.instance_config_template) super(InstanceConfig, self).__init__( co...
Constructor. Inherit from the ConfigManager class. Read the template for instance defaults and write new sections and options. This prevents package updates from overriding user set defaults. Args: logger: logger object, used to write to SysLog and serial port. instance_config_metadata: string, a config file specifie...
juraj-google-style
def _StubMethod(self, stub, method_descriptor, rpc_controller, request, callback): return stub.rpc_channel.CallMethod( method_descriptor, rpc_controller, request, method_descriptor.output_type._concrete_class, callback)
The body of all service methods in the generated stub class. Args: stub: Stub instance. method_descriptor: Descriptor of the invoked method. rpc_controller: Rpc controller to execute the method. request: Request protocol message. callback: A callback to execute when the method finishes. Returns: Response message (in c...
juraj-google-style
def calculate(self, token_list_x, token_list_y): match_list = [tanimoto_value for tanimoto_value in token_list_x if tanimoto_value in token_list_y] return float(len(match_list) / (len(token_list_x) + len(token_list_y) - len(match_list)))
Calculate similarity with the Tanimoto coefficient. Concrete method. Args: token_list_x: [token, token, token, ...] token_list_y: [token, token, token, ...] Returns: Similarity.
juraj-google-style
def get(self, value): config = self.get_block(('vrf definition %s' % value)) if (not config): return None response = dict(vrf_name=value) response.update(self._parse_rd(config)) response.update(self._parse_description(config)) config = self.get_block(('no ip routing vrf %s' % value)) ...
Returns the VRF configuration as a resource dict. Args: value (string): The vrf name to retrieve from the running configuration. Returns: A Python dict object containing the VRF attributes as key/value pairs.
codesearchnet
def __xor__(self, other: 'TensorFluent') -> 'TensorFluent': return self._binary_op(self, other, tf.logical_xor, tf.bool)
Returns a TensorFluent for the xor logical operator. Args: self: The first operand. other: The second operand. Returns: A TensorFluent wrapping the operator's output.
juraj-google-style
def op_and(self, *elements): expression = self.add_operator(Operator(';')) for element in elements: expression.add_element(element) return expression
Update the ``Expression`` by joining the specified additional ``elements`` using an "AND" ``Operator`` Args: *elements (BaseExpression): The ``Expression`` and/or ``Constraint`` elements which the "AND" ``Operator`` applies to. Returns: Expression: ``self`` or related ``Expression``.
codesearchnet
def send_file(self, file_name, remote_destination=None, **kwargs): if not remote_destination: remote_destination = file_name return SubprocessTask( self._rsync_cmd() + ['-ut', file_name, '%s:%s' % (self.hostname, remote_destination)], **kwargs)
Send a file to a remote host with rsync. Args: file_name (str): The relative location of the file on the local host. remote_destination (str): The destination for the file on the remote host. If `None`, will be assumed to be the same as **file_name**. Default `None`. **kwargs: Passed to ``SubprocessTask``'s init met...
juraj-google-style
def VerifyStructure(self, parser_mediator, lines): try: structure = self._SDF_HEADER.parseString(lines) except pyparsing.ParseException: logger.debug('Not a SkyDrive log file') return False try: dfdatetime_time_elements.TimeElementsInMilliseconds(time_elements_tuple=structure...
Verify that this file is a SkyDrive log file. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. lines (str): one or more lines from the text file. Returns: bool: True if this is the correct parser, False otherwise.
codesearchnet
def key_exists(self, namespace, key): return namespace in self.__data and key in self.__data[namespace]
Checks a namespace for the existence of a specific key Args: namespace (str): Namespace to check in key (str): Name of the key to check for Returns: `True` if key exists in the namespace, else `False`
juraj-google-style
def add(self, path, compress=None): if os.path.isdir(path): self.add_dir(path, compress) else: self.add_file(path, compress)
Add `path` to the MAR file. If `path` is a file, it will be added directly. If `path` is a directory, it will be traversed recursively and all files inside will be added. Args: path (str): path to file or directory on disk to add to this MAR file compress (str): One of 'xz', 'bz2', or None. Defaults to None.
codesearchnet
def ensure(self, func, *args, **kwargs): data = self.tryload() if (data is None): data = func(*args, **kwargs) self.save(data) return data
r""" Wraps around a function. A cfgstr must be stored in the base cacher. Args: func (callable): function that will compute data on cache miss *args: passed to func **kwargs: passed to func Example: >>> from ubelt.util_cache import * # NOQA >>> def func(): >>> return 'expensive result' >>> fname = 'test_cacher_e...
codesearchnet
def delete_tag(self, key, update_session=True): existing_tags = {x.key: x for x in self.tags} if (key in existing_tags): if update_session: db.session.delete(existing_tags[key]) self.tags.remove(existing_tags[key]) return True return False
Removes a tag from a resource based on the tag key. Returns `True` if the tag was removed or `False` if the tag didn't exist Args: key (str): Key of the tag to delete update_session (bool): Automatically add the change to the SQLAlchemy session. Default: True Returns:
codesearchnet
def __init__(self, resolver_context, file_object=None): super(VHDIFile, self).__init__(resolver_context, file_object=file_object) self._parent_vhdi_files = [] self._sub_file_objects = []
Initializes a file-like object. Args: resolver_context (Context): resolver context. file_object (Optional[FileIO]): file-like object.
juraj-google-style
def cloud_train(train_dataset, eval_dataset, analysis_dir, output_dir, features, model_type, max_steps, num_epochs, train_batch_size, eval_batch_size, min_eval_frequency, top_n, layer_sizes, learning_rate, epsilon, job_name, job_name_prefix, config): import google.datalab.ml as ml if ((len(train_dataset.input_f...
Train model using CloudML. See local_train() for a description of the args. Args: config: A CloudTrainingConfig object. job_name: Training job name. A default will be picked if None.
codesearchnet
def metric_streaming(self): if (not self.__metric_streaming): self.__metric_streaming = MetricStreaming(self.__connection) return self.__metric_streaming
Gets the MetricStreaming API client. Returns: MetricStreaming:
codesearchnet
def load_extra(cls, filename): try: with open(filename, 'rb') as configuration_file: cls.load_extra_data(configuration_file.read()) sys.stderr.write('Config successfully loaded from {0:s}\n'.format(filename)) return True except IOError: return False
Loads extra JSON configuration parameters from a file on the filesystem. Args: filename: str, the filename to open. Returns: bool: True if the extra configuration parameters were read.
codesearchnet
def list_outputs(self, args, screen_info=None): _ = screen_info parsed = self._arg_parsers['list_outputs'].parse_args(args) output = self._list_inputs_or_outputs(parsed.recursive, parsed.node_name, parsed.depth, parsed.control, parsed.op_type, do_outputs=True) node_name = debug_graphs.get_node_name(pars...
Command handler for inputs. Show inputs to a given node. Args: args: Command-line arguments, excluding the command prefix, as a list of str. screen_info: Optional dict input containing screen information such as cols. Returns: Output text lines as a RichTextLines object.
github-repos
def log_cert_info(logger, msg_str, cert_obj): list( map( logger, ["{}:".format(msg_str)] + [ " {}".format(v) for v in [ "Subject: {}".format( _get_val_str(cert_obj, ["subject", "value"], rev...
Dump basic certificate values to the log. Args: logger: Logger Logger to which to write the certificate values. msg_str: str A message to write to the log before the certificate values. cert_obj: cryptography.Certificate Certificate containing values to log. Returns: None
juraj-google-style
def _replace_event_shape_in_shape_tensor(input_shape, event_shape_in, event_shape_out, validate_args): (output_tensorshape, is_validated) = _replace_event_shape_in_tensorshape(tensorshape_util.constant_value_as_shape(input_shape), event_shape_in, event_shape_out) validation_dependencies = (map(tf.identity, (eve...
Replaces the rightmost dims in a `Tensor` representing a shape. Args: input_shape: a rank-1 `Tensor` of integers event_shape_in: the event shape expected to be present in rightmost dims of `shape_in`. event_shape_out: the event shape with which to replace `event_shape_in` in the rightmost dims of `input_shape`. valida...
codesearchnet
def __init__(self, config=None, all_linters=None): self._classes = all_linters or LINTERS self._config = config or Config(self._classes) LinterRunner.config = self._config
Initialize the only Config object and assign it to other classes. Args: config (Config): Config object. all_linters (dict): Names and classes of all available linters.
juraj-google-style
def getFilesFromAFolder(path): from os import listdir from os.path import isfile, join onlyFiles = [] for f in listdir(path): if isfile(join(path, f)): onlyFiles.append(f) return onlyFiles
Getting all the files in a folder. Args: ----- path: The path in which looking for the files Returns: -------- list: The list of filenames found.
codesearchnet
def get_urls(self): urls = self.get_subfields('856', 'u', i1='4', i2='2') return map((lambda x: x.replace('&amp;', '&')), urls)
Content of field ``856u42``. Typically URL pointing to producers homepage. Returns: list: List of URLs defined by producer.
codesearchnet
def build_offset_mapping_with_special_tokens(self, offset_mapping_0, offset_mapping_1=None): if offset_mapping_1 is None: return [(0, 0)] + offset_mapping_0 + [(0, 0)] return [(0, 0)] + offset_mapping_0 + [(0, 0), (0, 0)] + offset_mapping_1 + [(0, 0)]
Build offset map from a pair of offset map by concatenating and adding offsets of special tokens. An Ernie-M offset_mapping has the following format: - single sequence: `(0,0) X (0,0)` - pair of sequences: `(0,0) A (0,0) (0,0) B (0,0)` Args: offset_mapping_ids_0 (`List[tuple]`): List of char offsets to which the spec...
github-repos
def lchmod(self, path, mode): if self.filesystem.is_windows_fs: raise (NameError, "name 'lchmod' is not defined") self.filesystem.chmod(path, mode, follow_symlinks=False)
Change the permissions of a file as encoded in integer mode. If the file is a link, the permissions of the link are changed. Args: path: (str) Path to the file. mode: (int) Permissions.
juraj-google-style
def mark_locations(h,section,locs,markspec='or',**kwargs): xyz = get_section_path(h,section) (r,theta,phi) = sequential_spherical(xyz) rcum = np.append(0,np.cumsum(r)) if type(locs) is float or type(locs) is np.float64: locs = np.array([locs]) if type(locs) is list: ...
Marks one or more locations on along a section. Could be used to mark the location of a recording or electrical stimulation. Args: h = hocObject to interface with neuron section = reference to section locs = float between 0 and 1, or array of floats optional arguments specify details of marker Returns: line = referen...
juraj-google-style
def populate_native_libraries(version): with open(BINARY_EXT_TEMPLATE, 'r') as file_obj: template = file_obj.read() contents = template.format(revision=version) with open(BINARY_EXT_FILE, 'w') as file_obj: file_obj.write(contents)
Populates ``binary-extension.rst`` with release-specific data. Args: version (str): The current version.
codesearchnet
def custom(colors, bins=None, bin_method=BinMethod.quantiles): return { 'colors': colors, 'bins': bins if bins is not None else len(colors), 'bin_method': bin_method, }
Create a custom scheme. Args: colors (list of str): List of hex values for styling data bins (int, optional): Number of bins to style by. If not given, the number of colors will be used. bin_method (str, optional): Classification method. One of the values in :obj:`BinMethod`. Defaults to `quantiles`, which only works ...
juraj-google-style
def build_inputs_with_special_tokens(self, token_ids_0: List[int], token_ids_1: Optional[List[int]]=None) -> List[int]: if token_ids_1 is None: return [self.cls_token_id] + token_ids_0 + [self.sep_token_id] cls = [self.cls_token_id] sep = [self.sep_token_id] return cls + token_ids_0 + sep + toke...
Build model inputs from a sequence or a pair of sequence for sequence classification tasks by concatenating and adding special tokens. A DeBERTa sequence has the following format: - single sequence: [CLS] X [SEP] - pair of sequences: [CLS] A [SEP] B [SEP] Args: token_ids_0 (`List[int]`): List of IDs to which the spec...
github-repos
class MusicgenProcessor(ProcessorMixin): feature_extractor_class = 'EncodecFeatureExtractor' tokenizer_class = ('T5Tokenizer', 'T5TokenizerFast') def __init__(self, feature_extractor, tokenizer): super().__init__(feature_extractor, tokenizer) self.current_processor = self.feature_extractor ...
Constructs a MusicGen processor which wraps an EnCodec feature extractor and a T5 tokenizer into a single processor class. [`MusicgenProcessor`] offers all the functionalities of [`EncodecFeatureExtractor`] and [`TTokenizer`]. See [`~MusicgenProcessor.__call__`] and [`~MusicgenProcessor.decode`] for more information. ...
github-repos
def run_generate(verbose=True): parser = argparse.ArgumentParser() parser.add_argument('model_name', type=str, help='like facebook/bart-large-cnn,google-t5/t5-base, etc.') parser.add_argument('input_path', type=str, help='like cnn_dm/test.source') parser.add_argument('save_path', type=str, help='where t...
Takes input text, generates output, and then using reference calculates the BLEU scores. The results are saved to a file and returned to the caller, and printed out unless ``verbose=False`` is passed. Args: verbose (:obj:`bool`, `optional`, defaults to :obj:`True`): print results to stdout Returns: a tuple: ``(score...
github-repos
def add_slot(self, var, slot_name, initializer='zeros', shape=None): if slot_name not in self._slot_names: self._slot_names.append(slot_name) var_key = _var_key(var) slot_dict = self._slots.setdefault(var_key, {}) weight = slot_dict.get(slot_name, None) if weight is None: if isinstan...
Add a new slot variable for `var`. A slot variable is an additional variable associated with `var` to train. It is allocated and managed by optimizers, e.g. `Adam`. Args: var: a `Variable` object. slot_name: name of the slot variable. initializer: initializer of the slot variable shape: (Optional) shape of the slot v...
github-repos
def __init__(self, channel): self.ParseResume = channel.unary_unary( "/google.cloud.talent.v4beta1.ResumeService/ParseResume", request_serializer=google_dot_cloud_dot_talent__v4beta1_dot_proto_dot_resume__service__pb2.ParseResumeRequest.SerializeToString, response_de...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def putfile(self, filepath, buildroot, metahash): def gen_obj_path(filename): filehash = util.hash_file(filepath).hexdigest() return (filehash, os.path.join(self.obj_cachedir, filehash[0:2], filehash[2:4], filehash)) filepath_relative = filepath.split(buildroot)[1][1:] incachepath = self._g...
Put a file in the cache. Args: filepath: Path to file on disk. buildroot: Path to buildroot buildrule: The rule that generated this file. metahash: hash object
codesearchnet
def device(self, name): if isinstance(name, LogicalDevice): name = name.name elif pydev.is_device_spec(name): name = name.to_string() return _EagerDeviceContext(self, name)
Context-manager to force placement of operations and Tensors on a device. Args: name: Name of the device or None to get default placement. Returns: Context manager that forces device placement. Raises: ValueError: If name is not a string or is an invalid device name. RuntimeError: If device scopes are not properly n...
github-repos
def _value_and_batch_jacobian(f, x): if tf.executing_eagerly(): with tf.GradientTape() as tape: tape.watch(x) value = f(x) batch_jacobian = tape.batch_jacobian(value, x) else: value = f(x) batch_jacobian = gradients.batch_jacobian(value, x) return (val...
Enables uniform interface to value and batch jacobian calculation. Works in both eager and graph modes. Arguments: f: The scalar function to evaluate. x: The value at which to compute the value and the batch jacobian. Returns: A tuple (f(x), J(x)), where J(x) is the batch jacobian.
codesearchnet
def read_first_header(self): self.file_obj.seek(0) (header_dict, pos) = self.read_header() self.file_obj.seek(0) return header_dict
Read first header in file Returns: header (dict): keyword:value pairs of header metadata
codesearchnet
def update(self, sparql_query_only=False, auto_refresh=None, update_binary=True): self._diff_graph() sq = SparqlUpdate(self.rdf.prefixes, self.rdf.diffs) if sparql_query_only: return sq.build_query() response = self.repo.api.http_request('PATCH', ('%s/fcr:metadata' % self.uri), data=sq.build_que...
Method to update resources in repository. Firing this method computes the difference in the local modified graph and the original one, creates an instance of SparqlUpdate and builds a sparql query that represents these differences, and sends this as a PATCH request. Note: send PATCH request, regardless of RDF or NonR...
codesearchnet
def liquid_precipitation_depth(self, value=999.0): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `liquid_precipitation_depth`'.format(value)) self._liquid_precipitation_depth = value
Corresponds to IDD Field `liquid_precipitation_depth` Args: value (float): value for IDD Field `liquid_precipitation_depth` Unit: mm Missing value: 999.0 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def promote_artifacts(self, promote_stage='latest'): if promote_stage.lower() == 'alpha': self._sync_to_uri(self.s3_canary_uri) elif promote_stage.lower() == 'canary': self._sync_to_uri(self.s3_latest_uri) else: self._sync_to_uri(self.s3_latest_uri)
Promote artifact version to dest. Args: promote_stage (string): Stage that is being promoted
juraj-google-style
def kde_partition_data(data, estimate_tails=True): kde = stats.kde.gaussian_kde(data) evaluation_bins = np.linspace(start=(np.min(data) - (kde.covariance_factor() / 2)), stop=(np.max(data) + (kde.covariance_factor() / 2)), num=np.floor((((np.max(data) - np.min(data)) / kde.covariance_factor()) + 1)).astype(int)...
Convenience method for building a partition and weights using a gaussian Kernel Density Estimate and default bandwidth. Args: data (list-like): The data from which to construct the estimate estimate_tails (bool): Whether to estimate the tails of the distribution to keep the partition object finite Returns: A new part...
codesearchnet
def get_soup_response(self): if (self.response is not None): if (self.__response_soup is None): result = BeautifulSoup(self.response.text, 'lxml') if self.decomposed: return result else: self.__response_soup = BeautifulSoup(self.response.te...
Get the response as a cached BeautifulSoup container. Returns: obj: The BeautifulSoup container.
codesearchnet
def MakeNewConfig(self): result = self.__class__() result.type_infos = self.type_infos result.defaults = self.defaults result.context = self.context result.valid_contexts = self.valid_contexts return result
Creates a new configuration option based on this one. Note that it is not normally possible to just instantiate the config object because it will have an empty set of type descriptors (i.e. no config options will be defined). Config options are normally defined at import time, and then they get added to the _CONFIG gl...
codesearchnet
def register(self, managed_object): if (not isinstance(managed_object, pobjects.ManagedObject)): raise TypeError('managed object must be a Pie ManagedObject') object_attributes = list() if hasattr(managed_object, 'cryptographic_usage_masks'): if (managed_object.cryptographic_usage_masks is n...
Register a managed object with a KMIP appliance. Args: managed_object (ManagedObject): A managed object to register. An instantiatable subclass of ManagedObject from the Pie API. Returns: string: The uid of the newly registered managed object. Raises: ClientConnectionNotOpen: if the client connection is unusable Kmi...
codesearchnet
def unpack(self, buff, offset=0): try: unpacked_data = struct.unpack('!4B', buff[offset:offset+4]) self._value = '.'.join([str(x) for x in unpacked_data]) except struct.error as exception: raise exceptions.UnpackException('%s; %s: %s' % (exception, ...
Unpack a binary message into this object's attributes. Unpack the binary value *buff* and update this object attributes based on the results. Args: buff (bytes): Binary data package to be unpacked. offset (int): Where to begin unpacking. Raises: Exception: If there is a struct unpacking error.
juraj-google-style
def dot(matrix, vector, matrix_ty, vector_ty): weld_obj = WeldObject(encoder_, decoder_) matrix_var = weld_obj.update(matrix) if isinstance(matrix, WeldObject): matrix_var = matrix.obj_id weld_obj.dependencies[matrix_var] = matrix vector_var = weld_obj.update(vector) loopsize_...
Computes the dot product between a matrix and a vector. Args: matrix (WeldObject / Numpy.ndarray): 2-d input matrix vector (WeldObject / Numpy.ndarray): 1-d input vector ty (WeldType): Type of each element in the input matrix and vector Returns: A WeldObject representing this computation
juraj-google-style
def time_and_memory(min_micros=1, min_bytes=1, min_accelerator_micros=0, min_cpu_micros=0, min_peak_bytes=0, min_residual_bytes=0, min_output_bytes=0): return {'max_depth': 10000, 'min_bytes': min_bytes, 'min_peak_bytes': min_peak_bytes, 'min_residual_bytes': min_residual_bytes, 'min_output_bytes': min_output_bytes...
Show operation time and memory consumptions. Args: min_micros: Only show profiler nodes with execution time no less than this. It sums accelerator and cpu times. min_bytes: Only show profiler nodes requested to allocate no less bytes than this. min_accelerator_micros: Only show profiler nodes spend no less than this t...
github-repos
def __init__(self, req): super(Gateway, self).__init__(req) self.started_response = False self.env = self.get_environ() self.remaining_bytes_out = None
Initialize WSGI Gateway instance with request. Args: req (HTTPRequest): current HTTP request
juraj-google-style
def _check_preconditions(self, state: Sequence[tf.Tensor], action: Sequence[tf.Tensor], bound_constraints: Dict[(str, Constraints)], default: Sequence[tf.Tensor]) -> Tuple[(tf.Tensor, Sequence[tf.Tensor], tf.Tensor)]: def condition(i, a, checking): not_checking = tf.reduce_any(tf.logical_not(checking)) ...
Samples action fluents until all preconditions are satisfied. Checks action preconditions for the sampled `action` and current `state`, and iff all preconditions are satisfied it returns the sampled action fluents. Args: state (Sequence[tf.Tensor]): A list of state fluents. action (Sequence[tf.Tensor]): A list of act...
codesearchnet
def add_multiple(self, flags): if (not isinstance(flags, list)): raise TypeError('Expected list of flags, got object of type{}'.format(type(flags))) for flag in flags: if isinstance(flag, Flag): self.add_item(flag) elif isinstance(flag, tuple): try: ...
Add multiple command line flags Arguments: flags (:obj:`list` of :obj:`tuple`): List of flags in tuples (name, flag_type, description, (optional) default) Raises: TypeError: Provided wrong arguments or arguments of wrong types, method will raise TypeError
codesearchnet
def _reduced_stack(istart=3, iend=5, ipython=True): import inspect return [i[istart:iend] for i in inspect.stack() if _decorated_path(i[1])]
Returns the reduced function call stack that includes only relevant function calls (i.e., ignores any that are not part of the specified package or acorn. Args: package (str): name of the package that the logged method belongs to.
codesearchnet
def DEFINE_multi_enum_class(name, default, enum_class, help, flag_values=_flagvalues.FLAGS, module_name=None, **args): DEFINE_flag(_flag.MultiEnumClassFlag(name, default, help, enum_class), flag_values, module_name, **args)
Registers a flag whose value can be a list of enum members. Use the flag on the command line multiple times to place multiple enum values into the list. Args: name: str, the flag name. default: Union[Iterable[Enum], Iterable[Text], Enum, Text, None], the default value of the flag; see `DEFINE_multi`; only differences...
codesearchnet
def account(transition, direction=Direction.BIDIRECTIONAL): if (direction != Direction.BIDIRECTIONAL): return directed_account(transition, direction) return Account((directed_account(transition, Direction.CAUSE) + directed_account(transition, Direction.EFFECT)))
Return the set of all causal links for a |Transition|. Args: transition (Transition): The transition of interest. Keyword Args: direction (Direction): By default the account contains actual causes and actual effects.
codesearchnet
def marquee(text="", width=78, mark='*'): if not text: return (mark*width)[:width] nmark = (width-len(text)-2) if nmark < 0: nmark = 0 marks = mark * nmark return '%s %s %s' % (marks, text, marks)
Return the input string centered in a 'marquee'. Args: text (str): Input string width (int): Width of final output string. mark (str): Character used to fill string. :Examples: >>> marquee('A test', width=40) '**************** A test ****************' >>> marquee('A test', width=40, mark='-') '---------------- A te...
juraj-google-style
def _StartWorkerProcess(self, process_name, storage_writer): process_name = 'Worker_{0:02d}'.format(self._last_worker_number) logger.debug('Starting worker process {0:s}'.format(process_name)) if self._use_zeromq: queue_name = '{0:s} task queue'.format(process_name) task_queue = zeromq_que...
Creates, starts, monitors and registers a worker process. Args: process_name (str): process name. storage_writer (StorageWriter): storage writer for a session storage used to create task storage. Returns: MultiProcessWorkerProcess: extraction worker process or None if the process could not be started.
juraj-google-style
def expand_tile(units, axis): assert axis in (1, 2) n_time_steps = K.int_shape(units)[1] repetitions = [1, 1, 1, 1] repetitions[axis] = n_time_steps if axis == 1: expanded = Reshape(target_shape=( (1,) + K.int_shape(units)[1:] ))(units) else: expanded = Reshape(target_shape=...
Expand and tile tensor along given axis Args: units: tf tensor with dimensions [batch_size, time_steps, n_input_features] axis: axis along which expand and tile. Must be 1 or 2
juraj-google-style
def segmentation_images(self,*args,**kwargs): if not self.db: raise ValueError("Need to set db") segs = SegmentationImages.read_cellframe(self,*args,**kwargs) segs.microns_per_pixel = segs.microns_per_pixel return segs
Use the segmented images to create per-image graphics Args: verbose (bool): output more details if true Returns: SegmentationImages: returns a class used to construct the image graphics
juraj-google-style
def run_analysis(args): import google.datalab.bigquery as bq if args.bigquery_table: table = bq.Table(args.bigquery_table) schema_list = table.schema._bq_schema else: schema_list = json.loads( file_io.read_file_to_string(args.schema_file).decode()) table = bq.ExternalDataSource( ...
Builds an analysis file for training. Uses BiqQuery tables to do the analysis. Args: args: command line args Raises: ValueError if schema contains unknown types.
juraj-google-style
def post(self, resource): response = self.api.execute( "POST", self.endpoint, json=(resource.as_dict())) if not response.ok: raise Error.parse(response.json()) return self._cls.parse(response.json())
Creates a new instance of the resource. Args: resource - gophish.models.Model - The resource instance
juraj-google-style
def diff_bisectSplit(self, text1, text2, x, y, deadline): text1a = text1[:x] text2a = text2[:y] text1b = text1[x:] text2b = text2[y:] diffs = self.diff_main(text1a, text2a, False, deadline) diffsb = self.diff_main(text1b, text2b, False, deadline) return diffs + diffsb
Given the location of the 'middle snake', split the diff in two parts and recurse. Args: text1: Old string to be diffed. text2: New string to be diffed. x: Index of split point in text1. y: Index of split point in text2. deadline: Time at which to bail if not yet complete. Returns: Array of diff tuples.
juraj-google-style
def set_join_rule(self, room_id, join_rule): content = { "join_rule": join_rule } return self.send_state_event(room_id, "m.room.join_rules", content)
Set the rule for users wishing to join the room. Args: room_id(str): The room to set the rules for. join_rule(str): The chosen rule. One of: ["public", "knock", "invite", "private"]
juraj-google-style
def compressuser(path, home='~'): path = normpath(path) userhome_dpath = userhome() if path.startswith(userhome_dpath): if (len(path) == len(userhome_dpath)): path = home elif (path[len(userhome_dpath)] == os.path.sep): path = (home + path[len(userhome_dpath):]) r...
Inverse of `os.path.expanduser` Args: path (PathLike): path in system file structure home (str): symbol used to replace the home path. Defaults to '~', but you might want to use '$HOME' or '%USERPROFILE%' instead. Returns: PathLike: path: shortened path replacing the home directory with a tilde CommandLine: xdoctest...
codesearchnet
def remove_vtep(self, name, vtep, vlan=None): if (not vlan): cmd = 'vxlan flood vtep remove {}'.format(vtep) else: cmd = 'vxlan vlan {} flood vtep remove {}'.format(vlan, vtep) return self.configure_interface(name, cmd)
Removes a VTEP endpoint from the global or local flood list EosVersion: 4.13.7M Args: name (str): The name of the interface to configure vtep (str): The IP address of the remote VTEP endpoint to add vlan (str): The VLAN ID associated with this VTEP. If the VLAN keyword is used, then the VTEP is configured as a local...
codesearchnet