code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def __ge__(self, other): other = self._cast_to_frameset(other) if other is NotImplemented: return NotImplemented return self.items >= other.items
Check if `self` >= `other` via a comparison of the contents. If `other` is not a :class:`FrameSet`, but is a set, frozenset, or is iterable, it will be cast to a :class:`FrameSet`. Args: other (:class:`FrameSet`): Also accepts an object that can be cast to a :class:`FrameSet` Returns: bool: :class:`NotImplemented`: i...
juraj-google-style
def unsqueeze(self, dim: int) -> Rigid: if dim >= len(self.shape): raise ValueError('Invalid dimension') rots = self._rots.unsqueeze(dim) trans = self._trans.unsqueeze(dim if dim >= 0 else dim - 1) return Rigid(rots, trans)
Analogous to torch.unsqueeze. The dimension is relative to the shared dimensions of the rotation/translation. Args: dim: A positive or negative dimension index. Returns: The unsqueezed transformation.
github-repos
def _BuildFindSpecsFromRegistrySourceKey(self, key_path): find_specs = [] for key_path_glob in path_helper.PathHelper.ExpandRecursiveGlobs(key_path, '\\'): logger.debug('building find spec from key path glob: {0:s}'.format(key_path_glob)) key_path_glob_upper = key_path_glob.upper() if ke...
Build find specifications from a Windows Registry source type. Args: key_path (str): Windows Registry key path defined by the source. Returns: list[dfwinreg.FindSpec]: find specifications for the Windows Registry source type.
codesearchnet
def write_test_cases(fp, model_name, examples): writer = TextFormatWriter(fp) writer.write_field('load_model', os.path.basename(model_name)) for example in examples: inputs = [] for name in example['inputs'].keys(): if name: inputs.append(name) outputs = [...
Given a dictionary of `examples`, write a text format representation. The file format is protocol-buffer-like, even though we don't use proto due to the needs of the Android team. Args: fp: File-like object to write to. model_name: Filename where the model was written to, relative to filename. examples: Example dicti...
github-repos
def GetDefinitionByName(self, name): lookup_name = name.lower() if (lookup_name not in self._definitions): lookup_name = self._aliases.get(name, None) return self._definitions.get(lookup_name, None)
Retrieves a specific data type definition by name. Args: name (str): name of the data type definition. Returns: DataTypeDefinition: data type definition or None if not available.
codesearchnet
class DabDetrEncoder(DabDetrPreTrainedModel): def __init__(self, config: DabDetrConfig): super().__init__(config) self.dropout = config.dropout self.query_scale = DabDetrMLP(config.hidden_size, config.hidden_size, config.hidden_size, 2) self.layers = nn.ModuleList([DabDetrEncoderLay...
Transformer encoder consisting of *config.encoder_layers* self attention layers. Each layer is a [`DabDetrEncoderLayer`]. The encoder updates the flattened feature map through multiple self-attention layers. Small tweak for DAB-DETR: - object_queries are added to the forward pass. Args: config: DabDetrConfig
github-repos
def write_dict_to_new_file(file_name, localization_key_to_comment): output_file_descriptor = open_strings_file(file_name, "w") for entry_key, entry_comment in sorted(localization_key_to_comment.iteritems(), key=operator.itemgetter(1)): write_entry_to_file(output_file_descriptor, entry_comment, entr...
Writes dictionary of localization keys and comments to a file. Args: localization_key_to_comment (dict): A mapping between localization keys and comments. file_name (str): The path of the file to append to.
juraj-google-style
def _ParseRegisteredDLLs(self, parser_mediator, registry_key): notify_key = registry_key.GetSubkeyByName('Notify') if not notify_key: return for subkey in notify_key.GetSubkeys(): for trigger in self._TRIGGERS: handler_value = subkey.GetValueByName(trigger) if not handler_v...
Parses the registered DLLs that receive event notifications. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. registry_key (dfwinreg.WinRegistryKey): Windows Registry key.
juraj-google-style
def add(self, value): value = int(value) if (value < 10): value = 10 if (value > 600): value = 600 self._data.setdefault(value, 0) self._data[value] += 1 self._len += 1
Add the value to this histogram. Args: value (int): The value. Values outside of ``10 <= x <= 600`` will be raised to ``10`` or reduced to ``600``.
codesearchnet
def add_buffer(self, buf_header, buf_payload): if 'num_buffers' in self._header: self._header['num_buffers'] += 1 else: self._header['num_buffers'] = 1 self._header_json = None self._buffers.append((buf_header, buf_payload))
Associate a buffer header and payload with this message. Args: buf_header (``JSON``) : a buffer header buf_payload (``JSON`` or bytes) : a buffer payload Returns: None Raises: MessageError
juraj-google-style
def validate_full_name(self, full_name, timeout=(- 1)): uri = ((self.URI + '/validateUserName/') + full_name) return self._client.create_with_zero_body(uri=uri, timeout=timeout)
Verifies if a fullName is already in use. Args: full_name: The fullName to be verified. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stops waiting for its completion. Returns: True if full name is in use, False if it is not.
codesearchnet
def __init__(self, host: str, port: int, username: Optional[str], password: Optional[str], batch_size: int=100): self.host = host self.port = port self.username = username | os.getenv('OPENSEARCH_USERNAME') self.password = password | os.getenv('OPENSEARCH_PASSWORD') self._batch_size = batch_size ...
Args: host (str): The opensearch host port (int): The opensearch port username (str): username of OpenSearch DB password (str): password of OpenSearch DB batch_size(int): Number of key, values pairs to write at once Returns: :class:`~apache_beam.transforms.ptransform.PTransform`
github-repos
def mul(left, right): from .mv_mul import MvMul length = max(left, right) if (length == 1): return Mul(left, right) return MvMul(left, right)
Distribution multiplication. Args: left (Dist, numpy.ndarray) : left hand side. right (Dist, numpy.ndarray) : right hand side.
codesearchnet
def _copy_hdxobjects(self, hdxobjects, hdxobjectclass, attribute_to_copy=None): newhdxobjects = list() for hdxobject in hdxobjects: newhdxobjectdata = copy.deepcopy(hdxobject.data) newhdxobject = hdxobjectclass(newhdxobjectdata, configuration=self.configuration) if attribute_to_copy: ...
Helper function to make a deep copy of a supplied list of HDX objects Args: hdxobjects (List[T <= HDXObject]): list of HDX objects to copy hdxobjectclass (type): Type of the HDX Objects to be copied attribute_to_copy (Optional[str]): An attribute to copy over from the HDX object. Defaults to None. Returns: List[T <= ...
codesearchnet
def __init__(self, timeout_s): self.start = time.time() self.timeout_s = timeout_s
Construct a PolledTimeout object. Args: timeout_s: This may either be a number or None. If a number, this object will consider to be expired after number seconds after construction. If None, this object never expires.
juraj-google-style
def add_comment(self, app_id, record_id, field_id, message): self._swimlane.request( 'post', 'app/{0}/record/{1}/{2}/comment'.format( app_id, record_id, field_id ), json={ 'message': message...
Directly add a comment to a record without retrieving the app or record first Warnings: Does not perform any app, record, or field ID validation Args: app_id (str): Full App ID string record_id (str): Full parent Record ID string field_id (str): Full field ID to target reference field on parent Record string message ...
juraj-google-style
def AddLogFileOptions(self, argument_group): argument_group.add_argument('--logfile', '--log_file', '--log-file', action='store', metavar='FILENAME', dest='log_file', type=str, default='', help='Path of the file in which to store log messages, by default this file will be named: "{0:s}-YYYYMMDDThhmmss.log.gz". Note...
Adds the log file option to the argument group. Args: argument_group (argparse._ArgumentGroup): argparse argument group.
codesearchnet
def write(self, writer: WriteStream) -> None: for untagged in self._untagged: untagged.write(writer) writer.write(b'%b %b\r\n' % (self.tag, self.text))
Write the object to the stream, with one or more calls to :meth:`~asyncio.WriteStream.write`. Args: writer: The output stream.
juraj-google-style
def parse(self, input_str, reference_date=""): if not jpype.isThreadAttachedToJVM(): jpype.attachThreadToJVM() if reference_date: return json.loads(self._sutime.annotate(input_str, reference_date)) return json.loads(self._sutime.annotate(input_str))
Parses datetime information out of string input. It invokes the SUTimeWrapper.annotate() function in Java. Args: input_str: The input as string that has to be parsed. reference_date: Optional reference data for SUTime. Returns: A list of dicts with the result from the SUTimeWrapper.annotate() call.
juraj-google-style
def _broadcast_arg(U, arg, argtype, name): if arg is None or isinstance(arg, argtype): return [arg for _ in range(U.ndim)] elif np.iterable(arg): if len(arg) != U.ndim: raise ValueError('Parameter {} was specified as a sequence of ' 'inco...
Broadcasts plotting option `arg` to all factors. Args: U : KTensor arg : argument provided by the user argtype : expected type for arg name : name of the variable, used for error handling Returns: iterable version of arg of length U.ndim
juraj-google-style
def resolve_pname(self, pname: PrefName, mid: ModuleId) -> Tuple[(YangIdentifier, ModuleId)]: (p, s, loc) = pname.partition(':') try: mdata = self.modules[mid] except KeyError: raise ModuleNotRegistered(*mid) from None try: return ((loc, mdata.prefix_map[p]) if s else (p, mdata.m...
Return the name and module identifier in which the name is defined. Args: pname: Name with an optional prefix. mid: Identifier of the module in which `pname` appears. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If the prefix specified in `pname` is not declared.
codesearchnet
def reset(self, entries_to_reset): num_updates = tf.size(entries_to_reset) update_vals = tf.scatter_update(self.mem_vals, entries_to_reset, tf.tile(tf.expand_dims(tf.fill([self.memory_size, self.val_depth], 0.0), 0), [num_updates, 1, 1])) update_logits = tf.scatter_update(self.mean_logits, entries_to_reset,...
Reset the entries in the memory. Args: entries_to_reset: a 1D tensor. Returns: the reset op.
codesearchnet
def __init__(self, cls, required=False, default=Empty): assert isclass(cls) assert issubclass(cls, Object) if default is not Empty and not isinstance(default, cls): self._default = cls(default) else: self._default = default self._cls = cls self._required = required
Create an instance of a type signature. Args: cls (Class): the "type" of the object this signature represents. required (bool): default(object): an instance of the type for a default value. This should be either an instance of cls or something coercable to cls.
juraj-google-style
def __init__(self, project, query, data): super().__init__(project, query, 'unused_checksum') self.expected_data = data self.actual_data = None
Initialize BigQueryMatcher object. Args: project: The name (string) of the project. query: The query (string) to perform. data: List of tuples with the expected data.
github-repos
def send_handshake_request(self, uid=UNKNOWN_UID, cmd=ConnectionHandshakeCommand.INIT): request = json.dumps({'cmd': cmd.value, 'uid': uid}) self.log.debug('Sending handshake request %s.', request) self._client_send(request) response = self._client_receive() if not response: raise errors.Pro...
Sends a handshake request to the server to prepare for the communication. Through the handshake response, this function checks whether the server is ready for the communication. If ready, it sets `self.uid` to the server session id. Otherwise, it sets `self.uid` to `UNKNOWN_UID`. Args: uid: int, the uid of the server...
github-repos
def _skip_remaining_tests(self, exception): for test_name in self.results.requested: if not self.results.is_test_executed(test_name): test_record = records.TestResultRecord(test_name, self.TAG) test_record.test_skip(exception) self.results.add_record(test_record) ...
Marks any requested test that has not been executed in a class as skipped. This is useful for handling abort class signal. Args: exception: The exception object that was thrown to trigger the skip.
github-repos
def __init__(self, features, targets, **kwargs): super().__init__(**kwargs) self.features = features self.targets = targets self.fit(features.train, targets.train)
Inits a Random Forest Classifier with a market attribute Args: **kwargs: Scikit Learn's RandomForestClassifier kwargs
juraj-google-style
def get_average_record(self, n): history_deque = collections.deque() averages = [] for d in self.data_points: history_deque.appendleft(d) if len(history_deque) > n: history_deque.pop() avg = sum(history_deque) / len(history_deque) ...
Returns a list of average current numbers, each representing the average over the last n data points. Args: n: Number of data points to average over. Returns: A list of average current values.
juraj-google-style
def json_to_bulk(tc_data, value_fields, resource_type, resource_type_parent): if (not isinstance(tc_data, list)): tc_data = [tc_data] bulk_array = [] for d in tc_data: values = [] for field in value_fields: if (d.get(field) is not None): values.append(d.ge...
Convert ThreatConnect JSON response to a Bulk Format. .. Attention:: This method is subject to frequent changes Args: tc_data (dictionary): Array of data returned from TC API call. value_fields (list): Field names that contain the "value" data. resource_type (string): The resource type of the tc_data provided. resour...
codesearchnet
def delete(filename, retry_params=None, _account_id=None): api = storage_api._get_storage_api(retry_params=retry_params, account_id=_account_id) common.validate_file_path(filename) filename = api_utils._quote_filename(filename) status, resp_headers, content = api.delete_o...
Delete a Google Cloud Storage file. Args: filename: A Google Cloud Storage filename of form '/bucket/filename'. retry_params: An api_utils.RetryParams for this call to GCS. If None, the default one is used. _account_id: Internal-use only. Raises: errors.NotFoundError: if the file doesn't exist prior to deletion.
juraj-google-style
def _testDrawBoundingBoxColorCycling(self, img, dtype=dtypes.float32, colors=None): color_table = colors if colors is None: color_table = np.asarray([[1, 1, 0, 1], [0, 0, 1, 1], [1, 0, 0, 1], [0, 1, 0, 1], [0.5, 0, 0.5, 1], [0.5, 0.5, 0, 1], [0.5, 0, 0, 1], [0, 0, 0.5, 1], [0, 1, 1, 1], [1, 0, 1, 1]]) ...
Tests if cycling works appropriately. Args: img: 3-D numpy image on which to draw. dtype: image dtype (float, half). colors: color table.
github-repos
def get_text_features(self, input_ids, attention_mask=None, position_ids=None, token_type_ids=None, params: Optional[dict]=None, dropout_rng: jax.random.PRNGKey=None, train=False): if position_ids is None: position_ids = jnp.broadcast_to(jnp.arange(jnp.atleast_2d(input_ids).shape[-1]), input_ids.shape) ...
Args: input_ids (`numpy.ndarray` of shape `(batch_size, sequence_length)`): Indices of input sequence tokens in the vocabulary. Padding will be ignored by default should you provide it. Indices can be obtained using [`PreTrainedTokenizer`]. See [`PreTrainedTokenizer.encode`] and [`PreTrainedTokenizer.__call__`] for de...
github-repos
def union(self, other): if not isinstance(other, self.__class__): m = "You can only union striplogs with each other." raise StriplogError(m) result = [] for iv in deepcopy(self): for jv in other: if iv.any_overlaps(jv): ...
Makes a striplog of all unions. Args: Striplog. The striplog instance to union with. Returns: Striplog. The result of the union.
juraj-google-style
def write_unitth(suites, out_dir): if not os.path.isdir(out_dir): os.mkdir(out_dir) for classname, cases in suites.items(): doc_xml = minidom.Document() suite_xml = doc_xml.createElement('testsuite') suite_xml.setAttribute('name', classname) ...
Write UnitTH-style test reports Args: suites (:obj:`dict`): dictionary of test suites out_dir (:obj:`str`): path to save UnitTH-style test reports
juraj-google-style
def get_pipeline_stage(self, pipeline_key, stage_key = None, sort_by = None): if not pipeline_key: return requests.codes.bad_request, None uri = '/'.join([ self.api_uri, self.pipelines_suffix, pipeline_key, self.stages_suffix ]) if stage_key: uri = '/'.join([ uri, ...
Gets a list of one/all stage objects in a pipeline. Performs a single GET. Args: pipeline_key key for pipeline stage_key key for stage (default: None i.e. ALL) sort_by in desc order by 'creationTimestamp' or 'lastUpdatedTimestamp' may or may not be supported returns (status code for the GET request, dict of stage...
juraj-google-style
def manual_invoice(cls, user, due_delta, description_price_pairs): line_items = [] for (description, price) in description_price_pairs: line_item = commerce.LineItem(description=description, quantity=1, price=Decimal(price), product=None) line_items.append(line_item) min_due_time = (timezone...
Generates an invoice for arbitrary items, not held in a user's cart. Arguments: user (User): The user the invoice is being generated for. due_delta (datetime.timedelta): The length until the invoice is due. description_price_pairs ([(str, long or Decimal), ...]): A list of pairs. Each pair consists of the description ...
codesearchnet
def generate_entry_label(entry): if isinstance(entry, MultiEntry): return " + ".join([latexify_ion(e.name) for e in entry.entry_list]) else: return latexify_ion(latexify(entry.name))
Generates a label for the pourbaix plotter Args: entry (PourbaixEntry or MultiEntry): entry to get a label for
juraj-google-style
def easeInBack(n, s=1.70158): _checkRange(n) return n * n * ((s + 1) * n - s)
A tween function that backs up first at the start and then goes to the destination. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
juraj-google-style
def render(raw_config, environment=None): t = Template(raw_config) buff = StringIO() if (not environment): environment = {} try: substituted = t.substitute(environment) except KeyError as e: raise exceptions.MissingEnvironment(e.args[0]) except ValueError: substit...
Renders a config, using it as a template with the environment. Args: raw_config (str): the raw stacker configuration string. environment (dict, optional): any environment values that should be passed to the config Returns: str: the stacker configuration populated with any values passed from the environment
codesearchnet
def read(self, istream, kmip_version=enums.KMIPVersion.KMIP_1_0): super(Interval, self).read(istream, kmip_version=kmip_version) if (self.length != Interval.LENGTH): raise exceptions.InvalidPrimitiveLength('interval length must be {0}'.format(Interval.LENGTH)) self.value = unpack('!I', istream.read(...
Read the encoding of the Interval from the input stream. Args: istream (stream): A buffer containing the encoded bytes of the value of an Interval. Usually a BytearrayStream object. Required. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, defaults ...
codesearchnet
def series_expand(self, param: Symbol, about, order: int): s = self.shape emats = zip(*[o.series_expand(param, about, order) for o in self.matrix.ravel()]) return tuple((Matrix(np_array(em).reshape(s)) for em in emats))
Expand the matrix expression as a truncated power series in a scalar parameter. Args: param: Expansion parameter. about (.Scalar): Point about which to expand. order: Maximum order of expansion >= 0 Returns: tuple of length (order+1), where the entries are the expansion coefficients.
codesearchnet
def generate_multiline_list(self, items, before='', after='', delim=('(', ')'), compact=True, sep=',', skip_last_sep=False): assert ((len(delim) == 2) and isinstance(delim[0], six.text_type) and isinstance(delim[1], six.text_type)), 'delim must be a tuple of two unicode strings.' if (len(items) == 0): s...
Given a list of items, emits one item per line. This is convenient for function prototypes and invocations, as well as for instantiating arrays, sets, and maps in some languages. TODO(kelkabany): A backend that uses tabs cannot be used with this if compact is false. Args: items (list[str]): Should contain the items ...
codesearchnet
def fix_variables(self, fixed): for v, val in fixed.items(): self.fix_variable(v, val)
Fix the value of the variables and remove it from a binary quadratic model. Args: fixed (dict): A dictionary of variable assignments. Examples: >>> bqm = dimod.BinaryQuadraticModel({'a': -.5, 'b': 0., 'c': 5}, {('a', 'b'): -1}, 0.0, dimod.SPIN) >>> bqm.fix_variables({'a': -1, 'b': +1})
juraj-google-style
def enable_napps(cls, napps): mgr = NAppsManager() for napp in napps: mgr.set_napp(*napp) LOG.info('NApp %s:', mgr.napp_id) cls.enable_napp(mgr)
Enable a list of NApps. Args: napps (list): List of NApps.
codesearchnet
def _run_inline_graph_optimization(func, lower_control_flow, aggressive_inlining): graph_def = func.graph.as_graph_def() if not lower_control_flow: graph_def = disable_lower_using_switch_merge(graph_def) for function in graph_def.library.function: if 'api_implements' in function.attr: ...
Apply function inline optimization to the graph. Returns the GraphDef after Grappler's function inlining optimization is applied. This optimization does not work on models with control flow. Args: func: ConcreteFunction. lower_control_flow: Boolean indicating whether or not to lower control flow ops such as If and Wh...
github-repos
def _sysapi_changed_nilrt(): nisysapi_path = '/usr/local/natinst/share/nisysapi.ini' if (os.path.exists(nisysapi_path) and _file_changed_nilrt(nisysapi_path)): return True restartcheck_state_dir = '/var/lib/salt/restartcheck_state' nisysapi_conf_d_path = '/usr/lib/{0}/nisysapi/conf.d/experts/'.f...
Besides the normal Linux kernel driver interfaces, NILinuxRT-supported hardware features an extensible, plugin-based device enumeration and configuration interface named "System API". When an installed package is extending the API it is very hard to know all repercurssions and actions to be taken, so reboot making sure...
codesearchnet
def search(self, **kwargs): path = self._get_path('search') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Get movies that match the search query string from the API. Args: q (optional): plain text search query; remember to URI encode page_limit (optional): number of search results to show per page, default=30 page (optional): results page number, default=1 Returns: A dict respresentation of the JSON returned from the API...
juraj-google-style
def _build(self, inputs, multiplier=1): input_shape = tuple(inputs.get_shape().as_list()) bias_shape = calculate_bias_shape(input_shape, self._bias_dims) if (len(input_shape) < 2): raise base.IncompatibleShapeError('Rank of input shape must be >=2 not: {}.'.format(len(input_shape))) if ((self._i...
Connects the Add module into the graph, with input Tensor `inputs`. Args: inputs: A Tensor of size `[batch_size, input_size1, ...]`. multiplier: A scalar or Tensor which the bias term is multiplied by before adding it to `inputs`. Anything which works in the expression `bias * multiplier` is acceptable here. This may ...
codesearchnet
def save_weights_to_hdf5_group(f, layers): from tensorflow.python.keras import __version__ as keras_version save_attributes_to_hdf5_group(f, 'layer_names', [layer.name.encode('utf8') for layer in layers]) f.attrs['backend'] = backend.backend().encode('utf8') f.attrs['keras_version'] = str(keras_version)...
Saves the weights of a list of layers to a HDF5 group. Args: f: HDF5 group. layers: List of layer instances.
github-repos
def result(self, timeout=None): self._blocking_poll(timeout=timeout) if self._exception is not None: raise self._exception return self._result
Get the result of the operation, blocking if necessary. Args: timeout (int): How long (in seconds) to wait for the operation to complete. If None, wait indefinitely. Returns: google.protobuf.Message: The Operation's result. Raises: google.api_core.GoogleAPICallError: If the operation errors or if the timeout is reac...
juraj-google-style
def set(self, *args): assert len(args) in (1, 2) if len(args) == 1: value = args[0] self._impl.set(value) else: index, value = args if isinstance(value, Real): self._impl.setTplDbl(Tuple(index)._impl, value) eli...
Set the value of a single instance of this parameter. Args: args: value if the parameter is scalar, index and value otherwise. Raises: RuntimeError: If the entity has been deleted in the underlying AMPL. TypeError: If the parameter is not scalar and the index is not provided.
juraj-google-style
def load_exons(self, exons, genes=None, build='37'): genes = genes or self.ensembl_genes(build) for exon in exons: exon_obj = build_exon(exon, genes) if not exon_obj: continue res = self.exon_collection.insert_one(exon_obj)
Create exon objects and insert them into the database Args: exons(iterable(dict))
juraj-google-style
def get(self, personId): check_type(personId, basestring, may_be_none=False) json_data = self._session.get(API_ENDPOINT + '/' + personId) return self._object_factory(OBJECT_TYPE, json_data)
Get a person's details, by ID. Args: personId(basestring): The ID of the person to be retrieved. Returns: Person: A Person object with the details of the requested person. Raises: TypeError: If the parameter types are incorrect. ApiError: If the Webex Teams cloud returns an error.
juraj-google-style
def _GenerateNames(name, fromlist, globals): def GetCurrentPackage(globals): 'Finds the name of the package for the currently executing module.' if (not globals): return None current = globals.get('__name__') if (not current): return None current_file...
Generates the names of modules that might be loaded via this import. Args: name: Argument as passed to the importer. fromlist: Argument as passed to the importer. globals: Argument as passed to the importer. Returns: A set that contains the names of all modules that are loaded by the currently executing import statem...
codesearchnet
def _write_object_proto(self, proto, options): write_object_proto_for_resource_variable(self, proto, options)
Writes additional information of the variable into the SavedObject proto. Subclasses of ResourceVariables could choose to override this method to customize extra information to provide when saving a SavedModel. Ideally, this should contain the logic in write_object_proto_for_resource_variable but `DistributedValue` i...
github-repos
def _set_median_session_metrics(session_group, aggregation_metric): measurements = sorted(_measurements(session_group, aggregation_metric), key=operator.attrgetter('metric_value.value')) median_session = measurements[(len(measurements) - 1) del session_group.metric_values[:] session_...
Sets the metrics for session_group to those of its "median session". The median session is the session in session_group with the median value of the metric given by 'aggregation_metric'. The median is taken over the subset of sessions in the group whose 'aggregation_metric' was measured at the largest training step am...
juraj-google-style
def init(self): resp = self._execute(Command.NEW_SESSION, {'desiredCapabilities': self.desired_capabilities}, False) resp.raise_for_status() self.session_id = str(resp.session_id) self.capabilities = resp.value
Create Session by desiredCapabilities Support: Android iOS Web(WebView) Returns: WebDriver Object.
codesearchnet
def round_to_nearest(dt, n_round_sec=1.0): ts = ts_from_dt(strip_timezone(dt)) + n_round_sec / 2.0 res = dt_from_ts(ts - (ts % n_round_sec)) return res.replace(tzinfo=dt.tzinfo)
Round datetime up or down to nearest divisor. Round datetime up or down to nearest number of seconds that divides evenly by the divisor. Any timezone is preserved but ignored in the rounding. Args: dt: datetime n_round_sec : int or float Divisor for rounding Examples: - ``n_round_sec`` = 0.1: nearest 10th of a sec...
juraj-google-style
def path_in_cache(self, filename, metahash): cpath = self._genpath(filename, metahash) if os.path.exists(cpath): return cpath else: raise CacheMiss
Generates the path to a file in the mh cache. The generated path does not imply the file's existence! Args: filename: Filename relative to buildroot rule: A targets.SomeBuildRule object metahash: hash object
codesearchnet
def get_entry(self, pathname_name): pathname_name = self._normalized_entryname(pathname_name) return self.contents[pathname_name]
Retrieves the specified child file or directory entry. Args: pathname_name: The basename of the child object to retrieve. Returns: The fake file or directory object. Raises: KeyError: if no child exists by the specified name.
codesearchnet
def check_get_splits(self, query, num_splits, num_entities): for id_or_name in [True, False, None]: if id_or_name is None: client_entities = helper.create_client_entities(num_entities, False) client_entities.extend(helper.create_client_entities(num_entities, True)) num_en...
A helper method to test the query_splitter get_splits method. Args: query: the query to be split num_splits: number of splits num_entities: number of scatter entities returned to the splitter.
github-repos
def slice(array, start, size, ty): weld_obj = WeldObject(encoder_, decoder_) array_var = weld_obj.update(array) if isinstance(array, WeldObject): array_var = array.obj_id weld_obj.dependencies[array_var] = array weld_template = weld_obj.weld_code = weld_template % {"array": a...
Returns a new array-of-arrays with each array truncated, starting at index `start` for `length` characters. Args: array (WeldObject / Numpy.ndarray): Input array start (int): starting index size (int): length to truncate at ty (WeldType): Type of each element in the input array Returns: A WeldObject representing this...
juraj-google-style
def _validate_testbed_configs(testbed_configs): seen_names = set() for config in testbed_configs: name = config[keys.Config.key_testbed_name.value] _validate_testbed_name(name) if name in seen_names: raise MoblyConfigError('Duplicate testb...
Validates the testbed configurations. Args: testbed_configs: A list of testbed configuration dicts. Raises: MoblyConfigError: Some parts of the configuration is invalid.
juraj-google-style
def cumulative_distribution(self, X): self.check_fit() def func(*args): return self.probability_density(list(args)) lower_bound = self.get_lower_bound() ranges = [[lower_bound, val] for val in X] return integrate.nquad(func, ranges)[0]
Computes the cumulative distribution function for the copula Args: X: `numpy.ndarray` or `pandas.DataFrame` Returns: np.array: cumulative probability
juraj-google-style
def build_authorization_endpoint(self, request, disable_sso=None): self.load_config() redirect_to = request.GET.get(REDIRECT_FIELD_NAME, None) if (not redirect_to): redirect_to = django_settings.LOGIN_REDIRECT_URL redirect_to = base64.urlsafe_b64encode(redirect_to.encode()).decode() query = ...
This function returns the ADFS authorization URL. Args: request(django.http.request.HttpRequest): A django Request object disable_sso(bool): Whether to disable single sign-on and force the ADFS server to show a login prompt. Returns: str: The redirect URI
codesearchnet
def interceptable(func): @functools.wraps(func) def func_wrapped(*args, **kwargs): with get_next_interceptor() as interceptor: return interceptor(func, *args, **kwargs) return func_wrapped
Decorator that wraps `func` so that its execution is intercepted. The wrapper passes `func` to the interceptor for the current thread. If there is no next interceptor, we perform an "immediate" call to `func`. That is, `func` terminates without forwarding its execution to another interceptor. Args: func: Function to...
codesearchnet
def dirac_notation(state: Sequence, decimals: int=2) -> str: perm_list = [''.join(seq) for seq in itertools.product('01', repeat=(int(len(state)).bit_length() - 1))] components = [] ket = '|{}⟩' for x in range(len(perm_list)): format_str = (('({:.' + str(decimals)) + 'g})') val = (round(...
Returns the wavefunction as a string in Dirac notation. For example: state = np.array([1/np.sqrt(2), 1/np.sqrt(2)], dtype=np.complex64) print(dirac_notation(state)) -> 0.71|0⟩ + 0.71|1⟩ Args: state: A sequence representing a wave function in which the ordering mapping to qubits follows the standard Kronecker convent...
codesearchnet
def _recreate(self, proto, node_id, nodes): registered_class = registration.get_registered_class(proto.registered_name) if registered_class is None: registered_class = _BUILT_IN_REGISTRATIONS.get(proto.WhichOneof('kind')) dependencies = {} for key, dep_node_id in self._get_node_dependencies(prot...
Creates a Python object from a SavedObject protocol buffer. Args: proto: a SavedObject proto node_id: int, the index of this object in the SavedObjectGraph node list. nodes: dict mapping int node_ids -> created objects. Returns: The recreated object, and the set-attribute function for reconnecting the trackable child...
github-repos
def import_module(self, module=None, recursive=False, **params): if module is None: if "module_" in params: warnings.warn( "Parameter 'module_' is deprecated. Use 'module' instead.") module = params.pop("module_") else: ...
Create a child space from an module. Args: module: a module object or name of the module object. recursive: Not yet implemented. **params: arguments to pass to ``new_space`` Returns: The new child space created from the module.
juraj-google-style
def transform_data(input_handle, outfile_prefix, working_dir, schema_file, transform_dir=None, max_rows=None, pipeline_args=None, publish_to_bq=False, project=None, metrics_table=None, metrics_dataset=None): def preprocessing_fn(inputs): outputs = {} for key in taxi.DENSE_FLOAT_FEATURE_KEY...
The main tf.transform method which analyzes and transforms data. Args: input_handle: BigQuery table name to process specified as DATASET.TABLE or path to csv file with input data. outfile_prefix: Filename prefix for emitted transformed examples working_dir: Directory in which transformed examples and transform functio...
github-repos
def main(raw_args=None): multifile_choices = frozenset(['c_files']) if (raw_args is None): raw_args = sys.argv[1:] parser = build_parser() args = parser.parse_args(raw_args) if ((args.output is None) and (args.format in multifile_choices)): print(('You must specify an output file wit...
Run the iotile-tbcompile script. Args: raw_args (list): Optional list of command line arguments. If not passed these are pulled from sys.argv.
codesearchnet
def __init__(self, iterable): if not is_iterable(iterable): raise TypeError("Cannot construct Queryable from non-iterable {0}" .format(str(type(iterable))[7: -2])) self._iterable = iterable
Construct a Queryable from any iterable. Args: iterable: Any object supporting the iterator protocol. Raises: TypeError: if iterable does not support the iterator protocol.
juraj-google-style
def binary_mask_to_rle(mask): if is_torch_tensor(mask): mask = mask.numpy() pixels = mask.flatten() pixels = np.concatenate([[0], pixels, [0]]) runs = np.where(pixels[1:] != pixels[:-1])[0] + 1 runs[1::2] -= runs[::2] return list(runs)
Converts given binary mask of shape `(height, width)` to the run-length encoding (RLE) format. Args: mask (`torch.Tensor` or `numpy.array`): A binary mask tensor of shape `(height, width)` where 0 denotes background and 1 denotes the target segment_id or class_id. Returns: `List`: Run-length encoded list of the binary...
github-repos
def parse(self, filename): filehandle = storage.open_vos_or_local(filename, 'rb') assert (filehandle is not None), 'Failed to open file {} '.format(filename) filestr = filehandle.read() filehandle.close() assert (filestr is not None), 'File contents are None' observations = self._parse_observati...
Parses a file into an AstromData structure. Args: filename: str The name of the file whose contents will be parsed. Returns: data: AstromData The file contents extracted into a data structure for programmatic access.
codesearchnet
def poll_error(self): if self.block: return self.error new_list = self.error[self.old_error_size:] self.old_error_size += len(new_list) return new_list
Append lines from stderr to self.errors. Returns: list: The lines added since last call
codesearchnet
def create_run_config(hp, output_dir=None): save_ckpt_steps = max(FLAGS.iterations_per_loop, FLAGS.local_eval_frequency) save_ckpt_secs = FLAGS.save_checkpoints_secs or None if save_ckpt_secs: save_ckpt_steps = None assert FLAGS.output_dir or FLAGS.checkpoint_path tpu_config_extra_kwargs = {} if FLAG...
Create a run config. Args: hp: model hyperparameters output_dir: model's output directory, defaults to output_dir flag. Returns: a run config
juraj-google-style
def get_operation(self, name, options=None): request = operations_pb2.GetOperationRequest(name=name) return self._get_operation(request, options)
Gets the latest state of a long-running operation. Clients can use this method to poll the operation result at intervals as recommended by the API service. Example: >>> from google.gapic.longrunning import operations_client >>> api = operations_client.OperationsClient() >>> name = '' >>> response = api.get_operation(...
codesearchnet
def _parse_address(self, config): match = re.search(r'ip address ([^\s]+)', config) value = match.group(1) if match else None return dict(address=value)
Parses the config block and returns the ip address value The provided configuration block is scaned and the configured value for the IP address is returned as a dict object. If the IP address value is not configured, then None is returned for the value Args: config (str): The interface configuration block to parse ...
juraj-google-style
def getsource(classorfunc): if _isbuiltin(classorfunc): return '' try: source = inspect.getsource(classorfunc) except TypeError: source = getsourcefallback(classorfunc) declaration = [] lines = source.splitlines() if PY2 and not isinstance(source, unicode): ...
Return the source code for a class or function. Notes: Returned source will not include any decorators for the object. This will only return the explicit declaration of the object, not any dependencies Args: classorfunc (type or function): the object to get the source code for Returns: str: text of source code (with...
juraj-google-style
def __call__(self, shape, dtype, axis=0): raise NotImplementedError
Partitions the given `shape` and returns the partition results. Examples of a partitioner that allocates a fixed number of shards: ```python partitioner = FixedShardsPartitioner(num_shards=2) partitions = partitioner(tf.TensorShape([10, 3], tf.float32), axis=0) print(partitions) # [2, 0] ``` Args: shape: a `tf.Tenso...
github-repos
def _unknown_args(self, args): for u in args: self.tcex.log.warning(u'Unsupported arg found ({}).'.format(u))
Log argparser unknown arguments. Args: args (list): List of unknown arguments
codesearchnet
def extract_table(tabletag): theadtag = tabletag.find_next('thead') headertags = theadtag.find_all('th') if len(headertags) == 0: headertags = theadtag.find_all('td') headers = [] for tag in headertags: headers.append(get_text(tag)) tbodytag = tabletag.find_next('tbod...
Extract HTML table as list of dictionaries Args: tabletag (Tag): BeautifulSoup tag Returns: str: Text of tag stripped of leading and trailing whitespace and newlines and with &nbsp replaced with space
juraj-google-style
def get_sharded_shape(self, shape, shard_index=None): if self._shard_dimension is None or self._number_of_shards is None: return None if shard_index is not None: if shard_index < 0 or shard_index >= self.number_of_shards: raise ValueError(f'Requested shard_index {shard_index}, but sh...
Returns the shape of a shard of a full Tensor. When given the shape of a 'full-size' Tensor, returns the shape of the sub-Tensor after it has been sharded. Freezes the policy if it has not yet been frozen. Args: shape: The shape of the full-size Tensor to be sharded. shard_index: The index of the shard whose shape sh...
github-repos
def add(self, data, conn_type, squash=True): if (data in self.children): return data if (not squash): self.children.append(data) return data if (self.connector == conn_type): if (isinstance(data, QBase) and (not data.negated) and ((data.connector == conn_type) or (len(data) =...
Combine this tree and the data represented by data using the connector conn_type. The combine is done by squashing the node other away if possible. This tree (self) will never be pushed to a child node of the combined tree, nor will the connector or negated properties change. Return a node which can be used in place ...
codesearchnet
def adversary(self, name, owner=None, **kwargs): return Adversary(self.tcex, name, owner=owner, **kwargs)
Create the Adversary TI object. Args: owner: name: **kwargs: Return:
juraj-google-style
def slh_associate(a_features, b_features, max_sigma=5): proximity = _weighted_proximity(a_features, b_features) association_matrix = _proximity_to_association(proximity) associations = [] if (association_matrix.shape[0] == 0): return np.zeros((0, 2)) col_max_idxs = np.argmax(association_matr...
An implementation of the Scott and Longuet-Higgins algorithm for feature association. This function takes two lists of features. Each feature is a :py:class:`MultivariateNormal` instance representing a feature location and its associated uncertainty. Args: a_features (list of MultivariateNormal) b_features (list of M...
codesearchnet
async def warn_user(channel, user): data = datatools.get_data() server_id = channel.server.id if "warnings_max" not in data["discord"]["servers"][server_id][_data.modulename]: data["discord"]["servers"][server_id][_data.modulename]["warnings_max"] = 3 if "warnings" not in data["discord"][...
Gives a user a warning, and bans them if they are over the maximum warnings Args: channel: The channel to send the warning message in user: The user to give the warning to
juraj-google-style
def broadcast_implementation(self, tensor, destinations): return simple_broadcast(tensor, destinations, always_mirrored=True, canonicalize_devices=self._canonicalize_devices)
Implementation of `broadcast`. Args: tensor: a `tf.Tensor` like object. The value to broadcast. destinations: a `tf.distribute.DistributedValues`, a `tf.Variable`, a `tf.Tensor` alike object, or a device string. It specifies the devices to broadcast to. `destinations`. Note that if it's a `tf.Variable`, the value is b...
github-repos
def get_version(): sys.modules['setup_helpers'] = object() sys.modules['setup_helpers_macos'] = object() sys.modules['setup_helpers_windows'] = object() filename = os.path.join(_ROOT_DIR, 'setup.py') loader = importlib.machinery.SourceFileLoader('setup', filename) setup_mod = loader.load_module(...
Get the current version from ``setup.py``. Assumes that importing ``setup.py`` will have no side-effects (i.e. assumes the behavior is guarded by ``if __name__ == "__main__"``). Returns: str: The current version in ``setup.py``.
codesearchnet
def WriteGraphExecutionTrace(self, graph_execution_trace): debug_event = debug_event_pb2.DebugEvent(graph_execution_trace=graph_execution_trace) self._EnsureTimestampAdded(debug_event) _pywrap_debug_events_writer.WriteGraphExecutionTrace(self._dump_root, debug_event)
Write a GraphExecutionTrace proto with the writer. Args: graph_execution_trace: A GraphExecutionTrace proto, concerning the value of an intermediate tensor or a list of intermediate tensors that are computed during the graph's execution.
github-repos
def _EscapeGlobCharacters(path): drive, path = os.path.splitdrive(path) return '%s%s' % (drive, _ESCAPE_GLOB_CHARACTERS_REGEX.sub(r'[\1]', path))
Escapes the glob characters in a path. Python 3 has a glob.escape method, but python 2 lacks it, so we manually implement this method. Args: path: The absolute path to escape. Returns: The escaped path string.
juraj-google-style
def merge_translations(localization_bundle_path): logging.info("Merging translations") for lang_dir in os.listdir(localization_bundle_path): if lang_dir == DEFAULT_LANGUAGE_DIRECTORY_NAME: continue for translated_path in glob.glob(os.path.join(localization_bundle_path, lang_dir,...
Merges the new translation with the old one. The translated files are saved as '.translated' file, and are merged with old translated file. Args: localization_bundle_path (str): The path to the localization bundle.
juraj-google-style
def prepend(self, node): if (not isinstance(node, grammar.STATEMENTS)): raise ValueError self.to_prepend[(- 1)].appendleft(node)
Prepend a statement to the current statement. Note that multiple calls to prepend will result in the last statement to be prepended to end up at the top. Args: node: The statement to prepend. Raises: ValueError: If the given node is not a statement.
codesearchnet
class Idefics3Encoder(nn.Module): def __init__(self, config: Idefics3Config): super().__init__() self.config = config self.layers = nn.ModuleList([Idefics3EncoderLayer(config) for _ in range(config.num_hidden_layers)]) self.gradient_checkpointing = False def forward(self, input...
Transformer encoder consisting of `config.num_hidden_layers` self attention layers. Each layer is a [`Idefics3EncoderLayer`]. Args: config: Idefics3Config
github-repos
def from_dict(cls, data): try: fulfillment = _fulfillment_from_details(data['condition']['details']) except KeyError: fulfillment = data['condition']['uri'] try: amount = int(data['amount']) except ValueError: raise AmountError(('Invalid amount: %s' % data['amount'])) ...
Transforms a Python dictionary to an Output object. Note: To pass a serialization cycle multiple times, a Cryptoconditions Fulfillment needs to be present in the passed-in dictionary, as Condition URIs are not serializable anymore. Args: data (dict): The dict to be transformed. Returns: :class:`~bigchaindb.common.tr...
codesearchnet
def _call_post_with_session(self, url, payload): now = datetime.datetime.utcnow() if (now >= self.expires_at): self.session.close() self._create_session() response = self.session.post(url, data=payload) return (response.status_code, response.text)
Make a post request using the session object to a SuccessFactors endpoint. Args: url (str): The url to post to. payload (str): The json encoded payload to post.
codesearchnet
def copy_script(self, filename, id_=(- 1)): if (('jss' in self.connection.keys()) and self.connection['jss'].jss_migrated): self._copy_script_migrated(filename, id_, SCRIPT_FILE_TYPE) else: basename = os.path.basename(filename) self._copy(filename, os.path.join(self.connection['mount_poi...
Copy a script to the repo's Script subdirectory. Scripts are copied as files to a path, or, on a "migrated" JSS, are POSTed to the JSS (pass an id if you wish to associate the script with an existing Script object). Args: filename: Path for file to copy. id_: Int ID, used _only_ for migrated repos. Default is -1, whi...
codesearchnet
def is_single_tree(data_wrapper): db = data_wrapper.data_block bad_ids = db[(db[(:, COLS.P)] == (- 1))][(1:, COLS.ID)] return CheckResult((len(bad_ids) == 0), bad_ids.tolist())
Check that data forms a single tree Only the first point has ID of -1. Returns: CheckResult with result and list of IDs Note: This assumes no_missing_parents passed.
codesearchnet
def extract_ranges(index_list, range_size_limit=32): if (not index_list): return ([], []) first = index_list[0] last = first ranges = [] singles = [] for i in index_list[1:]: if ((i == (last + 1)) and ((last - first) <= range_size_limit)): last = i else: ...
Extract consecutive ranges and singles from index_list. Args: index_list: List of monotone increasing non-negative integers. range_size_limit: Largest size range to return. If a larger consecutive range exists it will be returned as multiple ranges. Returns: ranges, singles where ranges is a list of [first, last] pa...
codesearchnet
def __init__(self, logger=None, timeout=60): self.etag = 0 self.logger = logger or logging self.timeout = timeout
Constructor. Args: logger: logger object, used to write to SysLog and serial port. timeout: int, timeout in seconds for metadata requests.
juraj-google-style