code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def publish(msg="checkpoint: publish package"): test = check() if test.succeeded: sdist = local("python setup.py sdist") if sdist.succeeded: build = local( 'python setup.py build && python setup.py bdist_egg') if build.succeeded: ...
Deploy the app to PYPI. Args: msg (str, optional): Description
juraj-google-style
def forward(self, hidden_states: torch.Tensor, position_embeddings: Optional[torch.Tensor]=None, reference_points=None, spatial_shapes=None, level_start_index=None, encoder_hidden_states: Optional[torch.Tensor]=None, encoder_attention_mask: Optional[torch.Tensor]=None, output_attentions: Optional[bool]=False): resi...
Args: hidden_states (`torch.FloatTensor`): Input to the layer of shape `(batch, seq_len, embed_dim)`. position_embeddings (`torch.FloatTensor`, *optional*): Position embeddings that are added to the queries and keys in the self-attention layer. reference_points (`torch.FloatTensor`, *optional*): Reference points. spati...
github-repos
def get_model_indexes(model): indexes = [] for index in get_index_names(): for app_model in get_index_models(index): if (app_model == model): indexes.append(index) return indexes
Return list of all indexes in which a model is configured. A model may be configured to appear in multiple indexes. This function will return the names of the indexes as a list of strings. This is useful if you want to know which indexes need updating when a model is saved. Args: model: a Django model class.
codesearchnet
def _add_row_partitions(self, flat_values, validate=False): if self.row_partitions: if validate: flat_values = self._validate_flat_values(flat_values) return ragged_tensor.RaggedTensor._from_nested_row_partitions(flat_values, self.row_partitions, validate=False) else: return ...
Add row partitions to flat_values, if necessary. If the shape is truly ragged, then this adds the row_partitions. The shape is dense, then this just returns flat_values. Args: flat_values: the flat_values of a ragged tensor with this shape, or a dense tensor with this shape. validate: validate the flat_values have t...
github-repos
def symbol_top(body_output, targets, model_hparams, vocab_size): del targets if model_hparams.shared_embedding_and_softmax_weights: scope_name = "shared" reuse = tf.AUTO_REUSE else: scope_name = "softmax" reuse = False with tf.variable_scope(scope_name, reuse=reuse): body_output_shape =...
Generate logits. Args: body_output: A Tensor with shape [batch, p0, p1, model_hparams.hidden_size]. targets: Unused. model_hparams: HParams, model hyperparmeters. vocab_size: int, vocabulary size. Returns: logits: A Tensor with shape [batch, p0, p1, ?, vocab_size].
juraj-google-style
def _get_event_id(object_type: str) -> str: key = _keys.event_counter(object_type) DB.watch(key, pipeline=True) count = DB.get_value(key) DB.increment(key) DB.execute() if count is None: count = 0 return '{}_event_{:08d}'.format(object_type, int(count))
Return an event key for the event on the object type. This must be a unique event id for the object. Args: object_type (str): Type of object Returns: str, event id
juraj-google-style
def convert(self, point): (x, y) = point (x1, y1) = ((x - self.x_offset), (y - self.y_offset)) logger.debug('converted {} {} ==> {} {}'.format(x, y, x1, y1)) return (x1, y1)
Convert a point from one coordinate system to another. Args: point: tuple(int x, int y) The point in the original coordinate system. Returns: converted_point: tuple(int x, int y) The point in the new coordinate system. Example: convert coordinate from original image into a pixel location within a cutout image. @rty...
codesearchnet
def users_setPresence(self, *, presence: str, **kwargs) -> SlackResponse: kwargs.update({"presence": presence}) return self.api_call("users.setPresence", json=kwargs)
Manually sets user presence. Args: presence (str): Either 'auto' or 'away'.
juraj-google-style
def convert_relu(params, w_name, scope_name, inputs, layers, weights, names): print('Converting relu ...') if names == 'short': tf_name = 'RELU' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) relu = keras.layers....
Convert relu layer. Args: params: dictionary with layer parameters w_name: name prefix in state_dict scope_name: pytorch scope name inputs: pytorch node inputs layers: dictionary with keras tensors weights: pytorch state_dict names: use short names for keras layers
juraj-google-style
def aggregate_and_return_name_for_input(self, out_graphdef): flattened = self.flatten_nodes() if self.aggregation == OpHint.AGGREGATE_FIRST or self.aggregation == OpHint.AGGREGATE_LAST: assert len(flattened) == 1 if len(flattened) == 1 and self.aggregation != OpHint.AGGREGATE_STACK: return _...
This adds the nodes to out_graphdef and returns an aggregated output. In particular, if you have 4 inputs to a hint stub, this will be the node that you can use as an output. I.e. you have 4 timesteps from a static rnn, then a fused UnidirectionalLSTM will expect 1 input with all 4 time steps. So here we make a pack a...
github-repos
def get(self, name): return self.prepare_model(self.client.api.inspect_image(name))
Gets an image. Args: name (str): The name of the image. Returns: (:py:class:`Image`): The image. Raises: :py:class:`docker.errors.ImageNotFound` If the image does not exist. :py:class:`docker.errors.APIError` If the server returns an error.
codesearchnet
def _parse_rd(self, config): match = RD_RE.search(config) if match: value = match.group('value') else: value = match return dict(rd=value)
_parse_rd scans the provided configuration block and extracts the vrf rd. The return dict is intended to be merged into the response dict. Args: config (str): The vrf configuration block from the nodes running configuration Returns: dict: resource dict attribute
juraj-google-style
def _build_mac_signature_key_information(self, value): if (value is None): return None if (not isinstance(value, dict)): raise TypeError('MAC/signature key information must be a dictionary.') cryptographic_parameters = value.get('cryptographic_parameters') if cryptographic_parameters: ...
Build an MACSignatureKeyInformation struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a MACSignatureKeyInformation struct. Returns: MACSignatureInformation: a MACSignatureKeyInformation struct Raises: TypeError: if the input argument is invalid
codesearchnet
def prefix(self, imod: YangIdentifier, mid: ModuleId) -> YangIdentifier: try: did = (imod, self.implement[imod]) except KeyError: raise ModuleNotImplemented(imod) from None try: pmap = self.modules[mid].prefix_map except KeyError: raise ModuleNotRegistered(*mid) from None...
Return the prefix corresponding to an implemented module. Args: imod: Name of an implemented module. mid: Identifier of the context module. Raises: ModuleNotImplemented: If `imod` is not implemented. ModuleNotRegistered: If `mid` is not registered in YANG library. ModuleNotImported: If `imod` is not imported in `mid`...
codesearchnet
def delete(self, key): path = self.object_path(key) if os.path.exists(path): os.remove(path)
Removes the object named by `key`. Args: key: Key naming the object to remove.
juraj-google-style
def _import_and_bind(self, imp): with self.block.alloc_temp() as mod, \ self.block.alloc_temp('[]*πg.Object') as mod_slice: self.writer.write_checked_call2( mod_slice, 'πg.ImportModule(πF, {})', util.go_str(imp.name)) for binding in imp.bindings: if bindi...
Generates code that imports a module and binds it to a variable. Args: imp: Import object representing an import of the form "import x.y.z" or "from x.y import z". Expects only a single binding.
juraj-google-style
def from_comm(cls, pub): filename = None if pub.b64_data: filename = cls._save_to_unique_filename(pub) return cls( title=pub.title, author=pub.author, pub_year=pub.pub_year, isbn=pub.isbn, urnnbn=pub.urnnbn, ...
Convert communication namedtuple to this class. Args: pub (obj): :class:`.Publication` instance which will be converted. Returns: obj: :class:`DBPublication` instance.
juraj-google-style
async def setup_round_robin_points(self, match_win: float = None, match_tie: float = None, game_win: float = None, game_tie: float = None): params = {} if match_win is not None: params['rr_pts_for_match_win'] = match_win if match_win is not None: params['rr_pts_f...
|methcoro| Args: match_win match_tie game_win game_tie Raises: APIException
juraj-google-style
def value_instance_to_pytd_type(self, node, v, instance, seen, view): if abstract_utils.is_recursive_annotation(v): return pytd.LateType(v.unflatten_expr() if self._detailed else v.expr) elif isinstance(v, abstract.Union): return pytd.UnionType(tuple((self.value_instance_to_pytd_type(node, t, in...
Get the PyTD type an instance of this object would have. Args: node: The node. v: The object. instance: The instance. seen: Already seen instances. view: A Variable -> binding map. Returns: A PyTD type.
github-repos
def bresenham(x1, y1, x2, y2): points = [] issteep = (abs((y2 - y1)) > abs((x2 - x1))) if issteep: (x1, y1) = (y1, x1) (x2, y2) = (y2, x2) rev = False if (x1 > x2): (x1, x2) = (x2, x1) (y1, y2) = (y2, y1) rev = True deltax = (x2 - x1) deltay = abs((y2 ...
Return a list of points in a bresenham line. Implementation hastily copied from RogueBasin. Returns: List[Tuple[int, int]]: A list of (x, y) points, including both the start and end-points.
codesearchnet
def ping(self, url, endpoint=''): r = self.get_url(url + "/" + endpoint) return r.status_code
Ping the server to make sure that you can access the base URL. Arguments: None Returns: `boolean` Successful access of server (or status code)
juraj-google-style
def _AddDSATargeting(client, ad_group_id, label_name): ad_group_criterion_service = client.GetService('AdGroupCriterionService', version='v201809') operation = { 'operand': { 'xsi_type': 'BiddableAdGroupCriterion', 'adGroupId': ad_...
Set custom targeting for the page feed URLs based on a list of labels. Args: client: an AdWordsClient instance. ad_group_id: a str AdGroup ID. label_name: a str label name. Returns: A suds.sudsobject.Object representing the newly created webpage criterion.
juraj-google-style
def DeregisterSourceType(cls, source_type_class): if source_type_class.TYPE_INDICATOR not in cls._source_type_classes: raise KeyError( 'Source type not set for type: {0:s}.'.format( source_type_class.TYPE_INDICATOR)) del cls._source_type_classes[source_type_class.TYPE_INDICAT...
Deregisters a source type. Source types are identified based on their type indicator. Args: source_type_class (type): source type. Raises: KeyError: if a source type is not set for the corresponding type indicator.
juraj-google-style
def GetDataByPath(self, path): (_, path_data) = self._paths.get(path, (None, None)) return path_data
Retrieves the data associated to a path. Args: path (str): path of the file entry. Returns: bytes: data or None if not available.
codesearchnet
def on_modified(self, event): if (not self._event_error): self.logger.info(u'Change detected from an edit on: %s', event.src_path) self.compile_dependencies(event.src_path)
Called when a file or directory is modified. Args: event: Watchdog event, ``watchdog.events.DirModifiedEvent`` or ``watchdog.events.FileModifiedEvent``.
codesearchnet
def skip(self, count=1): if self.closed(): raise ValueError('Attempt to call skip() on a closed Queryable.') count = max(0, count) if (count == 0): return self if hasattr(self._iterable, '__getitem__'): try: stop = len(self._iterable) return self._create(s...
Skip the first count contiguous elements of the source sequence. If the source sequence contains fewer than count elements returns an empty sequence and does not raise an exception. Note: This method uses deferred execution. Args: count: The number of elements to skip from the beginning of the sequence. If omitted d...
codesearchnet
def enum(cls): assert cls.__bases__ == (object,) d = dict(cls.__dict__) new_type = type(cls.__name__, (int,), d) new_type.__module__ = cls.__module__ map_ = {} for key, value in iteritems(d): if key.upper() == key and isinstance(value, integer_types): value_instance =...
A decorator for creating an int enum class. Makes the values a subclass of the type and implements repr/str. The new class will be a subclass of int. Args: cls (type): The class to convert to an enum Returns: type: A new class :: @enum class Foo(object): FOO = 1 BAR = 2
juraj-google-style
def _callable_func(self, func, axis, *args, **kwargs): def callable_apply_builder(df, axis=0): if not axis: df.index = index df.columns = pandas.RangeIndex(len(df.columns)) else: df.columns = index df.index = panda...
Apply callable functions across given axis. Args: func: The functions to apply. axis: Target axis to apply the function along. Returns: A new PandasQueryCompiler.
juraj-google-style
def _read_hopopt_options(self, length): counter = 0 optkind = list() options = dict() while (counter < length): code = self._read_unpack(1) if (not code): break (abbr, desc) = _HOPOPT_OPT.get(code, ('none', 'Unassigned')) data = _HOPOPT_PROC(abbr)(self, code, ...
Read HOPOPT options. Positional arguments: * length -- int, length of options Returns: * dict -- extracted HOPOPT options
codesearchnet
def bench(image, thread_count): threads = [threading.Thread(target=(lambda : encoder.encode_png(image))) for _ in xrange(thread_count)] start_time = datetime.datetime.now() for thread in threads: thread.start() for thread in threads: thread.join() end_time = datetime.datetime.now() ...
Encode `image` to PNG on `thread_count` threads in parallel. Returns: A `float` representing number of seconds that it takes all threads to finish encoding `image`.
codesearchnet
def _get_manager(cluster_info, host, executor_id): for node in cluster_info: if node['host'] == host and node['executor_id'] == executor_id: addr = node['addr'] authkey = node['authkey'] TFSparkNode.mgr = TFManager.connect(addr, authkey) break if TFSparkNode.mgr is None: msg = "N...
Returns this executor's "singleton" instance of the multiprocessing.Manager, reconnecting per python-worker if needed. Args: :cluster_info: cluster node reservations :host: host IP address :executor_id: unique id per executor (created during initial call to run()) Returns: TFManager instance for this executor/python-...
juraj-google-style
def output_mask(self): output = self.output if isinstance(output, list): return [getattr(x, '_keras_mask', None) for x in output] else: return getattr(output, '_keras_mask', None)
Retrieves the output mask tensor(s) of a layer. Only applicable if the layer has exactly one inbound node, i.e. if it is connected to one incoming layer. Returns: Output mask tensor (potentially None) or list of output mask tensors. Raises: AttributeError: if the layer is connected to more than one incoming layers.
github-repos
def _get_config_instance(group_or_term, session, **kwargs): path = group_or_term._get_path() cached = group_or_term._top._cached_configs.get(path) if cached: config = cached created = False else: config, created = get_or_create(session, Config, **kwargs) return ...
Finds appropriate config instance and returns it. Args: group_or_term (Group or Term): session (Sqlalchemy session): kwargs (dict): kwargs to pass to get_or_create. Returns: tuple of (Config, bool):
juraj-google-style
def __init__(self, conf_path=ZEO_CLIENT_PATH, project_key=PROJECT_KEY): super(self.__class__, self).__init__( conf_path=conf_path, project_key=project_key ) self.name_db_key = "name_db" self.name_db = self._get_key_or_create(self.name_db_key) ...
Constructor. Args: conf_path (str): Path to the ZEO configuration file. Default :attr:`~storage.settings.ZEO_CLIENT_PATH`. project_key (str): Project key, which is used for lookups into ZEO. Default :attr:`~storage.settings.TREE_PROJECT_KEY`.
juraj-google-style
def _get_connection(self, conn_or_int_id): key = conn_or_int_id if isinstance(key, str): table = self._int_connections elif isinstance(key, int): table = self._connections else: return None try: data = table[key] except KeyError: return None return dat...
Get the data for a connection by either conn_id or internal_id Args: conn_or_int_id (int, string): The external integer connection id or and internal string connection id Returns: dict: The context data associated with that connection or None if it cannot be found. Raises: ArgumentError: When the key is not found in...
codesearchnet
def WriteTimestamp(timestamp, filename): if timestamp is None: return True timestamp_dir = os.path.dirname(filename) filedesc, temp_filename = tempfile.mkstemp(prefix='nsscache-update-', dir=timestamp_dir) time_string = time.strftime('%Y-%m-%dT%H:%M:%SZ', timestamp) try: os.write(fil...
Write a given timestamp out to a file, converting to the ISO-8601 format. We convert internal timestamp format (epoch) to ISO-8601 format, i.e. YYYY-MM-DDThh:mm:ssZ which is basically UTC time, then write it out to a file. Args: timestamp: A struct time.struct_time or time tuple. filename: A String naming the file to...
github-repos
def finish(self, end='\n', dirty=False): if not dirty: self.end_time = datetime.now() self.update(self.max_value, force=True) StdRedirectMixin.finish(self, end=end) ResizableMixin.finish(self) ProgressBarBase.finish(self)
Puts the ProgressBar bar in the finished state. Also flushes and disables output buffering if this was the last progressbar running. Args: end (str): The string to end the progressbar with, defaults to a newline dirty (bool): When True the progressbar kept the current state and won't be set to 100 percent
juraj-google-style
def _init_from_args(self, queue=None, enqueue_ops=None, close_op=None, cancel_op=None, queue_closed_exception_types=None): if not queue or not enqueue_ops: raise ValueError('Must provide queue and enqueue_ops.') self._queue = queue self._enqueue_ops = enqueue_ops self._close_op = close_op se...
Create a QueueRunner from arguments. Args: queue: A `Queue`. enqueue_ops: List of enqueue ops to run in threads later. close_op: Op to close the queue. Pending enqueue ops are preserved. cancel_op: Op to close the queue and cancel pending enqueue ops. queue_closed_exception_types: Tuple of exception types, which indic...
github-repos
def _get_python_exe_version(python_exe: list[str]): try: python_exe_version = subprocess.check_output(python_exe + ['-V'], stderr=subprocess.STDOUT).decode() except (subprocess.CalledProcessError, FileNotFoundError): return None return _parse_exe_version_string(python_exe_version)
Determine the major and minor version of given Python executable. Arguments: python_exe: absolute path to the Python executable Returns: Version as (major, minor) tuple, or None if it could not be determined.
github-repos
def add(self, term): if isinstance(term, Conjunction): for term_ in term.terms: self.add(term_) elif isinstance(term, Term): self._terms.append(term) else: raise TypeError('Not a Term or Conjunction')
Add a term to the conjunction. Args: term (:class:`Term`, :class:`Conjunction`): term to add; if a :class:`Conjunction`, all of its terms are added to the current conjunction. Raises: :class:`TypeError`: when *term* is an invalid type
juraj-google-style
def delete(self, *names: str, pipeline=False): if pipeline: self._pipeline.delete(*names) else: self._db.delete(*names)
Delete one or more keys specified by names. Args: names (str): Names of keys to delete pipeline (bool): True, start a transaction block. Default false.
codesearchnet
def _extract_cell_info(self, structure, site_idx, sites, targets, voro, compute_adj_neighbors=False): all_vertices = voro.vertices center_coords = sites[site_idx].coords results = {} for (nn, vind) in voro.ridge_dict.items(): if (site_idx in nn): other_site = (nn[0] if (nn[1] == site...
Get the information about a certain atom from the results of a tessellation Args: structure (Structure) - Structure being assessed site_idx (int) - Index of the atom in question sites ([Site]) - List of all sites in the tessellation targets ([Element]) - Target elements voro - Output of qvoronoi compute_adj_neighbors ...
codesearchnet
def is_http_running_on(port): try: conn = httplib.HTTPConnection(('127.0.0.1:' + str(port))) conn.connect() conn.close() return True except Exception: return False
Check if an http server runs on a given port. Args: The port to check. Returns: True if it is used by an http server. False otherwise.
codesearchnet
def _to_dict(self, include=None, exclude=None): if (include is not None and not isinstance(include, (list, tuple, set, frozenset))): raise TypeError('include should be a list, tuple or set') if (exclude is not None and not isinstance(exclude, (list, tuple, set, frozenset))): rai...
Return a dict containing the entity's property values. Args: include: Optional set of property names to include, default all. exclude: Optional set of property names to skip, default none. A name contained in both include and exclude is excluded.
juraj-google-style
def append_transformed_structures(self, tstructs_or_transmuter): if isinstance(tstructs_or_transmuter, self.__class__): self.transformed_structures.extend(tstructs_or_transmuter.transformed_structures) else: for ts in tstructs_or_transmuter: assert isinstance(ts, TransformedStructure...
Method is overloaded to accept either a list of transformed structures or transmuter, it which case it appends the second transmuter"s structures. Args: tstructs_or_transmuter: A list of transformed structures or a transmuter.
codesearchnet
async def peers(self): response = (await self._api.get('/v1/status/peers')) if (response.status == 200): return set(response.body)
Returns the current Raft peer set Returns: Collection: addresses of peers This endpoint retrieves the Raft peers for the datacenter in which the agent is running. It returns a collection of addresses, such as:: [ "10.1.10.12:8300", "10.1.10.11:8300", "10.1.10.10:8300" ] This list of peers is strongly consistent and...
codesearchnet
def ensemble_center(self, site_list, indices, cartesian=True): if cartesian: return np.average([site_list[i].coords for i in indices], axis=0) else: return np.average([site_list[i].frac_coords for i in indices], axis=0)
Finds the center of an ensemble of sites selected from a list of sites. Helper method for the find_adsorption_sites algorithm. Args: site_list (list of sites): list of sites indices (list of ints): list of ints from which to select sites from site list cartesian (bool): whether to get average fractional or cartesian ...
codesearchnet
def scale_vmss(access_token, subscription_id, resource_group, vmss_name, capacity): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachine...
Change the instance count of an existing VM Scale Set. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vmss_name (str): Name of the virtual machine scale set. capacity (int): New number of VMs. Returns: HTTP re...
juraj-google-style
def _make_output_composite_tensors_match(op_type, branch_graphs): assert branch_graphs branch_outputs = [g.structured_outputs for g in branch_graphs] outputs_per_branch = list((len(outs) for outs in branch_outputs)) assert len(set(outputs_per_branch)) == 1, outputs_per_branch for output_idx, branch_...
Modifies each branch_graph's outputs to have the same output signature. Currently the only transformation implemented is turning a Tensor into an equivalent IndexedSlices if the other branch returns an IndexedSlices. Updates branch_graph.{outputs,structured_outputs} for each branch_graph in branch_graphs. Args: op_ty...
github-repos
def get_arrays(self, type_img): if (type_img.lower() == 'lola'): return LolaMap(self.ppdlola, *self.window, path_pdsfile=self.path_pdsfiles).image() elif (type_img.lower() == 'wac'): return WacMap(self.ppdwac, *self.window, path_pdsfile=self.path_pdsfiles).image() else: raise ValueEr...
Return arrays the region of interest Args: type_img (str): Either lola or wac. Returns: A tupple of three arrays ``(X,Y,Z)`` with ``X`` contains the longitudes, ``Y`` contains the latitude and ``Z`` the values extracted for the region of interest. Note: The argument has to be either lola or wac. Note case sensitive....
codesearchnet
def _validate_symbol_names(self) -> None: all_symbol_names = set(self._names) | set(self._names_v1) if self._api_name == TENSORFLOW_API_NAME: for subpackage in SUBPACKAGE_NAMESPACES: if any((n.startswith(subpackage) for n in all_symbol_names)): raise InvalidSymbolNameError('@...
Validate you are exporting symbols under an allowed package. We need to ensure things exported by tf_export, etc. export symbols under disjoint top-level package names. For TensorFlow, we check that it does not export anything under subpackage names used by components (keras, etc.). For each component, we check that...
github-repos
def add_resource(self, resource, *class_args, **class_kwargs): name = resource.__name__.lower() meta_resource = parse_docs(resource.__doc__, ["$shared"]) self.meta[name] = meta_resource shared = self.meta["$shared"].copy() shared.update(meta_resource.get("$shared", {})) ...
Add resource Parse resource and it's actions, route actions by naming rule. Args: resource: resource class class_args: class_args class_kwargs: class_kwargs
juraj-google-style
def _ParseInternetPasswordRecord(self, parser_mediator, record): key = record.get('_key_', None) if ((not key) or (not key.startswith(b'ssgp'))): raise errors.ParseError('Unsupported Internet password record key value does not start with: "ssgp".') protocol_string = codecs.decode('{0:08x}'.format(re...
Extracts the information from an Internet password record. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. record (dict[str, object]): database record. Raises: ParseError: if Internet password record cannot be parsed.
codesearchnet
def normal_mean(data, variance): if not isinstance(data, np.ndarray): data = np.array(data) i_variance_2 = 1 / (variance ** 2) cmm = [0.0] cmm.extend(np.cumsum(data)) cmm2 = [0.0] cmm2.extend(np.cumsum(np.abs(data))) def cost(start, end): cmm2_diff = cmm2[end...
Creates a segment cost function for a time series with a Normal distribution with changing mean Args: data (:obj:`list` of float): 1D time series data variance (float): variance Returns: function: Function with signature (int, int) -> float where the first arg is the starting index, and the second is the last arg. Ret...
juraj-google-style
def read_passwd_file(pass_file): with open(pass_file) as fin: passwd = fin.read().strip() return passwd
Read password from external file and retrun as string. The file should contain just single line. Prevents hard-coding password anywhere in this script. IMPORTANT! Password is stored as plain text! Do NOT use with your personal account!" Args: pass_file (str): /path/to/pass_file
codesearchnet
def tpu_core_ids_to_locations(self, tpu_core_ids): return _pywrap_dtensor_device.TPUCoreIDsToLocations(context.context()._handle, self._device_info, tpu_core_ids)
Translates TPU core IDs to TPU core locations. Args: tpu_core_ids: A list of TPU core IDs. Each one is an unsigned integer. Returns: A list of corresponding TPU core locations.
github-repos
def crossCombine(l): resultList = [] firstList = l[0] rest = l[1:] if (len(rest) == 0): return firstList for e in firstList: for e1 in crossCombine(rest): resultList.append(combinteDict(e, e1)) return resultList
Taken a list of lists, returns a big list of lists contain all the possibilities of elements of sublist combining together. It is basically a Combinatorics of list. For example: >>> crossCombine([[a,a1,a2,...], [b,b1,b2,...]]) >>> [[a,b], [a,b1], [a,b2], [a1,b], [a1,b1], [a1, b2], [a2,b], [a2,b1], [a2,b2], ...] For ...
codesearchnet
def __init__(self, retry_params, retriable_exceptions=_RETRIABLE_EXCEPTIONS, should_retry=lambda r: False): self.retry_params = retry_params self.retriable_exceptions = retriable_exceptions self.should_retry = should_retry
Init. Args: retry_params: an RetryParams instance. retriable_exceptions: a list of exception classes that are retriable. should_retry: a function that takes a result from the tasklet and returns a boolean. True if the result should be retried.
juraj-google-style
def get_task(config): path = os.path.join(config['work_dir'], "task.json") message = "Can't read task from {}!\n%(exc)s".format(path) contents = load_json_or_yaml(path, is_path=True, message=message) return contents
Read the task.json from work_dir. Args: config (dict): the running config, to find work_dir. Returns: dict: the contents of task.json Raises: ScriptWorkerTaskException: on error.
juraj-google-style
def member_command(self, member_id, command): server_id = self._servers.host_to_server_id( self.member_id_to_host(member_id)) return self._servers.command(server_id, command)
apply command (start/stop/restart) to member instance of replica set Args: member_id - member index command - string command (start/stop/restart) return True if operation success otherwise False
juraj-google-style
def make_preprocessing_fn(frequency_threshold): def preprocessing_fn(inputs): result = {'clicked': inputs['clicked']} for name in _INTEGER_COLUMN_NAMES: feature = inputs[name] feature = tft.sparse_tensor_to_dense_with_shape(feature, [None, 1], default_value=-1) ...
Creates a preprocessing function for criteo. Args: frequency_threshold: The frequency_threshold used when generating vocabularies for the categorical features. Returns: A preprocessing function.
github-repos
def __init__(self, format_string): try: struct_object = struct.Struct(format_string) except (TypeError, struct.error) as exception: raise errors.FormatError(( 'Unable to create struct object from data type definition ' 'with error: {0!s}').format(exception)) super(Struc...
Initializes a Python struct-base byte stream operation. Args: format_string (str): format string as used by Python struct. Raises: FormatError: if the struct operation cannot be determined from the data type definition.
juraj-google-style
def copy_and_move_messages(from_channel, to_channel): with BlockSave(Message, query_dict={'channel_id': to_channel.key}): for message in Message.objects.filter(channel=from_channel, typ=15): message.key = '' message.channel = to_channel message.save()
While splitting channel and moving chosen subscribers to new channel, old channel's messages are copied and moved to new channel. Args: from_channel (Channel object): move messages from channel to_channel (Channel object): move messages to channel
codesearchnet
def propagate(self, date): if (type(date) is timedelta): date = (self.orbit.date + date) _date = [float(x) for x in '{:%Y %m %d %H %M %S.%f}'.format(date).split()] (p, v) = self.tle.propagate(*_date) result = [(x * 1000) for x in (p + v)] return self.orbit.__class__(date, result, 'cartesian'...
Propagate the initialized orbit Args: date (Date or datetime.timedelta) Return: Orbit
codesearchnet
def insert(self, i, species, coords, validate_proximity=False, properties=None): new_site = Site(species, coords, properties=properties) if validate_proximity: for site in self: if site.distance(new_site) < self.DISTANCE_TOLERANCE: ...
Insert a site to the molecule. Args: i (int): Index to insert site species: species of inserted site coords (3x1 array): coordinates of inserted site validate_proximity (bool): Whether to check if inserted site is too close to an existing site. Defaults to True. properties (dict): Dict of properties for the Site. Ret...
juraj-google-style
def with_step(self, step): self._options['step'] = step return self
Which profile step to use for profiling. The 'step' here refers to the step defined by `Profiler.add_step()` API. Args: step: When multiple steps of profiles are available, select which step's profile to use. If -1, use average of all available steps. Returns: self
github-repos
def setup_low_rank_optimizer(optimizer_name: str, optimizer_mapping: dict[str, Any], optim_kwargs: dict[str, Any], is_layerwise_supported: bool=True) -> tuple[Any, Any]: is_layerwise = optimizer_name.lower().endswith('layerwise') if is_layerwise and args.parallel_mode == ParallelMode.DISTRIBUTED and is_layerwis...
Helper function to set up low-rank optimizers like GaLore and Apollo. Args: optimizer_name (str): Name of the optimizer. optimizer_mapping (dict): Mapping of optimizer names to their classes. optim_kwargs (dict): Keyword arguments for the optimizer. is_layerwise_supported (bool): Whether layerwise optimization is supp...
github-repos
def indent(lines, amount=2, char=' '): lines = str(lines) padding = (amount * char) return (padding + ('\n' + padding).join(lines.split('\n')))
r"""Indent a string. Prepends whitespace to every line in the passed string. (Lines are separated by newline characters.) Args: lines (str): The string to indent. Keyword Args: amount (int): The number of columns to indent by. char (str): The character to to use as the indentation. Returns: str: The indented string...
codesearchnet
def mat2quat(rmat, precise=False): M = np.array(rmat, dtype=np.float32, copy=False)[:3, :3] if precise: q = np.empty((4,)) t = np.trace(M) if t > M[3, 3]: q[0] = t q[3] = M[1, 0] - M[0, 1] q[2] = M[0, 2] - M[2, 0] q[1] = M[2, 1] - M[1,...
Converts given rotation matrix to quaternion. Args: rmat: 3x3 rotation matrix precise: If isprecise is True, the input matrix is assumed to be a precise rotation matrix and a faster algorithm is used. Returns: vec4 float quaternion angles
juraj-google-style
def replace_iterable_params(args, kwargs, iterable_params): args = list(args) for name, index in iterable_params: if index < len(args): args[index] = list(args[index]) elif name in kwargs: kwargs[name] = list(kwargs[name]) return (tuple(args), kwargs)
Returns (args, kwargs) with any iterable parameters converted to lists. Args: args: Positional rguments to a function kwargs: Keyword arguments to a function. iterable_params: A list of (name, index) tuples for iterable parameters. Returns: A tuple (args, kwargs), where any positional or keyword parameters in `iterab...
github-repos
def init(config, workdir=None, logfile=None, loglevel=logging.INFO, **kwargs): setup_sdk_logging(logfile, loglevel) defaults = lago_config.get_section('init') if (workdir is None): workdir = os.path.abspath('.lago') defaults['workdir'] = workdir defaults['virt_config'] = config defaults....
Initialize the Lago environment Args: config(str): Path to LagoInitFile workdir(str): Path to initalize the workdir, defaults to "$PWD/.lago" **kwargs(dict): Pass arguments to :func:`~lago.cmd.do_init` logfile(str): A path to setup a log file. loglevel(int): :mod:`logging` log level. Returns: :class:`~lago.sdk.SDK`: ...
codesearchnet
def adjoint(matrix, name=None): with ops.name_scope(name, 'adjoint', [matrix]): matrix = ops.convert_to_tensor(matrix, name='matrix') return array_ops.matrix_transpose(matrix, conjugate=True)
Transposes the last two dimensions of and conjugates tensor `matrix`. For example: ```python x = tf.constant([[1 + 1j, 2 + 2j, 3 + 3j], [4 + 4j, 5 + 5j, 6 + 6j]]) tf.linalg.adjoint(x) # [[1 - 1j, 4 - 4j], # [2 - 2j, 5 - 5j], # [3 - 3j, 6 - 6j]] ``` Args: matrix: A `Tensor`. Must be `float16`, `float32`, `float64...
github-repos
def get_structure_by_id(self, cod_id, **kwargs): r = requests.get(('http: return Structure.from_str(r.text, fmt='cif', **kwargs)
Queries the COD for a structure by id. Args: cod_id (int): COD id. kwargs: All kwargs supported by :func:`pymatgen.core.structure.Structure.from_str`. Returns: A Structure.
codesearchnet
def fts_count(self, fts, inv): return len(list(filter((lambda s: self.fts_match(fts, s)), inv)))
Return the count of segments in an inventory matching a given feature mask. Args: fts (set): feature mask given as a set of (value, feature) tuples inv (set): inventory of segments (as Unicode IPA strings) Returns: int: number of segments in `inv` that match feature mask `fts`
codesearchnet
def load_default(self): path = ctypes_util.find_library(self._sdk) if (path is None): if (self._windows or self._cygwin): path = next(self.find_library_windows(), None) elif sys.platform.startswith('linux'): path = next(self.find_library_linux(), None) elif sys.pl...
Loads the default J-Link SDK DLL. The default J-Link SDK is determined by first checking if ``ctypes`` can find the DLL, then by searching the platform-specific paths. Args: self (Library): the ``Library`` instance Returns: ``True`` if the DLL was loaded, otherwise ``False``.
codesearchnet
def classify_format(f): l0, l1 = _get_two_lines(f) if loader.glove.check_valid(l0, l1): return _glove elif loader.word2vec_text.check_valid(l0, l1): return _word2vec_text elif loader.word2vec_bin.check_valid(l0, l1): return _word2vec_bin else: raise OSError(b"Inv...
Determine the format of word embedding file by their content. This operation only looks at the first two lines and does not check the sanity of input file. Args: f (Filelike): Returns: class
juraj-google-style
def distinct(l): seen = set() seen_add = seen.add return (_ for _ in l if (not ((_ in seen) or seen_add(_))))
Return a list where the duplicates have been removed. Args: l (list): the list to filter. Returns: list: the same list without duplicates.
codesearchnet
def Search(self, search_base, search_filter, search_scope, attrs): self._last_search_params = (search_base, search_filter, search_scope, attrs) self.log.debug('searching for base=%r, filter=%r, scope=%r, attrs=%r', search_base, search_filter, search_scope, attrs) if 'dn' in attrs: self._dn_requested...
Search the data source. The search is asynchronous; data should be retrieved by iterating over the source object itself (see __iter__() below). Args: search_base: the base of the tree being searched search_filter: a filter on the objects to be returned search_scope: the scope of the search from ldap.SCOPE_* attrs: a ...
github-repos
def initializer(self): if self._initializer is not None: return self._initializer else: raise ValueError('The iterator does not have an initializer. This means it was likely created using `tf.data.Dataset.make_one_shot_iterator()`. For an initializable iterator, use `tf.data.Dataset.make_initial...
A `tf.Operation` that should be run to initialize this iterator. Returns: A `tf.Operation` that should be run to initialize this iterator Raises: ValueError: If this iterator initializes itself automatically.
github-repos
def Serialize(self, writer): writer.WriteUInt32(self.Version) writer.WriteUInt64(self.Services) writer.WriteUInt32(self.Timestamp) writer.WriteUInt16(self.Port) writer.WriteUInt32(self.Nonce) writer.WriteVarString(self.UserAgent) writer.WriteUInt32(self.S...
Serialize object. Args: writer (neo.IO.BinaryWriter):
juraj-google-style
def is_artifact_optional(chain, task_id, path): upstream_artifacts = chain.task['payload'].get('upstreamArtifacts', []) optional_artifacts_per_task_id = get_optional_artifacts_per_task_id(upstream_artifacts) return path in optional_artifacts_per_task_id.get(task_id, [])
Tells whether an artifact is flagged as optional or not. Args: chain (ChainOfTrust): the chain of trust object task_id (str): the id of the aforementioned task Returns: bool: True if artifact is optional
juraj-google-style
async def import_image(self, data, stream: bool = False): headers = {"Content-Type": "application/x-tar"} response = await self.docker._query_chunked_post( "images/load", "POST", data=data, headers=headers ) return await json_stream_result(response, stream=stream)
Import tarball of image to docker. Args: data: tarball data of image to be imported Returns: Tarball of the image
juraj-google-style
def list_datasets(self, get_global_public): appending = "" if get_global_public: appending = "public" url = self.url() + "/resource/{}dataset/".format(appending) req = self.remote_utils.get_url(url) if req.status_code is not 200: raise RemoteData...
Lists datasets in resources. Setting 'get_global_public' to 'True' will retrieve all public datasets in cloud. 'False' will get user's public datasets. Arguments: get_global_public (bool): True if user wants all public datasets in cloud. False if user wants only their public datasets. Returns: dict: Returns datasets ...
juraj-google-style
def _AddShardedRestoreOps(self, filename_tensor, per_device, restore_sequentially, reshape): sharded_restores = [] for shard, (device, saveables) in enumerate(per_device): with ops.device(device): sharded_restores.append(self._AddRestoreOps(filename_tensor, saveables, restore_sequentially, r...
Add Ops to restore variables from multiple devices. Args: filename_tensor: Tensor for the path of the file to load. per_device: A list of (device, SaveableObject) pairs, as returned by _GroupByDevices(). restore_sequentially: True if we want to restore variables sequentially within a shard. reshape: True if we want to...
github-repos
def desc_from_uri(uri): if (':' in uri): (_, uri) = uri.split(':', 1) query_string = parse_qs(urlparse(uri, 'http').query) if query_string.get('sn'): account_serial_number = query_string['sn'][0] try: account = Account.get_accounts()[account_serial_number] des...
Create the content of DIDL desc element from a uri. Args: uri (str): A uri, eg: ``'x-sonos-http:track%3a3402413.mp3?sid=2&amp;flags=32&amp;sn=4'`` Returns: str: The content of a desc element for that uri, eg ``'SA_RINCON519_email@example.com'``
codesearchnet
def getOption(self, name): try: value = lock_and_call((lambda : self._impl.getOption(name).value()), self._lock) except RuntimeError: return None else: try: return int(value) except ValueError: try: return float(value) excep...
Get the current value of the specified option. If the option does not exist, returns None. Args: name: Option name. Returns: Value of the option. Raises: InvalidArgumet: if the option name is not valid.
codesearchnet
def get_query_columns(engine, query): con = engine.connect() result = con.execute(query).fetchone() values = list(result) cols_names = result.keys() cols = OrderedDict() for i in range(len(cols_names)): cols[cols_names[i]] = type(values[i]).__name__ return cols
Extract columns names and python typos from query Args: engine: SQLAlchemy connection engine query: SQL query Returns: dict with columns names and python types
juraj-google-style
def heightmap_get_minmax(hm: np.ndarray) -> Tuple[(float, float)]: mi = ffi.new('float *') ma = ffi.new('float *') lib.TCOD_heightmap_get_minmax(_heightmap_cdata(hm), mi, ma) return (mi[0], ma[0])
Return the min and max values of this heightmap. Args: hm (numpy.ndarray): A numpy.ndarray formatted for heightmap functions. Returns: Tuple[float, float]: The (min, max) values. .. deprecated:: 2.0 Use ``hm.min()`` or ``hm.max()`` instead.
codesearchnet
def stop_replace(self, accountID, orderID, **kwargs): return self.replace( accountID, orderID, order=StopOrderRequest(**kwargs) )
Shortcut to replace a pending Stop Order in an Account Args: accountID : The ID of the Account orderID : The ID of the Stop Order to replace kwargs : The arguments to create a StopOrderRequest Returns: v20.response.Response containing the results from submitting the request
juraj-google-style
def implement(self, implementation, for_type=None, for_types=None): unbound_implementation = self.__get_unbound_function(implementation) for_types = self.__get_types(for_type, for_types) for t in for_types: self._write_lock.acquire() try: self.im...
Registers an implementing function for for_type. Arguments: implementation: Callable implementation for this type. for_type: The type this implementation applies to. for_types: Same as for_type, but takes a tuple of types. for_type and for_types cannot both be passed (for obvious reasons.) Raises: ValueError
juraj-google-style
def _to_map_job_config(cls, mr_spec, queue_name): mapper_spec = mr_spec.mapper api_version = mr_spec.params.get('api_version', 0) old_api = (api_version == 0) input_reader_cls = mapper_spec.input_reader_class() input_reader_params = input_readers._get_params(mapper_spec) if issubclass(input_read...
Converts model.MapreduceSpec back to JobConfig. This method allows our internal methods to use JobConfig directly. This method also allows us to expose JobConfig as an API during execution, despite that it is not saved into datastore. Args: mr_spec: model.MapreduceSpec. queue_name: queue name. Returns: The JobConfig...
codesearchnet
def configure_interface(self, name, commands): commands = make_iterable(commands) commands.insert(0, ('interface %s' % name)) return self.configure(commands)
Configures the specified interface with the commands Args: name (str): The interface name to configure commands: The commands to configure in the interface Returns: True if the commands completed successfully
codesearchnet
def query(self, query): if (str(query.key) in self._items): return query(self._items[str(query.key)].values()) else: return query([])
Returns an iterable of objects matching criteria expressed in `query` Naively applies the query operations on the objects within the namespaced collection corresponding to ``query.key.path``. Args: query: Query object describing the objects to return. Raturns: iterable cursor with all objects matching criteria
codesearchnet
def calculate_part_visibility(self, ports): source_port_lookup = {} for (part_name, port_infos) in SourcePortInfo.filter_parts(ports).items(): for port_info in port_infos: source_port_lookup[port_info.connected_value] = (part_name, port_info.port) for (part_name, port_infos) in SinkPortI...
Calculate what is connected to what Args: ports: {part_name: [PortInfo]} from other ports
codesearchnet
def passgen(length=12, punctuation=False, digits=True, letters=True, case='both', **kwargs): p_min = punctuation p_max = (0 if (punctuation is False) else length) d_min = digits d_max = (0 if (digits is False) else length) a_min = letters a_max = (0 if (letters is False) else length) if (((d...
Generate random password. Args: length (int): The length of the password. Must be greater than zero. Defaults to 12. punctuation (bool): Whether to use punctuation or not. Defaults to False. limit_punctuation (str): Limits the allowed puncturation to defined characters. digits (bool): Whether to use digits or not. ...
codesearchnet
def results(self, use_cache=True, dialect=None, billing_tier=None): if ((not use_cache) or (self._results is None)): self.execute(use_cache=use_cache, dialect=dialect, billing_tier=billing_tier) return self._results.results
Retrieves table of results for the query. May block if the query must be executed first. Args: use_cache: whether to use cached results or not. Ignored if append is specified. dialect : {'legacy', 'standard'}, default 'legacy' 'legacy' : Use BigQuery's legacy SQL dialect. 'standard' : Use BigQuery's standard SQL (beta...
codesearchnet
def get_log_file_name(level=INFO): if level not in converter.ABSL_LEVELS: raise ValueError('Invalid absl.logging level {}'.format(level)) stream = get_absl_handler().python_handler.stream if (stream == sys.stderr or stream == sys.stdout or not hasattr(stream, 'name')): return '' else: retur...
Returns the name of the log file. For Python logging, only one file is used and level is ignored. And it returns empty string if it logs to stderr/stdout or the log stream has no `name` attribute. Args: level: int, the absl.logging level. Raises: ValueError: Raised when `level` has an invalid value.
juraj-google-style
def rate_to_mcs(rate, bw=20, long_gi=True): if bw not in [20, 40, 80, 160]: raise Exception("Unknown bandwidth: %d MHz" % (bw)) idx = int((math.log(bw/10, 2)-1)*2) if not long_gi: idx += 1 for mcs, rates in MCS_TABLE.items(): if abs(rates[idx] - rate) < 1e-3: re...
Convert bit rate to MCS index. Args: rate (float): bit rate in Mbps bw (int): bandwidth, 20, 40, 80, ... long_gi (bool): True if long GI is used. Returns: mcs (int): MCS index >>> rate_to_mcs(120, bw=40, long_gi=False) 5
juraj-google-style
def call(self, inputs, training=None, mask=None): raise NotImplementedError('When subclassing the `Model` class, you should implement a `call` method.')
Calls the model on new inputs. In this case `call` just reapplies all ops in the graph to the new inputs (e.g. build a new computational graph from the provided inputs). Note: This method should not be called directly. It is only meant to be overridden when subclassing `tf.keras.Model`. To call a model on an input, a...
github-repos
def _build_cryptographic_parameters(self, value): if value is None: return None elif not isinstance(value, dict): raise TypeError("Cryptographic parameters must be a dictionary.") cryptographic_parameters = CryptographicParameters( block_cipher_mode=...
Build a CryptographicParameters struct from a dictionary. Args: value (dict): A dictionary containing the key/value pairs for a CryptographicParameters struct. Returns: None: if value is None CryptographicParameters: a CryptographicParameters struct Raises: TypeError: if the input argument is invalid
juraj-google-style