code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def fetch(self, refund_id, data={}, **kwargs): return super(Refund, self).fetch(refund_id, data, **kwargs)
Refund object for given paymnet Id Args: refund_id : Refund Id for which refund has to be retrieved Returns: Refund dict for given refund Id
juraj-google-style
def __init__( self, cls, diff, ): msg = "\n".join([ "", "ctor: {}".format(cls), "extras: {}".format(diff) ]) Exception.__init__(self, msg) self.type = str( type(self), ) self.cls = str(c...
Note that type_assert can't be used because it would create a circular dependency. Args: cls, type, The type that was attempted to unmarshal into diff: dict, The extra arguments that were passed to @cls
juraj-google-style
def imread(img_or_path, flag='color'): if isinstance(img_or_path, np.ndarray): return img_or_path elif is_str(img_or_path): flag = (imread_flags[flag] if is_str(flag) else flag) check_file_exist(img_or_path, 'img file does not exist: {}'.format(img_or_path)) return cv2.imread(img...
Read an image. Args: img_or_path (ndarray or str): Either a numpy array or image path. If it is a numpy array (loaded image), then it will be returned as is. flag (str): Flags specifying the color type of a loaded image, candidates are `color`, `grayscale` and `unchanged`. Returns: ndarray: Loaded image array.
codesearchnet
def get(self, language: str=None, default: str=None) -> str: language = language or settings.LANGUAGE_CODE value = super().get(language, default) return value if value is not None else default
Gets the underlying value in the specified or primary language. Arguments: language: The language to get the value in. Returns: The value in the current language, or the primary language in case no language was specified.
juraj-google-style
def to_dataframe(self): data = [] for (target_index, target_row) in enumerate(self._cm): for (predicted_index, count) in enumerate(target_row): data.append((self._labels[target_index], self._labels[predicted_index], count)) return pd.DataFrame(data, columns=['target', 'predicted', 'count...
Convert the confusion matrix to a dataframe. Returns: A DataFrame with "target", "predicted", "count" columns.
codesearchnet
def smart_device_selection(preferred_device_type=None): cl_environments = CLEnvironmentFactory.all_devices(cl_device_type=preferred_device_type) platform_names = [env.platform.name for env in cl_environments] has_amd_pro_platform = any((('AMD Accelerated Parallel Processing' in name) for name in platform_na...
Get a list of device environments that is suitable for use in MOT. Basically this gets the total list of devices using all_devices() and applies a filter on it. This filter does the following: 1) if the 'AMD Accelerated Parallel Processing' is available remove all environments using the 'Clover' platform. More thing...
codesearchnet
def _decrypt_asymmetric(self, decryption_algorithm, decryption_key, cipher_text, padding_method, hashing_algorithm=None): if (decryption_algorithm == enums.CryptographicAlgorithm.RSA): if (padding_method == enums.PaddingMethod.OAEP): hash_algorithm = self._encryption_hash_algorithms.get(hashing_...
Encrypt data using asymmetric decryption. Args: decryption_algorithm (CryptographicAlgorithm): An enumeration specifying the asymmetric decryption algorithm to use for decryption. Required. decryption_key (bytes): The bytes of the private key to use for decryption. Required. cipher_text (bytes): The bytes to be decryp...
codesearchnet
def save_page(self, path=None): path = _prepare_path(path, 'html') with open(path, 'wb') as f: f.write(encode_string(self.body)) return path
Save a snapshot of the page. If invoked without arguments, it will save a file to :data:`capybara.save_path` and the file will be given a randomly generated filename. If invoked with a relative path, the path will be relative to :data:`capybara.save_path`. Args: path (str, optional): The path to where it should be sa...
codesearchnet
def __init__(self, conf, conn=None): super(HttpFilesSource, self).__init__(conf) self._SetDefaults(conf) if not conn: conn = pycurl.Curl() conn.setopt(pycurl.NOPROGRESS, 1) conn.setopt(pycurl.NOSIGNAL, 1) conn.setopt(pycurl.TIMEOUT, 60) conn.setopt(pycurl.USERAGENT, '...
Initialise the HTTP Data Source. Args: conf: config.Config instance conn: pycurl Curl object
github-repos
def _send_request(url_id, data=None, json=None, req_type=None): url = (settings.SEEDER_INFO_URL % url_id) if (not req_type): req_type = requests.get resp = req_type(url, data=data, json=json, timeout=settings.SEEDER_TIMEOUT, headers={'User-Agent': settings.USER_AGENT, 'Authorization': settings.SEEDE...
Send request to Seeder's API. Args: url_id (str): ID used as identification in Seeder. data (obj, default None): Optional parameter for data. json (obj, default None): Optional parameter for JSON body. req_type (fn, default None): Request method used to send/download the data. If none, `requests.get` is used. Returns...
codesearchnet
def update_vm(access_token, subscription_id, resource_group, vm_name, body): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Compute/virtualMachines/', vm_name, '?api-version=', COMP_API]) return do_put(endpoint, body, access_t...
Update a virtual machine with a new JSON body. E.g. do a GET, change something, call this. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vm_name (str): Name of the virtual machine. body (dict): JSON body of t...
codesearchnet
def CheckTaskReadyForMerge(self, task): if self._storage_type != definitions.STORAGE_TYPE_SESSION: raise IOError('Unsupported storage type.') if not self._processed_task_storage_path: raise IOError('Missing processed task storage path.') processed_storage_file_path = self._GetProcessedSto...
Checks if a task is ready for merging with this session storage. If the task is ready to be merged, this method also sets the task's storage file size. Args: task (Task): task. Returns: bool: True if the task is ready to be merged. Raises: IOError: if the storage type is not supported or OSError: if the storage typ...
juraj-google-style
def update_connection_endpoint(self, connection_id, endpoint): if connection_id in self._connections: connection_info = self._connections[connection_id] self._connections[connection_id] = \ ConnectionInfo(connection_info.connection_type, ...
Adds the endpoint to the connection definition. When the connection is created by the send/receive thread, we do not yet have the endpoint of the remote node. That is not known until we process the incoming ConnectRequest. Args: connection_id (str): The identifier for the connection. endpoint (str): A zmq-style uri wh...
juraj-google-style
def usergroups_disable(self, *, usergroup: str, **kwargs) -> SlackResponse: self._validate_xoxp_token() kwargs.update({'usergroup': usergroup}) return self.api_call('usergroups.disable', json=kwargs)
Disable an existing User Group Args: usergroup (str): The encoded ID of the User Group to disable. e.g. 'S0604QSJC'
codesearchnet
def msgBox(self, promptType, _timeout=(- 1), **options): if (promptType == 'confirm'): return self._sendConfirmPrompt(_timeout, options) else: raise ValueError('Unknown prompt type: {}'.format(promptType))
Send a user prompt request to the GUI Arguments: promptType (string): The prompt type to send to the GUI. Currently the only type supported is 'confirm'. _timeout (int): The optional amount of time for which the prompt should be displayed to the user before a timeout occurs. Defaults to -1 which indicates there is no...
codesearchnet
def Deserialize(self, reader): self.Script = reader.ReadVarBytes() self.ParameterList = reader.ReadVarBytes() self.ReturnType = reader.ReadByte()
Deserialize full object. Args: reader (neo.IO.BinaryReader):
juraj-google-style
def from_pretrained(cls, pretrained_model_name_or_path: Union[str, os.PathLike], *init_inputs, **kwargs): try: tokenizer = BertTokenizer.from_pretrained(pretrained_model_name_or_path, *init_inputs, **kwargs) except: from .tokenization_bert_fast import BertTokenizerFast tokenizer = BertTo...
Instantiate a `TFBertTokenizer` from a pre-trained tokenizer. Args: pretrained_model_name_or_path (`str` or `os.PathLike`): The name or path to the pre-trained tokenizer. Examples: ```python from transformers import TFBertTokenizer tf_tokenizer = TFBertTokenizer.from_pretrained("google-bert/bert-base-uncased") ```
github-repos
def _resolve_attribute_match(self, match): if (match.group(1) == 'cluster'): return str(self.cluster_id) return self.get(match.group(1), match.group(0))
Replaces a reference to an attribute with the value of the attribute. Args: match (re.match object): A match object containing a match to a reference to an attribute.
codesearchnet
def closest_eere(latitude, longitude): with open(env.SRC_PATH + '/eere_meta.csv') as eere_meta: stations = csv.DictReader(eere_meta) d = 9999 station_code = '' station_name = '' for station in stations: new_dist = great_circle((latitude, longitude), ...
Find closest station from the new(er) list. Warning: There may be some errors with smaller non US stations. Args: latitude (float) longitude (float) Returns: tuple (station_code (str), station_name (str))
juraj-google-style
def set_pipeline_definition(self): if (not self.pipeline_id): self.get_pipeline_id() json_def = self.datapipeline_data['json_definition'] try: pipelineobjects = translator.definition_to_api_objects(json_def) parameterobjects = translator.definition_to_api_parameters(json_def) ...
Translates the json definition and puts it on created pipeline Returns: dict: the response of the Boto3 command
codesearchnet
def login_with_password_no_sync(self, username, password): warn('login_with_password_no_sync is deprecated. Use login with sync=False.', DeprecationWarning) return self.login(username, password, sync=False)
Deprecated. Use ``login`` with ``sync=False``. Login to the homeserver. Args: username (str): Account username password (str): Account password Returns: str: Access token Raises: MatrixRequestError
codesearchnet
def get_attribute(self, obj, attr): if (attr == '*'): return obj if isinstance(obj, Mapping): return obj.get(attr, None) return getattr(obj, attr, None)
Get attribute of given object instance. Reason for existence of this method is the fact that 'attribute' can be also object's key from if is a dict or any other kind of mapping. Note: it will return None if attribute key does not exist Args: obj (object): internal object to retrieve data from Returns: internal obj...
codesearchnet
async def remove(self, index=""): if not self.state == 'ready': logger.debug("Trying to remove from wrong state '{}'".format(self.state)) return if index == "": self.statuslog.error("Must provide index to remove") return elif index == "a...
The remove command Args: index (str): The index to remove, can be either a number, or a range in the for '##-##'
juraj-google-style
def display_hierarchy(root_ad_unit, all_ad_units): parent_id_to_children = collections.defaultdict(list) for ad_unit in all_ad_units: if ('parentId' in ad_unit): parent_id_to_children[ad_unit['parentId']].append(ad_unit) parent_id_to_children = dict(parent_id_to_children) display_hie...
Display the ad units as a tree. Args: root_ad_unit: The root ad unit to begin from. all_ad_units: A list containing all ad units.
codesearchnet
def from_paths(cls, path, bs=64, tfms=(None, None), trn_name='train', val_name='valid', test_name=None, test_with_labels=False, num_workers=8): assert (not ((tfms[0] is None) or (tfms[1] is None))), 'please provide transformations for your train and validation sets' (trn, val) = [folder_source(path, o) for o in...
Read in images and their labels given as sub-folder names Arguments: path: a root path of the data (used for storing trained models, precomputed values, etc) bs: batch size tfms: transformations (for data augmentations). e.g. output of `tfms_from_model` trn_name: a name of the folder that contains training images. val...
codesearchnet
def encode_schedule(schedule): (interpolation, steps, pmfs) = schedule return ((interpolation + ' ') + ' '.join((((('@' + str(s)) + ' ') + ' '.join(map(str, p))) for (s, p) in zip(steps, pmfs))))
Encodes a schedule tuple into a string. Args: schedule: A tuple containing (interpolation, steps, pmfs), where interpolation is a string specifying the interpolation strategy, steps is an int array_like of shape [N] specifying the global steps, and pmfs is an array_like of shape [N, M] where pmf[i] is the sampling dis...
codesearchnet
def as_json_range(self, name): return {'Name': name, 'Values': [json.dumps(v) for v in self.values]}
Represent the parameter range as a dictionary suitable for a request to create an Amazon SageMaker hyperparameter tuning job using one of the deep learning frameworks. The deep learning framework images require that hyperparameters be serialized as JSON. Args: name (str): The name of the hyperparameter. Returns: dic...
codesearchnet
def _Open(self, path_spec, mode='rb'): if not path_spec.HasParent(): raise errors.PathSpecError( 'Unsupported path specification without parent.') file_object = resolver.Resolver.OpenFileObject( path_spec.parent, resolver_context=self._resolver_context) try: vshadow_volu...
Opens the file system object defined by path specification. Args: path_spec (PathSpec): path specification. mode (Optional[str]): file access mode. The default is 'rb' which represents read-only binary. Raises: AccessError: if the access to open the file was denied. IOError: if the file system object could not be ope...
juraj-google-style
def less(x, y): return math_ops.less(x, y)
Element-wise truth value of (x < y). Args: x: Tensor or variable. y: Tensor or variable. Returns: A bool tensor.
github-repos
def apply(self, func, num_splits=None, other_axis_partition=None, maintain_partitioning=True, **kwargs): import dask if (num_splits is None): num_splits = len(self.list_of_blocks) if (other_axis_partition is not None): return [DaskFramePartition(dask.delayed(obj)) for obj in deploy_func_betw...
Applies func to the object. See notes in Parent class about this method. Args: func: The function to apply. num_splits: The number of times to split the result object. other_axis_partition: Another `DaskFrameAxisPartition` object to apply to func with this one. Returns: A list of `DaskFramePartition` objects.
codesearchnet
def make_adapt_function(self): if self._adapt_function is not None: return self._adapt_function def adapt_step(iterator): data = next(iterator) self._adapt_maybe_build(data) self.update_state(data) if self._steps_per_execution.numpy().item() == 1: adapt_fn = adapt_st...
Creates a function to execute one step of `adapt`. This method can be overridden to support custom adapt logic. This method is called by `PreprocessingLayer.adapt`. Typically, this method directly controls `tf.function` settings, and delegates the actual state update logic to `PreprocessingLayer.update_state`. This ...
github-repos
def energy_upperbound(self, spins): subtheta = self.theta.copy() subtheta.fix_variables(spins) trees = self._trees if (not trees): assert ((not subtheta.linear) and (not subtheta.quadratic)) return subtheta.offset energy = Plus(self.message_upperbound(trees, {}, subtheta), subtheta.o...
A formula for an upper bound on the energy of Theta with spins fixed. Args: spins (dict): Spin values for a subset of the variables in Theta. Returns: Formula that upper bounds the energy with spins fixed.
codesearchnet
def sync_proxy(self, mri, block): subscribe = Subscribe(path=[mri], delta=True) done_queue = Queue() def handle_response(response): if not isinstance(response, Delta): self.log.debug("Proxy got response %r", response) ...
Abstract method telling the ClientComms to sync this proxy Block with its remote counterpart. Should wait until it is connected Args: mri (str): The mri for the remote block block (BlockModel): The local proxy Block to keep in sync
juraj-google-style
def restore(self, fade=False): try: if self.is_coordinator: self._restore_coordinator() finally: self._restore_volume(fade) if self.is_coordinator: if self.transport_state == 'PLAYING': self.device.p...
Restore the state of a device to that which was previously saved. For coordinator devices restore everything. For slave devices only restore volume etc., not transport info (transport info comes from the slave's coordinator). Args: fade (bool): Whether volume should be faded up on restore.
juraj-google-style
def comments_1(self, value=None): if (value is not None): try: value = str(value) except ValueError: raise ValueError('value {} need to be of type str for field `comments_1`'.format(value)) if (',' in value): raise ValueError('value should not contain a co...
Corresponds to IDD Field `comments_1` Args: value (str): value for IDD Field `comments_1` if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ValueError: if `value` is not a valid value
codesearchnet
def get_aggregate(self): return dict([(aggregate.find('query').text, [ET.tostring(data).lstrip('<data xmlns:cps="www.clusterpoint.com" xmlns:cpse="www.clusterpoint.com">').strip().rstrip('</data>') for data in aggregate.findall('data')]) for aggregate in self._content.findall('aggregate')])
Get aggregate data. Returns: A dict in with queries as keys and results as values.
codesearchnet
def Add(self, rdf_value, timestamp=None, suffix=None, mutation_pool=None): return self.StaticAdd(self.collection_id, rdf_value, timestamp=timestamp, suffix=suffix, mutation_pool=mutation_pool)
Adds an rdf value to the collection. Adds an rdf value to the collection. Does not require that the collection be locked. Args: rdf_value: The rdf value to add to the collection. timestamp: The timestamp (in microseconds) to store the rdf value at. Defaults to the current time. suffix: A 'fractional timestamp' suffix...
codesearchnet
def tf_initialize(self, x_init, base_value, target_value, estimated_improvement): self.base_value = base_value if estimated_improvement is None: estimated_improvement = tf.abs(x=base_value) first_step = super(LineSearch, self).tf_initialize(x_init) improvement =...
Initialization step preparing the arguments for the first iteration of the loop body. Args: x_init: Initial solution guess $x_0$. base_value: Value $f(x')$ at $x = x'$. target_value: Value $f(x_0)$ at $x = x_0$. estimated_improvement: Estimated value at $x = x_0$, $f(x')$ if None. Returns: Initial arguments for tf_st...
juraj-google-style
def _extract_id(self) -> str: match = re.match(self._VALID_URL, self.url) if match: return match.group('video_id') else: raise VideoIdNotMatchedError
Get video_id needed to obtain the real_url of the video. Raises: VideoIdNotMatchedError: If video_id is not matched with regular expression.
codesearchnet
def __add__(self, other): if not all(np.equal(self.energies, other.energies)): raise ValueError("Energies of both COHP are not compatible.") populations = {spin: self.populations[spin] + other.populations[spin] for spin in self.cohp} if self.icohp is n...
Adds two COHP together. Checks that energy scales are the same. Otherwise, it raises a ValueError. It also adds ICOHP if present. If ICOHP is only present in one object, it displays a warning and will not add ICOHP. Args: other: Another COHP object. Returns: Sum of the two COHPs as a COHP object.
juraj-google-style
def create_clusters(provider, context, **kwargs): conn = get_session(provider.region).client('ecs') try: clusters = kwargs['clusters'] except KeyError: logger.error('setup_clusters hook missing "clusters" argument') return False if isinstance(clusters, basestring): cluste...
Creates ECS clusters. Expects a "clusters" argument, which should contain a list of cluster names to create. Args: provider (:class:`stacker.providers.base.BaseProvider`): provider instance context (:class:`stacker.context.Context`): context instance Returns: boolean for whether or not the hook succeeded.
codesearchnet
def __to_plain_containers(self, container: Union[(CommentedSeq, CommentedMap)]) -> Union[(OrderedDict, list)]: if isinstance(container, CommentedMap): new_container = OrderedDict() for (key, value_obj) in container.items(): if (isinstance(value_obj, CommentedMap) or isinstance(value_obj,...
Converts any sequence or mapping to list or OrderedDict Stops at anything that isn't a sequence or a mapping. One day, we'll extract the comments and formatting and store \ them out-of-band. Args: mapping: The mapping of constructed subobjects to edit
codesearchnet
def designPrimers(seq_args, global_args=None, misprime_lib=None, mishyb_lib=None, debug=False): if global_args: primerdesign.setGlobals(global_args, misprime_lib, mishyb_lib) primerdesign.setSeqArgs(seq_args) return primerdesign.runDesign(debug)
Run the Primer3 design process. If the global args have been previously set (either by a pervious `designPrimers` call or by a `setGlobals` call), `designPrimers` may be called with seqArgs alone (as a means of optimization). Args: seq_args (dict) : Primer3 sequence/design args as per Primer3 docs glob...
codesearchnet
def from_tensor(cls, tensor): if isinstance(tensor, core.Value): return EagerWeakTensor(tensor) if isinstance(tensor, core.Symbol): return GraphWeakTensor(tensor) raise errors.InvalidArgumentError(None, None, f'WeakTensor can only be constructed from tf.Tensor or tf.WeakTensor, but {type(ten...
Converts a 'tf.Tensor' into a 'WeakTensor'. This should be the standard way of creating a WeakTensor instead of directly calling the WeakTensor constructor. Args: tensor: The `tf.Tensor` that should be converted into a 'WeakTensor'. Returns: A `EagerWeakTensor` or 'GraphWeakTensor' that holds the `tensor`.
github-repos
def to_hashable_table_ref(table_ref_elem_kv: Tuple[Union[str, TableReference], V]) -> Tuple[str, V]: table_ref = table_ref_elem_kv[0] hashable_table_ref = get_hashable_destination(table_ref) return (hashable_table_ref, table_ref_elem_kv[1])
Turns the key of the input tuple to its string representation. The key should be either a string or a TableReference. Args: table_ref_elem_kv: A tuple of table reference and element. Returns: A tuple of string representation of input table and input element.
github-repos
def push(self, x): self._quantile_tracker.push(x)
Pushes a new value and updates the internal quantile tracker. Args: x: The new value to be pushed.
github-repos
def _lookup_model(cls, kind, default_model=None): modelclass = cls._kind_map.get(kind, default_model) if (modelclass is None): raise KindError(("No model class found for kind '%s'. Did you forget to import it?" % kind)) return modelclass
Get the model class for the kind. Args: kind: A string representing the name of the kind to lookup. default_model: The model class to use if the kind can't be found. Returns: The model class for the requested kind. Raises: KindError: The kind was not found and no default_model was provided.
codesearchnet
def _poll_once(self, timeout_ms, max_records): self._coordinator.poll() if not self._subscription.has_all_fetch_positions(): self._update_fetch_positions(self._subscription.missing_fetch_positions()) records, partial = self._fetcher.fetc...
Do one round of polling. In addition to checking for new data, this does any needed heart-beating, auto-commits, and offset updates. Arguments: timeout_ms (int): The maximum time in milliseconds to block. Returns: dict: Map of topic to list of records (may be empty).
juraj-google-style
def settings(package, reload_=False): global packages if ((package not in packages) or reload_): from os import path result = CaseConfigParser() if (package != 'acorn'): confpath = _package_path(package) _read_single(result, confpath) _read_single(result, ...
Returns the config settings for the specified package. Args: package (str): name of the python package to get settings for.
codesearchnet
def refresh(self, request): try: self._retrieve_info(request) self.token, self.expiry = _metadata.get_service_account_token( request, service_account=self._service_account_email) except exceptions.TransportError as caught_exc: ...
Refresh the access token and scopes. Args: request (google.auth.transport.Request): The object used to make HTTP requests. Raises: google.auth.exceptions.RefreshError: If the Compute Engine metadata service can't be reached if if the instance has not credentials.
juraj-google-style
def unpack(self, buff=None, offset=0): instruction_type = UBInt16(enum_ref=InstructionType) instruction_type.unpack(buff, offset) self.__class__ = InstructionType(instruction_type.value).find_class() length = UBInt16() length.unpack(buff, offset=offset+2) super...
Unpack *buff* into this object. This method will convert a binary data into a readable value according to the attribute format. Args: buff (bytes): Binary buffer. offset (int): Where to begin unpacking. Raises: :exc:`~.exceptions.UnpackException`: If unpack fails.
juraj-google-style
def _MakeRequestNoRetry(http, http_request, redirections=5, check_response_func=CheckResponse): connection_type = None if getattr(http, 'connections', None): url_scheme = parse.urlsplit(http_request.url).scheme if (url_scheme and (url_scheme in http.connections)): connection_type = h...
Send http_request via the given http. This wrapper exists to handle translation between the plain httplib2 request/response types and the Request and Response types above. Args: http: An httplib2.Http instance, or a http multiplexer that delegates to an underlying http, for example, HTTPMultiplexer. http_request: A R...
codesearchnet
def controlled_by(self, *control_qubits: Qid) -> 'Operation': from cirq.ops import ControlledOperation if control_qubits is None or len(control_qubits) is 0: raise ValueError( "Can't get controlled operation without control qubit. Op: {}" .fo...
Returns a controlled version of this operation. Args: control_qubits: Qubits to control the operation by. Required.
juraj-google-style
def convert_reshape(params, w_name, scope_name, inputs, layers, weights, names): print('Converting reshape ...') if names == 'short': tf_name = 'RESH' + random_string(4) elif names == 'keep': tf_name = w_name else: tf_name = w_name + str(random.random()) if len(inputs) ...
Convert reshape 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 _generate_assignments(splittable_dimensions, mesh_dimension_to_size): assignments = [] for assignment_size in six.moves.xrange((1 + min(len(splittable_dimensions), len(mesh_dimension_to_size)))): for s_dims_chosen in itertools.combinations(splittable_dimensions, assignment_size): for m_d...
Generates all ways to map splittable dimensions to mesh dimensions. Args: splittable_dimensions: a frozenset of the names of splittable dimensions. mesh_dimension_to_size: a dictionary from mesh dimension name to size. Returns: A list of the valid assignments. Each assignment is a dict keyed by every splittable dimen...
codesearchnet
def _print_args(arguments, argument_type='Argument', indent=0): indent_str = ' ' * indent def _maybe_add_quotes(value): is_quotes = "'" * isinstance(value, str) return is_quotes + str(value) + is_quotes def in_print(s, end='\n'): print(indent_str + s, end=end) for index, eleme...
Formats and prints the argument of the concrete functions defined in the model. Args: arguments: Arguments to format print. argument_type: Type of arguments. indent: How far (in increments of 2 spaces) to indent each line of output.
github-repos
def ParseCodeToTree(code): if not code.endswith(os.linesep): code += os.linesep try: parser_driver = driver.Driver(_PYTHON_GRAMMAR, convert=pytree.convert) tree = parser_driver.parse_string(code, debug=False) except parse.ParseError: ast.parse(code) raise return _...
Parse the given code to a lib2to3 pytree. Arguments: code: a string with the code to parse. Raises: SyntaxError if the code is invalid syntax. parse.ParseError if some other parsing failure. Returns: The root node of the parsed tree.
github-repos
def _build_all_reduce_ring(core_locations: List[_CoreLocation], rotate: bool=False) -> List[int]: permutation = list(range(len(core_locations))) if not permutation: return permutation logging.vlog(2, 'Core locations in: %s', core_locations) first_column = min([l.x for l in core_locations]) f...
Reorders a list of TPU cores to optimize for AllReduce performance. This is ported from the C++ tensorflow::BuildAllReduceRing function, mixed with some logic from TF TPU's device_assignment._ring_3d. Args: core_locations: A list of core locations expressed as [x, y, z, core]. rotate: If true, scan the cores in a col...
github-repos
def from_dict(cls, cls_dict, fallback_xsi_type=None): if not cls_dict: return None if isinstance(cls_dict, six.string_types): if not getattr(cls, "_convert_strings", False): return cls_dict try: typekey = cls.dictkey(cls_dict...
Parse the dictionary and return an Entity instance. This will attempt to extract type information from the input dictionary and pass it to entity_class to resolve the correct class for the type. Args: cls_dict: A dictionary representation of an Entity object. fallback_xsi_type: An xsi_type to use for string input, wh...
juraj-google-style
def generate_link(flag, np_fun_name): if flag == 'dev': template = 'https: elif flag == 'stable': template = 'https: elif re.match('\\d+(\\.\\d+(\\.\\d+)?)?$', flag): template = f'https: else: return None return template % np_fun_name
Generates link from numpy function name. Args: flag: the flag to control link form. See `set_np_doc_form`. np_fun_name: the numpy function name. Returns: A string.
github-repos
def SetIamPolicy(self, request, global_params=None): config = self.GetMethodConfig('SetIamPolicy') return self._RunMethod(config, request, global_params=global_params)
Sets the access control policy on the specified resource. Replaces any existing policy. Can return `NOT_FOUND`, `INVALID_ARGUMENT`, and `PERMISSION_DENIED` errors. Args: request: (BigqueryTablesSetIamPolicyRequest) input message global_params: (StandardQueryParameters, default: None) global arguments Returns: (Policy)...
github-repos
def prepare_http_request(self, method_type, params, **kwargs): prepared_request = self.session.prepare_request( requests.Request(method=method_type, **params) ) return prepared_request
Prepares the HTTP REQUEST and returns it. Args: method_type: The HTTP method type params: Additional parameters for the HTTP request. kwargs: Any extra keyword arguements passed into a client method. returns: prepared_request: An HTTP request object.
juraj-google-style
def find_usbserial(vendor, product): if (platform.system() == 'Linux'): (vendor, product) = [('%04x' % x).strip() for x in (vendor, product)] return linux_find_usbserial(vendor, product) elif (platform.system() == 'Darwin'): return osx_find_usbserial(vendor, product) else: ra...
Find the tty device for a given usbserial devices identifiers. Args: vendor: (int) something like 0x0000 product: (int) something like 0x0000 Returns: String, like /dev/ttyACM0 or /dev/tty.usb...
codesearchnet
def ParseOptions(cls, options, configuration_object): if not isinstance(configuration_object, tools.CLITool): raise errors.BadConfigObject( 'Configuration object is not an instance of CLITool') artifacts_path = getattr(options, 'artifact_definitions_path', None) data_location = getatt...
Parses and validates options. Args: options (argparse.Namespace): parser options. configuration_object (CLITool): object to be configured by the argument helper. Raises: BadConfigObject: when the configuration object is of the wrong type. BadConfigOption: if the required artifact definitions are not defined.
juraj-google-style
def download(self, file: Optional[IO]=None, rewind: bool=True, duration_timeout: Optional[float]=None) -> Response: if self._session_state != SessionState.file_request_sent: raise RuntimeError('File request not sent') if rewind and file and hasattr(file, 'seek'): ...
Read the response content into file. Args: file: A file object or asyncio stream. rewind: Seek the given file back to its original offset after reading is finished. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated with the final data connection reply. Be ...
juraj-google-style
def run_inference(self, batch: Sequence[ExampleT], model: ModelT, inference_args: Optional[dict[str, Any]]=None) -> Iterable[PredictionT]: raise NotImplementedError(type(self))
Runs inferences on a batch of examples. Args: batch: A sequence of examples or features. model: The model used to make inferences. inference_args: Extra arguments for models whose inference call requires extra parameters. Returns: An Iterable of Predictions.
github-repos
def apply(self, predictions: Iterable[AnomalyPrediction]) -> AnomalyPrediction: raise NotImplementedError
Applies the aggregation function to an iterable of predictions, either on their outlier scores or labels. Args: predictions: An Iterable of `AnomalyPrediction` objects to aggregate. Returns: An `AnomalyPrediction` object containing the aggregated result.
github-repos
def set_redirect(self, url, status=HttpStatusCodes.HTTP_303): self.set_status(status) self.set_content('') self.set_header(HttpResponseHeaders.LOCATION, url)
Helper method to set a redirect response. Args: url (:obj:`str`): URL to redirect to status (:obj:`str`, optional): Status code of the response
juraj-google-style
def _PackArgumentsHelper(self, elem, data, set_type_attrs): if self._packer: data = self._packer.Pack(data, self._version) if isinstance(data, dict): type_override = data.get('xsi_type') if type_override: elem_type = self._DiscoverElementTypeFromLocalname(type_override) ...
Recursive helper for PackArguments. Args: elem: The element type we are creating. data: The data to instantiate it with. set_type_attrs: A boolean indicating whether or not attributes that end in .Type should be set. This is only necessary for batch job service. Returns: An instance of type 'elem'.
codesearchnet
def _piecewise_learning_rate(step, boundaries, values): values = [1.0] + values boundaries = [float(x) for x in boundaries] return tf.train.piecewise_constant( step, boundaries, values, name="piecewise_lr")
Scale learning rate according to the given schedule. Multipliers are not cumulative. Args: step: global step boundaries: List of steps to transition on. values: Multiplier to apply at each boundary transition. Returns: Scaled value for the learning rate.
juraj-google-style
def generate(self, information, timeout=-1): return self._client.create(information, timeout=timeout)
Generates a self signed certificate or an internal CA signed certificate for RabbitMQ clients. Args: information (dict): Information to generate the certificate for RabbitMQ clients. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView; it just stops wai...
juraj-google-style
def _validate_exp(claims, leeway=0): if ('exp' not in claims): return try: exp = int(claims['exp']) except ValueError: raise JWTClaimsError('Expiration Time claim (exp) must be an integer.') now = timegm(datetime.utcnow().utctimetuple()) if (exp < (now - leeway)): rai...
Validates that the 'exp' claim is valid. The "exp" (expiration time) claim identifies the expiration time on or after which the JWT MUST NOT be accepted for processing. The processing of the "exp" claim requires that the current date/time MUST be before the expiration date/time listed in the "exp" claim. Implementers...
codesearchnet
def list_tags(self, image_name): tags_url = (self.registry_url + '/v2/{}/tags/list') r = self.get(tags_url.format(image_name), auth=self.auth) data = r.json() if ('tags' in data): return reversed(sorted(data['tags'])) return []
List all tags for the given image stored in the registry. Args: image_name (str): The name of the image to query. The image must be present on the registry for this call to return any values. Returns: list[str]: List of tags for that image.
codesearchnet
def open_tunnel(self, serial_no, port=19020): return self.open(ip_addr='tunnel:' + str(serial_no) + ':' + str(port))
Connects to the J-Link emulator (over SEGGER tunnel). Args: self (JLink): the ``JLink`` instance serial_no (int): serial number of the J-Link port (int): optional port number (default to 19020). Returns: ``None``
juraj-google-style
def find_element_by_id(self, id_, update=False) -> Elements: return self.find_element(by=By.ID, value=id_, update=update)
Finds an element by id. Args: id_: The id of the element to be found. update: If the interface has changed, this option should be True. Returns: The element if it was found. Raises: NoSuchElementException - If the element wasn't found. Usage: element = driver.find_element_by_id('foo')
juraj-google-style
def update_mim_version(self, new_genes, new_panel, old_version): LOG.info('Updating versions for new genes') version = new_panel['version'] for gene in new_panel['genes']: gene_symbol = gene['hgnc_id'] if gene_symbol in new_genes: gen...
Set the correct version for each gene Loop over the genes in the new panel Args: new_genes(set(str)): Set with the new gene symbols new_panel(dict)
juraj-google-style
def chain_to_quadratic(chain, target_adjacency, chain_strength): quadratic = {} seen = set() try: next_level = {next(iter(chain))} except StopIteration: raise ValueError('chain must have at least one variable') while next_level: this_level = next_level next_level = se...
Determine the quadratic biases that induce the given chain. Args: chain (iterable): The variables that make up a chain. target_adjacency (dict/:class:`networkx.Graph`): Should be a dict of the form {s: Ns, ...} where s is a variable in the target graph and Ns is the set of neighbours of s. chain_strength (float): Th...
codesearchnet
def _CallMethod(self, srvc, method_descriptor, rpc_controller, request, callback): if (method_descriptor.containing_service != self.descriptor): raise RuntimeError('CallMethod() given method descriptor for wrong service type.') method = getattr(srvc, method_descriptor.name) return method(rpc_control...
Calls the method described by a given method descriptor. Args: srvc: Instance of the service for which this method is called. method_descriptor: Descriptor that represent the method to call. rpc_controller: RPC controller to use for this method's execution. request: Request protocol message. callback: A callback to in...
codesearchnet
def length_squared(x, keep_dims=False, name=None, reduction_dim=None): with tf.name_scope(name, 'length_squared', [x]) as scope: x = tf.convert_to_tensor(x, name='x') if not reduction_dim: reduction_dim = _last_index(x, 1) return tf.reduce_sum( tf.square(x), reduction_dim, ...
Computes the squared length of x. Args: x: A tensor. keep_dims: If true, reduction does not change the rank of the input. name: Optional name for this op. reduction_dim: The dimension to reduce, by default choose the last one and if no shape is specified guess 1. Returns: The squared length of x.
juraj-google-style
def combine_columns(columns): columns_zipped = itertools.zip_longest(*columns) return ''.join(x for zipped in columns_zipped for x in zipped if x)
Combine ``columns`` into a single string. Example: >>> combine_columns(['eape', 'xml']) 'example' Args: columns (iterable): ordered columns to combine Returns: String of combined columns
juraj-google-style
def _gather_saveables_for_checkpoint(self): def _saveable_factory(name=self._common_name): return _SyncOnReadSaveable(self, name) return {trackable.VARIABLE_VALUE_KEY: _saveable_factory}
Overrides Trackable method. This allows both name-based and object-based save and restore of `SyncOnReadVariable`s. Returns: A dictionary mapping attribute names to `SaveableObject` factories.
github-repos
def GetBlockHash(self, height): if self._current_block_height < height: return if len(self._header_index) <= height: return return self._header_index[height]
Get the block hash by its block height Args: height(int): height of the block to retrieve hash from. Returns: bytes: a non-raw block hash (e.g. b'6dd83ed8a3fc02e322f91f30431bf3662a8c8e8ebe976c3565f0d21c70620991', but not b'\x6d\xd8...etc'
juraj-google-style
def _AddParentDirectories(self, path): path_segments = self.file_system.SplitPath(path) for segment_index in range(len(path_segments)): parent_path = self.file_system.JoinPath(path_segments[:segment_index]) file_entry = self.file_system.GetFileEntryByPath(parent_path) if (file_entry and ...
Adds the parent directories of a path to the fake file system. Args: path (str): path of the file within the fake file system. Raises: ValueError: if a parent directory is already set and is not a directory.
codesearchnet
def parse_arguments(argv): parser = argparse.ArgumentParser(description='write-to-pubsub') parser.add_argument('-m', '--mode', help='Mode to run pipeline in.', choices=['local', 'cloud'], default='local') parser.add_argument('-p', '--project', help='GCP project to run pipeline on.', default=cfg.PROJECT_ID) ...
It parses the arguments passed to the command line and returns them as an object Args: argv: The arguments passed to the command line. Returns: The arguments that are being passed in.
github-repos
def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs): df = pandas.read_hdf(path_or_buf, columns=columns, **kwargs) return (_split_result_for_readers(0, num_splits, df) + [len(df.index)])
Use a Ray task to read columns from HDF5 into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path_or_buf: The path of the HDF5 file. columns: The list of column names to read. num_splits: The number of partitions to split the column into. Returns: A list containing ...
codesearchnet
def edge(self, tail_name, head_name, label=None, _attributes=None, **attrs): tail_name = self._quote_edge(tail_name) head_name = self._quote_edge(head_name) attr_list = self._attr_list(label, attrs, _attributes) line = (self._edge % (tail_name, head_name, attr_list)) self.body.append(line)
Create an edge between two nodes. Args: tail_name: Start node identifier. head_name: End node identifier. label: Caption to be displayed near the edge. attrs: Any additional edge attributes (must be strings).
codesearchnet
def request_stop(self, ex=None): self._coord.request_stop(ex=ex)
Request that the coordinator stop the threads. See `Coordinator.request_stop()`. Args: ex: Optional `Exception`, or Python `exc_info` tuple as returned by `sys.exc_info()`. If this is the first call to `request_stop()` the corresponding exception is recorded and re-raised from `join()`.
github-repos
def _get_bonds(self, mol): num_atoms = len(mol) if self.ignore_ionic_bond: covalent_atoms = [i for i in range(num_atoms) if mol.species[i].symbol not in self.ionic_element_list] else: covalent_atoms = list(range(num_atoms)) all_pairs = list(itert...
Find all the bond in a molcule Args: mol: the molecule. pymatgen Molecule object Returns: List of tuple. Each tuple correspond to a bond represented by the id of the two end atoms.
juraj-google-style
def classify_coupling(coupling): (lower, upper) = coupling if ((lower is None) and (upper is None)): return CouplingClass.Uncoupled elif ((lower is None) or (upper is None)): return CouplingClass.DirectionalReverse elif ((lower == 0.0) and (upper == 0.0)): return CouplingClass.In...
Return a constant indicating the type of coupling. Depending on the type of coupling, one of the constants from :class:`.CouplingClass` is returned. Args: coupling: Tuple of minimum and maximum flux ratio
codesearchnet
def __init__(self, option): self.option = option super().__init__('invalid option name: {}'.format(option))
Initialization of instances: Args: option (str): invalid option name. Attributes: option (str): invalid option name.
juraj-google-style
def extend(self, step): self.timesteps.extend(step.timesteps) self.masks.extend(step.masks) self.x.extend(step.x) self.y.extend(step.y) self.i.extend(step.i) self.j.extend(step.j) self.end_time = step.end_time self.times = np.arange(self.start_tim...
Adds the data from another STObject to this object. Args: step: another STObject being added after the current one in time.
juraj-google-style
def getFilepaths(self, filename): return (os.path.join(os.environ['HOME'], filename), os.path.join(self.mackup.mackup_folder, filename))
Get home and mackup filepaths for given file Args: filename (str) Returns: home_filepath, mackup_filepath (str, str)
juraj-google-style
def align_segmentation(beat_times, song): try: segment_times, segment_labels = msaf.io.read_references(song) except: return None, None, None segment_times = np.asarray(segment_times) segment_intervals = msaf.utils.times_to_intervals(segment_times) beat_intervals = np...
Load a ground-truth segmentation, and align times to the nearest detected beats. Arguments: beat_times -- array song -- path to the audio file Returns: segment_beats -- array beat-aligned segment boundaries segment_times -- array true segment times segment_labels -- array list of segment labels
juraj-google-style
def get_capacity_vol(self, min_voltage=None, max_voltage=None, use_overall_normalization=True): pairs_in_range = self._select_in_voltage_range(min_voltage, max_voltage) normalization_vol = (self.normalization_volume if (use_overall_normalization or (len(pairs_in_range) == 0)) else pairs_in_range[(- 1)].vol_disc...
Get the volumetric capacity of the electrode. Args: min_voltage (float): The minimum allowable voltage for a given step. max_voltage (float): The maximum allowable voltage allowable for a given step. use_overall_normalization (booL): If False, normalize by the discharged state of only the voltage pairs matching the vo...
codesearchnet
def read(self, input_buffer, kmip_version=enums.KMIPVersion.KMIP_1_0): super(CreateKeyPairResponsePayload, self).read(input_buffer, kmip_version=kmip_version) local_buffer = utils.BytearrayStream(input_buffer.read(self.length)) if self.is_tag_next(enums.Tags.PRIVATE_KEY_UNIQUE_IDENTIFIER, local_buffer): ...
Read the data encoding the CreateKeyPair response payload and decode it into its constituent parts. Args: input_buffer (stream): A data buffer containing encoded object data, supporting a read method. kmip_version (KMIPVersion): An enumeration defining the KMIP version with which the object will be decoded. Optional, ...
codesearchnet
def PopEventSource(self): try: (_, _, event_source) = heapq.heappop(self._heap) except IndexError: return None return event_source
Pops an event source from the heap. Returns: EventSource: an event source or None on if no event source is available.
codesearchnet
def _hexencode(bytestring, insert_spaces=False): _checkString(bytestring, description='byte string') separator = ('' if (not insert_spaces) else ' ') byte_representions = [] for c in bytestring: byte_representions.append('{0:02X}'.format(ord(c))) return separator.join(byte_representions).str...
Convert a byte string to a hex encoded string. For example 'J' will return '4A', and ``'\\x04'`` will return '04'. Args: bytestring (str): Can be for example ``'A\\x01B\\x45'``. insert_spaces (bool): Insert space characters between pair of characters to increase readability. Returns: A string of twice the length, wi...
codesearchnet
def GetTopLevel(self, file_object): try: top_level_object = biplist.readPlist(file_object) except (biplist.InvalidPlistException, biplist.NotBinaryPlistException) as exception: raise errors.UnableToParseFile( 'Unable to parse plist with error: {0!s}'.format(exception)) ...
Returns the deserialized content of a plist as a dictionary object. Args: file_object (dfvfs.FileIO): a file-like object to parse. Returns: dict[str, object]: contents of the plist. Raises: UnableToParseFile: when the file cannot be parsed.
juraj-google-style
def retrieve_taf(station_icao) -> typing.Tuple[(typing.Union[(str, None)], typing.Union[(str, None)])]: url = _BASE_TAF_URL.format(station=station_icao) with requests.get(url) as resp: if (not resp.ok): return (f'''unable to obtain TAF for station {station_icao} Got to "http: return ...
Retrieves a TAF string from an online database Args: station_icao: ICAO of the station Returns: tuple of error, metar_str
codesearchnet
def get_path_to_datafile(path): if runfiles: r = runfiles.Create() new_fpath = r.Rlocation(_os.path.abspath(_os.path.join('tensorflow', path))) if new_fpath is not None and _os.path.exists(new_fpath): return new_fpath old_filepath = _os.path.join(_os.path.dirname(_inspect.get...
Get the path to the specified file in the data dependencies. The path is relative to tensorflow/ Args: path: a string resource path relative to tensorflow/ Returns: The path to the specified file present in the data attribute of py_test or py_binary. Raises: IOError: If the path is not found, or the resource can't ...
github-repos