code
stringlengths
20
4.93k
docstring
stringlengths
33
1.27k
source
stringclasses
3 values
def related_domains(self, domains): api_name = 'opendns-related_domains' fmt_url_path = u'links/name/{0}.json' return self._multi_get(api_name, fmt_url_path, domains)
Get list of domain names that have been seen requested around the same time (up to 60 seconds before or after) to the given domain name. Args: domains: an enumerable of strings domain names Returns: An enumerable of [domain name, scores]
juraj-google-style
def _parse_line(self, instrumentation_block, line): if instrumentation_block.state == _InstrumentationBlockStates.METHOD: return self._parse_method_block_line(instrumentation_block, line) elif instrumentation_block.state == _InstrumentationBlockStates.RESULT: return self._parse_result_block_line...
Parses an arbitrary line from the instrumentation output based upon the current parser state. Args: instrumentation_block: _InstrumentationBlock, an instrumentation block with any of the possible parser states. line: string, the raw instrumentation output line to parse appropriately. Returns: The next instrumenation ...
github-repos
def add_get(self, path, controller, template, raw=False): if raw: fn = controller else: fn = self._prepare_controller(controller, template) self.app.router.add_get(path, fn)
Setup a route of type GET Args: path (str): URL to listen to controller (coroutine): the coroutine to handle the request template (str): the template to render the response or None if it is a JSON response raw (bool): indicates if post-processing (jinja, json, etc) is needed or not
juraj-google-style
def empty_like(x, init=None): x = ops.convert_to_tensor(x) return gen_array_ops.empty(array_ops.shape(x), x.dtype, init=init)
Returns a non-initialized tensor with the same shape and dtype as x. Args: x: A Tensor. init: Initialize the returned tensor with the default value of x.dtype(), if True. Otherwise, do not initialize. Defaults to None. Returns: A tensor y, whose dtype and shape are the same as those of x. y is guaranteed not to be an...
github-repos
def valid(self, value, level=[]): self.validation_failures = [] if value is None and self._optional: return True if not isinstance(value, dict): self.validation_failures.append(('.'.join(level), str(value))) return False bRet = True for k in self._nodes: lLevel = level[...
Valid Checks if a value is valid based on the instance's values Arguments: value {mixed} -- The value to validate Returns: bool
juraj-google-style
def chmod_r(root: str, permission: int) -> None: os.chmod(root, permission) for (dirpath, dirnames, filenames) in os.walk(root): for d in dirnames: os.chmod(os.path.join(dirpath, d), permission) for f in filenames: os.chmod(os.path.join(dirpath, f), permission)
Recursive ``chmod``. Args: root: directory to walk down permission: e.g. ``e.g. stat.S_IWUSR``
codesearchnet
def pre_run_cell(self, cellno, code): self.cellid = cellno import ast if findloop(ast.parse(code)): from acorn.logging.decoration import set_streamlining set_streamlining(True) ...
Executes before the user-entered code in `ipython` is run. This intercepts loops and other problematic code that would produce lots of database entries and streamlines it to produce only a single entry. Args: cellno (int): the cell number that is about to be executed. code (str): python source code that is about to be...
juraj-google-style
def get_ini(self, incl_unset=False): configp = configparser.ConfigParser(allow_no_value=True) configp.read_dict(self._config) with StringIO() as config_ini: if self._parser: self._parser.set_defaults( **self.get_section(self.root_section)...
Return the config dictionary in INI format Args: incl_unset (bool): include variables with no defaults. Returns: str: string of the config file in INI format
juraj-google-style
def _display(port=None, height=None, print_message=False, display_handle=None): if (height is None): height = 800 if (port is None): infos = manager.get_all() if (not infos): raise ValueError("Can't display TensorBoard: no known instances running.") else: ...
Internal version of `display`. Args: port: As with `display`. height: As with `display`. print_message: True to print which TensorBoard instance was selected for display (if applicable), or False otherwise. display_handle: If not None, an IPython display handle into which to render TensorBoard.
codesearchnet
def set_flowcontrol(self, name, direction, value=None, default=False, disable=False): if (value is not None): if (value not in ['on', 'off']): raise ValueError('invalid flowcontrol value') if (direction not in ['send', 'receive']): raise ValueError('invalid direction specified') ...
Configures the interface flowcontrol value Args: name (string): The interface identifier. It must be a full interface name (ie Ethernet, not Et) direction (string): one of either 'send' or 'receive' value (boolean): True if the interface should enable flow control packet handling, otherwise False default (boolean)...
codesearchnet
def process(self, batch, device=None): padded = self.pad(batch) tensor = self.numericalize(padded, device=device) return tensor
Process a list of examples to create a torch.Tensor. Pad, numericalize, and postprocess a batch and create a tensor. Args: batch (list(object)): A list of object from a batch of examples. Returns: torch.autograd.Variable: Processed object given the input and custom postprocessing Pipeline.
juraj-google-style
def coupling_efficiency(mode_solver, fibre_mfd, fibre_offset_x=0, fibre_offset_y=0, n_eff_fibre=1.441): etas = [] gaus = _make_gaussian(mode_solver._structure.xc, mode_solver._structure.yc, fibre_mfd, fibre_offset_x, fibre_offset_y) for (mode, n_eff) in zip(mode_solver.modes, mode_solver.n_effs): o ...
Finds the coupling efficiency between a solved fundamental mode and a fibre of given MFD. Args: mode_solver (_ModeSolver): Mode solver that has found a fundamental mode. fibre_mfd (float): The mode-field diameter (MFD) of the fibre. fibre_offset_x (float): Offset the fibre from the centre position of the window in x. ...
codesearchnet
def needle_statistics(infile): alignments = list(AlignIO.parse(infile, "emboss")) alignment_properties = defaultdict(dict) with open(infile) as f: line = f.readline() for i in range(len(alignments)): while line.rstrip() != " line = f.readline() ...
Reads in a needle alignment file and spits out statistics of the alignment. Args: infile (str): Alignment file name Returns: dict: alignment_properties - a dictionary telling you the number of gaps, identity, etc.
juraj-google-style
def assign_nested_vars(variables, tensors, indices=None): if isinstance(variables, (tuple, list)): return tf.group(*[assign_nested_vars(variable, tensor) for (variable, tensor) in zip(variables, tensors)]) if (indices is None): return variables.assign(tensors) else: return tf.scatter...
Assign tensors to matching nested tuple of variables. Args: variables: Nested tuple or list of variables to update. tensors: Nested tuple or list of tensors to assign. indices: Batch indices to assign to; default to all. Returns: Operation.
codesearchnet
def abs_path_from_base(base_path, rel_path): return os.path.abspath( os.path.join( os.path.dirname(sys._getframe(1).f_code.co_filename), base_path, rel_path ) )
Join a base and a relative path and return an absolute path to the resulting location. Args: base_path: str Relative or absolute path to prepend to ``rel_path``. rel_path: str Path relative to the location of the module file from which this function is called. Returns: str : Absolute path to the location specified b...
juraj-google-style
async def search_participant(self, name, force_update=False): if force_update or self.participants is None: await self.get_participants() if self.participants is not None: for p in self.participants: if p.name == name: return p ...
search a participant by (display) name |methcoro| Args: name: display name of the participant force_update (dfault=False): True to force an update to the Challonge API Returns: Participant: None if not found Raises: APIException
juraj-google-style
def get_credentials(self): with self.AUTHENTICATION_LOCK: log.info('Starting authentication for %s', self.target) store = oauth2client.file.Storage(self.credentials_path) credentials = store.get() if ((not credentials) or credentials.invalid): log.info('No valid login. St...
Gets valid user credentials from storage. If nothing has been stored, or if the stored credentials are invalid, the OAuth2 flow is completed to obtain the new credentials. Returns: Credentials, the obtained credential.
codesearchnet
def _get_example_from_basic_type(type): if (type == 'integer'): return [42, 24] elif (type == 'number'): return [5.5, 5.5] elif (type == 'string'): return ['string', 'string2'] elif (type == 'datetime'): return ['2015-08-28T09:02:57.481Z', '2015-08-28T09:02:57.481Z'] ...
Get example from the given type. Args: type: the type you want an example of. Returns: An array with two example values of the given type.
codesearchnet
def drop_if(df, fun): def _filter_f(col): try: return fun(df[col]) except: return False cols = list(filter(_filter_f, df.columns)) return df.drop(cols, axis=1)
Drops columns where fun(ction) is true Args: fun: a function that will be applied to columns
juraj-google-style
def as_functor(func: Callable, ignore_extra_args: bool=False) -> Functor: return functor_class(func)(ignore_extra_args=ignore_extra_args)
Make a functor object from a regular python function. NOTE(daiyip): This method is designed to create on-the-go functor object, usually for lambdas. To create a reusable functor class, please use `functor_class` method. Args: func: A regular python function. ignore_extra_args: If True, extra argument which is not acc...
github-repos
def push_file(self, local_source, remote_dir): remote_dest = ((remote_dir + '/') + os.path.basename(local_source)) try: self.makedirs(remote_dir, exist_ok=True) except IOError as e: logger.exception('Pushing {0} to {1} failed'.format(local_source, remote_dir)) if (e.errno == 2): ...
Transport a local file to a directory on a remote machine Args: - local_source (string): Path - remote_dir (string): Remote path Returns: - str: Path to copied file on remote machine Raises: - BadScriptPath : if script path on the remote side is bad - BadPermsScriptPath : You do not have perms to make the channel sc...
codesearchnet
def decorate_set_on_listener(prototype): def add_annotation(method): method._event_info = {} method._event_info['name'] = method.__name__ method._event_info['prototype'] = prototype return method return add_annotation
Private decorator for use in the editor. Allows the Editor to create listener methods. Args: params (str): The list of parameters for the listener method (es. "(self, new_value)")
juraj-google-style
def _ParseRecords(self, parser_mediator, evtx_file): for record_index in range(evtx_file.number_of_records): if parser_mediator.abort: break try: evtx_record = evtx_file.get_record(record_index) self._ParseRecord(parser_mediator, record_index, evtx_reco...
Parses Windows XML EventLog (EVTX) records. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. evtx_file (pyevt.file): Windows XML EventLog (EVTX) file.
juraj-google-style
def linear(self, x): with tf.name_scope("presoftmax_linear"): batch_size = tf.shape(x)[0] length = tf.shape(x)[1] x = tf.reshape(x, [-1, self.hidden_size]) logits = tf.matmul(x, self.shared_weights, transpose_b=True) return tf.reshape(logits, [batch_size, length, self.vocab_size...
Computes logits by running x through a linear layer. Args: x: A float32 tensor with shape [batch_size, length, hidden_size] Returns: float32 tensor with shape [batch_size, length, vocab_size].
juraj-google-style
def get_environ(cls, prefix): return ((key[(len(prefix) + 1):], value) for (key, value) in os.environ.items() if key.startswith(('%s_' % prefix)))
Retrieves environment variables from a namespace. Args: prefix (str): The prefix, without a trailing underscore. Returns: list: A list of environment variable keys and values.
codesearchnet
def swipe(self, x1, y1, x2, y2, duration=0.5): scale = self.scale x1, y1, x2, y2 = x1/scale, y1/scale, x2/scale, y2/scale self.session.swipe(x1, y1, x2, y2, duration)
Simulate swipe operation Args: x1, y1(int): from position x2, y2(int): to position duration(float): swipe duration, unit seconds
juraj-google-style
def compare(expr, value, regex_expr=False): if (expr == value): return True negate = False if isinstance(expr, str): negate = expr.startswith(NEGATE) expr = (strip_negate(expr) if negate else expr) try: test(expr, value, regex_expr=regex_expr) except Exception as err:...
Compares an string or regular expression againast a given value. Arguments: expr (str|regex): string or regular expression value to compare. value (str): value to compare against to. regex_expr (bool, optional): enables string based regex matching. Raises: AssertionError: in case of assertion error. Returns: bool
codesearchnet
def firmware_version(self): buf = (ctypes.c_char * self.MAX_BUF_SIZE)() self._dll.JLINKARM_GetFirmwareString(buf, self.MAX_BUF_SIZE) return ctypes.string_at(buf).decode()
Returns a firmware identification string of the connected J-Link. It consists of the following: - Product Name (e.g. J-Link) - The string: compiled - Compile data and time. - Optional additional information. Args: self (JLink): the ``JLink`` instance Returns: Firmware identification string.
juraj-google-style
def poll(self, channel_id=None, json=None, **kwargs): path = '/event-service/v1/channels/{}/poll'.format(channel_id) r = self._httpclient.request(method='POST', url=self.url, json=json, path=path, **kwargs) return r
Read one or more events from a channel. Reads events (log records) from the identified channel. Events are read in chronological order. Args: channel_id (str): The channel ID. json (dict): Payload/request body. **kwargs: Supported :meth:`~pancloud.httpclient.HTTPClient.request` parameters. Returns: requests.Response...
codesearchnet
def _GetTimeValue(self, name): timestamp = getattr(self._tsk_file.info.meta, name, None) if self._file_system_type in self._TSK_HAS_NANO_FS_TYPES: name_fragment = '{0:s}_nano'.format(name) fraction_of_second = getattr( self._tsk_file.info.meta, name_fragment, None) else: fr...
Retrieves a date and time value. Args: name (str): name of the date and time value, for example "atime" or "mtime". Returns: dfdatetime.DateTimeValues: date and time value or None if not available.
juraj-google-style
def get_commands_in_namespace(namespace=None, level=1): from ..command import Command commands = {} if namespace is None: frame = inspect.stack()[level][0] namespace = frame.f_globals elif inspect.ismodule(namespace): namespace = vars(namespace) for name in namespace: ...
Get commands in namespace. Args: namespace (dict|module): Typically a module. If not passed, the globals from the call site will be used. level (int): If not called from the global scope, set this appropriately to account for the call stack. Returns: OrderedDict: The commands found in the namespace, ordered by name. ...
juraj-google-style
def get_current(self, cycle=None, dataset_number=None, full=True): dataset_number = self._validate_dataset_number(dataset_number) if dataset_number is None: self._report_empty_dataset() return cycle_index_header = self.headers_normal.cycle_index_txt curr...
Returns current (in mA). Args: cycle: cycle number (all cycles if None) dataset_number: first dataset if None full: valid only for cycle=None (i.e. all cycles), returns the full pandas.Series if True, else a list of pandas.Series Returns: pandas.Series (or list of pandas.Series if cycle=None og full=False)
juraj-google-style
def enumeration(*values, **kwargs): if (not (values and all(((isinstance(value, string_types) and value) for value in values)))): raise ValueError(('expected a non-empty sequence of strings, got %s' % values)) if (len(values) != len(set(values))): raise ValueError(('enumeration items must be uni...
Create an |Enumeration| object from a sequence of values. Call ``enumeration`` with a sequence of (unique) strings to create an Enumeration object: .. code-block:: python #: Specify the horizontal alignment for rendering text TextAlign = enumeration("left", "right", "center") Args: values (str) : string enumeration...
codesearchnet
def username(self, value): self._username = value self._connectionXML.set('username', value)
Set the connection's username property. Args: value: New username value. String. Returns: Nothing.
codesearchnet
def build_kalman_mean_step(get_transition_matrix_for_timestep, get_transition_noise_for_timestep, get_observation_matrix_for_timestep, get_observation_noise_for_timestep): def mean_step(previous_means, t): 'Single step of prior mean recursion.' (previous_latent_mean, _) = previous_means lat...
Build a callable that performs one step of Kalman mean recursion. Args: get_transition_matrix_for_timestep: callable taking a timestep as an integer `Tensor` argument, and returning a `LinearOperator` of shape `[latent_size, latent_size]`. get_transition_noise_for_timestep: callable taking a timestep as an integer `Te...
codesearchnet
def inspect_plugin(self, name): url = self._url('/plugins/{0}/json', name) return self._result(self._get(url), True)
Retrieve plugin metadata. Args: name (string): The name of the plugin. The ``:latest`` tag is optional, and is the default if omitted. Returns: A dict containing plugin info
codesearchnet
def searchsorted(sorted_sequence, values, side='left'): if any_symbolic_tensors((sorted_sequence, values)): return SearchSorted(side=side).symbolic_call(sorted_sequence, values) sorted_sequence = backend.convert_to_tensor(sorted_sequence) values = backend.convert_to_tensor(values) return backend...
Perform a binary search, returning indices for insertion of `values` into `sorted_sequence` that maintain the sorting order. Args: sorted_sequence: 1-D input tensor, sorted along the innermost dimension. values: N-D tensor of query insertion values. side: 'left' or 'right', specifying the direction in which to insert ...
github-repos
def Benchmark(tf_bench, builder_fn, use_xla_jit, device, separate_compiled_gradients=False): with ops.Graph().as_default(): name = None targets = [] with ops.device(device): fetches = [] jit_scope = jit.experimental_jit_scope with jit_scope(compile_ops=use...
Build a graph and run benchmarks against it, with or without XLA. Args: tf_bench: An instance of tf.test.Benchmark, used to run the benchmark. builder_fn: A function that builds a graph when invoked, and returns (name, fetches), where name is the name of the test, and fetches is a list of tensors to fetch as output. u...
github-repos
def activate(self, uid=None): if (uid is not None): if (not isinstance(uid, six.string_types)): raise TypeError('uid must be a string') result = self.proxy.activate(uid) status = result.result_status.value if (status == enums.ResultStatus.SUCCESS): return else: re...
Activate a managed object stored by a KMIP appliance. Args: uid (string): The unique ID of the managed object to activate. Optional, defaults to None. Returns: None Raises: ClientConnectionNotOpen: if the client connection is unusable KmipOperationFailure: if the operation result is a failure TypeError: if the input...
codesearchnet
def _find_classes(self, dir): if sys.version_info >= (3, 5): classes = [d.name for d in os.scandir(dir) if d.is_dir()] else: classes = [d for d in os.listdir(dir) if os.path.isdir(os.path.join(dir, d))] classes.sort() class_to_idx = {classes[...
Finds the class folders in a dataset. Args: dir (string): Root directory path. Returns: tuple: (classes, class_to_idx) where classes are relative to (dir), and class_to_idx is a dictionary. Ensures: No class is a subdirectory of another.
juraj-google-style
def migrate(belstr: str) -> str: bo.ast = bel.lang.partialparse.get_ast_obj(belstr, '2.0.0') return migrate_ast(bo.ast).to_string()
Migrate BEL 1 to 2.0.0 Args: bel: BEL 1 Returns: bel: BEL 2
codesearchnet
def register_domain(self, domain=0, tokenizer=None, trie=None): self.domains[domain] = IntentDeterminationEngine(tokenizer=tokenizer, trie=trie)
Register a domain with the intent engine. Args: tokenizer(tokenizer): The tokenizer you wish to use. trie(Trie): the Trie() you wish to use. domain(str): a string representing the domain you wish to add
codesearchnet
def _get_func_name(): return tf_inspect.stack()[1][3]
Get the name of current function. Returns: String that is the name of current function.
github-repos
def solve(self): hierarchy = type_match.get_all_subclasses([self.ast, self.builtins]) factory_protocols = type_match.TypeMatch(hierarchy) factory_partial = type_match.TypeMatch(hierarchy) solver_protocols = factory_protocols.solver solver_partial = factory_partial.solver unknown_classes = set() ...
Solve the equations generated from the pytd. Returns: A dictionary (str->str), mapping unknown class names to known class names. Raises: AssertionError: If we detect an internal error.
github-repos
def reply_code_tuple(code: int) -> Tuple[(int, int, int)]: return ((code
Return the reply code as a tuple. Args: code: The reply code. Returns: Each item in the tuple is the digit.
codesearchnet
def process(self): client = self._get_client_by_hostname(self.host) self._await_flow(client, self.flow_id) collected_flow_data = self._download_files(client, self.flow_id) if collected_flow_data: print('{0:s}: Downloaded: {1:s}'.format(self.flow_id, collected_flow_data)) fqdn = client.da...
Collect the results. Raises: DFTimewolfError: if no files specified
codesearchnet
def TerminateFlow(client_id, flow_id, reason=None, flow_state=rdf_flow_objects.Flow.FlowState.ERROR): to_terminate = [data_store.REL_DB.ReadFlowObject(client_id, flow_id)] while to_terminate: next_to_terminate = [] for rdf_flow in to_terminate: _TerminateFlow(rdf_flow, reason=reason,...
Terminates a flow and all of its children. Args: client_id: Client ID of a flow to terminate. flow_id: Flow ID of a flow to terminate. reason: String with a termination reason. flow_state: Flow state to be assigned to a flow after termination. Defaults to FlowState.ERROR.
codesearchnet
def fasta_verifier(entries, ambiguous=False): if ambiguous: regex = '^>.+{0}[ACGTURYKMSWBDHVNX]+{0}$'.format(os.linesep) else: regex = '^>.+{0}[ACGTU]+{0}$'.format(os.linesep) delimiter = '{0}'.format(os.linesep) for entry in entries: try: entry_verifier([entry.write(...
Raises error if invalid FASTA format detected Args: entries (list): A list of FastaEntry instances ambiguous (bool): Permit ambiguous bases, i.e. permit non-ACGTU bases Raises: FormatError: Error when FASTA format incorrect with descriptive message Example: >>> from bio_utils.iterators import fasta_iter >>> import ...
codesearchnet
def __init__(self, column_names=None, title=None): super(BaseTableView, self).__init__() self._columns = column_names or [] self._number_of_columns = len(self._columns) self._rows = [] self._title = title
Initializes a table view. Args: column_names (Optional[list[str]]): column names. title (Optional[str]): title.
juraj-google-style
def _get_tensor_details(self, tensor_index, subgraph_index): tensor_index = int(tensor_index) subgraph_index = int(subgraph_index) tensor_name = self._interpreter.TensorName(tensor_index, subgraph_index) tensor_size = self._interpreter.TensorSize(tensor_index, subgraph_index) tensor_size_signature =...
Gets tensor details. Args: tensor_index: Tensor index of tensor to query. subgraph_index: Index of the subgraph. Returns: A dictionary containing the following fields of the tensor: 'name': The tensor name. 'index': The tensor index in the subgraph. 'shape': The shape of the tensor. 'quantization': Deprecated, use 'q...
github-repos
def ParseFileObject(self, parser_mediator, file_object): regf_file = pyregf.file() try: regf_file.open_file_object(file_object) except IOError: return root_key = regf_file.get_root_key() if root_key is None: regf_file.close() return root_file_key = r...
Parses an Amcache.hve file for events. Args: parser_mediator (ParserMediator): mediates interactions between parsers and other components, such as storage and dfvfs. file_object (dfvfs.FileIO): file-like object.
juraj-google-style
def calculate_entropy(self, entropy_string): total = 0 for char in entropy_string: if char.isalpha(): prob = self.frequency[char.lower()] total += - math.log(prob) / math.log(2) logging.debug("Entropy score: {0}".format(total)) return ...
Calculates the entropy of a string based on known frequency of English letters. Args: entropy_string: A str representing the string to calculate. Returns: A negative float with the total entropy of the string (higher is better).
juraj-google-style
def list_merge(list_a, list_b): result = [] for item in list_a: if (not (item in result)): result.append(item) for item in list_b: if (not (item in result)): result.append(item) return result
Merge two lists without duplicating items Args: list_a: list list_b: list Returns: New list with deduplicated items from list_a and list_b
codesearchnet
def get(self, key=None, indices=None, name=None): if key is None: return self._popitem(indices=indices, name=name) else: return self._pop(key, indices=indices, name=name)
If the key is provided, the associated (key, value) is returned from the staging area. If the key is not in the staging area, this method will block until the associated (key, value) is inserted. If no key is provided and the staging area is ordered, the (key, value) with the smallest key will be returned. Otherwise, ...
github-repos
def is_adb_available(): ret, out, err = utils.run_command('which adb', shell=True) clean_out = out.decode('utf-8').strip() if clean_out: return True return False
Checks if adb is available as a command line tool. Returns: True if adb binary is available in console, False otherwise.
github-repos
def search(self, scope, search, **kwargs): data = {'scope': scope, 'search': search} path = '/projects/%s/search' % self.get_id() return self.manager.gitlab.http_list(path, query_data=data, **kwargs)
Search the project resources matching the provided string.' Args: scope (str): Scope of the search search (str): Search string **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabSearchError: If the server failed to perform the request R...
juraj-google-style
def discretize(self, contact_id=0, accuracy=0.004, dt=0.001): if not self.event_points: return [] events = [] action_dt = accuracy / self.speed dt = dt or action_dt ep0 = self.event_points[0] for _ in range(int(ep0[0] / dt)): events.app...
Sample this motion track into discretized motion events. Args: contact_id: contact point id accuracy: motion minimum difference in space dt: sample time difference
juraj-google-style
def pop(self, key, default=None): return self._dictionary.pop(key.lower(), default)
Remove the key and return the associated value or default if not found Args: key (str): The key to remove default (obj): The value to return if key is not present
juraj-google-style
def copy_update(pb_message, **kwds): result = pb_message.__class__() result.CopyFrom(pb_message) for k, v in kwds.items(): setattr(result, k, v) return result
Returns a copy of the PB object, with some fields updated. Args: pb_message: **kwds: Returns:
juraj-google-style
def call_plugins(self, step): for plugin in self.plugins: try: getattr(plugin, step)() except AttributeError: self.logger.debug("{} doesn't exist on plugin {}".format(step, plugin)) except TypeError: self.logger.debug('{} on plugin {} is not callable'.form...
For each plugins, check if a "step" method exist on it, and call it Args: step (str): The method to search and call on each plugin
codesearchnet
def is44(msg): if allzeros(msg): return False d = hex2bin(data(msg)) if wrongstatus(d, 5, 6, 23): return False if wrongstatus(d, 35, 36, 46): return False if wrongstatus(d, 47, 48, 49): return False if wrongstatus(d, 50, 51, 56): return Fals...
Check if a message is likely to be BDS code 4,4. Meteorological routine air report Args: msg (String): 28 bytes hexadecimal message string Returns: bool: True or False
juraj-google-style
def __init__( self, name, aliases=None, description=None, false_value=0, urls=None): super(BooleanDefinition, self).__init__( name, aliases=aliases, description=description, urls=urls) self.false_value = false_value self.true_value = None
Initializes a boolean data type definition. Args: name (str): name. aliases (Optional[list[str]]): aliases. description (Optional[str]): description. false_value (Optional[int]): value that represents false. urls (Optional[list[str]]): URLs.
juraj-google-style
def _free_array(self, handle: int): with self._lock: if self._arrays[handle] is not None: self._arrays[handle] = None self._count -= 1
Frees the memory for the array with the given handle. Args: handle: The handle of the array whose memory should be freed. This handle must come from the _create_array method.
juraj-google-style
def _make_model(self, data, key=None): if data['deleted'] and not self.adapter.want_deleted: raise ObjectDoesNotExist('Deleted object returned') model = self._model_class(self._current_context, _pass_perm_checks=self._pass_perm_checks) mode...
Creates a model instance with the given data. Args: data: Model data returned from DB. key: Object key Returns: pyoko.Model object.
juraj-google-style
def delete(self, resource, timeout=(- 1)): self._client.delete(resource=resource, timeout=timeout)
Delete all the labels for a resource. Args: resource (dict): Object to delete. timeout: Timeout in seconds. Wait for task completion by default. The timeout does not abort the operation in OneView, just stop waiting for its completion.
codesearchnet
def write(self, source=None, **kwargs): if (not source): source = self.msg return self._writer.write(source=source, **kwargs)
Wrappe r to call the writer's write method if present. Args: source(pandasdmx.model.Message, iterable): stuff to be written. If a :class:`pandasdmx.model.Message` is given, the writer itself must determine what to write unless specified in the keyword arguments. If an iterable is given, the writer should write each...
codesearchnet
def _get_object_from_python_path(python_path): python_path = python_path.split('.') module_path = python_path[:-1] object_class = python_path[-1] if isinstance(module_path, list): module_path = '.'.join(module_path) module = import_module(...
Method that will fetch a Marshmallow schema from a path to it. Args: python_path (str): The string path to the Marshmallow schema. Returns: marshmallow.Schema: The schema matching the provided path. Raises: TypeError: This is raised if the specified object isn't a Marshmallow schema.
juraj-google-style
def load_json(json_filespec): json_fh = open(json_filespec) config_dict = json.load(json_fh) json_fh.close() return config_dict
Loads JSON from a config file Args: json_filespec: path/to/file.json Returns: a dict made from the JSON read, if successful Raises: IOError if the file could not be opened ValueError if the JSON could not be read successfully RuntimeError if something else went wrong
juraj-google-style
def _SendItem(self, zmq_socket, item, block=True): try: logger.debug('{0:s} sending item'.format(self.name)) if block: zmq_socket.send_pyobj(item) else: zmq_socket.send_pyobj(item, zmq.DONTWAIT) logger.debug('{0:s} sent item'.format(self.name)) return True exc...
Attempts to send an item to a ZeroMQ socket. Args: zmq_socket (zmq.Socket): used to the send the item. item (object): sent on the queue. Will be pickled prior to sending. block (Optional[bool]): whether the push should be performed in blocking or non-blocking mode. Returns: bool: whether the item was sent successfull...
juraj-google-style
def set_shutter_level(self, level=0.0): data = {"channelIndex": 1, "deviceId": self.id, "shutterLevel": level} return self._restCall("device/control/setShutterLevel", body=json.dumps(data))
sets the shutter level Args: level(float): the new level of the shutter. 0.0 = open, 1.0 = closed Returns: the result of the _restCall
juraj-google-style
def pkcs12_key_as_pem(private_key_bytes, private_key_password): private_key_password = _helpers._to_bytes(private_key_password) pkcs12 = crypto.load_pkcs12(private_key_bytes, private_key_password) return crypto.dump_privatekey(crypto.FILETYPE_PEM, pkcs12.get_privatekey...
Convert the contents of a PKCS#12 key to PEM using pyOpenSSL. Args: private_key_bytes: Bytes. PKCS#12 key in DER format. private_key_password: String. Password for PKCS#12 key. Returns: String. PEM contents of ``private_key_bytes``.
juraj-google-style
def set_all_pattern_variables(self, patternnumber, \ sp0, ti0, sp1, ti1, sp2, ti2, sp3, ti3, sp4, ti4, sp5, ti5, sp6, ti6, sp7, ti7, \ actual_step, additional_cycles, link_pattern): _checkPatternNumber(patternnumber) self.set_pattern_step_setpoint(patternnumber, 0, sp0)...
Set all variables for a given pattern at one time. Args: * patternnumber (integer): 0-7 * sp[*n*] (float): setpoint value for step *n* * ti[*n*] (integer??): step time for step *n*, 0-900 * actual_step (int): ? * additional_cycles(int): ? * link_pattern(int): ?
juraj-google-style
def get_orbit(name, date): if name not in [x.name for x in Bsp().top.list]: raise UnknownBodyError(name) for a, b in Bsp().top.steps(name): if b.name not in _propagator_cache: propagator = type( "%sBspPropagator" % b.name, (G...
Retrieve the orbit of a solar system object Args: name (str): The name of the body desired. For exact nomenclature, see :py:func:`available_planets` date (Date): Date at which the state vector will be extracted Return: Orbit: Orbit of the desired object, in the reference frame in which it is declared in the .bsp file
juraj-google-style
def es_indexers(cls, base_class=None, role='rdf_class', **kwargs): def _prop_filter(prop, value, **kwargs): try: use_prop = len(set(value.owl_inverseOf) - parent_props) > 0 except AttributeError: use_prop = True if prop ...
Returns the es mapping for the class args: ----- base_class: The root class being indexed role: the role states how the class should be mapped depending upon whether it is used as a subject of an object. options are es_Nested or rdf_class
juraj-google-style
def get_image_features(self, pixel_values: torch.FloatTensor): image_outputs = self.vision_tower(pixel_values) selected_image_feature = image_outputs.last_hidden_state image_features = self.multi_modal_projector(selected_image_feature) image_features = image_features / self.config.text_config.hidden_siz...
Obtains image last hidden states from the vision tower and apply multimodal projection. Args: pixel_values (`torch.FloatTensor]` of shape `(batch_size, channels, height, width)`) The tensors corresponding to the input images. Returns: image_features (`torch.Tensor`): Image feature tensor of shape `(num_images, image_l...
github-repos
def compress_summary(summary, epsilon): if summary.shape[1] * epsilon < 1: return summary percents = epsilon + np.arange(0.0, 1.0, epsilon) cum_weights = summary[1].cumsum() cum_weight_percents = cum_weights / cum_weights[-1] new_bins = np.interp(percents, cum_weight_percents, summary[0]) ...
Compress a summary to within `epsilon` accuracy. The compression step is needed to keep the summary sizes small after merging, and also used to return the final target boundaries. It finds the new bins based on interpolating cumulative weight percentages from the large summary. Taking the difference of the cumulative...
github-repos
def __move(self, current_pos): if self.__move_range is not None: next_pos = np.random.randint(current_pos - self.__move_range, current_pos + self.__move_range) if next_pos < 0: next_pos = 0 elif next_pos >= self.var_arr.shape[0] - 1: n...
Move in the feature map. Args: current_pos: The now position. Returns: The next position.
juraj-google-style
def search(self, query, results=10, suggestion=False): self._check_query(query, "Query must be specified") search_params = { "list": "search", "srprop": "", "srlimit": results, "srsearch": query, } if suggestion: sear...
Search for similar titles Args: query (str): Page title results (int): Number of pages to return suggestion (bool): Use suggestion Returns: tuple or list: tuple (list results, suggestion) if \ suggestion is **True**; list of results \ otherwise
juraj-google-style
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) except TypeError: typekey = f...
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...
codesearchnet
def find_elements_by_class(self, class_, update=False) -> Elements: return self.find_elements(by=By.CLASS, value=class_, update=update)
Finds multiple elements by class. Args: class_: The class of the elements to be found. update: If the interface has changed, this option should be True. Returns: A list with elements if any was found. An empty list if not. Raises: NoSuchElementException - If the element wasn't found. Usage: elements = driver.find_e...
codesearchnet
def to_element(self, include_namespaces=False): elt_attrib = {} if include_namespaces: elt_attrib.update({ 'xmlns': "urn:schemas-upnp-org:metadata-1-0/DIDL-Lite/", 'xmlns:dc': "http: 'xmlns:upnp': "urn:schemas-upnp-org:metadata-1-0/upn...
Return an ElementTree Element representing this instance. Args: include_namespaces (bool, optional): If True, include xml namespace attributes on the root element Return: ~xml.etree.ElementTree.Element: an Element.
juraj-google-style
def run_tpm(tpm, time_scale): sbs_tpm = convert.state_by_node2state_by_state(tpm) if sparse(tpm): tpm = sparse_time(sbs_tpm, time_scale) else: tpm = dense_time(sbs_tpm, time_scale) return convert.state_by_state2state_by_node(tpm)
Iterate a TPM by the specified number of time steps. Args: tpm (np.ndarray): A state-by-node tpm. time_scale (int): The number of steps to run the tpm. Returns: np.ndarray
codesearchnet
def _add_arg(self, key, value, mask=False): if self.lang == 'python': self._add_arg_python(key, value, mask) elif self.lang == 'java': self._add_arg_java(key, value, mask)
Add CLI Arg for the correct language. Args: key (string): The CLI Args key (e.g., --name). value (string): The CLI Args value (e.g., bob). mask (boolean, default:False): Indicates whether no mask value.
juraj-google-style
def _resize_image(image, height, width): return tf.image.resize_images( image, [height, width], method=tf.image.ResizeMethod.BILINEAR, align_corners=False)
Simple wrapper around tf.resize_images. This is primarily to make sure we use the same `ResizeMethod` and other details each time. Args: image: A 3-D image `Tensor`. height: The target height for the resized image. width: The target width for the resized image. Returns: resized_image: A 3-D tensor containing the res...
juraj-google-style
def onchange(self, new_value): self.disable_refresh() self.set_value(new_value) self.enable_refresh() return (new_value, )
Called when the user changes the TextInput content. With single_line=True it fires in case of focus lost and Enter key pressed. With single_line=False it fires at each key released. Args: new_value (str): the new string content of the TextInput.
juraj-google-style
def clear_extra_selections(self, key): for decoration in self.extra_selections_dict.get(key, []): self.decorations.remove(decoration) self.extra_selections_dict[key] = []
Remove decorations added through set_extra_selections. Args: key (str) name of the extra selections group.
juraj-google-style
def get(self, key): path = self.object_path(key) return self._read_object(path)
Return the object named by key or None if it does not exist. Args: key: Key naming the object to retrieve Returns: object or None
codesearchnet
def expand(self, url): url = self.clean_url(url) expand_url = f'{self.api_url}v1/expand' payload = { 'domain': getattr(self, 'domain', 'adf.ly'), 'advert_type': getattr(self, 'type', 'int'), 'group_id': getattr(self, 'group_id', None), 'ke...
Expand implementation for Adf.ly Args: url: the URL you want to expand Returns: A string containing the expanded URL Raises: BadAPIResponseException: If the data is malformed or we got a bad status code on API response ShorteningErrorException: If the API Returns an error as response
juraj-google-style
def _log_unnorm_prob(self, x, name=None): with tf.name_scope((name or 'log_unnorm_prob_lkj')): x = tf.convert_to_tensor(value=x, name='x') if self.input_output_cholesky: logdet = (2.0 * tf.reduce_sum(input_tensor=tf.math.log(tf.linalg.diag_part(x)), axis=[(- 1)])) else: ...
Returns the unnormalized log density of an LKJ distribution. Args: x: `float` or `double` `Tensor` of correlation matrices. The shape of `x` must be `B + [D, D]`, where `B` broadcasts with the shape of `concentration`. name: Python `str` name prefixed to Ops created by this function. Returns: log_p: A Tensor of the ...
codesearchnet
def truncate(string, maxchar): if maxchar < 4: raise TruncateError("Maxchar must be > 3") if len(string) <= maxchar: return string else: return string[:maxchar - 3] + "..."
Truncate a string to a maximum number of characters. If the string is longer than maxchar, then remove excess characters and append an ellipses. Arguments: string (str): String to truncate. maxchar (int): Maximum length of string in characters. Must be >= 4. Returns: str: Of length <= maxchar. Raises: TruncateEr...
juraj-google-style
def _ConditionalFormatMessages(self, event_values): string_pieces = [] for (map_index, attribute_name) in enumerate(self._format_string_pieces_map): if ((not attribute_name) or (attribute_name in event_values)): if attribute_name: attribute = event_values.get(attribute_name, ...
Determines the conditional formatted message strings. Args: event_values (dict[str, object]): event values. Returns: tuple(str, str): formatted message string and short message string.
codesearchnet
def add_group_coordinator(self, group, response): log.debug('Updating coordinator for %s: %s', group, response) error_type = Errors.for_code(response.error_code) if (error_type is not Errors.NoError): log.error('GroupCoordinatorResponse error: %s', error_type) self._groups[group] = (- 1) ...
Update with metadata for a group coordinator Arguments: group (str): name of group from GroupCoordinatorRequest response (GroupCoordinatorResponse): broker response Returns: bool: True if metadata is updated, False on error
codesearchnet
def request(session, url, rule_payload, **kwargs): if isinstance(rule_payload, dict): rule_payload = json.dumps(rule_payload) logger.debug("sending request") result = session.post(url, data=rule_payload, **kwargs) return result
Executes a request with the given payload and arguments. Args: session (requests.Session): the valid session object url (str): Valid API endpoint rule_payload (str or dict): rule package for the POST. If you pass a dictionary, it will be converted into JSON.
juraj-google-style
def _ParseOrMerge(self, lines, message): tokenizer = Tokenizer(lines) while not tokenizer.AtEnd(): self._MergeField(tokenizer, message)
Converts a text representation of a protocol message into a message. Args: lines: Lines of a message's text representation. message: A protocol buffer message to merge into. Raises: ParseError: On text parsing problems.
juraj-google-style
def _sample_actions(self, state: Sequence[tf.Tensor]) -> Tuple[(Sequence[tf.Tensor], tf.Tensor, tf.Tensor)]: default = self.compiler.compile_default_action(self.batch_size) bound_constraints = self.compiler.compile_action_bound_constraints(state) action = self._sample_action(bound_constraints, default) ...
Returns sampled action fluents and tensors related to the sampling. Args: state (Sequence[tf.Tensor]): A list of state fluents. Returns: Tuple[Sequence[tf.Tensor], tf.Tensor, tf.Tensor]: A tuple with action fluents, an integer tensor for the number of samples, and a boolean tensor for checking all action precondition...
codesearchnet
def retry_loop(retries, delay_in_seconds, conditions, function): if (not isinstance(retries, Integral)): raise TypeError(retries) if (delay_in_seconds < 0): raise TypeError(delay_in_seconds) attempts = 0 value = None err = None while (attempts <= retries): try: ...
Actually performs the retry loop used by the retry decorator and handler functions. Failures for retrying are defined by the RetryConditions passed in. If the maximum number of retries has been reached then it raises the most recent error or a ValueError on the most recent result value. Args: retries (Integral): Maxim...
codesearchnet
def start_naive_bayes(automated_run, session, path): module = functions.import_string_code_as_module(automated_run.source) random_state = 8 if not hasattr(module, 'random_state') else module.random_state assert module.metric_to_optimize in automated_run.base_learner_origin.metric_generators b...
Starts naive bayes automated run Args: automated_run (xcessiv.models.AutomatedRun): Automated run object session: Valid SQLAlchemy session path (str, unicode): Path to project folder
juraj-google-style
def setup_logging(args=None): logging_level = logging.WARNING if ((args is not None) and args.verbose): logging_level = logging.INFO config = {'level': logging_level, 'format': 'jtlocalize:%(message)s'} if ((args is not None) and (args.log_path != '')): config['filename'] = args.log_path...
Setup logging module. Args: args (optional): The arguments returned by the argparse module.
codesearchnet
def gen_cartesian_product(*args): if (not args): return [] elif (len(args) == 1): return args[0] product_list = [] for product_item_tuple in itertools.product(*args): product_item_dict = {} for item in product_item_tuple: product_item_dict.update(item) ...
generate cartesian product for lists Args: args (list of list): lists to be generated with cartesian product Returns: list: cartesian product in list Examples: >>> arg1 = [{"a": 1}, {"a": 2}] >>> arg2 = [{"x": 111, "y": 112}, {"x": 121, "y": 122}] >>> args = [arg1, arg2] >>> gen_cartesian_product(*args) >>> # same ...
codesearchnet
def get_generic_type(val: '_base.BaseValue') -> '_classes.ParameterizedClass | None': is_class = isinstance(val, _abstract.Class) if is_class: cls = val elif isinstance(val.cls, _abstract.Class): cls = val.cls else: return None for parent_cls in cls.mro: if isinstance...
Gets the generic type of an abstract value. Args: val: The abstract value. Returns: The type of the value, with concrete type parameters replaced by TypeVars. For example, the generic type of `[0]` is `List[T]`.
github-repos