code
stringlengths
51
2.38k
docstring
stringlengths
4
15.2k
def get_output(self, style=OutputStyle.file): return self.manager.get_output(style=style)
Returns the result of all previous calls to execute_code.
def get_nagios_unit_name(relation_name='nrpe-external-master'): host_context = get_nagios_hostcontext(relation_name) if host_context: unit = "%s:%s" % (host_context, local_unit()) else: unit = local_unit() return unit
Return the nagios unit name prepended with host_context if needed :param str relation_name: Name of relation nrpe sub joined to
def _get_bq_service(credentials=None, service_url=None): assert credentials, 'Must provide ServiceAccountCredentials' http = credentials.authorize(Http()) service = build( 'bigquery', 'v2', http=http, discoveryServiceUrl=service_url, cache_discovery=False ) re...
Construct an authorized BigQuery service object.
def filter_rows(self, filters, rows): ret = [] for row in rows: if not self.row_is_filtered(row, filters): ret.append(row) return ret
returns rows as filtered by filters
def register_template_directory(kb_app: kb, sphinx_app: Sphinx, sphinx_env: BuildEnvironment, docnames=List[str], ): template_bridge = sphinx_app.builder.templates actions = ResourceAc...
Add this resource's templates dir to template paths
def _load_fofn(cls, fofn): filenames = {} f = pyfastaq.utils.open_file_read(fofn) for line in f: fields = line.rstrip().split() if len(fields) == 1: filenames[fields[0]] = None elif len(fields) == 2: filenames[fields[0]] = field...
Returns dictionary of filename -> short name. Value is None whenever short name is not provided
def set_gamma_value(self, value): if isinstance(value, float) is False: raise TypeError("The type of __gamma_value must be float.") self.__gamma_value = value
setter Gamma value.
def _update_parsed_node_info(self, parsed_node, config): schema_override = config.config.get('schema') get_schema = self.get_schema_func() parsed_node.schema = get_schema(schema_override).strip() alias_override = config.config.get('alias') get_alias = self.get_alias_func() ...
Given the SourceConfig used for parsing and the parsed node, generate and set the true values to use, overriding the temporary parse values set in _build_intermediate_parsed_node.
def dims_intersect(self): return set.intersection(*map( set, (getattr(arr, 'dims_intersect', arr.dims) for arr in self)))
Dimensions of the arrays in this list that are used in all arrays
def cd(self, dir_p): if not isinstance(dir_p, basestring): raise TypeError("dir_p can only be an instance of type basestring") progress = self._call("cd", in_p=[dir_p]) progress = IProgress(progress) return progress
Change the current directory level. in dir_p of type str The name of the directory to go in. return progress of type :class:`IProgress` Progress object to track the operation completion.
def get_moods(self): mood_parent = self._get_mood_parent() def process_result(result): return [self.get_mood(mood, mood_parent=mood_parent) for mood in result] return Command('get', [ROOT_MOODS, mood_parent], process_result=process_result)
Return moods defined on the gateway. Returns a Command.
def _stringify_predicate_value(value): if isinstance(value, bool): return str(value).lower() elif isinstance(value, Sequence) and not isinstance(value, six.string_types): return ','.join(_stringify_predicate_value(x) for x in value) elif isinstance(value, datetime.datetime): return v...
Convert Python objects to Space-Track compatible strings - Booleans (``True`` -> ``'true'``) - Sequences (``[25544, 34602]`` -> ``'25544,34602'``) - dates/datetimes (``date(2015, 12, 23)`` -> ``'2015-12-23'``) - ``None`` -> ``'null-val'``
def remove_all_network_profiles(self, obj): profile_name_list = self.network_profile_name_list(obj) for profile_name in profile_name_list: self._logger.debug("delete profile: %s", profile_name) str_buf = create_unicode_buffer(profile_name) ret = self._wlan_delete_prof...
Remove all the AP profiles.
def assert_matching_time_coord(arr1, arr2): message = ('Time weights not indexed by the same time coordinate as' ' computed data. This will lead to an improperly computed' ' time weighted average. Exiting.\n' 'arr1: {}\narr2: {}') if not (arr1[TIME_STR].identical(a...
Check to see if two DataArrays have the same time coordinate. Parameters ---------- arr1 : DataArray or Dataset First DataArray or Dataset arr2 : DataArray or Dataset Second DataArray or Dataset Raises ------ ValueError If the time coordinates are not identical betw...
def _uninstall(cls): if cls._hook: sys.meta_path.remove(cls._hook) cls._hook = None
uninstall the hook if installed
def _resolve_formatter(self, attr): if attr in COLORS: return self._resolve_color(attr) elif attr in COMPOUNDABLES: return self._formatting_string(self._resolve_capability(attr)) else: formatters = split_into_formatters(attr) if all(f in COMPOUNDAB...
Resolve a sugary or plain capability name, color, or compound formatting function name into a callable capability. Return a ``ParametrizingString`` or a ``FormattingString``.
def template_to_base_path(template, google_songs): if template == os.getcwd() or template == '%suggested%': base_path = os.getcwd() else: template = os.path.abspath(template) song_paths = [template_to_filepath(template, song) for song in google_songs] base_path = os.path.dirname(os.path.commonprefix(song_path...
Get base output path for a list of songs for download.
def _validate_jpx_box_sequence(self, boxes): self._validate_label(boxes) self._validate_jpx_compatibility(boxes, boxes[1].compatibility_list) self._validate_singletons(boxes) self._validate_top_level(boxes)
Run through series of tests for JPX box legality.
def rename(self, new_name_or_name_dict=None, **names): if names or utils.is_dict_like(new_name_or_name_dict): name_dict = either_dict_or_kwargs( new_name_or_name_dict, names, 'rename') dataset = self._to_temp_dataset().rename(name_dict) return self._from_temp_...
Returns a new DataArray with renamed coordinates or a new name. Parameters ---------- new_name_or_name_dict : str or dict-like, optional If the argument is dict-like, it it used as a mapping from old names to new names for coordinates. Otherwise, use the argument ...
def get_zipped_dataset_from_predictions(predictions): targets = stack_data_given_key(predictions, "targets") outputs = stack_data_given_key(predictions, "outputs") num_videos, num_steps = targets.shape[:2] outputs = outputs[:, :num_steps] targets_placeholder = tf.placeholder(targets.dtype, targets.shape) ou...
Creates dataset from in-memory predictions.
def set_user_passwd(self, userid, data): return self.api_call( ENDPOINTS['users']['password'], dict(userid=userid), body=data)
Set user password
def path(path_name=None, override=None, *, root=None, name=None, ext=None, inject=None, relpath=None, reduce=False): path_name, identity, root = _initialize(path_name, override, root, inject) new_name = _process_name(path_name, identity, name, ext) new_directory = _process_directory(path_name, iden...
Path manipulation black magic
def _margtimephase_loglr(self, mf_snr, opt_snr): return special.logsumexp(numpy.log(special.i0(mf_snr)), b=self._deltat) - 0.5*opt_snr
Returns the log likelihood ratio marginalized over time and phase.
def get_currentDim(self): selfDim = self._dimensions.copy() if not isinstance(selfDim,dimStr): if selfDim.has_key('_ndims') : nself = selfDim.pop('_ndims') else : self.warning(1, 'self._dimensions does not have the _ndims key') nself = len(s...
returns the current dimensions of the object
def _prepare_menu(self, node, flat=None): if flat is None: flat = self.flat ItemGroup = MenuSection if flat else SubMenu return [ ItemGroup(branch.label, self._collapse_device(branch, flat)) for branch in node.branches if branch.methods or branch.b...
Prepare the menu hierarchy from the given device tree. :param Device node: root node of device hierarchy :returns: menu hierarchy as list
def get(self): self.lock.acquire() try: c = self.conn.popleft() yield c except self.exc_classes: gevent.spawn_later(1, self._addOne) raise except: self.conn.append(c) self.lock.release() raise els...
Get a connection from the pool, to make and receive traffic. If the connection fails for any reason (socket.error), it is dropped and a new one is scheduled. Please use @retry as a way to automatically retry whatever operation you were performing.
def plot(self): msg = "'%s.plot': ADW 2018-05-05"%self.__class__.__name__ DeprecationWarning(msg) import ugali.utils.plotting mask = hp.UNSEEN * np.ones(hp.nside2npix(self.nside)) mask[self.roi.pixels] = self.mask_roi_sparse mask[mask == 0.] = hp.UNSEEN ugali.util...
Plot the magnitude depth.
def get_requirements(self, arguments, max_retries=None, use_wheels=False): arguments = self.decorate_arguments(arguments) with DownloadLogFilter(): with SetupRequiresPatch(self.config, self.eggs_links): self.create_build_directory() if any(match_option(a, '-U'...
Use pip to download and unpack the requested source distribution archives. :param arguments: The command line arguments to ``pip install ...`` (a list of strings). :param max_retries: The maximum number of times that pip will be asked to download di...
def buildcommit(self): if len(self.dutinformation) > 0 and (self.dutinformation.get(0).build is not None): return self.dutinformation.get(0).build.commit_id return None
get build commit id. :return: build commit id or None if not found
def action_update(self): order = [] form = self.request.form attachments = form.get("attachments", []) for attachment in attachments: values = dict(attachment) uid = values.pop("UID") obj = api.get_object_by_uid(uid) if values.pop("delete",...
Form action enpoint to update the attachments
def close(self): close_command = StandardSend(self._address, COMMAND_LIGHT_OFF_0X13_0X00) self._send_method(close_command, self._close_message_received)
Send CLOSE command to device.
def _try_join_cancelled_thread(thread): thread.join(10) if thread.is_alive(): logging.warning("Thread %s did not terminate within grace period after cancellation", thread.name)
Join a thread, but if the thread doesn't terminate for some time, ignore it instead of waiting infinitely.
def sni2route(self, sni: SchemaNodeId, sctx: SchemaContext) -> SchemaRoute: nlist = sni.split("/") res = [] for qn in (nlist[1:] if sni[0] == "/" else nlist): res.append(self.translate_node_id(qn, sctx)) return res
Translate schema node identifier to a schema route. Args: sni: Schema node identifier (absolute or relative). sctx: Schema context. Raises: ModuleNotRegistered: If `mid` is not registered in the data model. UnknownPrefix: If a prefix specified in `sni` i...
def dispatch_to_index_op(op, left, right, index_class): left_idx = index_class(left) if getattr(left_idx, 'freq', None) is not None: left_idx = left_idx._shallow_copy(freq=None) try: result = op(left_idx, right) except NullFrequencyError: raise TypeError('incompatible type for a ...
Wrap Series left in the given index_class to delegate the operation op to the index implementation. DatetimeIndex and TimedeltaIndex perform type checking, timezone handling, overflow checks, etc. Parameters ---------- op : binary operator (operator.add, operator.sub, ...) left : Series ri...
def add_ref(self, reftype, data): ref = (reftype, data) try: index = self.refs.index(ref) except ValueError: self.refs.append(ref) index = len(self.refs) - 1 return str(index)
Add a reference and returns the identifier.
def _csv_temp(self, cursor, fieldnames): temp_fd, temp_path = tempfile.mkstemp(text=True) with open(temp_fd, 'w', encoding='utf-8', newline='') as results_fh: self._csv(cursor, fieldnames, results_fh) return temp_path
Writes the rows of `cursor` in CSV format to a temporary file and returns the path to that file. :param cursor: database cursor containing data to be output :type cursor: `sqlite3.Cursor` :param fieldnames: row headings :type fieldnames: `list` :rtype: `str`
def enable(states): ret = { 'res': True, 'msg': '' } states = salt.utils.args.split_input(states) log.debug('states %s', states) msg = [] _disabled = __salt__['grains.get']('state_runs_disabled') if not isinstance(_disabled, list): _disabled = [] _changed = False ...
Enable state function or sls run CLI Example: .. code-block:: bash salt '*' state.enable highstate salt '*' state.enable test.succeed_without_changes .. note:: To enable a state file from running provide the same name that would be passed in a state.sls call. sa...
def validate(self, attrs): user = authenticate(**self.user_credentials(attrs)) if user: if user.is_active: self.instance = user else: raise serializers.ValidationError(_("This account is currently inactive.")) else: error = _("I...
checks if login credentials are correct
def from_lines(lines: Iterable[str], **kwargs) -> BELGraph: graph = BELGraph() parse_lines(graph=graph, lines=lines, **kwargs) return graph
Load a BEL graph from an iterable over the lines of a BEL script. :param lines: An iterable of strings (the lines in a BEL script) The remaining keyword arguments are passed to :func:`pybel.io.line_utils.parse_lines`.
def migrateFileFields(portal): portal_types = [ "Attachment", "ARImport", "Instrument", "InstrumentCertification", "Method", "Multifile", "Report", "ARReport", "SamplePoint"] for portal_type in portal_types: migrate_to_blob( ...
This function walks over all attachment types and migrates their FileField fields.
def get_channelstate_filter( chain_state: ChainState, payment_network_id: PaymentNetworkID, token_address: TokenAddress, filter_fn: Callable, ) -> List[NettingChannelState]: token_network = get_token_network_by_token_address( chain_state, payment_network_id, t...
Return the state of channels that match the condition in `filter_fn`
def remove(self): "Remove the hook from the model." if not self.removed: self.hook.remove() self.removed=True
Remove the hook from the model.
def add(self, data, name=None): if name is None: n = len(self.data) while "Series %d"%n in self.data: n += 1 name = "Series %d"%n self.data[name] = data return name
Appends a new column of data to the data source. Args: data (seq) : new data to add name (str, optional) : column name to use. If not supplied, generate a name of the form "Series ####" Returns: str: the column name used
def sync_time(self): now = time.localtime(time.time()) self.remote(set_time, (now.tm_year, now.tm_mon, now.tm_mday, now.tm_wday + 1, now.tm_hour, now.tm_min, now.tm_sec, 0)) return now
Sets the time on the pyboard to match the time on the host.
def optimal_part_info(length, part_size): if length == -1: length = MAX_MULTIPART_OBJECT_SIZE if length > MAX_MULTIPART_OBJECT_SIZE: raise InvalidArgumentError('Input content size is bigger ' ' than allowed maximum of 5TiB.') if part_size != MIN_PART_SIZE: ...
Calculate optimal part size for multipart uploads. :param length: Input length to calculate part size of. :return: Optimal part size.
def parse_image_spec(spec): match = re.match(r'(.+)\s+\"(.*)\"\s*$', spec) if match: spec, title = match.group(1, 2) else: title = None match = re.match(r'([^\{]*)(\{(.*)\})\s*$', spec) if match: spec = match.group(1) args = parse_arglist(match.group(3)) else: ...
Parses out a Publ-Markdown image spec into a tuple of path, args, title
def _get_extended(scene, resp): root = ElementTree.fromstring(resp.text) items = root.findall("eemetadata:metadataFields/eemetadata:metadataField", NAMESPACES) scene['extended'] = {item.attrib.get('name').strip(): xsi.get(item[0]) for item in items} return scene
Parse metadata returned from the metadataUrl of a USGS scene. :param scene: Dictionary representation of a USGS scene :param resp: Response object from requests/grequests
def list(self, filter_args=None): res = list() for oid in self._resources: resource = self._resources[oid] if self._matches_filters(resource, filter_args): res.append(resource) return res
List the faked resources of this manager. Parameters: filter_args (dict): Filter arguments. `None` causes no filtering to happen. See :meth:`~zhmcclient.BaseManager.list()` for details. Returns: list of FakedBaseResource: The faked resource objects of this ...
def get_all_tags_of_confirmation(self, confirmation_id): return self._iterate_through_pages( get_function=self.get_tags_of_confirmation_per_page, resource=CONFIRMATION_TAGS, **{'confirmation_id': confirmation_id} )
Get all tags of confirmation This will iterate over all pages until it gets all elements. So if the rate limit exceeded it will throw an Exception and you will get nothing :param confirmation_id: the confirmation id :return: list
def map(**kwargs): d = {} e = lower_dict(environ.copy()) for k, v in kwargs.items(): d[k] = e.get(v.lower()) return d
Returns a dictionary of the given keyword arguments mapped to their values from the environment, with input keys lower cased.
def get(self, sid): return IpAccessControlListMappingContext( self._version, account_sid=self._solution['account_sid'], domain_sid=self._solution['domain_sid'], sid=sid, )
Constructs a IpAccessControlListMappingContext :param sid: A 34 character string that uniquely identifies the resource to fetch. :returns: twilio.rest.api.v2010.account.sip.domain.ip_access_control_list_mapping.IpAccessControlListMappingContext :rtype: twilio.rest.api.v2010.account.sip.domain....
def set_system_id(self, system_id): yield from self._hypervisor.send('{platform} set_system_id "{name}" {system_id}'.format(platform=self._platform, name=self._name, ...
Sets the system ID. :param system_id: a system ID (also called board processor ID)
def tarbell_update(command, args): with ensure_settings(command, args) as settings, ensure_project(command, args) as site: puts("Updating to latest blueprint\n") git = sh.git.bake(_cwd=site.base.base_dir) puts(colored.yellow("Stashing local changes")) puts(git.stash()) puts(c...
Update the current tarbell project.
def shift(self, shifts=None, fill_value=dtypes.NA, **shifts_kwargs): variable = self.variable.shift( shifts=shifts, fill_value=fill_value, **shifts_kwargs) return self._replace(variable=variable)
Shift this array by an offset along one or more dimensions. Only the data is moved; coordinates stay in place. Values shifted from beyond array bounds are replaced by NaN. This is consistent with the behavior of ``shift`` in pandas. Parameters ---------- shifts : Mappin...
def parse(self, rrstr): if self._initialized: raise pycdlibexception.PyCdlibInternalError('TF record already initialized!') (su_len, su_entry_version_unused, self.time_flags,) = struct.unpack_from('=BBB', rrstr[:5], 2) if su_len < 5: raise pycdlibexception.PyCdlibInvalidI...
Parse a Rock Ridge Time Stamp record out of a string. Parameters: rrstr - The string to parse the record out of. Returns: Nothing.
def end_experience_collection_timer(self): if self.time_start_experience_collection: curr_delta = time() - self.time_start_experience_collection if self.delta_last_experience_collection is None: self.delta_last_experience_collection = curr_delta else: ...
Inform Metrics class that experience collection is done.
def icon(self): if isinstance(self._icon, str): if QtGui.QIcon.hasThemeIcon(self._icon): return QtGui.QIcon.fromTheme(self._icon) else: return QtGui.QIcon(self._icon) elif isinstance(self._icon, tuple): return QtGui.QIcon.fromTheme(self...
Gets the icon file name. Read-only.
def deserialize(data): key = data.get('exc_path') if key in registry: exc_args = data.get('exc_args', ()) return registry[key](*exc_args) exc_type = data.get('exc_type') value = data.get('value') return RemoteError(exc_type=exc_type, value=value)
Deserialize `data` to an exception instance. If the `exc_path` value matches an exception registered as ``deserializable``, return an instance of that exception type. Otherwise, return a `RemoteError` instance describing the exception that occurred.
def _get_running_config(self, split=True): conn = self._get_connection() config = conn.get_config(source="running") if config: root = ET.fromstring(config._raw) running_config = root[0][0] if split is True: rgx = re.compile("\r*\n+") ...
Get the IOS XE device's current running config. :return: Current IOS running config as multiline string
def _get_long_description(self): if self.description is None: return None lines = [x for x in self.description.split('\n')] if len(lines) == 1: return None elif len(lines) >= 3 and lines[1] == '': return '\n'.join(lines[2:]) return self.descrip...
Return the subsequent lines of a multiline description Returns: string: The long description, otherwise None
def _default_key_normalizer(key_class, request_context): context = request_context.copy() context['scheme'] = context['scheme'].lower() context['host'] = context['host'].lower() for key in ('headers', '_proxy_headers', '_socks_options'): if key in context and context[key] is not None: ...
Create a pool key out of a request context dictionary. According to RFC 3986, both the scheme and host are case-insensitive. Therefore, this function normalizes both before constructing the pool key for an HTTPS request. If you wish to change this behaviour, provide alternate callables to ``key_fn_by_s...
def load_module(prefix, epoch, data_names, data_shapes): sym, arg_params, aux_params = mx.model.load_checkpoint(prefix, epoch) pred_fc = sym.get_internals()['pred_fc_output'] sym = mx.sym.softmax(data=pred_fc) mod = mx.mod.Module(symbol=sym, context=mx.cpu(), data_names=data_names, label_names=None) ...
Loads the model from checkpoint specified by prefix and epoch, binds it to an executor, and sets its parameters and returns a mx.mod.Module
def check(self, spec, data): path_eval = self.path_eval for keypath, specvalue in spec.items(): if keypath.startswith('$'): optext = keypath checkable = data args = (optext, specvalue, checkable) generator = self.dispatch_operat...
Given a mongo-style spec and some data or python object, check whether the object complies with the spec. Fails eagerly.
def bounds(self): the_bounds = [np.inf, -np.inf, np.inf, -np.inf, np.inf, -np.inf] def _update_bounds(bounds): def update_axis(ax): if bounds[ax*2] < the_bounds[ax*2]: the_bounds[ax*2] = bounds[ax*2] if bounds[ax*2+1] > the_bounds[ax*2+1]: ...
Bounds of all actors present in the rendering window
def _bounds_from_array(arr, dim_name, bounds_name): spacing = arr.diff(dim_name).values lower = xr.DataArray(np.empty_like(arr), dims=arr.dims, coords=arr.coords) lower.values[:-1] = arr.values[:-1] - 0.5*spacing lower.values[-1] = arr.values[-1] - 0.5*spacing[-1] upper = xr...
Get the bounds of an array given its center values. E.g. if lat-lon grid center lat/lon values are known, but not the bounds of each grid box. The algorithm assumes that the bounds are simply halfway between each pair of center values.
def cluster_application(self, application_id): path = '/ws/v1/cluster/apps/{appid}'.format(appid=application_id) return self.request(path)
An application resource contains information about a particular application that was submitted to a cluster. :param str application_id: The application id :returns: API response object with JSON data :rtype: :py:class:`yarn_api_client.base.Response`
def filter(self, info, releases): for version in list(releases.keys()): if any(pattern.match(version) for pattern in self.patterns): del releases[version]
Remove all release versions that match any of the specificed patterns.
def _compute_std(self, C, stddevs, idx): for stddev in stddevs: stddev[idx] += C['sigma']
Compute total standard deviation, see tables 3 and 4, pages 227 and 228.
def _read_pretrained_embeddings_file(file_uri: str, embedding_dim: int, vocab: Vocabulary, namespace: str = "tokens") -> torch.FloatTensor: file_ext = get_file_extension(file_uri) if file_ext in ['.h5'...
Returns and embedding matrix for the given vocabulary using the pretrained embeddings contained in the given file. Embeddings for tokens not found in the pretrained embedding file are randomly initialized using a normal distribution with mean and standard deviation equal to those of the pretrained embedding...
def update_models(new_obj, current_table, tables, relations): _update_check_inputs(current_table, tables, relations) _check_no_current_table(new_obj, current_table) if isinstance(new_obj, Table): tables_names = [t.name for t in tables] _check_not_creating_duplicates(new_obj.name, tables_name...
Update the state of the parsing.
def compress(self): for ast_token in self.ast_tokens: if type(ast_token) in self.dispatcher: self.dispatcher[type(ast_token)](ast_token) else: self.dispatcher['default'](ast_token)
Main function of compression.
def vm_result_update(self, payload): port_id = payload.get('port_id') result = payload.get('result') if port_id and result: params = dict(columns=dict(result=result)) self.update_vm_db(port_id, **params)
Update the result field in VM database. This request comes from an agent that needs to update the result in VM database to success or failure to reflect the operation's result in the agent.
def asxc(cls, obj): if isinstance(obj, cls): return obj if is_string(obj): return cls.from_name(obj) raise TypeError("Don't know how to convert <%s:%s> to Xcfunc" % (type(obj), str(obj)))
Convert object into Xcfunc.
def xml_records(filename): with Evtx(filename) as evtx: for xml, record in evtx_file_xml_view(evtx.get_file_header()): try: yield to_lxml(xml), None except etree.XMLSyntaxError as e: yield xml, e
If the second return value is not None, then it is an Exception encountered during parsing. The first return value will be the XML string. @type filename str @rtype: generator of (etree.Element or str), (None or Exception)
def quit(self): self.script.LOG.warn("Abort due to user choice!") sys.exit(self.QUIT_RC)
Exit the program due to user's choices.
def add_transition_list (self, list_input_symbols, state, action=None, next_state=None): if next_state is None: next_state = state for input_symbol in list_input_symbols: self.add_transition (input_symbol, state, action, next_state)
This adds the same transition for a list of input symbols. You can pass a list or a string. Note that it is handy to use string.digits, string.whitespace, string.letters, etc. to add transitions that match character classes. The action may be set to None in which case the process() meth...
def get_compositions(self): collection = JSONClientValidated('repository', collection='Composition', runtime=self._runtime) result = collection.find(self._view_filter()).sort('_id', DESCENDING) return objects.Compo...
Gets all ``Compositions``. return: (osid.repository.CompositionList) - a list of ``Compositions`` raise: OperationFailed - unable to complete request raise: PermissionDenied - authorization failure *compliance: mandatory -- This method must be implemented.*
def rainDelay(self, dev_id, duration): path = 'device/rain_delay' payload = {'id': dev_id, 'duration': duration} return self.rachio.put(path, payload)
Rain delay device.
def parse_impl(self): parser = XMLParser(encoding=str('UTF-8')) element_iter = ET.iterparse(self.handle, events=("start", "end"), parser=parser) for pos, element in element_iter: tag, class_attr = _tag_and_class_attr(element) if tag == "h1" and pos == "end": ...
Parses the HTML content as a stream. This is far less memory intensive than loading the entire HTML file into memory, like BeautifulSoup does.
def items(self): for word in self._dictionary.keys(): yield word, self._dictionary[word]
Iterator over the words in the dictionary Yields: str: The next word in the dictionary int: The number of instances in the dictionary Note: This is the same as `dict.items()`
def set_interactive_policy(*, locals=None, banner=None, serve=None, prompt_control=None): policy = InteractiveEventLoopPolicy( locals=locals, banner=banner, serve=serve, prompt_control=prompt_control) asyncio.set_event_loop_policy(policy)
Use an interactive event loop by default.
def get_inner_fts(elt)->List[str]: "List the inner functions of a class." fts = [] for ft_name in elt.__dict__.keys(): if ft_name.startswith('_'): continue ft = getattr(elt, ft_name) if inspect.isfunction(ft): fts.append(f'{elt.__name__}.{ft_name}') if inspect.ismethod(ft): f...
List the inner functions of a class.
def _split_diff(merge_result, context_lines=3): collect = [] for item in _visible_in_diff(merge_result, context_lines=context_lines): if item is None: if collect: yield collect collect = [] else: collect.append(item)
Split diffs and context lines into groups based on None sentinel
def chk_qualifiers(self): if self.name == 'id2gos': return for ntd in self.associations: qual = ntd.Qualifier assert isinstance(qual, set), '{NAME}: QUALIFIER MUST BE A LIST: {NT}'.format( NAME=self.name, NT=ntd) assert qual != set(['']), n...
Check format of qualifier
def infer_enum(node, context=None): enum_meta = extract_node( ) class_node = infer_func_form(node, enum_meta, context=context, enum=True)[0] return iter([class_node.instantiate_class()])
Specific inference function for enum Call node.
def _post(self, q, payload='', params=''): if (q[-1] == '/'): q = q[:-1] headers = {'Content-Type': 'application/json'} r = requests.post('{url}{q}?api_key={key}{params}'.format(url=self.url, q=q, key=self.api_key, params=params), headers=headers, data=payload) re...
Generic POST wrapper including the api_key
def string_to_decimal(value, strict=True): if is_undefined(value): if strict: raise ValueError('The value cannot be null') return None try: return float(value) except ValueError: raise ValueError( 'The specified string "%s" does not represent an intege...
Return a decimal corresponding to the string representation of a number. @param value: a string representation of an decimal number. @param strict: indicate whether the specified string MUST be of a valid decimal number representation. @return: the decimal value represented by the string. ...
def phase_progeny_by_transmission(g): g = GenotypeArray(g, dtype='i1', copy=True) check_ploidy(g.ploidy, 2) check_min_samples(g.n_samples, 3) is_phased = _opt_phase_progeny_by_transmission(g.values) g.is_phased = np.asarray(is_phased).view(bool) return g
Phase progeny genotypes from a trio or cross using Mendelian transmission. Parameters ---------- g : array_like, int, shape (n_variants, n_samples, 2) Genotype array, with parents as first two columns and progeny as remaining columns. Returns ------- g : ndarray, int8, shap...
def addReferenceSet(self, referenceSet): id_ = referenceSet.getId() self._referenceSetIdMap[id_] = referenceSet self._referenceSetNameMap[referenceSet.getLocalId()] = referenceSet self._referenceSetIds.append(id_)
Adds the specified reference set to this data repository.
def add_subscription(self, channel, callback_function): if channel not in CHANNELS: CHANNELS.append(channel) SUBSCRIPTIONS[channel] = [callback_function] else: SUBSCRIPTIONS[channel].append(callback_function) if self._subscribed: _LOGGER.info("New ...
Add a channel to subscribe to and a callback function to run when the channel receives an update. If channel already exists, create a new "subscription" and append another callback function. Args: channel (str): The channel to add a subscription too. callback_fun...
def _debug_mode_responses(self, request, response): if django.conf.settings.DEBUG_GMN: if 'pretty' in request.GET: response['Content-Type'] = d1_common.const.CONTENT_TYPE_TEXT if ( 'HTTP_VENDOR_PROFILE_SQL' in request.META or django.conf.se...
Extra functionality available in debug mode. - If pretty printed output was requested, force the content type to text. This causes the browser to not try to format the output in any way. - If SQL profiling is turned on, return a page with SQL query timing information instead of the ...
def _start_monitoring(self): before = self._file_timestamp_info(self.path) while True: gevent.sleep(1) after = self._file_timestamp_info(self.path) added = [fname for fname in after.keys() if fname not in before.keys()] removed = [fname for fname in before...
Internal method that monitors the directory for changes
def save_csv(self, filename, write_header_separately=True): txt = '' with open(filename, "w") as f: if write_header_separately: f.write(','.join([c for c in self.header]) + '\n') for row in self.arr: txt = ','.join([self.force_to_string(col) for co...
save the default array as a CSV file
def registered(self, socket_client): self._socket_client = socket_client if self.target_platform: self._message_func = self._socket_client.send_platform_message else: self._message_func = self._socket_client.send_app_message
Called when a controller is registered.
def multi_select(self, elements_to_select): first_element = elements_to_select.pop() self.click(first_element) for index, element in enumerate(elements_to_select, start=1): self.multi_click(element)
Multi-select any number of elements. :param elements_to_select: list of WebElement instances :return: None
def sign_message(self, key, message, verbose=False): secret_exponent = key.secret_exponent() if not secret_exponent: raise ValueError("Private key is required to sign a message") addr = key.address() msg_hash = self.hash_for_signing(message) is_compressed = key.is_com...
Return a signature, encoded in Base64, which can be verified by anyone using the public key.
def custom_property_prefix_lax(instance): for prop_name in instance.keys(): if (instance['type'] in enums.PROPERTIES and prop_name not in enums.PROPERTIES[instance['type']] and prop_name not in enums.RESERVED_PROPERTIES and not CUSTOM_PROPERTY_LAX_PREFIX_RE.ma...
Ensure custom properties follow lenient naming style conventions for forward-compatibility. Does not check property names in custom objects.
def add_data_attribute(self, data_attr): if data_attr.header.attr_type_id is not AttrTypes.DATA: raise DataStreamError("Invalid attribute. A Datastream deals only with DATA attributes") if data_attr.header.attr_name != self.name: raise DataStreamError(f"Data from a different stre...
Interprets a DATA attribute and add it to the datastream.
def resolve(tex): soup = TexSoup(tex) for subimport in soup.find_all('subimport'): path = subimport.args[0] + subimport.args[1] subimport.replace_with(*resolve(open(path)).contents) for _import in soup.find_all('import'): _import.replace_with(*resolve(open(_import.args[0])).contents)...
Resolve all imports and update the parse tree. Reads from a tex file and once finished, writes to a tex file.
def authorization_code_pkce(self, client_id, code_verifier, code, redirect_uri, grant_type='authorization_code'): return self.post( 'https://{}/oauth/token'.format(self.domain), data={ 'client_id': client_id, 'code_verifier'...
Authorization code pkce grant This is the OAuth 2.0 grant that mobile apps utilize in order to access an API. Use this endpoint to exchange an Authorization Code for a Token. Args: grant_type (str): Denotes the flow you're using. For authorization code pkce use authoriz...