code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def add_op_callback(self, callback): if callback not in self._thread_local_data.op_callbacks: self._thread_local_data.op_callbacks.append(callback)
Add a post-op callback to the context. A post-op callback is invoked immediately after an eager operation or function has finished execution or after a op has been added to a graph, providing access to the op's type, name input and output tensors. Multiple op callbacks can be added, in which case the callbacks will be...
github-repos
def append_to_list(self, key, *value, pipeline=False): if pipeline: self._pipeline.rpush(key, *value) else: self._db.rpush(key, *value)
Add new element to the end of the list stored at key. Args: key (str): Key where the list is stored value: Value to add to the list pipeline (bool): True, start a transaction block. Default false.
codesearchnet
def set_compare_estimator_and_feature_spec(self, estimator, feature_spec): self.delete('compare_custom_predict_fn') self.store('compare_estimator_and_spec', {'estimator': estimator, 'feature_spec': feature_spec}) self.set_compare_inference_address('estimator') if (not self.has_compare_model_name()): ...
Sets a second model for inference as a TF Estimator. If you wish to compare the results of two models in WIT, use this method to setup the details of the second model. Instead of using TF Serving to host a model for WIT to query, WIT can directly use a TF Estimator object as the model to query. In order to accomplish...
codesearchnet
def unwrap_values(distribution_strategy, grouped_inputs, grouped_outputs, grouped_updates=None, grouped_session_args=None, with_loss_tensor=False): all_inputs = flatten_per_replica_values(distribution_strategy, grouped_inputs) all_outputs = unwrap_outputs(distribution_strategy, grouped_outputs, with_loss_tensor...
Unwrap the list of values contained in the PerReplica parameters. This function calls `flatten_per_replica_values` to parse each of the input parameters into a list of values on the different devices. If we set `with_loss_tensor` to be True, we also call `reduce` on the list of losses on the different devices to give ...
github-repos
def to_pytd_type_of_instance(self, val: abstract.BaseValue) -> pytd.Type: if val is self._ctx.consts.Any: return pytd.AnythingType() elif val is self._ctx.consts[None]: return pytd.NamedType('builtins.NoneType') elif isinstance(val, abstract.Union): return pytd_utils.JoinTypes((self....
Returns the type of an instance of the abstract value, as a pytd node. For example, if the abstract value is: InterpreterClass(C) then to_pytd_type_of_instance() produces: pytd.NamedType(C) Args: val: The abstract value.
github-repos
def add_inputs(self, *args, **kwargs): if 'names' in kwargs: return [self._inputs.add(arg, name=name) for arg, name in zip(args, kwargs['names'])] else: return [self._inputs.add(arg) for arg in args]
Add a sequence of inputs to the function invocation. Args: *args: List of inputs to be converted (should be Tf.Tensor). **kwargs: This allows 'names' which should be a list of names. Returns: Wrapped inputs (identity standins that have additional metadata). These are also are also tf.Tensor's.
github-repos
def _GetIntegerValue(self, row, value_name): value = row.get(value_name, None) try: return int(value, 10) except (TypeError, ValueError): return None
Converts a specific value of the row to an integer. Args: row (dict[str, str]): fields of a single row, as specified in COLUMNS. value_name (str): name of the value within the row. Returns: int: value or None if the value cannot be converted.
juraj-google-style
def on_epoch_begin(self, epoch, logs=None):
Called at the start of an epoch. Subclasses should override for any actions to run. This function should only be called during TRAIN mode. Args: epoch: Integer, index of epoch. logs: Dict. Currently no data is passed to this argument for this method but that may change in the future.
github-repos
def detect_functions_called(contract): result = [] for func in contract.all_functions_called: for node in func.nodes: for ir in node.irs: if isinstance(ir, (InternalCall, SolidityCall)): result.append(ir.function) return result
Returns a list of InternallCall, SolidityCall calls made in a function Returns: (list): List of all InternallCall, SolidityCall
codesearchnet
def make(cls, name: str, *, def_opcode: 'opcodes.Opcode', code: 'blocks.OrderedCode', f_locals: _instances.LazyConcreteDict, f_globals: _instances.LazyConcreteDict, defaults, kw_defaults, closure, annotations: 'dict[str, _base.BaseValue]', ctx: 'context.Context'): annotations = annotations or {} overloads = ctx...
Get an InterpreterFunction. Things like anonymous functions and generator expressions are created every time the corresponding code executes. Caching them makes it easier to detect when the environment hasn't changed and a function call can be optimized away. Arguments: name: Function name. def_opcode: The opcode for...
github-repos
def hex_is_dark(hexx, percent=50): r, g, b = hex_to_rgb(hexx) luma = (0.2126 * r + 0.7152 * g + 0.0722 * b) / 2.55 return (luma < percent)
Function to decide if a hex colour is dark. Args: hexx (str): A hexadecimal colour, starting with '#'. Returns: bool: The colour's brightness is less than the given percent.
juraj-google-style
def debye_integral(y): factor = 3. / y ** 3 if y < 155: integral = quadrature(lambda x: x ** 3 / (np.exp(x) - 1.), 0, y) return list(integral)[0] * factor else: return 6.493939 * factor
Debye integral. Eq(5) in doi.org/10.1016/j.comphy.2003.12.001 Args: y (float): debye temperature/T, upper limit Returns: float: unitless
juraj-google-style
def check_type(value, type_def): if (type_def == 'integer'): try: int(value) return True except ValueError: return (isinstance(value, six.integer_types) and (not isinstance(value, bool))) elif (type_def == 'number'): return (isinstance(value, (six.inte...
Check if the value is in the type given in type_def. Args: value: the var to test. type_def: string representing the type in swagger. Returns: True if the type is correct, False otherwise.
codesearchnet
def _arguments(code, module): arg_parser = CommandParser.create('') try: builtins = {'source': _table, 'datestring': _datestring} env = {} env.update(builtins) exec(code, env) for key in env: if key in builtins or key[0] == '_': continue ...
Define pipeline arguments. Args: code: the Python code to execute that defines the arguments.
juraj-google-style
def __init__(self, wrapped: message.Message, unused_context: Context) -> None: self.wrapped = wrapped
Initializes a new PrimitiveWrapper with wrapped. Args: wrapped: The primitive message to wrap.
github-repos
def TempDirPath(suffix='', prefix='tmp'): precondition.AssertType(suffix, Text) precondition.AssertType(prefix, Text) return tempfile.mkdtemp(suffix=suffix, prefix=prefix, dir=_TempRootPath())
Creates a temporary directory based on the environment configuration. The directory will be placed in folder as specified by the `TEST_TMPDIR` environment variable if available or fallback to `Test.tmpdir` of the current configuration if not. Args: suffix: A suffix to end the directory name with. prefix: A prefix to ...
codesearchnet
def read(name, default=None, allow_none=False, fallback=None): raw_value = environ.get(name) if raw_value is None and fallback is not None: if not isinstance(fallback, builtins.list) and not isinstance(fallback, builtins.tuple): fallback = [fallback] for fall in fallback: ...
Read the raw env value. Read the raw environment variable or use the default. If the value is not found and no default is set throw an exception. Args: name: The environment variable name default: The default value to use if no environment variable is found allow_none: If the return value can be `None` (i.e. optional...
juraj-google-style
def check_semidefinite_positiveness(A): B = empty_like(A) B[:] = A B[diag_indices_from(B)] += sqrt(finfo(float).eps) try: cholesky(B) except LinAlgError: return False return True
Check if ``A`` is a semi-definite positive matrix. Args: A (array_like): Matrix. Returns: bool: ``True`` if ``A`` is definite positive; ``False`` otherwise.
codesearchnet
def WriteEventBody(self, event): for field_name in self._fields: if field_name == 'datetime': output_value = self._FormatDateTime(event) else: output_value = self._dynamic_fields_helper.GetFormattedField( event, field_name) output_value = self._RemoveIllegalXMLCha...
Writes the body of an event object to the spreadsheet. Args: event (EventObject): event.
juraj-google-style
def CredibleInterval(pmf, percentage=90): cdf = pmf.MakeCdf() prob = (1 - percentage / 100.0) / 2 interval = cdf.Value(prob), cdf.Value(1 - prob) return interval
Computes a credible interval for a given distribution. If percentage=90, computes the 90% CI. Args: pmf: Pmf object representing a posterior distribution percentage: float between 0 and 100 Returns: sequence of two floats, low and high
juraj-google-style
def __init__(self, enum_values, case_sensitive=True): if not enum_values: raise ValueError( 'enum_values cannot be empty, found "{}"'.format(enum_values)) super(EnumParser, self).__init__() self.enum_values = enum_values self.case_sensitive = case_sensitive
Initializes EnumParser. Args: enum_values: [str], a non-empty list of string values in the enum. case_sensitive: bool, whether or not the enum is to be case-sensitive. Raises: ValueError: When enum_values is empty.
juraj-google-style
def parse_date(value): if not value: return None if isinstance(value, datetime.date): return value return parse_datetime(value).date()
Attempts to parse `value` into an instance of ``datetime.date``. If `value` is ``None``, this function will return ``None``. Args: value: A timestamp. This can be a string, datetime.date, or datetime.datetime value.
juraj-google-style
def can_match(cls, pattern: Pattern) -> bool: if not isinstance(pattern.expression, Operation) or isinstance(pattern.expression, CommutativeOperation): return False if op_len(pattern.expression) < 3: return False first, *_, last = op_iter(pattern.expression) ...
Check if a pattern can be matched with a sequence matcher. Args: pattern: The pattern to check. Returns: True, iff the pattern can be matched with a sequence matcher.
juraj-google-style
def write(self, output='jsonstat'): if output == 'jsonstat': return json.dumps(self) elif output == 'dataframe_list': df_list = [] unnest_collection(self, df_list) return df_list else: raise ValueError( "Allowe...
Writes data from a Collection object to JSONstat or list of \ Pandas Dataframes. Args: output(string): can accept 'jsonstat' or 'dataframe_list' Returns: Serialized JSONstat or a list of Pandas Dataframes,depending on \ the 'output' parameter.
juraj-google-style
def map_tensor_fn(self, fn: Callable[[torch.Tensor], torch.Tensor]) -> Rigid: new_rots = self._rots.map_tensor_fn(fn) new_trans = torch.stack(list(map(fn, torch.unbind(self._trans, dim=-1))), dim=-1) return Rigid(new_rots, new_trans)
Apply a Tensor -> Tensor function to underlying translation and rotation tensors, mapping over the translation/rotation dimensions respectively. Args: fn: A Tensor -> Tensor function to be mapped over the Rigid Returns: The transformed Rigid object
github-repos
def __init__(self, underlying_runner=None, render_option=None, skip_display=True, force_compute=True, blocking=True): self._underlying_runner = underlying_runner or direct_runner.DirectRunner() self._render_option = render_option self._in_session = False self._skip_display = skip_display self._force...
Constructor of InteractiveRunner. Args: underlying_runner: (runner.PipelineRunner) render_option: (str) this parameter decides how the pipeline graph is rendered. See display.pipeline_graph_renderer for available options. skip_display: (bool) whether to skip display operations when running the pipeline. Useful if runn...
github-repos
def item_status(self, **kwargs): path = self._get_id_path('item_status') response = self._GET(path, kwargs) self._set_attrs_to_values(response) return response
Check to see if a movie id is already added to a list. Args: movie_id: The id of the movie. Returns: A dict respresentation of the JSON returned from the API.
codesearchnet
def _FormatArgToken(self, token_data): return { 'string': token_data.argument_value.rstrip('\x00'), 'num_arg': token_data.argument_index, 'is': token_data.argument_name}
Formats an argument token as a dictionary of values. Args: token_data (bsm_token_data_arg32|bsm_token_data_arg64): AUT_ARG32 or AUT_ARG64 token data. Returns: dict[str, str]: token values.
juraj-google-style
def create(self, key, value, lease='1h'): return self._client.write(key, value, lease=lease)
Create key/value pair in Vault. Args: key (string): The data key. value (string): The data value. lease (string): The least time.
juraj-google-style
def single_qubit_matrix_to_gates(mat: np.ndarray, tolerance: float=0) -> List[ops.SingleQubitGate]: rotations = single_qubit_matrix_to_pauli_rotations(mat, tolerance) return [(cast(ops.SingleQubitGate, pauli) ** ht) for (pauli, ht) in rotations]
Implements a single-qubit operation with few gates. Args: mat: The 2x2 unitary matrix of the operation to implement. tolerance: A limit on the amount of error introduced by the construction. Returns: A list of gates that, when applied in order, perform the desired operation.
codesearchnet
def _send_rpc(self, client, uuid, address, rpc, payload, timeout, key): conn_id = self._validate_connection('send_rpc', uuid, key) if (conn_id is None): return conn_data = self._connections[uuid] conn_data['last_touch'] = monotonic() slug = self._build_device_slug(uuid) try: resp...
Send an RPC to a connected device Args: client (string): The client that sent the rpc request uuid (int): The id of the device we're opening the interface on address (int): The address of the tile that we want to send the RPC to rpc (int): The id of the rpc that we want to send. payload (bytearray): The payload of arg...
codesearchnet
def build_url(self, data): query_part_one = [] query_part_two = [] keys_to_be_removed = [] for key, value in data.items(): if key not in ['version', 'restApi', 'resourcePath']: if key == 'mapArea': query_part_one.append(','.join(st...
This method occurs after dumping the data into the class. Args: data (dict): dictionary of all the query values Returns: data (dict): ordered dict of all the values
juraj-google-style
def history(self, hash): txs = self._t.get(hash, max_transactions=10000)['transactions'] tree = defaultdict(list) number_editions = 0 for tx in txs: _tx = self._t.get(tx['txid']) txid = _tx['txid'] verb_str = BlockchainSpider.check_script(_tx...
Retrieve the ownership tree of all editions of a piece given the hash. Args: hash (str): Hash of the file to check. Can be created with the :class:`File` class Returns: dict: Ownsership tree of all editions of a piece. .. note:: For now we only support searching the blockchain by the piece hash.
juraj-google-style
def track(self, event_key, user_id, attributes=None, event_tags=None): if not self.is_valid: self.logger.error(enums.Errors.INVALID_DATAFILE.format('track')) return if not validator.is_non_empty_string(event_key): self.logger.error(enums.Errors.INVALID_INPUT_ERROR.format('event_key')) ...
Send conversion event to Optimizely. Args: event_key: Event key representing the event which needs to be recorded. user_id: ID for user. attributes: Dict representing visitor attributes and values which need to be recorded. event_tags: Dict representing metadata associated with the event.
juraj-google-style
def _sync_content_metadata(self, serialized_data, http_method): try: (status_code, response_body) = getattr(self, ('_' + http_method))(urljoin(self.enterprise_configuration.degreed_base_url, self.global_degreed_config.course_api_path), serialized_data, self.CONTENT_PROVIDER_SCOPE) except requests.except...
Synchronize content metadata using the Degreed course content API. Args: serialized_data: JSON-encoded object containing content metadata. http_method: The HTTP method to use for the API request. Raises: ClientError: If Degreed API request fails.
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') storage_format = cls._ParseStringOption(options, 'storage_format') if not storage_format: ...
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 storage format is not defined or supported.
juraj-google-style
def occupations( self, site_label ): return sum( atom.site.label == site_label for atom in self.atoms )
Number of these atoms occupying a specific site type. Args: site_label (Str): Label for the site type being considered. Returns: (Int): Number of atoms occupying sites of type `site_label`.
juraj-google-style
def InventoryReceived(self, inventory): if inventory.Hash.ToBytes() in self._MissedBlocks: self._MissedBlocks.remove(inventory.Hash.ToBytes()) if inventory is MinerTransaction: return False if type(inventory) is Block: if BC.Default() is None: ...
Process a received inventory. Args: inventory (neo.Network.Inventory): expect a Block type. Returns: bool: True if processed and verified. False otherwise.
juraj-google-style
def extractDays(self, inp): inp = self._preprocess(inp) def extractDayOfWeek(dayMatch): if dayMatch.group(5) in self.__daysOfWeek__: return self.__daysOfWeek__.index(dayMatch.group(5)) elif dayMatch.group(6) in self.__daysOfWeek__: return...
Extracts all day-related information from an input string. Ignores any information related to the specific time-of-day. Args: inp (str): Input string to be parsed. Returns: A list of datetime objects containing the extracted date from the input snippet, or an empty list if none found.
juraj-google-style
def download_listing(self, file: Optional[IO], duration_timeout: Optional[float]=None) -> \ ListingResponse: if self._session_state != SessionState.directory_request_sent: raise RuntimeError('File request not sent') self._session_state = Session...
Read file listings. Args: file: A file object or asyncio stream. duration_timeout: Maximum time in seconds of which the entire file must be read. Returns: A Response populated the file listings Be sure to call :meth:`start_file_listing` first. Coroutine.
juraj-google-style
def _print(self, *args): def _format(name, arr): title = ' tlen = len(title) print('-' * tlen) print(title) print('-' * tlen) print(' Total if arr: for item in arr: detail = '' if isinstance(item[1], list)...
Prints compatibility check status and failure or warning messages. Prints to console without using `logging`. Args: *args: String(s) that is one of: [`failures`, # all failures `successes`, # all successes `failure_msgs`, # failure message(s) recorded upon failure(s) `warning_msgs`] # warning message(s...
github-repos
def make_reply(self): return Message(to=str(self.sender), sender=str(self.to), body=self.body, thread=self.thread, metadata=self.metadata)
Creates a copy of the message, exchanging sender and receiver Returns: spade.message.Message: a new message with exchanged sender and receiver
codesearchnet
def has_shell_command(self, command) -> bool: try: output = self.shell(['command', '-v', command]).decode('utf-8').strip() return command in output except AdbError: return False
Checks to see if a given check command exists on the device. Args: command: A string that is the name of the command to check. Returns: A boolean that is True if the command exists and False otherwise.
github-repos
def update_fetch_positions(self, partitions): for tp in partitions: if not self._subscriptions.is_assigned(tp): log.warning("partition %s is not assigned - skipping offset" " update", tp) continue elif self._su...
Update the fetch positions for the provided partitions. Arguments: partitions (list of TopicPartitions): partitions to update Raises: NoOffsetForPartitionError: if no offset is stored for a given partition and no reset policy is available
juraj-google-style
def _load_submissions_from_datastore_dir(self, dir_suffix, id_pattern): submissions = self._storage_client.list_blobs( prefix=os.path.join(self._round_name, dir_suffix)) return { id_pattern.format(idx): SubmissionDescriptor( path=s, participant_id=participant_from_submission_pat...
Loads list of submissions from the directory. Args: dir_suffix: suffix of the directory where submissions are stored, one of the folowing constants: ATTACK_SUBDIR, TARGETED_ATTACK_SUBDIR or DEFENSE_SUBDIR. id_pattern: pattern which is used to generate (internal) IDs for submissins. One of the following constants: ATTA...
juraj-google-style
def create(self, validated_data): email_query = models.EmailAddress.objects.filter(email=self.validated_data['email']) if email_query.exists(): email = email_query.get() email.send_duplicate_notification() else: email = super(EmailSerializer, self).create(validated_data) emai...
Create a new email and send a confirmation to it. Returns: The newly creating ``EmailAddress`` instance.
codesearchnet
def execute_by_options(args): if (args['subcommand'] == 'sphinx'): s = Sphinx(proj_info) if args['quickstart']: s.quickstart() elif args['gen_code_api']: s.gen_code_api() elif args['rst2html']: s.rst2html() pass elif (args['subcommand']...
execute by argument dictionary Args: args (dict): command line argument dictionary
codesearchnet
def valueReadPreprocessor(valueString, replaceParamsFile=None): if type(valueString) is bool: log.warning("Only numerical variable types can be handled by the valueReadPreprocessor function.") return valueString processedValue = valueString if replaceParamsFile is not None a...
Apply global pre-processing to values during reading throughout the project. Args: valueString (str): String representing the value to be preprocessed. replaceParamsFile (gsshapy.orm.ReplaceParamFile, optional): Instance of the replace param file. Required if replacement variables are included in the project. Returns...
juraj-google-style
def plot_series(filename, plot_kwargs=None): import matplotlib.pyplot as plt if plot_kwargs is None: plot_kwargs = {} data = np.genfromtxt(filename, dtype='i8,f4', names=['k', 'v']) index = data['k'] values = data['v'] plt.plot(index, values, **plot_kwargs)
Plot series data from MonitorSeries output text file. Args: filename (str): Path to *.series.txt file produced by :obj:`~nnabla.MonitorSeries` class. plot_kwags (dict, optional): Keyward arguments passed to :function:`matplotlib.pyplot.plot`. Note: matplotlib package is required.
juraj-google-style
def console_wait_for_keypress(flush: bool) -> Key: key = Key() lib.TCOD_console_wait_for_keypress_wrapper(key.key_p, flush) return key
Block until the user presses a key, then returns a new Key. Args: flush bool: If True then the event queue is cleared before waiting for the next event. Returns: Key: A new Key instance. .. deprecated:: 9.3 Use the :any:`tcod.event.wait` function to wait for events.
codesearchnet
def resname_in_proximity(resname, model, chains, resnums, threshold=5): residues = [r for r in model.get_residues() if (r.get_resname() == resname)] chains = ssbio.utils.force_list(chains) resnums = ssbio.utils.force_list(resnums) for chain in chains: for resnum in resnums: my_residu...
Search within the proximity of a defined list of residue numbers and their chains for any specifed residue name. Args: resname (str): Residue name to search for in proximity of specified chains + resnums model: Biopython Model object chains (str, list): Chain ID or IDs to check resnums (int, list): Residue numbers wit...
codesearchnet
def front(self, n): new_dtypes = ( self._dtype_cache if self._dtype_cache is None else self._dtype_cache[:n] ) if self._is_transposed: result = self.__constructor__( self.data.transpose().take(0, n).transpose(), self.index...
Returns the first n columns. Args: n: Integer containing the number of columns to return. Returns: DataManager containing the first n columns of the original DataManager.
juraj-google-style
def proba2onehot(proba: [list, np.ndarray], confident_threshold: float, classes: [list, np.ndarray]) -> np.ndarray: return labels2onehot(proba2labels(proba, confident_threshold, classes), classes)
Convert vectors of probabilities to one-hot representations using confident threshold Args: proba: samples where each sample is a vector of probabilities to belong with given classes confident_threshold: boundary of probability to belong with a class classes: array of classes' names Returns: 2d array with one-hot rep...
codesearchnet
def send(self, message): body = { 'notificationType': self._notification_type, 'priority': self._priority, 'isOrganization': self._is_organization, 'message': message, } if self._recipients: body['recipients'] = self._recipien...
Send our message Args: message (str): The message to be sent. Returns: requests.models.Response: The response from the request.
juraj-google-style
def tabledata_insert_all(self, table_name, rows): url = ((Api._ENDPOINT + (Api._TABLES_PATH % table_name)) + '/insertAll') data = {'kind': 'bigquery return datalab.utils.Http.request(url, data=data, credentials=self._credentials)
Issues a request to insert data into a table. Args: table_name: the name of the table as a tuple of components. rows: the data to populate the table, as a list of dictionaries. Returns: A parsed result object. Raises: Exception if there is an error performing the operation.
codesearchnet
def format_arguments(*args): positional_args = [] kwargs = {} split_key = None for arg in args: if arg.startswith('--'): arg = arg[2:] if '=' in arg: key, value = arg.split('=', 1) kwargs[key.replace('-', '_')] = value el...
Converts a list of arguments from the command line into a list of positional arguments and a dictionary of keyword arguments. Handled formats for keyword arguments are: * --argument=value * --argument value Args: *args (list): a list of arguments Returns: ([positional_args], {kwargs})
juraj-google-style
def retry_api_check(exception): if isinstance(exception, apiclient.errors.HttpError): if exception.resp.status in TRANSIENT_HTTP_ERROR_CODES: _print_error('Retrying...') return True if isinstance(exception, socket.error): if exception.errno in TRANSIENT_SOCKET_ERROR_CODES: _print_error...
Return True if we should retry. False otherwise. Args: exception: An exception to test for transience. Returns: True if we should retry. False otherwise.
juraj-google-style
def process_gatt_service(services, event): length = (len(event.payload) - 5) (handle, start, end, uuid) = unpack(('<BHH%ds' % length), event.payload) uuid = process_uuid(uuid) services[uuid] = {'uuid_raw': uuid, 'start_handle': start, 'end_handle': end}
Process a BGAPI event containing a GATT service description and add it to a dictionary Args: services (dict): A dictionary of discovered services that is updated with this event event (BGAPIPacket): An event containing a GATT service
codesearchnet
def set_ignores(self, folder, *patterns): if not patterns: return {} data = {'ignore': list(patterns)} return self.post('ignores', params={'folder': folder}, data=data)
Applies ``patterns`` to ``folder``'s ``.stignore`` file. Args: folder (str): patterns (str): Returns: dict
juraj-google-style
def ParseTextToDicts(self, *args, **kwargs): result_lists = self.ParseText(*args, **kwargs) result_dicts = [] for row in result_lists: result_dicts.append(dict(zip(self.header, row))) return result_dicts
Calls ParseText and turns the result into list of dicts. List items are dicts of rows, dict key is column header and value is column value. Args: text: (str), Text to parse with embedded newlines. eof: (boolean), Set to False if we are parsing only part of the file. Suppresses triggering EOF state. Raises: TextFSMEr...
codesearchnet
def set_shape(self, shape): raise NotImplementedError
Overrides the shape for this variable. Args: shape: the `TensorShape` representing the overridden shape.
github-repos
def send_email_message(self, recipient, subject, html_message, text_message, sender_email, sender_name): sender = (('"%s" <%s>' % (sender_name, sender_email)) if sender_name else sender_email) if (not current_app.testing): try: from flask_mail import Message message = Message(sub...
Send email message via Flask-Mail. Args: recipient: Email address or tuple of (Name, Email-address). subject: Subject line. html_message: The message body in HTML. text_message: The message body in plain text.
codesearchnet
def _generate_state(self, trans): state = PDAState() state.id = self.nextstate() state.type = 2 state.sym = state.id state.trans = trans.copy() self.toadd.append(state) return state.id
Creates a new POP state (type - 2) with the same transitions. The POPed symbol is the unique number of the state. Args: trans (dict): Transition dictionary Returns: Int: The state identifier
juraj-google-style
def __init__(self, scope, parent, paren=False): CodeLiteral.__init__(self, scope, parent, None, 'null', paren)
Constructor for null literals. Args: scope (CodeEntity): The program scope where this object belongs. parent (CodeEntity): This object's parent in the program tree. Kwargs: paren (bool): Whether the null literal is enclosed in parentheses.
juraj-google-style
def affine_coupling(name, x, mid_channels=512, activation="relu", reverse=False, dropout=0.0): with tf.variable_scope(name, reuse=tf.AUTO_REUSE): x_shape = common_layers.shape_list(x) x1, x2 = tf.split(x, num_or_size_splits=2, axis=-1) z1 = x1 log_scale...
Reversible affine coupling layer. Args: name: variable scope. x: 4-D Tensor. mid_channels: number of channels in the coupling layer. activation: Can be either "relu" or "gatu". reverse: Forward or reverse operation. dropout: default, 0.0 Returns: output: x shifted and scaled by an affine transformation. objective: log...
juraj-google-style
def remove_attribute(self, attr): update = [fapi._attr_rem(attr)] r = fapi.update_workspace_attributes(self.namespace, self.name, update, self.api_url) self.data["workspace"]["attributes"].pop(attr, None) fapi._check_response_code(...
Remove attribute from a workspace. Args: attr (str): attribute name
juraj-google-style
def ReadPathInfoHistory(self, client_id, path_type, components): histories = self.ReadPathInfosHistories(client_id, path_type, [components]) return histories[components]
Reads a collection of hash and stat entry for given path. Args: client_id: An identifier string for a client. path_type: A type of a path to retrieve path history for. components: A tuple of path components corresponding to path to retrieve information for. Returns: A list of `rdf_objects.PathInfo` ordered by timesta...
juraj-google-style
def _format_batch_statuses(statuses, batch_ids, tracker): proto_statuses = [] for batch_id in batch_ids: if statuses[batch_id] == \ client_batch_submit_pb2.ClientBatchStatus.INVALID: invalid_txns = tracker.get_invalid_txn_info(batch_id) for txn_info in invalid_tx...
Takes a statuses dict and formats it for transmission with Protobuf and ZMQ. Args: statuses (dict of int): Dict with batch ids as the key, status as value batch_ids (list of str): The batch ids in their original order tracker (BatchTracker): A batch tracker with access to invalid info
juraj-google-style
def easeInOutQuart(n): _checkRange(n) n = (2 * n) if (n < 1): return (0.5 * (n ** 4)) else: n = (n - 2) return ((- 0.5) * ((n ** 4) - 2))
A quartic tween function that accelerates, reaches the midpoint, and then decelerates. Args: n (float): The time progress, starting at 0.0 and ending at 1.0. Returns: (float) The line progress, starting at 0.0 and ending at 1.0. Suitable for passing to getPointOnLine().
codesearchnet
def cmd_ssh(options): import os import subprocess from os.path import expanduser options.inst_state = 'running' (i_info, param_str) = gather_data(options) (tar_inst, tar_idx) = determine_inst(i_info, param_str, options.command) home_dir = expanduser('~') if (options.user is None): ...
Connect to the specified instance via ssh. Finds instances that match the user specified args that are also in the 'running' state. The target instance is determined, the required connection information is retreived (IP, key and ssh user-name), then an 'ssh' connection is made to the instance. Args: options (object)...
codesearchnet
def _render_node_traceback(self, node_name): lines = [RL(''), RL(''), RL('Traceback of node construction:', 'bold')] try: node_stack = self._debug_dump.node_traceback(node_name) for depth, (file_path, line, function_name, text) in enumerate(node_stack): lines.append('%d: %s' % (depth...
Render traceback of a node's creation in Python, if available. Args: node_name: (str) name of the node. Returns: A RichTextLines object containing the stack trace of the node's construction.
github-repos
def fill_with_past_key_values_(self, inputs_or_outputs: Mapping[str, Mapping[int, str]], direction: str, inverted_values_shape: bool=False): if direction not in ['inputs', 'outputs']: raise ValueError(f'direction must either be "inputs" or "outputs", but {direction} was given') name = 'past_key_values' ...
Fill the input_or_outputs mapping with past_key_values dynamic axes considering. Args: inputs_or_outputs: The mapping to fill. direction: either "inputs" or "outputs", it specifies whether input_or_outputs is the input mapping or the output mapping, this is important for axes naming. inverted_values_shape: If `True`, ...
github-repos
def all_subnets_longer_prefix(ip_net, cidr): subnets_list = list() while int(cidr) <= 32: try: subnets_list.append('%s/%s' % (whole_subnet_maker(ip_net, cidr), cidr)) except Exception as e: LOGGER.critical('Function all_subnets_longer_prefix {item}'.format(item=e)) ...
Function to return every subnet a ip can belong to with a longer prefix Args: ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 0 to 32 Returns: returns a list of subnets
juraj-google-style
def _parse_trunk_allowed_vlans(self, config): match = re.search(r'switchport trunk allowed vlan (.+)$', config, re.M) return dict(trunk_allowed_vlans=match.group(1))
Scans the specified config and parse the trunk allowed vlans value Args: config (str): The interface configuration block to scan Returns: dict: A Python dict object with the value of switchport trunk allowed vlans value. The dict returned is intended to be merged into the resource dict
juraj-google-style
def layout(self, dimensions=None, **kwargs): dimensions = self._valid_dimensions(dimensions) if len(dimensions) == self.ndims: with item_check(False): return NdLayout(self, **kwargs).reindex(dimensions) return self.groupby(dimensions, container_type=NdLayout,...
Group by supplied dimension(s) and lay out groups Groups data by supplied dimension(s) laying the groups along the dimension(s) out in a NdLayout. Args: dimensions: Dimension(s) to group by Returns: NdLayout with supplied dimensions
juraj-google-style
def clipping_params(ts, capacity=100): ts_sorted = ts.order(ascending=False) i, t0, t1, integral = 1, None, None, 0 while integral <= capacity and i+1 < len(ts): i += 1 t0_within_capacity = t0 t1_within_capacity = t1 t0 = min(ts_sorted.index[:i]) t1 = max(ts_sort...
Start and end index that clips the price/value of a time series the most Assumes that the integrated maximum includes the peak (instantaneous maximum). Arguments: ts (TimeSeries): Time series to attempt to clip to as low a max value as possible capacity (float): Total "funds" or "energy" available for clipping (integ...
juraj-google-style
def _GetVisitSource(self, visit_identifier, cache, database): sync_cache_results = cache.GetResults('sync') if not sync_cache_results: result_set = database.Query(self._SYNC_CACHE_QUERY) cache.CacheQueryResults(result_set, 'sync', 'id', ('source',)) sync_cache_results = cache.GetResults(...
Retrieves a visit source type based on the identifier. Args: visit_identifier (str): identifier from the visits table for the particular record. cache (SQLiteCache): cache which contains cached results from querying the visit_source table. database (SQLiteDatabase): database. Returns: int: visit source type or None i...
juraj-google-style
def export_template(access_token, subscription_id, rgname): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourcegroups/', rgname, '/exportTemplate', '?api-version=', RESOURCE_API]) ...
Capture the specified resource group as a template Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. rgname (str): Azure resource group name. Returns: HTTP response. JSON body.
juraj-google-style
def determine_encoding(path, default=None): byte_order_marks = (('utf-8-sig', (codecs.BOM_UTF8,)), ('utf-16', (codecs.BOM_UTF16_LE, codecs.BOM_UTF16_BE)), ('utf-32', (codecs.BOM_UTF32_LE, codecs.BOM_UTF32_BE))) try: with open(path, 'rb') as infile: raw = infile.read(4) except IOError: ...
Determines the encoding of a file based on byte order marks. Arguments: path (str): The path to the file. default (str, optional): The encoding to return if the byte-order-mark lookup does not return an answer. Returns: str: The encoding of the file.
codesearchnet
def set_presence(self, state=None, status=None, priority=None): state = (state if (state is not None) else self.state) status = (status if (status is not None) else self.status) priority = (priority if (priority is not None) else self.priority) self.presenceserver.set_presence(state, status, priority)
Change the presence broadcast by the client. If the client is currently connected, the new presence is broadcast immediately. Args: state(aioxmpp.PresenceState, optional): New presence state to broadcast (Default value = None) status(dict or str, optional): New status information to broadcast (Default value = None) pr...
codesearchnet
def __pad_value(value, pad_len_multiple, pad_char): assert (pad_len_multiple > 0) assert (len(pad_char) == 1) padding_length = ((pad_len_multiple - (len(value) % pad_len_multiple)) % pad_len_multiple) return (value + (pad_char * padding_length))
Add padding characters to the value if needed. Args: value: The string value to be padded. pad_len_multiple: Pad the result so its length is a multiple of pad_len_multiple. pad_char: The character to use for padding. Returns: The string value with padding characters added.
codesearchnet
def ready(self, node_id, metadata_priority=True): self.maybe_connect(node_id) return self.is_ready(node_id, metadata_priority=metadata_priority)
Check whether a node is connected and ok to send more requests. Arguments: node_id (int): the id of the node to check metadata_priority (bool): Mark node as not-ready if a metadata refresh is required. Default: True Returns: bool: True if we are ready to send to the given node
juraj-google-style
def get_compatible_func(op, func): op_signature = _remove_annotation(tf_inspect.signature(op)) func_signature = _remove_annotation(tf_inspect.signature(func)) if op_signature == func_signature: return func op_pos_names = _get_required_param_names(op_signature) func_pos_names = _get_required_...
Returns a compatible function. Args: op: a callable with whose signature the returned function is compatible. func: a callable which is called by the returned function. Returns: a compatible function, which conducts the actions of `func` but can be called like `op`, given that: - the list of required arguments in `fu...
github-repos
def generate_chrome_trace_format(self, show_dataflow: bool=True, show_memory: bool=False, op_time: str='schedule') -> str: step_stats_analysis = self.analyze_step_stats(show_dataflow=show_dataflow, show_memory=show_memory, op_time=op_time) return step_stats_analysis.chrome_trace.format_to_string(pretty=True)
Produces a trace in Chrome Trace Format. Args: show_dataflow: (Optional.) If True, add flow events to the trace connecting producers and consumers of tensors. show_memory: (Optional.) If True, add object snapshot events to the trace showing the sizes and lifetimes of tensors. op_time: (Optional.) How the execution tim...
github-repos
def get_lock_state_transaction(self, transaction_id): response = None try: response = requests.get(urls.get_lockstate_transaction(self._giid, transaction_id), headers={'Accept': 'application/json, text/javascript, */*; q=0.01', 'Cookie': 'vid={}'.format(self._vid)}) except requests.exceptions.Reques...
Get lock state transaction status Args: transaction_id: Transaction ID received from set_lock_state
codesearchnet
def __init__(self, validate_args=False, name="cholesky_outer_product"): self._graph_parents = [] self._name = name super(CholeskyOuterProduct, self).__init__( forward_min_event_ndims=2, validate_args=validate_args, name=name)
Instantiates the `CholeskyOuterProduct` bijector. Args: validate_args: Python `bool` indicating whether arguments should be checked for correctness. name: Python `str` name given to ops managed by this object.
juraj-google-style
def _get_internal_slot(slot_key=None, filler_pipeline_key=None, slot_dict=None): if (slot_dict is None): slot_dict = {} slot_record = slot_dict.get(slot_key) if (slot_record is None): raise PipelineStatusError(('Could not find data for output slot key "%s".' % slot_key)) output = {} ...
Gets information about a _SlotRecord for display in UI. Args: slot_key: The db.Key of the slot to fetch. filler_pipeline_key: In the case the slot has not yet been filled, assume that the given db.Key (for a _PipelineRecord) will be the filler of the slot in the future. slot_dict: The slot JSON dictionary. Returns: D...
codesearchnet
def __init__(self, name: str, path: str): self._test_suite = self.create_test_suite(name, path)
Initializes the YamlExamplesTestSuite. Args: name: The name of the test suite. This will be used as the class name for the dynamically generated test suite. path: A string representing the path or glob pattern to search for YAML example files.
github-repos
def __call__(self, **kwargs): assert self._last_report_time is not None, ( "StatusReporter._start() must be called before the first " "report __call__ is made to ensure correct runtime metrics.") report_time = time.time() if TIME_THIS_ITER_S n...
Report updated training status. Pass in `done=True` when the training job is completed. Args: kwargs: Latest training result status. Example: >>> reporter(mean_accuracy=1, training_iteration=4) >>> reporter(mean_accuracy=1, training_iteration=4, done=True) Raises: StopIteration: A StopIteration exception is raised ...
juraj-google-style
def ProduceAnalysisReport(self, plugin): analysis_report = plugin.CompileReport(self) if (not analysis_report): return analysis_report.time_compiled = timelib.Timestamp.GetNow() plugin_name = getattr(analysis_report, 'plugin_name', plugin.plugin_name) if plugin_name: analysis_report....
Produces an analysis report. Args: plugin (AnalysisPlugin): plugin.
codesearchnet
def _CreateCampaign(client, budget): campaign_service = client.GetService('CampaignService') operations = [{ 'operator': 'ADD', 'operand': { 'name': 'Interplanetary Cruise 'status': 'PAUSED', 'advertisingChannelType': 'SEARCH', ...
Creates the campaign. Args: client: an AdWordsClient instance. budget: a suds.sudsobject.Object representation of a created budget. Returns: An integer campaign ID.
juraj-google-style
def _ReadN(self, n): ret = "" while True: chunk = self._read_file.read(n - len(ret)) ret += chunk if len(ret) == n or not chunk: return ret
Reads n characters from the input stream, or until EOF. This is equivalent to the current CPython implementation of read(n), but not guaranteed by the docs. Args: n: int Returns: string
juraj-google-style
def _binding_to_coroutine(state, b, bad_bindings, ret, top, ctx): if b not in bad_bindings: ret.PasteBinding(b) return state if ctx.matcher(state.node).match_var_against_type(b.variable, ctx.convert.generator_type, {}, {b.variable: b}) is not None: ret_param = b.data.get_instance_type_pa...
Helper for _to_coroutine. Args: state: The current state. b: A cfg.Binding. bad_bindings: Bindings that are not coroutines. ret: A return variable that this helper will add to. top: Whether this is the top-level recursive call. ctx: The current context. Returns: The state.
github-repos
def encode(self, input_ids: jnp.ndarray, attention_mask: Optional[jnp.ndarray]=None, output_attentions: Optional[bool]=None, output_hidden_states: Optional[bool]=None, return_dict: Optional[bool]=None, train: bool=False, params: Optional[dict]=None, dropout_rng: PRNGKey=None): output_attentions = output_attentions ...
Returns: Example: ```python >>> from transformers import AutoTokenizer, FlaxT5ForConditionalGeneration >>> tokenizer = AutoTokenizer.from_pretrained("google-t5/t5-small") >>> model = FlaxT5ForConditionalGeneration.from_pretrained("google-t5/t5-small") >>> text = "My friends are cool but they eat too many carbs." >>...
github-repos
def save_to_mat_file(self, parameter_space, result_parsing_function, filename, runs): for key in parameter_space: if (not isinstance(parameter_space[key], list)): parameter_space[key] = [parameter_space[key]] dimension_labels = ([{key: str(parameter_space[key])} for key in parameter_space.ke...
Return the results relative to the desired parameter space in the form of a .mat file. Args: parameter_space (dict): dictionary containing parameter/list-of-values pairs. result_parsing_function (function): user-defined function, taking a result dictionary as argument, that can be used to parse the result files and re...
codesearchnet
def find_pad_index(self, array): try: return list(array).index(self.pad_value) except ValueError: return len(array)
Find padding index. Args: array (list): integer list. Returns: idx: padding index. Examples: >>> array = [1, 2, 0] >>> self.find_pad_index(array) 2
codesearchnet
def display(port=None, height=None): _display(port=port, height=height, print_message=True, display_handle=None)
Display a TensorBoard instance already running on this machine. Args: port: The port on which the TensorBoard server is listening, as an `int`, or `None` to automatically select the most recently launched TensorBoard. height: The height of the frame into which to render the TensorBoard UI, as an `int` number of pixels...
juraj-google-style
async def _notify_event_internal(self, conn_string, name, event): try: self._currently_notifying = True conn_id = self._get_conn_id(conn_string) event_maps = self._monitors.get(conn_string, {}) wildcard_maps = self._monitors.get(None, {}) wildcard_handlers = wildcard_maps.get...
Notify that an event has occured. This method will send a notification and ensure that all callbacks registered for it have completed by the time it returns. In particular, if the callbacks are awaitable, this method will await them before returning. The order in which the callbacks are called is undefined. This is...
codesearchnet
def to_csv(self, filename=None, as_text=True, use_descriptions=False, dlm=',', header=True): if (filename is None): if (not as_text): raise StriplogError('You must provide a filename or set as_text to True.') else: as_text = False if as_text: output = StringIO() else:...
Returns a CSV string built from the summaries of the Intervals. Args: use_descriptions (bool): Whether to use descriptions instead of summaries, if available. dlm (str): The delimiter. header (bool): Whether to form a header row. Returns: str: A string of comma-separated values.
codesearchnet
def get_vnet(access_token, subscription_id, resource_group, vnet_name): endpoint = ''.join([get_rm_endpoint(), '/subscriptions/', subscription_id, '/resourceGroups/', resource_group, '/providers/Microsoft.Network/virtualNetworks/', vnet_na...
Get details about the named virtual network. Args: access_token (str): A valid Azure authentication token. subscription_id (str): Azure subscription id. resource_group (str): Azure resource group name. vnet_name (str): Name of the VNet. Returns: HTTP response. VNet JSON body.
juraj-google-style