code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def convert_drive(self, shift, instruction): command_dict = { 'name': instruction.command.name, 't0': shift+instruction.start_time, 'ch': instruction.channels[0].name } return self._qobj_model(**command_dict)
Return converted `PulseInstruction`. Args: shift(int): Offset time. instruction (PulseInstruction): drive instruction. Returns: dict: Dictionary of required parameters.
juraj-google-style
def ApplyParsersToResponses(parser_factory, responses, flow_obj): knowledge_base = flow_obj.state.knowledge_base parsed_responses = [] if parser_factory.HasSingleResponseParsers(): for response in responses: for parser in parser_factory.SingleResponseParsers(): parsed_res...
Parse responses with applicable parsers. Args: parser_factory: A parser factory for specific artifact. responses: A list of responses from the client. flow_obj: An artifact collection flow. Returns: A list of (possibly parsed) responses.
codesearchnet
def get_route_lines_route(self, **kwargs): select_date = ('%02d/%02d/%d' % (kwargs.get('day', '01'), kwargs.get('month', '01'), kwargs.get('year', '1970'))) params = {'SelectDate': select_date, 'Lines': util.ints_to_string(kwargs.get('lines', []))} result = self.make_request('geo', 'get_route_lines_route', ...
Obtain itinerary for one or more lines in the given date. Args: day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only has one digit. year (int): Year number in format YYYY. lines (list...
codesearchnet
def generate(self): result = self._gen(self.optimized, self.splitstring) if self.splitstring and result is not None: result = result[1:] return result
Generates a new random string from the start symbol Args: None Returns: str: The generated string
juraj-google-style
def match(self, url): try: urlSchemes = self._urlSchemes.itervalues() except AttributeError: urlSchemes = self._urlSchemes.values() for urlScheme in urlSchemes: if urlScheme.match(url): return True return False
Try to find if url matches against any of the schemes within this endpoint. Args: url: The url to match against each scheme Returns: True if a matching scheme was found for the url, False otherwise
codesearchnet
def parse_vep_header(vcf_obj): vep_header = [] if 'CSQ' in vcf_obj: csq_info = vcf_obj['CSQ'] format_info = parse_header_format(csq_info['Description']) vep_header = [key.upper() for key in format_info.split('|')] return vep_header
Return a list with the VEP header The vep header is collected from CSQ in the vcf file All keys are capitalized Args: vcf_obj(cyvcf2.VCF) Returns: vep_header(list)
juraj-google-style
def plot_grid(step): rad = get_rprof(step, 'r')[0] drad = get_rprof(step, 'dr')[0] (_, unit) = step.sdat.scale(1, 'm') if unit: unit = ' ({})'.format(unit) (fig, (ax1, ax2)) = plt.subplots(2, sharex=True) ax1.plot(rad, '-ko') ax1.set_ylabel(('$r$' + unit)) ax2.plot(drad, '-ko') ...
Plot cell position and thickness. The figure is call grid_N.pdf where N is replace by the step index. Args: step (:class:`~stagpy.stagyydata._Step`): a step of a StagyyData instance.
codesearchnet
def to_polars(evset: EventSet, tp_string_to_pl_string: bool=True, timestamp_to_datetime: bool=True, timestamps: bool=True) -> 'pl.DataFrame': pl = import_pl() timestamp_key = 'timestamp' index_names = evset.schema.index_names() feature_names = evset.schema.feature_names() column_names = index_names ...
Converts an [`EventSet`][temporian.EventSet] to a Polars DataFrame. Usage example: ```python >>> from datetime import datetime >>> evset = tp.event_set( ... timestamps=[datetime(2015, 1, 1), datetime(2015, 1, 2)], ... features={ ... "feature_1": [0.5, 0.6], ... "my_index": ["red", "yellow"], ...
github-repos
def adversary(self, name, **kwargs): group_obj = Adversary(name, **kwargs) return self._group(group_obj)
Add Adversary data to Batch object. Args: name (str): The name for this Group. date_added (str, kwargs): The date timestamp the Indicator was created. xid (str, kwargs): The external id for this Group. Returns: obj: An instance of Adversary.
juraj-google-style
def get_data_location(self, catalog_id): try: record = self.get(catalog_id) except: return None if (('Landsat8' in record['type']) and ('LandsatAcquisition' in record['type'])): bucket = record['properties']['bucketName'] prefix = record['properties']['bucketPrefix'] ...
Find and return the S3 data location given a catalog_id. Args: catalog_id: The catalog ID Returns: A string containing the s3 location of the data associated with a catalog ID. Returns None if the catalog ID is not found, or if there is no data yet associated with it.
codesearchnet
def add_update_resources(self, resources, ignore_datasetid=False): if not isinstance(resources, list): raise HDXError('Resources should be a list!') for resource in resources: self.add_update_resource(resource, ignore_datasetid)
Add new or update existing resources with new metadata to the dataset Args: resources (List[Union[hdx.data.resource.Resource,Dict,str]]): A list of either resource ids or resources metadata from either Resource objects or dictionaries ignore_datasetid (bool): Whether to ignore dataset id in the resource. Defaults to F...
juraj-google-style
def one_or_more(e, delimiter=None): if delimiter is None: delimiter = lambda s, grm, pos: (s, Ignore, (pos, pos)) msg = 'Expected one or more of: {}'.format(repr(e)) def match_one_or_more(s, grm=None, pos=0): start = pos s, obj, span = e(s, grm, pos) pos = span[1] ...
Create a PEG function to match one or more expressions. Args: e: the expression to match delimiter: an optional expression to match between the primary *e* matches.
juraj-google-style
def _evaluateTFLiteModel(self, tflite_model, input_data, input_shapes=None): interpreter = Interpreter(model_content=tflite_model) input_details = interpreter.get_input_details() if input_shapes: for idx, (shape_signature, final_shape) in enumerate(input_shapes): self.assertTrue((input_d...
Evaluates the model on the `input_data`. Args: tflite_model: TensorFlow Lite model. input_data: List of EagerTensor const ops containing the input data for each input tensor. input_shapes: List of tuples representing the `shape_signature` and the new shape of each input tensor that has unknown dimensions. Returns: [n...
github-repos
def add_imported_namespace(self, namespace, imported_alias=False, imported_data_type=False, imported_annotation=False, imported_annotation_type=False): assert (self.name != namespace.name), 'Namespace cannot import itself.' reason = self._imported_namespaces.setdefault(namespace, _ImportReason()) if importe...
Keeps track of namespaces that this namespace imports. Args: namespace (Namespace): The imported namespace. imported_alias (bool): Set if this namespace references an alias in the imported namespace. imported_data_type (bool): Set if this namespace references a data type in the imported namespace. imported_annotation ...
codesearchnet
def match_tracks(self, model_tracks, obs_tracks, unique_matches=True, closest_matches=False): if unique_matches: pairings = self.track_matcher.match_tracks(model_tracks, obs_tracks, closest_matches=closest_matches) else: pairings = self.track_matcher.neighbor_matches(model_tracks, obs_tracks) ...
Match forecast and observed tracks. Args: model_tracks: obs_tracks: unique_matches: closest_matches: Returns:
codesearchnet
def run_shell_cmd(args): proc = subprocess.Popen(args, shell=True, stdout=subprocess.PIPE, stderr=subprocess.STDOUT) return proc.communicate()
Executes shell commands and returns output. Args: args: String of shell commands to run. Returns: Tuple output (stdoutdata, stderrdata) from running the shell commands.
github-repos
def merge(self, status: 'Status[Input, Output]') -> 'Status[Input, Output]': if ((status is None) or (status.farthest is None)): pass elif (self.farthest is None): self.farthest = status.farthest self.expected = status.expected elif (status.farthest.position < self.farthest.position)...
Merge the failure message from another status into this one. Whichever status represents parsing that has gone the farthest is retained. If both statuses have gone the same distance, then the expected values from both are retained. Args: status: The status to merge into this one. Returns: This ``Status`` which may h...
codesearchnet
def _get_mpr_table(self, connection, partition): virtual_table = partition.vid table = '{}_v'.format(virtual_table) logger.debug('Looking for materialized table of the partition.\n partition: {}'.format(partition.name)) table_exists = self._relation_exists(connection, table) if table_exists: ...
Returns name of the sqlite table who stores mpr data. Args: connection (apsw.Connection): connection to sqlite database who stores mpr data. partition (orm.Partition): Returns: str: Raises: MissingTableError: if partition table not found in the db.
codesearchnet
def MakeType(name, base_classes, namespace): precondition.AssertType(name, str) if PY2: name = name.encode('ascii') return type(name, base_classes, namespace)
A compatibility wrapper for the `type` built-in function. In Python 2 `type` (used as a type constructor) requires the name argument to be a `bytes` object whereas in Python 3 it is required to be an `unicode` object. Since class name is human readable text rather than arbitrary stream of bytes, the Python 3 behaviour...
codesearchnet
def SetParseFn(fn, *arguments): def _Decorator(func): parse_fns = GetParseFns(func) if not arguments: parse_fns['default'] = fn else: for argument in arguments: parse_fns['named'][argument] = fn _SetMetadata(func, FIRE_PARSE_FNS, parse_fns) ...
Sets the fn for Fire to use to parse args when calling the decorated fn. Args: fn: The function to be used for parsing arguments. *arguments: The arguments for which to use the parse fn. If none are listed, then this will set the default parse function. Returns: The decorated function, which now has metadata telling F...
github-repos
def __init__(self, org=None, library=None, branch=None, version_guid=None, **kwargs): if 'offering' in kwargs: raise ValueError("'offering' is not a valid field for a LibraryLocator.") if 'course' in kwargs: if library is not None: raise ValueError("Cann...
Construct a LibraryLocator Args: version_guid (string or ObjectId): optional unique id for the version org, library: the standard definition. Optional only if version_guid given. branch (string): the optional branch such as 'draft', 'published', 'staged', 'beta'
juraj-google-style
def flatten(vari): if isinstance(vari, Poly): shape = int(numpy.prod(vari.shape)) return reshape(vari, (shape,)) return numpy.array(vari).flatten()
Flatten a shapeable quantity. Args: vari (chaospy.poly.base.Poly, numpy.ndarray): Shapeable input quantity. Returns: (chaospy.poly.base.Poly, numpy.ndarray): Same type as ``vari`` with `len(Q.shape)==1`. Examples: >>> P = chaospy.reshape(chaospy.prange(4), (2,2)) >>> print(P) [[1, q0], [q0^2, q0^3]] >>> print(chaosp...
codesearchnet
def play_match(black_model, white_model, games, sgf_dir): with utils.logged_timer('Loading weights'): black_net = dual_net.DualNetwork(black_model) white_net = dual_net.DualNetwork(white_model) readouts = FLAGS.num_readouts black = MCTSPlayer(black_net, two_player_mode=True) white = MCTS...
Plays matches between two neural nets. Args: black_model: Path to the model for black player white_model: Path to the model for white player
codesearchnet
def guess_leb_size(path): f = open(path, 'rb') f.seek(0, 2) file_size = (f.tell() + 1) f.seek(0) block_size = None for _ in range(0, file_size, FILE_CHUNK_SZ): buf = f.read(FILE_CHUNK_SZ) for m in re.finditer(UBIFS_NODE_MAGIC, buf): start = m.start() chdr ...
Get LEB size from superblock Arguments: Str:path -- Path to file. Returns: Int -- LEB size. Searches file for superblock and retrieves leb size.
codesearchnet
def on_deleted(self, event): if (not self._event_error): self.logger.info(u'Change detected from deletion of: %s', event.src_path) self.compile_dependencies(event.src_path, include_self=False)
Called when a file or directory is deleted. Todo: May be bugged with inspector and sass compiler since the does not exists anymore. Args: event: Watchdog event, ``watchdog.events.DirDeletedEvent`` or ``watchdog.events.FileDeletedEvent``.
codesearchnet
def _check_approval_wrapper(self, grr_object, grr_function, *args, **kwargs): approval_sent = False while True: try: return grr_function(*args, **kwargs) except grr_errors.AccessForbiddenError as exception: print('No valid approval found: {0!s}'.format(exception)) ...
Wraps a call to GRR functions checking for approval. Args: grr_object: the GRR object to create the eventual approval on. grr_function: The GRR function requiring approval. *args: Positional arguments that are to be passed to `grr_function`. **kwargs: Keyword arguments that are to be passed to `grr_function`. Returns...
juraj-google-style
def load(self, languages=[]): duckling_load = self.clojure.var('duckling.core', 'load!') clojure_hashmap = self.clojure.var('clojure.core', 'hash-map') clojure_list = self.clojure.var('clojure.core', 'list') if languages: iso_languages = [Language.convert_to_iso(lang) for lang in languages] ...
Loads the Duckling corpus. Languages can be specified, defaults to all. Args: languages: Optional parameter to specify languages, e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"])
codesearchnet
def _delete_from_hdx(self, object_type, id_field_name): if id_field_name not in self.data: raise HDXError('No %s field (mandatory) in %s!' % (id_field_name, object_type)) self._save_to_hdx('delete', id_field_name)
Helper method to deletes a resource from HDX Args: object_type (str): Description of HDX object type (for messages) id_field_name (str): Name of field containing HDX object identifier Returns: None
juraj-google-style
def decorate(self, record): color = 'gray' if (record.levelno == logging.WARNING): color = 'yellow' if (record.levelno == logging.INFO): color = 'green' if (record.levelno == logging.DEBUG): color = 'gray' if (record.levelno >= logging.ERROR): color = 'red' notify...
Build up HipChat specific values for log record Args: record (:obj:`logging.record`): log message object Returns: dict: params for POST request
codesearchnet
def get_compatible_generator_action(self, filename): for action in self.__generator_actions: if action.act_on_file(filename): return action return None
Return the **first** compatible :class:`GeneratorAction` for a given filename or ``None`` if none is found. Args: filename (str): The filename of the template to process.
juraj-google-style
def set_column_sizes(self, values): self.style['grid-template-columns'] = ' '.join(map(lambda value: (str(value) if str(value).endswith('%') else str(value) + '%') , values))
Sets the size value for each column Args: values (iterable of int or str): values are treated as percentage.
juraj-google-style
def __init__(self, scopes, service_account_id=None, token_maker=None, retry_params=None): if isinstance(scopes, basestring): scopes = [scopes] self.scopes = scopes self.service_account_id = service_account_id self.make_token_async = token_maker or _config.TOKEN_MAKER if no...
Constructor. Args: scopes: A scope or a list of scopes. service_account_id: Internal use only. token_maker: An asynchronous function of the form (scopes, service_account_id) -> (token, expires). retry_params: An instance of api_utils.RetryParams. If None, the default for current thread will be used.
juraj-google-style
def get_key(key, data_structure): if key == '/': return data_structure path = key.split('/') path[0] or path.pop(0) current_value = data_structure while path: current_key = path.pop(0) try: current_key = int(c...
Helper method for extracting values from a nested data structure. Args: key (str): The path to the vales (a series of keys and indexes separated by '/') data_structure (dict or list): The data structure from which the value will be extracted. Returns: str: The values associated with key
juraj-google-style
def from_join(cls, join: Join) -> 'ConditionalJoin': return cls( join.table_name, join.parent_alias, join.table_alias, join.join_type, join.join_field, join.nullable )
Creates a new :see:ConditionalJoin from the specified :see:Join object. Arguments: join: The :see:Join object to create the :see:ConditionalJoin object from. Returns: A :see:ConditionalJoin object created from the :see:Join object.
juraj-google-style
def set_all_pattern_variables(self, patternnumber, sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, actual_step, additional_cycles, link_pattern): _checkPatternNumber(patternnumber) self.set_pattern_step_setpoint(patternnumber, 0, sp0) self.set_pattern_step_setpoint(patternnum...
Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? * link_pattern(int): ?
codesearchnet
def inner_text(node): from lxml import etree parts = [node.text] for child in node.getchildren(): parts.append(etree.tostring(child, encoding='utf-8', method='text')) parts.append(child.tail) return ''.join(map(decode_bytes, filter(None, parts)))
Returns the inner text of a given XML node, excluding tags. Args: node: (lxml.etree.Element): The node whose inner text is desired. Returns: str: The inner text of the node.
codesearchnet
def fts_contrast2(self, fs, ft_name, inv): inv_fts = [self.fts(x) for x in inv if (set(fs) <= self.fts(x))] for a in inv_fts: for b in inv_fts: if (a != b): diff = (a ^ b) if (len(diff) == 2): if all([(nm == ft_name) for (_, nm) in diff]): ...
Return `True` if there is a segment in `inv` that contrasts in feature `ft_name`. Args: fs (list): feature specifications used to filter `inv`. ft_name (str): name of the feature where contrast must be present. inv (list): collection of segments represented as Unicode segments. Returns: bool: `True` if two segments i...
codesearchnet
def on_test_begin(self, logs=None):
Called at the beginning of evaluation or validation. Subclasses should override for any actions to run. Args: logs: Dict. Currently no data is passed to this argument for this method but that may change in the future.
github-repos
def set_sig_figs(n=4): u.default_format = (('.' + str(n)) + 'g') pd.options.display.float_format = (('{:,.' + str(n)) + '}').format
Set the number of significant figures used to print Pint, Pandas, and NumPy quantities. Args: n (int): Number of significant figures to display.
codesearchnet
def derive_annotations(self, annotations): cls = type(self) return cls(self[0], self[1], self[2], self[3], annotations, self[5])
Derives a new event from this one setting the ``annotations`` attribute. Args: annotations: (Sequence[Union[amazon.ion.symbols.SymbolToken, unicode]]): The annotations associated with the derived event. Returns: IonEvent: The newly generated event.
codesearchnet
def _ProduceContent(self, mods, showprivate=False, showinh=False): result = '' nestedresult = '' for mod in mods: try: all = mod[1].__all__ except AttributeError: raise RuntimeError(('Module (%s) MUST have `__all__` defined.' % mod[1].__name__)) if ((not showp...
An internal helper to create pages for several modules that do not have nested modules. This will automatically generate the needed RSF to document each module module and save the module to its own page appropriately. Args: mods (module): The modules to document that do not contain nested modules showprivate (bool): A...
codesearchnet
def _freeze_keras_model(self, output_dir): try: self._keras_model.save(output_dir, save_format='tf') except Exception: return None tag_set = set([_tag_constants.SERVING]) signature_key = _signature_constants.DEFAULT_SERVING_SIGNATURE_DEF_KEY graph_def, input_tensors, output_tensors, ...
Save Keras model to Saved Model format. Args: output_dir: The output directory to save the SavedModel.
github-repos
def build(self, client, nobuild=False, usecache=True, pull=False): if (not nobuild): self.update_source_images(client, usecache=usecache, pull=pull) width = utils.get_console_width() cprint(('\n' + ('=' * width)), color='white', attrs=['bold']) line = ('STARTING BUILD for "%s" (image definition ...
Drives the build of the final image - get the list of steps and execute them. Args: client (docker.Client): docker client object that will build the image nobuild (bool): just create dockerfiles, don't actually build the image usecache (bool): use docker cache, or rebuild everything from scratch? pull (bool): try to p...
codesearchnet
def stop(self, wait=True): assert (not self._stopped), 'Already stopped' self._stopped = True self._tornado.stop(wait) self._http.stop()
Stop the Bokeh Server. This stops and removes all Bokeh Server ``IOLoop`` callbacks, as well as stops the ``HTTPServer`` that this instance was configured with. Args: fast (bool): Whether to wait for orderly cleanup (default: True) Returns: None
codesearchnet
def _CompositeMapByteStream( self, byte_stream, byte_offset=0, context=None, **unused_kwargs): elements_data_size = None elements_terminator = None number_of_elements = None if self._HasElementsDataSize(): elements_data_size = self._EvaluateElementsDataSize(context) element_byte...
Maps a sequence of composite data types on a byte stream. Args: byte_stream (bytes): byte stream. byte_offset (Optional[int]): offset into the byte stream where to start. context (Optional[DataTypeMapContext]): data type map context. Returns: tuple[object, ...]: mapped values. Raises: ByteStreamTooSmallError: if the...
juraj-google-style
def with_rank_at_least(x, rank): return type(x)(tf.TensorShape(x).with_rank_at_least(rank))
Returns a shape based on `x` with at least the given `rank`. For more details, see `help(tf.TensorShape.with_rank_at_least)`. Args: x: object representing a shape; convertible to `tf.TensorShape`. rank: An `int` representing the minimum rank of `x` or else an assertion is raised. Returns: shape: a shape having `type...
codesearchnet
def _GetISO8601String(self, structure): time_zone_offset = structure.time_zone_offset try: time_zone_offset_hours = int(time_zone_offset[1:3], 10) time_zone_offset_minutes = int(time_zone_offset[3:5], 10) except (IndexError, TypeError, ValueError) as exception: raise ValueError( ...
Retrieves an ISO 8601 date time string from the structure. The date and time values in Google Drive Sync log files are formatted as: "2018-01-24 18:25:08,454 -0800". Args: structure (pyparsing.ParseResults): structure of tokens derived from a line of a text file. Returns: str: ISO 8601 date time string. Raises: Val...
juraj-google-style
def __init__(self, mackup, files, dry_run, verbose): assert isinstance(mackup, Mackup) assert isinstance(files, set) self.mackup = mackup self.files = list(files) self.dry_run = dry_run self.verbose = verbose
Create an ApplicationProfile instance. Args: mackup (Mackup) files (list)
juraj-google-style
def _add_impact_severity(self, variant_obj): if variant_obj.most_severe_consequence: variant_obj.impact_severity = IMPACT_SEVERITIES.get( variant_obj.most_severe_consequence )
Add the impact severity for the most severe consequence Args: variant_obj (puzzle.models.Variant)
juraj-google-style
def _do_revoke(self, http, token): logger.info('Revoking token') query_params = {'token': token} token_revoke_uri = _helpers.update_query_params( self.revoke_uri, query_params) resp, content = transport.request(http, token_revoke_uri) if resp.status == http_c...
Revokes this credential and deletes the stored copy (if it exists). Args: http: an object to be used to make HTTP requests. token: A string used as the token to be revoked. Can be either an access_token or refresh_token. Raises: TokenRevokeError: If the revoke request does not return with a 200 OK.
juraj-google-style
def __init__(self, address, ap): super(ReadRequest, self).__init__(address=address, ap=ap)
Initializes the base class. Args: self (ReadRequest): the ``ReadRequest`` instance address (int): the register index ap (bool): ``True`` if this request is to an Access Port Access Register, otherwise ``False`` for a Debug Port Access Register Returns: ``None``
juraj-google-style
def CreateAdGroup(client, campaign_id): ad_group_service = client.GetService('AdGroupService', 'v201809') ad_group = { 'name': 'Dynamic remarketing ad group', 'campaignId': campaign_id, 'status': 'ENABLED' } operations = [{ 'operator': 'ADD', 'operand': ad_group }] return...
Creates a dynamic remarketing campaign. Args: client: an AdWordsClient instance. campaign_id: an int campaign ID. Returns: The ad group that was successfully created.
juraj-google-style
def init_app(self, app, client_id=None): if (not self.client_id): if client_id: self.client_id = client_id else: self.client_id = app.name
Initialize the Micropub extension if it was not given app in the constructor. Args: app (flask.Flask): the flask application to extend. client_id (string, optional): the IndieAuth client id, will be displayed when the user is asked to authorize this client. If not provided, the app name will be used.
codesearchnet
def Append(self, value=None, **kwarg): if self.rdf_type is not None: if (isinstance(value, rdfvalue.RDFValue) and value.__class__ != self.rdf_type): raise ValueError("Can only accept %s" % self.rdf_type) try: value = self.rdf_type(value, **kwarg) except (...
Add another member to the array. Args: value: The new data to append to the array. **kwarg: Create a new element from these keywords. Returns: The value which was added. This can be modified further by the caller and changes will be propagated here. Raises: ValueError: If the value to add is not allowed.
juraj-google-style
def load(self, data_dir): K.set_learning_phase(0) try: latest_ckpt = max(glob.iglob( os.path.join(data_dir, '*.h*5')), key=os.path.getctime) latest_ckpt_name = os.path.basename(latest_ckpt) latest_ckpt_time = str( ...
Load graph and weight data. Args: data_dir (:obj:`str`): location of Keras checkpoint (`.hdf5`) files and model (in `.json`) structure. The default behavior is to take the latest of each, by OS timestamp.
juraj-google-style
def close(self): if not self.closed: self._uploader.finish() super().close()
Complete the upload and close this stream. This method has no effect if the stream is already closed. Raises: Any error encountered by the uploader.
github-repos
def _get_args(cls, args): if isinstance(args, tuple): raise TypeError( "{}[...] takes exactly one argument.".format(cls.__name__) ) return super(_StringMeta, cls)._get_args((_STR_TYPE, args))
Return the parameters necessary to check type boundaries. Args: args: A slice representing the minimum and maximum lengths allowed for values of that string. Returns: A tuple with three parameters: a type, a slice, and the len function.
juraj-google-style
def save_archive(archive): _assert_obj_type(archive, obj_type=DBArchive) _get_handler().store_object(archive) return archive.to_comm(light_request=True)
Save `archive` into database and into proper indexes. Attr: archive (obj): Instance of the :class:`.DBArchive`. Returns: obj: :class:`.DBArchive` without data. Raises: InvalidType: When the `archive` is not instance of :class:`.DBArchive`. UnindexablePublication: When there is no index (property) which can be used t...
codesearchnet
def get_num_patches(self, image_height: int, image_width: int, patch_size: Optional[Dict[str, int]]=None) -> int: patch_size = patch_size if patch_size is not None else self.patch_size patch_height, patch_width = (self.patch_size['height'], self.patch_size['width']) if image_height % patch_height != 0: ...
Calculate number of patches required to encode an image. Args: image_height (`int`): Height of the image. image_width (`int`): Width of the image. patch_size (`Dict[str, int]`, *optional*, defaults to `self.patch_size`): Dictionary in the format `{"height": int, "width": int}` specifying the size of the patches.
github-repos
def _CreateStyleFromConfigParser(config): section = 'yapf' if config.has_section('yapf') else 'style' if config.has_option('style', 'based_on_style'): based_on = config.get('style', 'based_on_style').lower() base_style = _STYLE_NAME_TO_FACTORY[based_on]() elif config.has_option('yapf', 'base...
Create a style dict from a configuration file. Arguments: config: a ConfigParser object. Returns: A style dict. Raises: StyleConfigError: if an unknown style option was encountered.
github-repos
def create_board(self, board_json): return trolly.board.Board(trello_client=self, board_id=board_json['id'], name=board_json['name'], data=board_json)
Create Board object from a JSON object Returns: Board: The board from the given `board_json`.
codesearchnet
def _html_tree_view_content(self, *, view: 'HtmlTreeView', name: Optional[str]=None, parent: Any=None, root_path: Optional[KeyPath]=None, **kwargs) -> Html: return view.content(self, name=name, parent=parent, root_path=root_path, **kwargs)
Returns the main content for the object. Args: view: The view to render the object. name: The name of the object. parent: The parent of the object. root_path: The key path of the object relative to the root. **kwargs: kwargs to pass to the view. See `_html_tree_view_config` for the builtin arguments. Returns: The ren...
github-repos
def ensure_valid_input(model, tokens, input_names): print('Ensuring inputs are in correct order') model_args_name = model.forward.__code__.co_varnames model_args, ordered_input_names = ([], []) for arg_name in model_args_name[1:]: if arg_name in input_names: ordered_input_names.appen...
Ensure inputs are presented in the correct order, without any Non Args: model: The model used to forward the input data tokens: BatchEncoding holding the input data input_names: The name of the inputs Returns: Tuple
github-repos
def _get_kernel_arguments(self): declarations = [] for (name, data) in self._kernel_data.items(): declarations.extend(data.get_kernel_parameters(('_' + name))) return declarations
Get the list of kernel arguments for loading the kernel data elements into the kernel. This will use the sorted keys for looping through the kernel input items. Returns: list of str: the list of parameter definitions
codesearchnet
def Open(self, file_object): file_object.seek(0, os.SEEK_SET) signature_data = file_object.read(6) self.file_format = None if len(signature_data) > 2: if signature_data[:2] == self._CPIO_SIGNATURE_BINARY_BIG_ENDIAN: self.file_format = 'bin-big-endian' elif signature_data[:2] ==...
Opens the CPIO archive file. Args: file_object (FileIO): a file-like object. Raises: IOError: if the file format signature is not supported. OSError: if the file format signature is not supported.
juraj-google-style
def _GetUserTypeAndPassword(username, password=None, is_admin=False): if is_admin: user_type = api_user.ApiGrrUser.UserType.USER_TYPE_ADMIN else: user_type = api_user.ApiGrrUser.UserType.USER_TYPE_STANDARD if (password is None): password = getpass.getpass(prompt=("Please enter passwo...
Returns the user-type and password for a user. Args: username: Username for the user. password: Password for the user. If None, or not provided, we will prompt for one via the terminal. is_admin: Indicates whether the user should have admin privileges.
codesearchnet
def _get_cuda_compute_capabilities_or_die() -> list[str]: try: nvidia_smi = _find_executable_or_die('nvidia-smi') nvidia_smi_proc = subprocess.run([nvidia_smi, '--query-gpu=compute_cap', '--format=csv,noheader'], capture_output=True, check=True, text=True) capabilities = sorted(set(nvidia_sm...
Finds compute capabilities via nvidia-smi or rasies exception. Returns: list of unique, sorted strings representing compute capabilities: Raises: RuntimeError: if path to nvidia-smi couldn't be found. subprocess.CalledProcessError: if nvidia-smi process failed.
github-repos
def relative_probability_from_lookup_table(self, jump_lookup_table): l1 = self.initial_site.label l2 = self.final_site.label c1 = self.initial_site.nn_occupation() c2 = self.final_site.nn_occupation() return jump_lookup_table.jump_probability[l1][l2][c1][c2]
Relative probability of accepting this jump from a lookup-table. Args: jump_lookup_table (LookupTable): the lookup table to be used for this jump. Returns: (Float): relative probability of accepting this jump.
codesearchnet
def copy_file(source, destination, unique=False, sort=False, case_sensitive=True, create_path=False): _File.copy(source, destination, unique, sort, case_sensitive, create_path)
Python utility to create file Args: source: absolute/relative path of source file destination: absolute/relative path of destination file. Use same as source for replacing the content of existing file. unique: Copy only unique lines from file sort: Sort the content of file case_sensitive: unique/sort operations to be ...
codesearchnet
def fashion_mnist_generator(tmp_dir, training, how_many, start_from=0): _get_fashion_mnist(tmp_dir) d = _FASHION_MNIST_LOCAL_FILE_PREFIX + ( _MNIST_TRAIN_DATA_FILENAME if training else _MNIST_TEST_DATA_FILENAME) l = _FASHION_MNIST_LOCAL_FILE_PREFIX + ( _MNIST_TRAIN_LABELS_FILENAME if training else ...
Image generator for FashionMNIST. Args: tmp_dir: path to temporary storage directory. training: a Boolean; if true, we use the train set, otherwise the test set. how_many: how many images and labels to generate. start_from: from which image to start. Returns: An instance of image_generator that produces MNIST images.
juraj-google-style
def replace(self, **kw): if "tzinfo" in kw: if kw["tzinfo"] is None: raise TypeError("Can not remove the timezone use asdatetime()") else: tzinfo = kw["tzinfo"] del kw["tzinfo"] else: tzinfo = None is_dst = None if "is_dst" in kw: is_dst = kw["is_dst...
Return datetime with new specified fields given as arguments. For example, dt.replace(days=4) would return a new datetime_tz object with exactly the same as dt but with the days attribute equal to 4. Any attribute can be replaced, but tzinfo can not be set to None. Args: Any datetime_tz attribute. Returns: A dateti...
juraj-google-style
def _get_index(self, data: _instance_base.Instance | ConcreteValue) -> int | None: if isinstance(data, ConcreteValue): return self.ctx.convert.value_to_constant(data, (int, type(None))) elif isinstance(data, _instance_base.Instance): if data.cls != self.ctx.convert.int_type: raise ab...
Helper function for getslice_slot that extracts int or None from data. If data is an Instance of int, None is returned. Args: data: The object to extract from. Usually a ConcreteValue or an Instance. Returns: The value (an int or None) of the index. Raises: abstract_utils.ConversionError: If the data could not be c...
github-repos
def register(self, name): if name not in settings.CODEMIRROR_SETTINGS: msg = ("Given config name '{}' does not exists in " "'settings.CODEMIRROR_SETTINGS'.") raise UnknowConfigError(msg.format(name)) parameters = copy.deepcopy(self.default_internal_co...
Register configuration for an editor instance. Arguments: name (string): Config name from available ones in ``settings.CODEMIRROR_SETTINGS``. Raises: UnknowConfigError: If given config name does not exist in ``settings.CODEMIRROR_SETTINGS``. Returns: dict: Registred config dict.
juraj-google-style
def __init__(self, input_reader=None, output_writer=None): super(PinfoTool, self).__init__( input_reader=input_reader, output_writer=output_writer) self._compare_storage_file_path = None self._output_filename = None self._output_format = None self._process_memory_limit = None self._...
Initializes the CLI tool object. Args: input_reader (Optional[InputReader]): input reader, where None indicates that the stdin input reader should be used. output_writer (Optional[OutputWriter]): output writer, where None indicates that the stdout output writer should be used.
juraj-google-style
def secondary_training_status_message(job_description, prev_description): if ((job_description is None) or (job_description.get('SecondaryStatusTransitions') is None) or (len(job_description.get('SecondaryStatusTransitions')) == 0)): return '' prev_description_secondary_transitions = (prev_description.g...
Returns a string contains last modified time and the secondary training job status message. Args: job_description: Returned response from DescribeTrainingJob call prev_description: Previous job description from DescribeTrainingJob call Returns: str: Job status string to be printed.
codesearchnet
def initialize_references_json(references_json, references, setter=None): for obj in references_json: obj_id = obj['id'] obj_attrs = obj['attributes'] instance = references[obj_id] HasProps.__init__(instance) instance.update_from_json(obj_attrs, models=references, setter=sett...
Given a JSON representation of the models in a graph, and new model objects, set the properties on the models from the JSON Args: references_json (``JSON``) JSON specifying attributes and values to initialize new model objects with. references (dict[str, Model]) A dictionary mapping model IDs to newly created (but no...
codesearchnet
def reduce_per_replica(values, strategy, reduction='first'): def _reduce(v): if reduction == 'concat' and _collective_all_reduce_multi_worker(strategy): return _multi_worker_concat(v, strategy) if not _is_per_replica_instance(v): return v elif reduction == '...
Reduce PerReplica objects. Args: values: Structure of `PerReplica` objects or `Tensor`s. `Tensor`s are returned as-is. strategy: `tf.distribute.Strategy` object. reduction: One of 'first', 'concat'. Returns: Structure of `Tensor`s.
github-repos
def replace_vars(config, env): if isinstance(config, dict): for (k, v) in list(config.items()): if (isinstance(v, dict) or isinstance(v, list) or isinstance(v, tuple)): replace_vars(v, env) elif isinstance(v, basestring): config[k] = expand_var(v, env)...
Replace variable references in config using the supplied env dictionary. Args: config: the config to parse. Can be a tuple, list or dict. env: user supplied dictionary. Raises: Exception if any variable references are not found in env.
codesearchnet
def get_interpolated_gap(self, tol=0.001, abs_tol=False, spin=None): tdos = (self.y if (len(self.ydim) == 1) else np.sum(self.y, axis=1)) if (not abs_tol): tol = ((tol * tdos.sum()) / tdos.shape[0]) energies = self.x below_fermi = [i for i in range(len(energies)) if ((energies[i] < self.efermi) ...
Expects a DOS object and finds the gap Args: tol: tolerance in occupations for determining the gap abs_tol: Set to True for an absolute tolerance and False for a relative one. spin: Possible values are None - finds the gap in the summed densities, Up - finds the gap in the up spin channel, Down - finds the gap in the ...
codesearchnet
def consume(self, callback, bindings=None, queues=None, exchanges=None): self._bindings = (bindings or config.conf['bindings']) self._queues = (queues or config.conf['queues']) self._exchanges = (exchanges or config.conf['exchanges']) if inspect.isclass(callback): cb_obj = callback() if ...
Consume messages from a message queue. Simply define a callable to be used as the callback when messages are delivered and specify the queue bindings. This call blocks. The callback signature should accept a single positional argument which is an instance of a :class:`Message` (or a sub-class of it). Args: callback (...
codesearchnet
def put(self, entity): actual_entity = _normalize_entity(entity) if actual_entity is None: return self.ndb_put(entity) self.puts.append(actual_entity)
Registers entity to put to datastore. Args: entity: an entity or model instance to put.
juraj-google-style
def Runs(self): with self._accumulators_mutex: items = list(six.iteritems(self._accumulators)) return {run_name: accumulator.Tags() for (run_name, accumulator) in items}
Return all the run names in the `EventMultiplexer`. Returns: ``` {runName: { scalarValues: [tagA, tagB, tagC], graph: true, meta_graph: true}} ```
codesearchnet
def Decode(data, encoding=None): encoding = encoding or GetConsoleAttr().GetEncoding() return encoding_util.Decode(data, encoding=encoding)
Converts the given string, bytes, or object to a text string. Args: data: Any bytes, string, or object that has str() or unicode() methods. encoding: A suggesting encoding used to decode. If this encoding doesn't work, other defaults are tried. Defaults to GetConsoleAttr().GetEncoding(). Returns: A text string repres...
github-repos
def __init__(self, location, resource_pool): super(MemoryPackageRepository, self).__init__(location, resource_pool) self.data = {} self.register_resource(MemoryPackageFamilyResource) self.register_resource(MemoryPackageResource) self.register_resource(MemoryVariantResour...
Create an in-memory package repository. Args: location (str): Path containing the package repository.
juraj-google-style
def log_histogram(self, name, value, step=None): if isinstance(value, six.string_types): raise TypeError('"value" should be a number, got {}' .format(type(value))) self._check_step(step) tf_name = self._ensure_tf_name(name) summary = sel...
Log a histogram for given name on given step. Args: name (str): name of the variable (it will be converted to a valid tensorflow summary name). value (tuple or list): either list of numbers to be summarized as a histogram, or a tuple of bin_edges and bincounts that directly define a histogram. step (int): non-negative...
juraj-google-style
def log_combinations(n, counts, name='log_combinations'): with ops.name_scope(name, values=[n, counts]): n = ops.convert_to_tensor(n, name='n') counts = ops.convert_to_tensor(counts, name='counts') total_permutations = math_ops.lgamma(n + 1) counts_factorial = math_ops.lgamma(counts ...
Multinomial coefficient. Given `n` and `counts`, where `counts` has last dimension `k`, we compute the multinomial coefficient as: ```n! / sum_i n_i!``` where `i` runs over all `k` classes. Args: n: Floating-point `Tensor` broadcastable with `counts`. This represents `n` outcomes. counts: Floating-point `Tensor` br...
github-repos
def check_tx(self, raw_transaction): self.abort_if_abci_chain_is_not_synced() logger.debug('check_tx: %s', raw_transaction) transaction = decode_transaction(raw_transaction) if self.bigchaindb.is_valid_transaction(transaction): logger.debug('check_tx: VALID') ...
Validate the transaction before entry into the mempool. Args: raw_tx: a raw string (in bytes) transaction.
juraj-google-style
def read_probes(self, key): assert key in list(self._PROBES.keys()) if key == 'output': value = self._output return value
requestes value from the instrument and returns it Args: key: name of requested value Returns: reads values from instrument
juraj-google-style
def _group_similar(items: List[T], comparer: Callable[[T, T], bool]) -> List[List[T]]: groups = [] used = set() for i in range(len(items)): if i not in used: group = [items[i]] for j in range(i + 1, len(items)): if j not in used and...
Combines similar items into groups. Args: items: The list of items to group. comparer: Determines if two items are similar. Returns: A list of groups of items.
juraj-google-style
def _MergeTaskStorage(self, storage_writer): if self._processing_profiler: self._processing_profiler.StartTiming('merge_check') for task_identifier in storage_writer.GetProcessedTaskIdentifiers(): try: task = self._task_manager.GetProcessedTaskByIdentifier(task_identifier) sel...
Merges a task storage with the session storage. This function checks all task stores that are ready to merge and updates the scheduled tasks. Note that to prevent this function holding up the task scheduling loop only the first available task storage is merged. Args: storage_writer (StorageWriter): storage writer for...
juraj-google-style
def find_library_linux(cls): dll = Library.JLINK_SDK_NAME root = os.path.join('/', 'opt', 'SEGGER') for (directory_name, subdirs, files) in os.walk(root): fnames = [] x86_found = False for f in files: path = os.path.join(directory_name, f) if (os.path.isfile(p...
Loads the SEGGER DLL from the root directory. On Linux, the SEGGER tools are installed under the ``/opt/SEGGER`` directory with versioned directories having the suffix ``_VERSION``. Args: cls (Library): the ``Library`` class Returns: The paths to the J-Link library files in the order that they are found.
codesearchnet
def _merge_choice_field(self, json_value: Any, choice_field: descriptor.FieldDescriptor, field_name: str, parent: message.Message) -> None: choice_field_name = _get_choice_field_name(choice_field, field_name) choice_field_map = _get_field_map(choice_field.message_type) choice_value_field = choice_field_map....
Creates a Message based on the choice_field Descriptor and json_value. The resulting message is merged into parent. Args: json_value: The JSON value to merge into a message of the type described by choice_field. choice_field: The field descriptor of the FHIR choice type on parent. field_name: The nested field name of...
github-repos
def get_metrics_collector(self, prefix: str=''): metrics_namespace = self._metrics_namespace if self._metrics_namespace else self._model_handler.get_metrics_namespace() if self._model_handler.override_metrics(metrics_namespace): return None return _MetricsCollector(metrics_namespace, prefix=prefix)
Args: prefix: Unique identifier for metrics, used when models are updated using side input.
github-repos
def error(channel, title, description): gui = ui_embed.UI( channel, title, description, modulename=modulename ) return gui
Creates an embed UI containing an error message Args: channel (discord.Channel): The Discord channel to bind the embed to title (str): The title of the embed description (str): The description for the error Returns: ui (ui_embed.UI): The embed UI object
juraj-google-style
def __call__(self, input_1: EventSet, input_2: EventSet) -> Dict[str, EventSet]: assert isinstance(self.operator, BaseBinaryOperator) output_schema = self.output_schema('output') if len(input_1.schema.features) != len(input_2.schema.features): raise ValueError('Both EventSets must have the same numb...
Applies the corresponding arithmetic operation between two EventSets. Args: input_1: First EventSet. input_2: Second EventSet. Returns: Result of the operation. Raises: ValueError: If sampling of both EventSets is not equal.
github-repos
def _is_valid(self, value): if hasattr(self._type, 'istypeof'): return self._type.istypeof(value) else: return isinstance(value, self._type)
Return True if the input value is valid for insertion into the inner list. Args: value: An object about to be inserted.
codesearchnet
def check_the_end_flag(self, state_key): x, y = state_key end_point_tuple = np.where(self.__map_arr == self.__end_point_label) end_point_x_arr, end_point_y_arr = end_point_tuple if x == end_point_x_arr[0] and y == end_point_y_arr[0]: return True else...
Check the end flag. If this return value is `True`, the learning is end. Args: state_key: The key of state in `self.t`. Returns: bool
juraj-google-style
def get_diff(value1, value2, name1, name2): lines1 = [(line + '\n') for line in value1.splitlines()] lines2 = [(line + '\n') for line in value2.splitlines()] diff_lines = difflib.context_diff(lines1, lines2, fromfile=name1, tofile=name2) return ''.join(diff_lines)
Get a diff between two strings. Args: value1 (str): First string to be compared. value2 (str): Second string to be compared. name1 (str): Name of the first string. name2 (str): Name of the second string. Returns: str: The full diff.
codesearchnet
def plot(self, ax=None, return_fig=False, **kwargs): if (ax is None): fig = plt.figure(figsize=(2, 10)) ax = fig.add_subplot(111) return_ax = False else: return_ax = True hypertime = np.linspace(self.start, self.stop, (((10 * self.size) - 1) + 1)) hyperamp = np.interp(hyp...
Plot a synthetic. Args: ax (ax): A matplotlib axis. legend (Legend): For now, only here to match API for other plot methods. return_fig (bool): whether to return the matplotlib figure. Default False. Returns: ax. If you passed in an ax, otherwise None.
codesearchnet
def open_repository(path, spor_dir='.spor'): root = _find_root_dir(path, spor_dir) return Repository(root, spor_dir)
Open an existing repository. Args: path: Path to any file or directory within the repository. spor_dir: The name of the directory containing spor data. Returns: A `Repository` instance. Raises: ValueError: No repository is found.
juraj-google-style