code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def ingress(self, envelope, http_headers, operation): if self._logger.isEnabledFor(logging.DEBUG): self._logger.debug(_RESPONSE_XML_LOG_LINE, etree.tostring(envelope, pretty_print=True)) if self._logger.isEnabledFor(logging.WARN): warn_data = {} header = envelope...
Overrides the ingress function for response logging. Args: envelope: An Element with the SOAP request data. http_headers: A dict of the current http headers. operation: The SoapOperation instance. Returns: A tuple of the envelope and headers.
juraj-google-style
def add_sample_tag_value(self, tag_name, new_sample_values): if tag_name in self.format_tags: msg = "New format value [{}] already exists.".format(tag_name) raise KeyError(msg) if not self._samples_match(new_sample_values): raise KeyError("Sample name values...
Appends a new format tag-value for all samples. Args: tag_name: string tag name; must not already exist new_sample Raises: KeyError: if tag_name to be added already exists
juraj-google-style
def update_restore_inputs(self, checkpoint_key: str, shape_and_slice_spec: str) -> tuple[Sequence[str], Sequence[str]]: keys = [] slices = [] logging.info('Updating restore v2 inputs for %s: %s', checkpoint_key, shape_and_slice_spec) for i, layout in enumerate(self._to_shard_layout): sub_checkpo...
Updates checkpoint key and slice spec acorrding to the resharding plan. Args: checkpoint_key: The input checkpoint key to be read. shape_and_slice_spec: The shape and slice spec of the checkpoint key to be read. Returns: A tuple of (keys, slices) that should be passed to restore_v2 inorder to reshard according to the...
github-repos
def eulers_totient(n): if not isinstance(n, int): raise TypeError("Expecting a strictly positive integer") if n <= 0: raise ValueError("Expecting a strictly positive integer") if n == 1: return 1 result = 0 for i in range(1, n): if gcd(i, n) == 1: ...
Calculate the value of Euler's totient for a given integer Args: n (int): strictly positive integer Returns: The value of Euler's totient for n Raises: TypeError: If either n or k is not an integer ValueError: If either n or k is negative, or if k is strictly greater than n
juraj-google-style
def write_uint8(self, value, little_endian=True): if little_endian: endian = '<' else: endian = '>' return self.pack(('%sB' % endian), value)
Pack the value as an unsigned byte and write 1 byte to the stream. Args: value: little_endian (bool): specify the endianness. (Default) Little endian. Returns: int: the number of bytes written.
codesearchnet
def check_copies(overwrite: bool=False, file: Optional[str]=None): buffer = {} if file is None: all_files = glob.glob(os.path.join(TRANSFORMERS_PATH, '***.py'), recursive=True) all_files = list(all_files) + list(all_test_files) else: all_files = [file] diffs = [] for filename...
Check every file is copy-consistent with the original. Also check the model list in the main README and other READMEs are consistent. Args: overwrite (`bool`, *optional*, defaults to `False`): Whether or not to overwrite the copies when they don't match. file (`bool`, *optional*): The path to a specific file to check ...
github-repos
def _is_in_control_flow(self, op): return control_flow_util.IsInCond(op)
Returns true if the given op is inside a tf.cond or in tf.while_loop. Args: op: A tensorflow op that should be checked whether in control flow or not. Returns: A boolean value whether the op is in control flow or not.
github-repos
def dice_loss(inputs: Tensor, labels: Tensor, num_masks: int) -> Tensor: probs = inputs.sigmoid().flatten(1) numerator = 2 * (probs * labels).sum(-1) denominator = probs.sum(-1) + labels.sum(-1) loss = 1 - (numerator + 1) / (denominator + 1) loss = loss.sum() / num_masks return loss
Compute the DICE loss, similar to generalized IOU for masks as follows: $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x \cap y }{x \cup y + 1}} $$ In practice, since `labels` is a binary mask, (only 0s and 1s), dice can be computed as follow $$ \mathcal{L}_{\text{dice}(x, y) = 1 - \frac{2 * x * y }{x + y + 1}} $...
github-repos
def start_new_feature(**cc_kwargs): project = Project.from_path(pathlib.Path.cwd().resolve()) contrib_dir = project.get('contrib', 'module_path') with tempfile.TemporaryDirectory() as tempdir: output_dir = tempdir cc_kwargs['output_dir'] = output_dir rendered_dir = ren...
Start a new feature within a ballet project Renders the feature template into a temporary directory, then copies the feature files into the proper path within the contrib directory. Args: **cc_kwargs: options for the cookiecutter template Raises: ballet.exc.BalletError: the new feature has the same name as an existi...
juraj-google-style
def get_data(self, file_path=sys.stdin, delimiter=',', categories_delimiter=None): if file_path == sys.stdin: logger.info('Read data from standard input') lines = [line.replace('\n', '') for line in file_path] else: ...
Implement get_dsm method from Provider class. Parse CSV to return an instance of DSM. Args: file_path (str/fd): path or file descriptor. delimiter (str): character(s) used as delimiter for columns. categories_delimiter (str): character(s) used as delimiter for categories and keys (first column). Returns: DSM: instan...
juraj-google-style
def expand_source_files(filenames, cwd=None): out = [] for f in expand_globpaths(filenames.split(), cwd): if path_utils.isdir(f): out += recursive_glob(path_utils.join(f, '**', '*.py')) elif f.endswith('.py'): out.append(f) elif is_file_script(f, cwd): ...
Expand a space-separated string of filenames passed in as sources. This is a helper function for handling command line arguments that specify a list of source files and directories. Any directories in filenames will be scanned recursively for .py files. Any files that do not end with ".py" will be dropped. Args: fil...
github-repos
def _maybe_create_attribute(self, name, default_value): if not hasattr(self, name): self.__setattr__(name, default_value)
Create the attribute with the default value if it hasn't been created. This is useful for fields that is used for tracking purpose, _trainable_weights, or _layers. Note that user could create a layer subclass and assign an internal field before invoking the Layer.__init__(), the __setattr__() need to create the tracki...
github-repos
def survey_basis(self, keys=None, alias=None, step=None): if keys is None: keys = [k for k, v in self.data.items() if isinstance(v, Curve)] else: keys = utils.flatten_list(keys) starts, stops, steps = [], [], [] for k in keys: d = self.get_cu...
Look at the basis of all the curves in ``well.data`` and return a basis with the minimum start, maximum depth, and minimum step. Args: keys (list): List of strings: the keys of the data items to survey, if not all of them. alias (dict): a dictionary mapping mnemonics to lists of mnemonics. step (float): a new step, if...
juraj-google-style
def to_molden(cartesian_list, buf=None, sort_index=True, overwrite=True, float_format='{:.6f}'.format): if sort_index: cartesian_list = [molecule.sort_index() for molecule in cartesian_list] give_header = (((((((('[MOLDEN FORMAT]\n' + '[N_GEO]\n') + str(len(cartesian_list))) + '\n') + '[GEOCONV]\n') + '...
Write a list of Cartesians into a molden file. .. note:: Since it permamently writes a file, this function is strictly speaking **not sideeffect free**. The list to be written is of course not changed. Args: cartesian_list (list): buf (str): StringIO-like, optional buffer to write to sort_index (bool): If sort_index ...
codesearchnet
def GetMessages(self, formatter_mediator, event): if self.DATA_TYPE != event.data_type: raise errors.WrongFormatter('Unsupported data type: {0:s}.'.format( event.data_type)) event_values = event.CopyToDict() priority_level = event_values.get('level', None) if isinstance(priority_l...
Determines the formatted message strings for an event object. Args: formatter_mediator (FormatterMediator): mediates the interactions between formatters and other components, such as storage and Windows EventLog resources. event (EventObject): event. Returns: tuple(str, str): formatted message string and short messag...
juraj-google-style
def markdown_to_html_with_extensions(text, options=0, extensions=None): if extensions is None: extensions = [] core_extensions_ensure_registered() cmark_extensions = [] for extension_name in extensions: extension = find_syntax_extension(extension_name) if extension is None...
Render the given text to Markdown, using extensions. This is a high-level wrapper over the various functions needed to enable extensions, attach them to a parser, and render html. Args: text (str): The text to render to Markdown. options (int): The cmark options. extensions (Sequence[str]): The list of extension name...
juraj-google-style
def __init__(self, *args, **kwargs): if "widget" not in kwargs: kwargs["widget"] = PasswordConfirmationInput( confirm_with=kwargs.pop('confirm_with', None)) super(PasswordConfirmationField, self).__init__(*args, **kwargs)
Init method. Args: *args (): Django's args for a form field. **kwargs (): Django's kwargs for a form field. Should contain a confirm_with keyword argument to point to the password field.
juraj-google-style
def add(self, term): if isinstance(term, Conjunction): for term_ in term.terms: self.add(term_) elif isinstance(term, Term): self._terms.append(term) else: raise TypeError('Not a Term or Conjunction')
Add a term to the conjunction. Args: term (:class:`Term`, :class:`Conjunction`): term to add; if a :class:`Conjunction`, all of its terms are added to the current conjunction. Raises: :class:`TypeError`: when *term* is an invalid type
codesearchnet
def set_domain_workgroup(workgroup): if six.PY2: workgroup = _to_unicode(workgroup) with salt.utils.winapi.Com(): conn = wmi.WMI() comp = conn.Win32_ComputerSystem()[0] res = comp.JoinDomainOrWorkgroup(Name=workgroup.upper()) return (True if (not res[0]) else False)
Set the domain or workgroup the computer belongs to. .. versionadded:: 2019.2.0 Returns: bool: ``True`` if successful, otherwise ``False`` CLI Example: .. code-block:: bash salt 'minion-id' system.set_domain_workgroup LOCAL
codesearchnet
def get_simulated_data(nmr_problems): nmr_observed_tanks = 10 nmr_tanks_ground_truth = normal(nmr_problems, 1, mean=250, std=30, ctype='uint') observations = uniform(nmr_problems, nmr_observed_tanks, low=0, high=nmr_tanks_ground_truth, ctype='uint') return observations, nmr_tanks_...
Simulate some data. This returns the simulated tank observations and the corresponding ground truth maximum number of tanks. Args: nmr_problems (int): the number of problems Returns: tuple: (observations, nmr_tanks_ground_truth)
juraj-google-style
def l2_distance_sq(t1, t2, name=None): with tf.name_scope(name, 'l2_distance_sq', [t1, t2]) as scope: t1 = tf.convert_to_tensor(t1, name='t1') t2 = tf.convert_to_tensor(t2, name='t2') return length_squared(tf.subtract(t1, t2), name=scope)
Square of l2 distance between t1 and t2. Args: t1: A tensor. t2: A tensor that is the same size as t1. name: Optional name for this op. Returns: The l2 distance between t1 and t2.
codesearchnet
def RunStateMethod(self, method_name, request=None, responses=None): if self.rdf_flow.pending_termination: self.Error(error_message=self.rdf_flow.pending_termination.reason) return client_id = self.rdf_flow.client_id deadline = self.rdf_flow.processing_deadline if deadline and rdfvalu...
Completes the request by calling the state method. Args: method_name: The name of the state method to call. request: A RequestState protobuf. responses: A list of FlowMessages responding to the request.
juraj-google-style
def _pick_or_create_inserted_op_moment_index( self, splitter_index: int, op: ops.Operation, strategy: InsertStrategy) -> int: if (strategy is InsertStrategy.NEW or strategy is InsertStrategy.NEW_THEN_INLINE): self._moments.insert(splitter_index, ops....
Determines and prepares where an insertion will occur. Args: splitter_index: The index to insert at. op: The operation that will be inserted. strategy: The insertion strategy. Returns: The index of the (possibly new) moment where the insertion should occur. Raises: ValueError: Unrecognized append strategy.
juraj-google-style
def CleanVacuousVersions(clients=None, dry_run=True): if (not clients): index = client_index.CreateClientIndex() clients = index.LookupClients(['.']) clients.sort() with data_store.DB.GetMutationPool() as pool: logging.info('checking %d clients', len(clients)) for batch in co...
A script to remove no-op client versions. This script removes versions of a client when it is identical to the previous, in the sense that no versioned attributes were changed since the previous client version. Args: clients: A list of ClientURN, if empty cleans all clients. dry_run: whether this is a dry run
codesearchnet
def _populate(cls, as_of=None, delete=False): billing_cycle_helper = get_billing_cycle() billing_cycles_exist = BillingCycle.objects.exists() try: current_billing_cycle = BillingCycle.objects.as_of(date=as_of) except BillingCycle.DoesNotExist: current_billing_cycle = None if (not bil...
Populate the table with billing cycles starting from `as_of` Args: as_of (date): The date at which to begin the populating delete (bool): Should future billing cycles be deleted?
codesearchnet
def from_string(cls, data, sigfigs=8): lines = data.split("\n")[:-1] struc_lines = {"HEADER": [], "VERS": [], "SYMGRP": [], "STRUC": [], "CLASS": [], "SITE": []} for line in lines: if line != "" and not line.isspace(): if not line[0].is...
Creates a CTRL file object from a string. This will mostly be used to read an LMTOCtrl object from a CTRL file. Empty spheres are ignored. Args: data: String representation of the CTRL file. Returns: An LMTOCtrl object.
juraj-google-style
def _call_post_with_user_override(self, sap_user_id, url, payload): SAPSuccessFactorsEnterpriseCustomerConfiguration = apps.get_model( 'sap_success_factors', 'SAPSuccessFactorsEnterpriseCustomerConfiguration' ) oauth_access_token, _ = SAPSuccessFactorsAPIClient...
Make a post request with an auth token acquired for a specific user to a SuccessFactors endpoint. Args: sap_user_id (str): The user to use to retrieve an auth token. url (str): The url to post to. payload (str): The json encoded payload to post.
juraj-google-style
def apply(self, flag_set: AbstractSet[Flag], operand: AbstractSet[Flag]) \ -> FrozenSet[Flag]: if self == FlagOp.ADD: return frozenset(flag_set | operand) elif self == FlagOp.DELETE: return frozenset(flag_set - operand) else: return froz...
Apply the flag operation on the two sets, returning the result. Args: flag_set: The flag set being operated on. operand: The flags to use as the operand.
juraj-google-style
def parse_time_indices(s): if not s.startswith('['): s = '[' + s + ']' parsed = command_parser._parse_slices(s) if len(parsed) != 1: raise ValueError( 'Invalid number of slicing objects in time indices (%d)' % len(parsed)) else: return parsed[0]
Parse a string as time indices. Args: s: A valid slicing string for time indices. E.g., '-1', '[:]', ':', '2:10' Returns: A slice object. Raises: ValueError: If `s` does not represent valid time indices.
juraj-google-style
def delete(table, keyset): delete = Mutation.Delete(table=table, key_set=keyset._to_pb()) return _Mutator(mutation=Mutation(delete=delete), rows=0, cells=0, operation=WriteMutation._OPERATION_DELETE, kwargs={'table': table, 'keyset': keyset})
Delete one or more table rows. Args: table: Name of the table to be modified. keyset: Keys/ranges identifying rows to delete.
github-repos
def build_global(self, global_node): config_block_lines = self.__build_config_block(global_node.config_block) return config.Global(config_block=config_block_lines)
parse `global` section, and return the config.Global Args: global_node (TreeNode): `global` section treenode Returns: config.Global: an object
codesearchnet
def _get_free_gpu(max_gpu_utilization=40, min_free_memory=0.5, num_gpu=1): def get_gpu_info(): gpu_info = subprocess.check_output(['nvidia-smi', '--format=csv,noheader,nounits', '--query-gpu=index,memory.total,memory.free,memory.used,utilization.gpu']).decode() gpu_info = gpu_info.split('\n') ...
Get available GPUs according to utilization thresholds. Args: :max_gpu_utilization: percent utilization threshold to consider a GPU "free" :min_free_memory: percent free memory to consider a GPU "free" :num_gpu: number of requested GPUs Returns: A tuple of (available_gpus, minimum_free_memory), where available_gpus i...
codesearchnet
def parent(self) -> 'KeyPath': if self.is_root: raise KeyError('Parent of a root KeyPath does not exist.') return KeyPath(self._keys[:-1])
The ``KeyPath`` object for current node's parent. Example:: path = pg.KeyPath.parse('a.b.c.') assert path.parent == 'a.b' Returns: A ``KeyPath`` object for the parent of current node. Raises: KeyError: If current path is the root.
github-repos
def _CopyDateFromString(self, date_string): date_string_length = len(date_string) if (date_string_length < 10): raise ValueError('Date string too short.') if ((date_string[4] != '-') or (date_string[7] != '-')): raise ValueError('Invalid date string.') try: year = int(date_string...
Copies a date from a string. Args: date_string (str): date value formatted as: YYYY-MM-DD Returns: tuple[int, int, int]: year, month, day of month. Raises: ValueError: if the date string is invalid or not supported.
codesearchnet
def deserialize_block(value): block = Block() block.ParseFromString(value) return BlockWrapper(block=block)
Deserialize a byte string into a BlockWrapper Args: value (bytes): the byte string to deserialze Returns: BlockWrapper: a block wrapper instance
codesearchnet
def OR(self): clone = copy.deepcopy(self) clone.adapter._QUERY_GLUE = ' OR ' return clone
Switches default query joiner from " AND " to " OR " Returns: Self. Queryset object.
codesearchnet
def build(self, spec, reset=True): if reset: self.reset() with self.model: self.mu = 0. for t in spec.terms.values(): data = t.data label = t.name dist_name = t.prior.name dist_args = t.prior...
Compile the PyMC3 model from an abstract model specification. Args: spec (Model): A bambi Model instance containing the abstract specification of the model to compile. reset (bool): if True (default), resets the PyMC3BackEnd instance before compiling.
juraj-google-style
def _get_num_multimodal_tokens(self, image_sizes=None, **kwargs): vision_data = {} if image_sizes is not None: num_image_tokens = [] for height, width in image_sizes: height, width = smart_resize(height, width, self.image_processor.spatial_factor, self.image_processor.min_pixels, sel...
Computes the number of placeholder tokens needed for multimodal inputs with the given sizes. Args: image_sizes (`List[List[int]]`, *optional*): The input sizes formatted as (height, width) per each image. Returns: `MultiModalData`: A `MultiModalData` object holding number of tokens per each of the provided input moda...
github-repos
def print_run_bidirectional_blast(reference, other_genome, dbtype, outdir): if dbtype == 'nucl': command = 'blastn' elif dbtype == 'prot': command = 'blastp' else: raise ValueError('dbtype must be "nucl" or "prot"') r_folder, r_name, r_ext = utils.split_folder_and_pat...
Write torque submission files for running bidirectional blast on a server and print execution command. Args: reference (str): Path to "reference" genome, aka your "base strain" other_genome (str): Path to other genome which will be BLASTed to the reference dbtype (str): "nucl" or "prot" - what format your genome files...
juraj-google-style
def write_reactions(self, stream, reactions, properties=None): self._write_entries( stream, reactions, self.convert_reaction_entry, properties)
Write iterable of reactions as YAML object to stream. Args: stream: File-like object. compounds: Iterable of reaction entries. properties: Set of reaction properties to output (or None to output all).
juraj-google-style
def Cleanse(obj, encoding='utf-8'): if isinstance(obj, int): return obj elif isinstance(obj, float): if (obj == _INFINITY): return 'Infinity' elif (obj == _NEGATIVE_INFINITY): return '-Infinity' elif math.isnan(obj): return 'NaN' else: ...
Makes Python object appropriate for JSON serialization. - Replaces instances of Infinity/-Infinity/NaN with strings. - Turns byte strings into unicode strings. - Turns sets into sorted lists. - Turns tuples into lists. Args: obj: Python data structure. encoding: Charset used to decode byte strings. Returns: Unicode ...
codesearchnet
def _ConsumeSingleByteString(self): text = self.token if ((len(text) < 1) or (text[0] not in _QUOTES)): raise self._ParseError(('Expected string but found: %r' % (text,))) if ((len(text) < 2) or (text[(- 1)] != text[0])): raise self._ParseError(('String missing ending quote: %r' % (text,))) ...
Consume one token of a string literal. String literals (whether bytes or text) can come in multiple adjacent tokens which are automatically concatenated, like in C or Python. This method only consumes one token. Returns: The token parsed. Raises: ParseError: When the wrong format data is found.
codesearchnet
def fulfill_transaction(transaction, *, private_keys): if not isinstance(private_keys, (list, tuple)): private_keys = [private_keys] if isinstance(private_keys, tuple): private_keys = list(private_keys) transaction_obj = Transaction.from_dict(transaction) try: si...
Fulfills the given transaction. Args: transaction (dict): The transaction to be fulfilled. private_keys (:obj:`str` | :obj:`list` | :obj:`tuple`): One or more private keys to be used for fulfilling the transaction. Returns: dict: The fulfilled transaction payload, ready to be sent to a BigchainDB federation. Raises:...
juraj-google-style
def _ExpandDirectories(filenames): expanded = set() for filename in filenames: if (not os.path.isdir(filename)): expanded.add(filename) continue for (root, _, files) in os.walk(filename): for loopfile in files: fullname = os.path.join(root, loo...
Searches a list of filenames and replaces directories in the list with all files descending from those directories. Files with extensions not in the valid extensions list are excluded. Args: filenames: A list of files or directories Returns: A list of all files that are members of filenames or descended from a direct...
codesearchnet
def raw_search(self, *args, **kwargs): limit = 50 try: limit = kwargs['limit'] except KeyError: pass self._mail.select("inbox") try: date = kwargs['date'] date_str = date.strftime("%d-%b-%Y") ...
Find the a set of emails matching each regular expression passed in against the (RFC822) content. Args: *args: list of regular expressions. Kwargs: limit (int) - Limit to how many of the most resent emails to search through. date (datetime) - If specified, it will filter avoid checking messages older than this date.
juraj-google-style
def __init__(self, value_type: typing.Optional[typing.Union[typing.Type[typing.Any], typing.Tuple[typing.Type[typing.Any], ...]]], default: typing.Any=MISSING_VALUE, transform: typing.Optional[typing.Callable[[typing.Any], typing.Any]]=None, is_noneable: bool=False, frozen: bool=False): super().__init__() self....
Constructor of ValueSpecBase. This class provides common facilities for implementing ValueSpec, including type check, default value assignment, noneable handling, missing value handling, and etc. Subclasses only need to handle value specific logics in `apply`, `extend`, and `is_compatible`. Args: value_type: Type or ...
github-repos
def Print(self, output_writer): if self._extensions: output_writer.Write('\textensions: {0:s}\n'.format( ', '.join(self._extensions)))
Prints a human readable version of the filter. Args: output_writer (CLIOutputWriter): output writer.
juraj-google-style
def compute_expand_dims_output_shape(input_shape, axis): input_shape = list(input_shape) if axis is None: axis = len(input_shape) axis = to_tuple_or_list(axis) out_ndim = len(axis) + len(input_shape) axis = [canonicalize_axis(a, out_ndim) for a in axis] shape_iter = iter(input_shape) ...
Compute the output shape for the `expand_dims` operation. Args: input_shape: Input shape. axis: int or sequence of ints for the axis to expand. Returns: Tuple of ints: The output shape after the `expand_dims` operation.
github-repos
def take_node_screenshot(self, element, screenshot_path): from PIL import Image temp_path = os.path.join(tempdir, screenshot_path) el_x = int(element.location['x']) el_y = int(element.location['y']) el_height = int(element.size['height']) el_width = int(element...
Take a screenshot of a node Args: element (object): the proxy_element screenshot_path (str): the path where the screenshot will be saved
juraj-google-style
def generated_tag_data(tags): generated_tags = [] for key, value in tags.items(): generated_tags.append({ 'Key': key, 'Value': value, }) return generated_tags
Convert :obj:`dict` to S3 Tag list. Args: tags (dict): Dictonary of tag key and tag value passed. Returns: list: List of dictionaries.
juraj-google-style
def __init__(self, port=None, queue_id=None): super().__init__(action_type=ActionType.OFPAT_ENQUEUE, length=16) self.port = port self.queue_id = queue_id
Create an ActionEnqueue with the optional parameters below. Args: port (physical port or :attr:`.Port.OFPP_IN_PORT`): Queue's port. queue_id (int): Where to enqueue the packets.
juraj-google-style
def get_data(name, train_batch_size, test_batch_size): if (name not in ['mnist', 'cifar10']): raise ValueError(("Expected dataset 'mnist' or 'cifar10', but got %s" % name)) dataset = getattr(tf.keras.datasets, name) num_classes = 10 raw_data = dataset.load_data() ((images_train, labels_train...
Gets training and testing dataset iterators. Args: name: String. Name of dataset, either 'mnist' or 'cifar10'. train_batch_size: Integer. Batch size for training. test_batch_size: Integer. Batch size for testing. Returns: Dict containing: train_iterator: A tf.data.Iterator, over training data. test_iterator: A tf.dat...
codesearchnet
def get_timestamp(self, url, xpath=None): if (not path.exists(self.db_path)): return None if (self._query(url, xpath).count() > 0): return self._query(url, xpath).one().queried_on
Get time stamp of cached query result. If DB has not yet been initialized or url/xpath has not been queried yet, return None. Args: url (str): If given, clear specific item only. Otherwise remove the DB file. xpath (str): xpath to search (may be ``None``) Returns: datetime.datetime: cached response timestamp, None i...
codesearchnet
def random_walk_uniform_fn(scale=1.0, name=None): def _fn(state_parts, seed): 'Adds a uniform perturbation to the input state.\n\n Args:\n state_parts: A list of `Tensor`s of any shape and real dtype representing\n the state parts of the `current_state` of the Markov chain.\n seed: `int...
Returns a callable that adds a random uniform perturbation to the input. For more details on `random_walk_uniform_fn`, see `random_walk_normal_fn`. `scale` might be a `Tensor` or a list of `Tensor`s that should broadcast with state parts of the `current_state`. The generated uniform perturbation is sampled as a unifor...
codesearchnet
def export_gpx_file(self): gpx = create_elem('gpx', GPX_ELEM_ATTRIB) if (not self.metadata.bounds): self.metadata.bounds = self[:] gpx.append(self.metadata.togpx()) for place in self: gpx.append(place.togpx()) return etree.ElementTree(gpx)
Generate GPX element tree from ``Waypoints`` object. Returns: etree.ElementTree: GPX element tree depicting ``Waypoints`` object
codesearchnet
def l2_regression_loss(y, target, name=None): with tf.name_scope(name, 'l2_regression', [y, target]) as scope: y = tf.convert_to_tensor(y, name='y') target = tf.convert_to_tensor(target, name='target') return tf.sqrt(l2_regression_sq_loss(y, target, name=scope))
Calculates the square root of the SSE between y and target. Args: y: the calculated values. target: the desired values. name: the name for this op, defaults to l2_regression Returns: A tensorflow op.
codesearchnet
def random_weights(n, bounds=(0., 1.), total=1.0): low = bounds[0] high = bounds[1] if high < low: raise ValueError('Higher bound must be greater or ' 'equal to lower bound') if n * high < total or n * low > total: raise ValueError('solution not possible w...
Generate pseudo-random weights. Returns a list of random weights that is of length n, where each weight is in the range bounds, and where the weights sum up to total. Useful for creating random portfolios when benchmarking. Args: * n (int): number of random weights * bounds ((low, high)): bounds for each weight * to...
juraj-google-style
def send_message(self): start = time.time() message = None if (not self.initialized): message = self.construct_start_message() self.initialized = True else: message = self.construct_end_message() self.send_UDP_message(message) end = time.time() return (end - start)
Send message over UDP. If tracking is disables, the bytes_sent will always be set to -1 Returns: (bytes_sent, time_taken)
codesearchnet
def debug_object(obj, log_level: int = logging.DEBUG) -> None: msgs = ["For {o!r}:".format(o=obj)] for attrname in dir(obj): attribute = getattr(obj, attrname) msgs.append("- {an!r}: {at!r}, of type {t!r}".format( an=attrname, at=attribute, t=type(attribute))) log.log(log_le...
Sends details about a Python to the log, specifically its ``repr()`` representation, and all of its attributes with their name, value, and type. Args: obj: object to debug log_level: log level to use; default is ``logging.DEBUG``
juraj-google-style
def accepts(self, tp, converter): tp = ParameterizedProperty._validate_type_param(tp) self.alternatives.append((tp, converter)) return self
Declare that other types may be converted to this property type. Args: tp (Property) : A type that may be converted automatically to this property type. converter (callable) : A function accepting ``value`` to perform conversion of the value to this property type. Returns: self
juraj-google-style
def add_curves_from_lasio(self, l, remap=None, funcs=None): params = {} for field, (sect, code) in LAS_FIELDS['data'].items(): params[field] = utils.lasio_get(l, sect, code, ...
Given a LAS file, add curves from it to the current well instance. Essentially just wraps ``add_curves_from_lasio()``. Args: fname (str): The path of the LAS file to read curves from. remap (dict): Optional. A dict of 'old': 'new' LAS field names. funcs (dict): Optional. A dict of 'las field': function() for implement...
juraj-google-style
def distances(self, word, words): point = self[word] vectors = np.asarray([self[w] for w in words]) diff = vectors - point distances = np.linalg.norm(diff, axis=1) return distances
Calculate eucledean pairwise distances between `word` and `words`. Args: word (string): single word. words (list): list of strings. Returns: numpy array of the distances. Note: L2 metric is used to calculate distances.
juraj-google-style
def get_cookie_header(queue_item): header = [] path = URLHelper.get_path(queue_item.request.url) for cookie in queue_item.request.cookies: root_path = ((cookie.path == '') or (cookie.path == '/')) if (path.startswith(cookie.path) or root_path): header.append(((cookie.name + '=') ...
Convert a requests cookie jar to a HTTP request cookie header value. Args: queue_item (:class:`nyawc.QueueItem`): The parent queue item of the new request. Returns: str: The HTTP cookie header value.
codesearchnet
def _render(self): message = Message() message.add(Heading(tr('Problem'), **ORANGE_LEVEL_4_STYLE)) message.add(Paragraph(tr( 'The following problem(s) were encountered whilst running the ' 'analysis.'))) items = BulletedList() for p in reversed(se...
Create a Message version of this ErrorMessage Args: none Returns: the Message instance of this ErrorMessage Raises: Errors are propagated
juraj-google-style
def set_inter_op_parallelism_threads(num_threads): context.context().inter_op_parallelism_threads = num_threads
Set number of threads used for parallelism between independent operations. Determines the number of threads used by independent non-blocking operations. 0 means the system picks an appropriate number. Args: num_threads: Number of parallel threads
github-repos
def create_timer(cb: Callable[[float], None], interval: float, delay_policy: TimerDelayPolicy = TimerDelayPolicy.DEFAULT, loop: Optional[asyncio.BaseEventLoop] = None) -> asyncio.Task: if not loop: loop = asyncio.get_event_loop() async def _timer(): fired_...
Schedule a timer with the given callable and the interval in seconds. The interval value is also passed to the callable. If the callable takes longer than the timer interval, all accumulated callable's tasks will be cancelled when the timer is cancelled. Args: cb: TODO - fill argument descriptions Returns: You can st...
juraj-google-style
def dbmin_mean(self, value=None): if (value is not None): try: value = float(value) except ValueError: raise ValueError('value {} need to be of type float for field `dbmin_mean`'.format(value)) self._dbmin_mean = value
Corresponds to IDD Field `dbmin_mean` Mean of extreme annual minimum dry-bulb temperature Args: value (float): value for IDD Field `dbmin_mean` Unit: C 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 gunzip_file(gz_path, new_path): if tf.gfile.Exists(new_path): tf.logging.info("File %s already exists, skipping unpacking" % new_path) return tf.logging.info("Unpacking %s to %s" % (gz_path, new_path)) mode = stat.S_IRWXU or stat.S_IXGRP or stat.S_IRGRP or stat.S_IROTH os.chmod(os.path.dirname...
Unzips from gz_path into new_path. Args: gz_path: path to the zipped file. new_path: path to where the file will be unzipped.
juraj-google-style
def script(experiment, projects): benchbuild_c = local[local.path(sys.argv[0])] slurm_script = local.cwd / experiment.name + "-" + str( CFG['slurm']['script']) srun = local["srun"] srun_args = [] if not CFG["slurm"]["multithread"]: srun_args.append("--hint=nomultithread") i...
Prepare a slurm script that executes the experiment for a given project. Args: experiment: The experiment we want to execute projects: All projects we generate an array job for.
juraj-google-style
def __init__(self, channel): self.ReadRows = channel.unary_stream( "/google.bigtable.v2.Bigtable/ReadRows", request_serializer=google_dot_cloud_dot_bigtable__v2_dot_proto_dot_bigtable__pb2.ReadRowsRequest.SerializeToString, response_deserializer=google_dot_cloud_dot_...
Constructor. Args: channel: A grpc.Channel.
juraj-google-style
def extend(*args): if (not args): return {} first = args[0] rest = args[1:] out = type(first)(first) for each in rest: out.update(each) return out
shallow dictionary merge Args: a: dict to extend b: dict to apply to a Returns: new instance of the same type as _a_, with _a_ and _b_ merged.
codesearchnet
def from_config(cls, config): config.pop('dtype', None) return cls(**config)
Instantiates an initializer from a configuration dictionary. Example: ```python initializer = RandomUniform(-1, 1) config = initializer.get_config() initializer = RandomUniform.from_config(config) ``` Args: config: A Python dictionary, the output of `get_config`. Returns: A `tf.keras.initializers.Initializer` insta...
github-repos
def opensearch(self, query, results=10, redirect=True): self._check_query(query, 'Query must be specified') query_params = {'action': 'opensearch', 'search': query, 'limit': (100 if (results > 100) else results), 'redirects': ('resolve' if redirect else 'return'), 'warningsaserror': True, 'namespace': ''} r...
Execute a MediaWiki opensearch request, similar to search box suggestions and conforming to the OpenSearch specification Args: query (str): Title to search for results (int): Number of pages within the radius to return redirect (bool): If **False** return the redirect itself, \ otherwise resolve redirects Returns: Lis...
codesearchnet
def has_same_sumformula(self, other): same_atoms = True for atom in set(self['atom']): own_atom_number = len(self[(self['atom'] == atom)]) other_atom_number = len(other[(other['atom'] == atom)]) same_atoms = (own_atom_number == other_atom_number) if (not same_atoms): ...
Determines if ``other`` has the same sumformula Args: other (molecule): Returns: bool:
codesearchnet
def get_oauth_data(self, code, client_id, client_secret, state): request = self._get_request() response = request.post(self.OAUTH_TOKEN_URL, { "state": state, "code": code, "grant_type": "authorization_code", "client_id": client_id, "c...
Get Oauth data from HelloSign Args: code (str): Code returned by HelloSign for our callback url client_id (str): Client id of the associated app client_secret (str): Secret token of the associated app Returns: A HSAccessTokenAuth object
juraj-google-style
def random_int_generator(maxrange): try: return random.randint(0,maxrange) except: line, filename, synerror = trace() raise ArcRestHelperError({ "function": "random_int_generator", "line": line, "filename": filename, ...
Generates a random integer from 0 to `maxrange`, inclusive. Args: maxrange (int): The upper range of integers to randomly choose. Returns: int: The randomly generated integer from :py:func:`random.randint`. Examples: >>> arcresthelper.common.random_int_generator(15) 9
juraj-google-style
def get_airport_metars_hist(self, iata): url = (AIRPORT_BASE.format(iata) + '/weather') return self._fr24.get_airport_metars_hist(url)
Retrieve the metar data for past 72 hours. The data will not be parsed to readable format. Given the IATA code of an airport, this method returns the metar information for last 72 hours. Args: iata (str): The IATA code for an airport, e.g. HYD Returns: The metar data for the airport Example:: from pyflightdata imp...
codesearchnet
def packVersion(major, minor=0, patch=0): ret = patch & mask20 ret = ret | (minor & mask20) << 20 ret = ret | (major & mask20) << 20 * 2 return ret
Pack a set of major/minor/patch integers into a single integer for storage. Args: major (int): Major version level integer. minor (int): Minor version level integer. patch (int): Patch version level integer. Returns: int: System normalized integer value to represent a software version.
juraj-google-style
def bin_hash160(string): intermed = hashlib.sha256(string).digest() return hashlib.new('ripemd160', intermed).hexdigest()
Get a hash of the provided message using the ripemd160 algorithm. Args: string (str): message to hash. Returns: str: hash as a double digit hex string.
juraj-google-style
def get_coords(variant): coordinates = { 'chrom': None, 'end_chrom': None, 'sv_length': None, 'sv_type': None, 'pos': None, 'end': None, } chrom = variant.CHROM if chrom.startswith(('chr', 'CHR', 'Chr')): chrom = chrom[3:] coordinates['chr...
Returns a dictionary with position information Args: variant(cyvcf2.Variant) Returns: coordinates(dict)
juraj-google-style
def get_instance(name, cls='system', storage=None, storage_parameters=None, unsecure=None, *args, **kwargs): system_parameters = _system_parameters(unsecure=unsecure, storage_parameters=storage_parameters) with _MOUNT_LOCK: for root in MOUNTED: if ((isinstance(root, Pattern) and root.match(n...
Get a cloud object storage instance. Args: name (str): File name, path or URL. cls (str): Type of class to instantiate. 'raw', 'buffered' or 'system'. storage (str): Storage name. storage_parameters (dict): Storage configuration parameters. Generally, client configuration and credentials. unsecure (bool): If True, dis...
codesearchnet
def run_program(self, src, filename, maximum_depth): self.filename = filename self._maximum_depth = maximum_depth src = preprocess.augment_annotations(src) src_tree = directors.parse_src(src, self.ctx.python_version) code = self.compile_src(src, filename=filename, store_blockgraph=True) director...
Run the code and return the CFG nodes. Args: src: The program source code. filename: The filename the source is from. maximum_depth: Maximum depth to follow call chains. Returns: A tuple (CFGNode, set) containing the last CFGNode of the program as well as all the top-level names defined by it.
github-repos
def asn(self, as_number, **kwargs): indicator_obj = ASN(as_number, **kwargs) return self._indicator(indicator_obj)
Add ASN data to Batch object. Args: as_number (str): The value for this Indicator. confidence (str, kwargs): The threat confidence for this Indicator. date_added (str, kwargs): The date timestamp the Indicator was created. last_modified (str, kwargs): The date timestamp the Indicator was last modified. rating (str, kw...
codesearchnet
def unpack(self, buff, item_class, offset=0): begin = offset limit_buff = len(buff) while begin < limit_buff: item = item_class() item.unpack(buff, begin) self.append(item) begin += item.get_size()
Unpack the elements of the list. Args: buff (bytes): The binary data to be unpacked. item_class (:obj:`type`): Class of the expected items on this list. offset (int): If we need to shift the beginning of the data.
juraj-google-style
def add_paths_argument(cls, group, argname, dest=None, help_=None): prefixed = '%s-%s' % (cls.argument_prefix, argname) if dest is None: dest = prefixed.replace('-', '_') final_dest = dest[len(cls.argument_prefix) + 1:] else: final_dest = dest ...
Subclasses may call this to expose a paths argument. Args: group: arparse.ArgumentGroup, the extension argument group argname: str, the name of the argument, will be namespaced. dest: str, similar to the `dest` argument of `argparse.ArgumentParser.add_argument`, will be namespaced. help_: str, similar to the `help` ar...
juraj-google-style
def inflate_nd_checker(identifier, definition): if isinstance(definition, bool): return Checker(name=identifier, passes=definition) elif isinstance(definition, dict): return Checker(definition.pop('name', identifier), **definition) else: raise ValueEr...
Inflate a no-data checker from a basic definition. Args: identifier (str): the no-data checker identifier / name. definition (bool/dict): a boolean acting as "passes" or a full dict definition with "passes" and "allow_failure". Returns: Checker: a checker instance. Raises: ValueError: when the definition type is not...
juraj-google-style
def write_json(data, path, file_name): if os.path.exists(path) and not os.path.isdir(path): return elif not os.path.exists(path): mkdir_p(path) with open(os.path.join(path, file_name), 'w') as f: json_tricks.dump(data, f, indent=4, primitives=True, allow_nan=True)
Write out data to a json file. Args: data: A dictionary representation of the data to write out path: The directory to output the file in file_name: The name of the file to write out
juraj-google-style
def __init__(self, metadata, registry): self.metadata = metadata self.fields = stats_utils.FieldDefinitionTuplesFromProtos( metadata.fields_defs) field_names = [name for name, _ in self.fields] if metadata.metric_type == rdf_stats.MetricMetadata.MetricType.COUNTER: sel...
Instantiates a new _Metric. Args: metadata: An rdf_stats.MetricMetadata instance describing this _Metric. registry: A prometheus_client.Registry instance. Raises: ValueError: metadata contains an unknown metric_type.
juraj-google-style
def convert_to_numpy(cls, x): return x
Convert a tensor to a NumPy array. Only called after slicing using `__getitem__`. Args: x: the tensor to convert. Returns: the converted tensor.
github-repos
def _add_write_pbs(self, write_pbs): if self._read_only: raise ValueError(_WRITE_READ_ONLY) super(Transaction, self)._add_write_pbs(write_pbs)
Add `Write`` protobufs to this transaction. Args: write_pbs (List[google.cloud.proto.firestore.v1beta1.\ write_pb2.Write]): A list of write protobufs to be added. Raises: ValueError: If this transaction is read-only.
juraj-google-style
def get_mapping_function(function_name, functions_mapping): if function_name in functions_mapping: return functions_mapping[function_name] elif function_name in ["parameterize", "P"]: from httprunner import loader return loader.load_csv_file elif function_name in ["environ", "...
get function from functions_mapping, if not found, then try to check if builtin function. Args: variable_name (str): variable name variables_mapping (dict): variables mapping Returns: mapping function object. Raises: exceptions.FunctionNotFound: function is neither defined in debugtalk.py nor builtin.
juraj-google-style
def setup_keyword(dist, _, value): if (value is not True): return dist.entry_points = _ensure_entry_points_is_dict(dist.entry_points) for (command, subcommands) in six.iteritems(_get_commands(dist)): entry_point = '{command} = rcli.dispatcher:main'.format(command=command) entry_point...
Add autodetected commands as entry points. Args: dist: The distutils Distribution object for the project being installed. _: The keyword used in the setup function. Unused. value: The value set to the keyword in the setup function. If the value is not True, this function will do nothing.
codesearchnet
def plot_pie(self, key='wall_time', minfract=0.05, **kwargs): timers = self.timers() n = len(timers) import matplotlib.pyplot as plt from matplotlib.gridspec import GridSpec fig = plt.gcf() gspec = GridSpec(n, 1) for (idx, timer) in enumerate(timers): ax = plt.subplot(gspec[(idx, 0)]...
Plot pie charts of the different timers. Args: key: Keyword used to extract data from timers. minfract: Don't show sections whose relative weight is less that minfract. Returns: `matplotlib` figure
codesearchnet
def _RemoveFromPool(self): with self.pool.lock: if (not self.pool.started): return False if (len(self.pool) <= self.pool.min_threads): return False self.pool._RemoveWorker(self.name) return True
Remove ourselves from the pool. Returns: True if removal was possible, and False if it was not possible.
codesearchnet
def partial_derivative_mu(mu, sigma, low, high, data): pd_mu = np.sum(data - mu) / sigma ** 2 pd_mu -= len(data) * ((norm.pdf(low, mu, sigma) - norm.pdf(high, mu, sigma)) / (norm.cdf(high, mu, sigma) - norm.cdf(low, mu, sigma))) return -pd_mu
The partial derivative with respect to the mean. Args: mu (float): the mean of the truncated normal sigma (float): the std of the truncated normal low (float): the lower truncation bound high (float): the upper truncation bound data (ndarray): the one dimension list of data points for which we want to calculate the li...
juraj-google-style
def _distance_graph(cls, inputs, clusters, distance_metric): assert isinstance(inputs, list) if distance_metric == SQUARED_EUCLIDEAN_DISTANCE: return cls._compute_euclidean_distance(inputs, clusters) elif distance_metric == COSINE_DISTANCE: return cls._compute_cosine_distance(inputs, cluster...
Computes distance between each input and each cluster center. Args: inputs: list of input Tensors. clusters: cluster Tensor. distance_metric: distance metric used for clustering Returns: list of Tensors, where each element corresponds to each element in inputs. The value is the distance of each row to all the cluster...
github-repos
def throw(self, exception_class, should_throw): return self.__copy_and_set('throws', (self._throws + [(exception_class, should_throw)]))
Defines if the an exception should be thrown after the request is sent Args: exception_class (class): The class of the exception to instantiate should_throw (function): The predicate that should indicate if the exception should be thrown. This function will be called with the response as a parameter Returns: The requ...
codesearchnet
def discount_bond_price(self, short_rate: types.RealTensor, times: types.RealTensor, maturities: types.RealTensor, name: str=None) -> types.RealTensor: name = name or self._name + '_discount_bond_prices' with tf.name_scope(name): short_rate = tf.convert_to_tensor(short_rate, self._dtype) times =...
Returns zero-coupon bond prices `P(t,T)` conditional on `r(t)`. Args: short_rate: A `Tensor` of real dtype and shape `batch_shape + [dim]` specifying the short rate `r(t)`. times: A `Tensor` of real dtype and shape `batch_shape`. The time `t` at which discount bond prices are computed. maturities: A `Tensor` of real d...
github-repos
def _add_variable_proxy_methods(var, proxy_tensor): proxy_tensor.read_value = (lambda : tf.identity(proxy_tensor)) proxy_tensor.assign_sub = var.assign_sub proxy_tensor.assign = var.assign proxy_tensor.initialized_value = var.initialized_value
Proxy methods of underlying variable. This enables our custom getters to still work with, e.g., batch norm. Args: var: Variable to proxy proxy_tensor: Tensor that is identity of var
codesearchnet
def DeserializeFrom(reader): ttype = reader.ReadByte() tx = None from neo.Core.TX.RegisterTransaction import RegisterTransaction from neo.Core.TX.IssueTransaction import IssueTransaction from neo.Core.TX.ClaimTransaction import ClaimTransaction from neo.Core.TX....
Deserialize full object. Args: reader (neo.IO.BinaryReader): Returns: Transaction:
juraj-google-style