code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _list(self, request, start_response): """Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333....
Sends HTTP response containing the API directory. This calls start_response and returns the response body. Args: request: An ApiRequest, the transformed request sent to the Discovery API. start_response: A function with semantics defined in PEP-333. Returns: A string containing the resp...
def undoable(generator): ''' Decorator which creates a new undoable action type. This decorator should be used on a generator of the following format:: @undoable def operation(*args): do_operation_code yield 'descriptive text' undo_operator_code ...
Decorator which creates a new undoable action type. This decorator should be used on a generator of the following format:: @undoable def operation(*args): do_operation_code yield 'descriptive text' undo_operator_code
def from_arg_kinds(cls, arch, fp_args, ret_fp=False, sizes=None, sp_delta=None, func_ty=None): """ Get an instance of the class that will extract floating-point/integral args correctly. :param arch: The Archinfo arch for this CC :param fp_args: A list, with one entry for each...
Get an instance of the class that will extract floating-point/integral args correctly. :param arch: The Archinfo arch for this CC :param fp_args: A list, with one entry for each argument the function can take. True if the argument is fp, false if it is integral. ...
def output_default(paragraphs, fp=sys.stdout, no_boilerplate=True): """ Outputs the paragraphs as: <tag> text of the first paragraph <tag> text of the second paragraph ... where <tag> is <p>, <h> or <b> which indicates standard paragraph, heading or boilerplate respecitvely. """ for ...
Outputs the paragraphs as: <tag> text of the first paragraph <tag> text of the second paragraph ... where <tag> is <p>, <h> or <b> which indicates standard paragraph, heading or boilerplate respecitvely.
def do_command(self): """Call a single command with arguments.""" method = self.args[0] raw_args = self.args[1:] if '=' in method: if raw_args: self.parser.error("Please don't mix rTorrent and shell argument styles!") method, raw_args = method.spl...
Call a single command with arguments.
def hpre(*content, sep='\n'): """ Make mono-width text block (HTML) :param content: :param sep: :return: """ return _md(quote_html(_join(*content, sep=sep)), symbols=MD_SYMBOLS[7])
Make mono-width text block (HTML) :param content: :param sep: :return:
def format_docstring(elt, arg_comments:dict={}, alt_doc_string:str='', ignore_warn:bool=False)->str: "Merge and format the docstring definition with `arg_comments` and `alt_doc_string`." parsed = "" doc = parse_docstring(inspect.getdoc(elt)) description = alt_doc_string or f"{doc['short_description']} {...
Merge and format the docstring definition with `arg_comments` and `alt_doc_string`.
def ReadClientLastPings(self, min_last_ping=None, max_last_ping=None, fleetspeak_enabled=None, cursor=None): """Reads client ids for all clients in the database.""" query = "SELECT client_id, UNIX_TIMESTAMP(l...
Reads client ids for all clients in the database.
def get_model_choices(): """ Get the select options for the model selector :return: """ result = [] for ct in ContentType.objects.order_by('app_label', 'model'): try: if issubclass(ct.model_class(), TranslatableModel): result.append( ('{} ...
Get the select options for the model selector :return:
def repr_failure(self, excinfo): """ called when self.runtest() raises an exception. """ exc = excinfo.value cc = self.colors if isinstance(exc, NbCellError): msg_items = [ cc.FAIL + "Notebook cell execution failed" + cc.ENDC] formatstring = ( ...
called when self.runtest() raises an exception.
def text_to_qcolor(text): """ Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated """ color = QColor() if not is_string(text): # testing for QString (PyQt API#1) text = str(text) if not is_text_string(text): return color if t...
Create a QColor from specified string Avoid warning from Qt when an invalid QColor is instantiated
def lookup(self, subcmd_prefix): """Find subcmd in self.subcmds""" for subcmd_name in list(self.subcmds.keys()): if subcmd_name.startswith(subcmd_prefix) \ and len(subcmd_prefix) >= \ self.subcmds[subcmd_name].__class__.min_abbrev: return self.su...
Find subcmd in self.subcmds
def is_empty_shape(sh: ShExJ.Shape) -> bool: """ Determine whether sh has any value """ return sh.closed is None and sh.expression is None and sh.extra is None and \ sh.semActs is None
Determine whether sh has any value
def scan_temperature_old(self, measure, temperature, rate, delay=1): """Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The targ...
Performs a temperature scan. Measures until the target temperature is reached. :param measure: A callable called repeatedly until stability at target temperature is reached. :param temperature: The target temperature in kelvin. :param rate: The sweep rate in kelvin per minu...
def clean_ticker(ticker): """ Cleans a ticker for easier use throughout MoneyTree Splits by space and only keeps first bit. Also removes any characters that are not letters. Returns as lowercase. >>> clean_ticker('^VIX') 'vix' >>> clean_ticker('SPX Index') 'spx' """ pattern = r...
Cleans a ticker for easier use throughout MoneyTree Splits by space and only keeps first bit. Also removes any characters that are not letters. Returns as lowercase. >>> clean_ticker('^VIX') 'vix' >>> clean_ticker('SPX Index') 'spx'
def _elements(self, IDs, func, aspList): """ Returns the IDs as objects considering the aspList and the function. """ res = [] for asp in aspList: if (asp in [0, 180]): # Generate func for conjunctions and oppositions if func =...
Returns the IDs as objects considering the aspList and the function.
def load_agents(self, config_file=None): """ Loads all agents for this team from the rlbot.cfg :param config_file: A config file that is similar to rlbot.cfg """ if config_file is not None: self.overall_config = config_file self.agents.clear() num_par...
Loads all agents for this team from the rlbot.cfg :param config_file: A config file that is similar to rlbot.cfg
def pre_calc(self, x, y, beta, n_order, center_x, center_y): """ calculates the H_n(x) and H_n(y) for a given x-array and y-array :param x: :param y: :param amp: :param beta: :param n_order: :param center_x: :param center_y: :return: list o...
calculates the H_n(x) and H_n(y) for a given x-array and y-array :param x: :param y: :param amp: :param beta: :param n_order: :param center_x: :param center_y: :return: list of H_n(x) and H_n(y)
def htmldiff_tokens(html1_tokens, html2_tokens): """ Does a diff on the tokens themselves, returning a list of text chunks (not tokens). """ # There are several passes as we do the differences. The tokens # isolate the portion of the content we care to diff; difflib does # all the actual hard w...
Does a diff on the tokens themselves, returning a list of text chunks (not tokens).
def _set_mstp(self, v, load=False): """ Setter method for mstp, mapped from YANG variable /protocol/spanning_tree/mstp (container) If this variable is read-only (config: false) in the source YANG file, then _set_mstp is considered as a private method. Backends looking to populate this variable shoul...
Setter method for mstp, mapped from YANG variable /protocol/spanning_tree/mstp (container) If this variable is read-only (config: false) in the source YANG file, then _set_mstp is considered as a private method. Backends looking to populate this variable should do so via calling thisObj._set_mstp() dire...
def _get_input_for_run(args, executable, preset_inputs=None, input_name_prefix=None): """ Returns an input dictionary that can be passed to executable.run() """ # The following may throw if the executable is a workflow with no # input spec available (because a stage is inaccessible) exec_inputs ...
Returns an input dictionary that can be passed to executable.run()
def _file_filter(cls, filename, include_patterns, exclude_patterns): """:returns: `True` if the file should be allowed through the filter.""" logger.debug('filename: {}'.format(filename)) for exclude_pattern in exclude_patterns: if exclude_pattern.match(filename): return False if include_p...
:returns: `True` if the file should be allowed through the filter.
def _update_roster(self): ''' Update default flat roster with the passed in information. :return: ''' roster_file = self._get_roster() if os.access(roster_file, os.W_OK): if self.__parsed_rosters[self.ROSTER_UPDATE_FLAG]: with salt.utils.files....
Update default flat roster with the passed in information. :return:
def files(self): """Return list of files in root directory""" self._printer('\tFiles Walk') for directory in self.directory: for path in os.listdir(directory): full_path = os.path.join(directory, path) if os.path.isfile(full_path): ...
Return list of files in root directory
def _moments_central(data, center=None, order=1): """ Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it wil...
Calculate the central image moments up to the specified order. Parameters ---------- data : 2D array-like The input 2D array. center : tuple of two floats or `None`, optional The ``(x, y)`` center position. If `None` it will calculated as the "center of mass" of the input ``da...
def layer_tagger_mapping(self): """Dictionary that maps layer names to taggers that can create that layer.""" return { PARAGRAPHS: self.tokenize_paragraphs, SENTENCES: self.tokenize_sentences, WORDS: self.tokenize_words, ANALYSIS: self.tag_analysis, ...
Dictionary that maps layer names to taggers that can create that layer.
def verifies( self, hash, signature ): """Verify that signature is a valid signature of hash. Return True if the signature is valid. """ # From X9.62 J.3.1. G = self.generator n = G.order() r = signature.r s = signature.s if r < 1 or r > n-1: return False if s < 1 or s > n-1: r...
Verify that signature is a valid signature of hash. Return True if the signature is valid.
def decode_response(client_message, to_object=None): """ Decode response from client message""" parameters = dict(response=None) response_size = client_message.read_int() response = [] for _ in range(0, response_size): response_item = client_message.read_data() response.append(respon...
Decode response from client message
def check_version(component, expected_version): """Make sure the package version in setuptools matches what we expect it to be""" comp = comp_names[component] compath = os.path.realpath(os.path.abspath(comp.path)) sys.path.insert(0, compath) import version if version.version != expected_vers...
Make sure the package version in setuptools matches what we expect it to be
def parse_xml_jtl(self, granularity): """ Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second' :return: status...
Parse Jmeter workload output in XML format and extract overall and per transaction data and key statistics :param string granularity: The time period over which to aggregate and average the raw data. Valid values are 'hour', 'minute' or 'second' :return: status of the metric parse
def copy(a): """ Copy an array to the shared memory. Notes ----- copy is not always necessary because the private memory is always copy-on-write. Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory """ shared = anonymousmemmap(a.shape, dtype=a....
Copy an array to the shared memory. Notes ----- copy is not always necessary because the private memory is always copy-on-write. Use :code:`a = copy(a)` to immediately dereference the old 'a' on private memory
def notUnique(iterable, reportMax=INF): """Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1] """ hash = {} n=0 if repo...
Returns the elements in `iterable` that aren't unique; stops after it found `reportMax` non-unique elements. Examples: >>> list(notUnique([1,1,2,2,3,3])) [1, 2, 3] >>> list(notUnique([1,1,2,2,3,3], 1)) [1]
def expand(self, other): """ Add all elements from an other result to the list of elements of this result object. It is used by the auto resolve feature. :param other: Expand the result with the elements from this result. :type other: overpy.Result :raises ValueError: I...
Add all elements from an other result to the list of elements of this result object. It is used by the auto resolve feature. :param other: Expand the result with the elements from this result. :type other: overpy.Result :raises ValueError: If provided parameter is not instance of :clas...
def print_about(self): """Print an info message about the tool.""" filepath = os.path.join(self.suite_path, "bin", self.tool_name) print "Tool: %s" % self.tool_name print "Path: %s" % filepath print "Suite: %s" % self.suite_path msg = "%s (%r)" % (self.context...
Print an info message about the tool.
def star(self, **args): ''' star any gist by providing gistID or gistname(for authenticated user) ''' if 'name' in args: self.gist_name = args['name'] self.gist_id = self.getMyID(self.gist_name) elif 'id' in args: self.gist_id = args['id'] else: raise Exception('Either provide authenticated user...
star any gist by providing gistID or gistname(for authenticated user)
def wallet_republish(self, wallet, count): """ Rebroadcast blocks for accounts from **wallet** starting at frontier down to **count** to the network .. enable_control required .. version 8.0 required :param wallet: Wallet to rebroadcast blocks for :type wallet: ...
Rebroadcast blocks for accounts from **wallet** starting at frontier down to **count** to the network .. enable_control required .. version 8.0 required :param wallet: Wallet to rebroadcast blocks for :type wallet: str :param count: Max amount of blocks to rebroadcast ...
def UnpackItems(*items, fields=None, defaults=None): """ >>> UnpackItems(0) :param items: :param fields: :param defaults: :return: callable """ defaults = defaults or {} @use_context @use_raw_input def _UnpackItems(context, bag): nonlocal fields, items, defaults ...
>>> UnpackItems(0) :param items: :param fields: :param defaults: :return: callable
def get_abstracts(self, refresh=True): """Return a list of ScopusAbstract objects using ScopusSearch.""" return [ScopusAbstract(eid, refresh=refresh) for eid in self.get_document_eids(refresh=refresh)]
Return a list of ScopusAbstract objects using ScopusSearch.
def deframesig(frames, siglen, frame_len, frame_step, winfunc=lambda x: numpy.ones((x,))): """Does overlap-add procedure to undo the action of framesig. :param frames: the array of frames. :param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples. :pa...
Does overlap-add procedure to undo the action of framesig. :param frames: the array of frames. :param siglen: the length of the desired signal, use 0 if unknown. Output will be truncated to siglen samples. :param frame_len: length of each frame measured in samples. :param frame_step: number of samples ...
def localize(dt, tz): """ Given a naive datetime object this method will return a localized datetime object """ if not isinstance(tz, tzinfo): tz = pytz.timezone(tz) return tz.localize(dt)
Given a naive datetime object this method will return a localized datetime object
def extract_bag_of_words_from_corpus_parallel(corpus, lemmatizing="wordnet"): """ This extracts one bag-of-words from a list of strings. The documents are mapped to parallel processes. Inputs: - corpus: A list of strings. - lemmatizing: A string containing one of the following: "porter", "snowb...
This extracts one bag-of-words from a list of strings. The documents are mapped to parallel processes. Inputs: - corpus: A list of strings. - lemmatizing: A string containing one of the following: "porter", "snowball" or "wordnet". Output: - bag_of_words: This is a bag-of-words in python dictionar...
def get_keys(self, lst): """ return a list of pk values from object list """ pk_name = self.get_pk_name() return [getattr(item, pk_name) for item in lst]
return a list of pk values from object list
def _broadcast_item(self, row_lookup, col_lookup, item, to_shape): """Use numpy to broadcast or reshape item. Notes: - Numpy is memory efficient, there shouldn't be performance issue. """ # It is valid to pass a DataFrame or Series to __setitem__ that is larger than ...
Use numpy to broadcast or reshape item. Notes: - Numpy is memory efficient, there shouldn't be performance issue.
def fromfilenames(filenames, coltype = int): """ Return a segmentlist describing the intervals spanned by the files whose names are given in the list filenames. The segmentlist is constructed by parsing the file names, and the boundaries of each segment are coerced to type coltype. The file names are parsed usi...
Return a segmentlist describing the intervals spanned by the files whose names are given in the list filenames. The segmentlist is constructed by parsing the file names, and the boundaries of each segment are coerced to type coltype. The file names are parsed using a generalization of the format described in Tec...
def get_assigned_licenses(service_instance, entity_ref=None, entity_name=None, license_assignment_manager=None): ''' Returns the licenses assigned to an entity. If entity ref is not provided, then entity_name is assumed to be the vcenter. This is later checked if the entity nam...
Returns the licenses assigned to an entity. If entity ref is not provided, then entity_name is assumed to be the vcenter. This is later checked if the entity name is provided. service_instance The Service Instance Object from which to obtain the licenses. entity_ref VMware entity to ge...
def calculate_squared_differences(image_tile_dict, transformed_array, template, sq_diff_tolerance=0.1): """As above, but for when the squared differences matching method is used """ template_norm_squared = np.sum(template**2) image_norms_squared = {(x,y):np.sum(image_tile_dict[(x,y)]**2) for (x,y) in im...
As above, but for when the squared differences matching method is used
def component_activated(self, component): """Initialize additional member variables for components. Every component activated through the `Environment` object gets an additional member variable: `env` (the environment object) """ component.env = self super(Environment, s...
Initialize additional member variables for components. Every component activated through the `Environment` object gets an additional member variable: `env` (the environment object)
def load_table_from_uri( self, source_uris, destination, job_id=None, job_id_prefix=None, location=None, project=None, job_config=None, retry=DEFAULT_RETRY, ): """Starts a job for loading data into a table from CloudStorage. Se...
Starts a job for loading data into a table from CloudStorage. See https://cloud.google.com/bigquery/docs/reference/rest/v2/jobs#configuration.load Arguments: source_uris (Union[str, Sequence[str]]): URIs of data files to be loaded; in format ``gs://<...
def _deriv_growth(z, **cosmo): """ Returns derivative of the linear growth factor at z for a given cosmology **cosmo """ inv_h = (cosmo['omega_M_0']*(1 + z)**3 + cosmo['omega_lambda_0'])**(-0.5) fz = (1 + z) * inv_h**3 deriv_g = growthfactor(z, norm=True, **cosmo)*(inv_h**2) *\ 1.5 * c...
Returns derivative of the linear growth factor at z for a given cosmology **cosmo
def Advertise(port, stype="SCOOP", sname="Broker", advertisername="Broker", location=""): """ stype = always SCOOP port = comma separated ports sname = broker unique name location = routable location (ip or dns) """ scoop.logger.info("Launching advertiser...") service = min...
stype = always SCOOP port = comma separated ports sname = broker unique name location = routable location (ip or dns)
def stream(identifier=None, priority=LOG_INFO, level_prefix=False): r"""Return a file object wrapping a stream to journal. Log messages written to this file as simple newline sepearted text strings are written to the journal. The file will be line buffered, so messages are actually sent after a ne...
r"""Return a file object wrapping a stream to journal. Log messages written to this file as simple newline sepearted text strings are written to the journal. The file will be line buffered, so messages are actually sent after a newline character is written. >>> from systemd import journal >>>...
def _HandleLegacy(self, args, token=None): """Creates a new hunt.""" # We only create generic hunts with /hunts/create requests. generic_hunt_args = rdf_hunts.GenericHuntArgs() generic_hunt_args.flow_runner_args.flow_name = args.flow_name generic_hunt_args.flow_args = args.flow_args # Clear al...
Creates a new hunt.
def ftr_get_config(website_url, exact_host_match=False): """ Download the Five Filters config from centralized repositories. Repositories can be local if you need to override siteconfigs. The first entry found is returned. If no configuration is found, `None` is returned. If :mod:`cacheops` is install...
Download the Five Filters config from centralized repositories. Repositories can be local if you need to override siteconfigs. The first entry found is returned. If no configuration is found, `None` is returned. If :mod:`cacheops` is installed, the result will be cached with a default expiration delay...
def gdf_to_geojson(gdf, date_format='epoch', properties=None, filename=None): """Serialize a GeoPandas dataframe to a geojson format Python dictionary / file """ # convert dates/datetimes to preferred string format if specified gdf = convert_date_columns(gdf, date_format) gdf_out = gdf[['geometry'...
Serialize a GeoPandas dataframe to a geojson format Python dictionary / file
def event_filter_type(self, event_filter_type): """Sets the event_filter_type of this Dashboard. How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501 :param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501 ...
Sets the event_filter_type of this Dashboard. How charts belonging to this dashboard should display events. BYCHART is default if unspecified # noqa: E501 :param event_filter_type: The event_filter_type of this Dashboard. # noqa: E501 :type: str
def compile_insert_get_id(self, query, values, sequence=None): """ Compile an insert and get ID statement into SQL. :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict :param sequence: The id se...
Compile an insert and get ID statement into SQL. :param query: A QueryBuilder instance :type query: QueryBuilder :param values: The values to insert :type values: dict :param sequence: The id sequence :type sequence: str :return: The compiled statement ...
def import_from_string(value): """Copy of rest_framework.settings.import_from_string""" value = value.replace('-', '_') try: module_path, class_name = value.rsplit('.', 1) module = import_module(module_path) return getattr(module, class_name) except (ImportError, AttributeError) ...
Copy of rest_framework.settings.import_from_string
def delete(self, url: StrOrURL, **kwargs: Any) -> '_RequestContextManager': """Perform HTTP DELETE request.""" return _RequestContextManager( self._request(hdrs.METH_DELETE, url, **kwargs))
Perform HTTP DELETE request.
def packetToDict(pkt): """ Given a packet, this turns it into a dictionary ... is this useful? in: packet, array of numbers out: dictionary (key, value) """ d = { 'id': pkt[4], 'instruction': xl320.InstrToStr[pkt[7]], 'length': (pkt[6] << 8) + pkt[5], 'params': pkt[8:-2], 'crc': pkt[-2:] } return d
Given a packet, this turns it into a dictionary ... is this useful? in: packet, array of numbers out: dictionary (key, value)
def rpc_get_pydoc_documentation(self, symbol): """Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting. """ try: docstring = pydoc.render_doc(str(symbol), ...
Get the Pydoc documentation for the given symbol. Uses pydoc and can return a string with backspace characters for bold highlighting.
def get_most_recent_event(self, originator_id, lt=None, lte=None): """ Gets a domain event from the sequence identified by `originator_id` at the highest position. :param originator_id: ID of a sequence of events :param lt: get highest before this position :param lte: ge...
Gets a domain event from the sequence identified by `originator_id` at the highest position. :param originator_id: ID of a sequence of events :param lt: get highest before this position :param lte: get highest at or before this position :return: domain event
def _subclass_must_implement(self, fn): """ Returns a NotImplementedError for a function that should be implemented. :param fn: name of the function """ m = "Missing function implementation in {}: {}".format(type(self), fn) return NotImplementedError(m)
Returns a NotImplementedError for a function that should be implemented. :param fn: name of the function
def load(source, triples=False, cls=PENMANCodec, **kwargs): """ Deserialize a list of PENMAN-encoded graphs from *source*. Args: source: a filename or file-like object to read from triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class k...
Deserialize a list of PENMAN-encoded graphs from *source*. Args: source: a filename or file-like object to read from triples: if True, read graphs as triples instead of as PENMAN cls: serialization codec class kwargs: keyword arguments passed to the constructor of *cls* Returns:...
def send(self, data, room=None, skip_sid=None, namespace=None, callback=None): """Send a message to the server. The only difference with the :func:`socketio.Client.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is u...
Send a message to the server. The only difference with the :func:`socketio.Client.send` method is that when the ``namespace`` argument is not given the namespace associated with the class is used.
def groups_moderators(self, room_id=None, group=None, **kwargs): """Lists all moderators of a group.""" if room_id: return self.__call_api_get('groups.moderators', roomId=room_id, kwargs=kwargs) elif group: return self.__call_api_get('groups.moderators', roomName=group, k...
Lists all moderators of a group.
def create_user(self, user): """ Creates a new user. :param user: The user object to be created. :type user: ``dict`` """ data = self._create_user_dict(user=user) response = self._perform_request( url='/um/users', method='POST...
Creates a new user. :param user: The user object to be created. :type user: ``dict``
def instantiate_by_name_with_default(self, object_name, default_value=None): """ Instantiate object from the environment, possibly giving some extra arguments """ if object_name not in self.instances: if object_name not in self.environment: return default_value el...
Instantiate object from the environment, possibly giving some extra arguments
def importSNPs(name) : """Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.""" path = os.path.join(this_dir, "bootstrap_data", "SNPs/" + name) PS.importSNPs(path)
Import a SNP set shipped with pyGeno. Most of the datawraps only contain URLs towards data provided by third parties.
def extract_path_info( environ_or_baseurl, path_or_url, charset="utf-8", errors="werkzeug.url_quote", collapse_http_schemes=True, ): """Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a W...
Extracts the path info from the given URL (or WSGI environment) and path. The path info returned is a unicode string, not a bytestring suitable for a WSGI environment. The URLs might also be IRIs. If the path info could not be determined, `None` is returned. Some examples: >>> extract_path_info...
def deactivate_user(query): """ Deactivate a user. """ user = _query_to_user(query) if click.confirm(f'Are you sure you want to deactivate {user!r}?'): user.active = False user_manager.save(user, commit=True) click.echo(f'Successfully deactivated {user!r}') else: ...
Deactivate a user.
def dynamize_attribute_updates(self, pending_updates): """ Convert a set of pending item updates into the structure required by Layer1. """ d = {} for attr_name in pending_updates: action, value = pending_updates[attr_name] if value is None: ...
Convert a set of pending item updates into the structure required by Layer1.
def query_raw(self, metric, **kwargs): # noqa: E501 """Perform a raw data query against Wavefront servers that returns second granularity points grouped by tags # noqa: E501 An API to check if ingested points are as expected. Points ingested within a single second are averaged when returned. # noqa...
Perform a raw data query against Wavefront servers that returns second granularity points grouped by tags # noqa: E501 An API to check if ingested points are as expected. Points ingested within a single second are averaged when returned. # noqa: E501 This method makes a synchronous HTTP request by d...
def load_interfaces(self, interfaces_dict): """ Populates the namespace under the instance """ if interfaces_dict.get('apilist', {}).get('interfaces', None) is None: raise ValueError("Invalid response for GetSupportedAPIList") interfaces = interfaces_dict['apilist'][...
Populates the namespace under the instance
def to_dict(self, index=0): """ Dict format for use in Javascript / Jason Chuang's display technology. """ index += 1 rep = {} rep["index"] = index rep["leaf"] = len(self.children) == 0 rep["depth"] = self.udepth rep["scoreDistr"] = [0.0] * len(Lab...
Dict format for use in Javascript / Jason Chuang's display technology.
def featureCounts_chart (self): """ Make the featureCounts assignment rates plot """ # Config for the plot config = { 'id': 'featureCounts_assignment_plot', 'title': 'featureCounts: Assignments', 'ylab': '# Reads', 'cpswitch_counts_label': 'Number...
Make the featureCounts assignment rates plot
def _run_server(self, multiprocessing): """Use server multiprocessing to extract PCAP files.""" if not self._flag_m: raise UnsupportedCall(f"Extractor(engine={self._exeng})' has no attribute '_run_server'") if not self._flag_q: self._flag_q = True warnings.wa...
Use server multiprocessing to extract PCAP files.
def pop(h): """Pop the heap value from the heap.""" n = h.size() - 1 h.swap(0, n) down(h, 0, n) return h.pop()
Pop the heap value from the heap.
def on_tab_close_clicked(self, event, state_m): """Triggered when the states-editor close button is clicked Closes the tab. :param state_m: The desired state model (the selected state) """ [page, state_identifier] = self.find_page_of_state_m(state_m) if page: ...
Triggered when the states-editor close button is clicked Closes the tab. :param state_m: The desired state model (the selected state)
def lfprob (dfnum, dfden, F): """ Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn """ p = betai(0.5*dfden,...
Returns the (1-tailed) significance level (p-value) of an F statistic given the degrees of freedom for the numerator (dfR-dfF) and the degrees of freedom for the denominator (dfF). Usage: lfprob(dfnum, dfden, F) where usually dfnum=dfbn, dfden=dfwn
def apply(self, key, value, prompt=None, on_load=lambda a: a, on_save=lambda a: a): """Applies a setting value to a key, if the value is not `None`. Returns without prompting if either of the following: * `value` is not `None` * already present in the dictionary ...
Applies a setting value to a key, if the value is not `None`. Returns without prompting if either of the following: * `value` is not `None` * already present in the dictionary Args: prompt: May either be a string to prompt via `raw_input` or a ...
def execute(self, progress_fn, print_verbose_info=None): """ Start the progress bar, and return only when the progress reaches 100%. :param progress_fn: the executor function (or a generator). This function should take no arguments and return either a single number -- the current pr...
Start the progress bar, and return only when the progress reaches 100%. :param progress_fn: the executor function (or a generator). This function should take no arguments and return either a single number -- the current progress level, or a tuple (progress level, delay), where delay is ...
def _get_default_iface_linux(): # type: () -> Optional[str] """Get the default interface by reading /proc/net/route. This is the same source as the `route` command, however it's much faster to read this file than to call `route`. If it fails for whatever reason, we can fall back on the system comma...
Get the default interface by reading /proc/net/route. This is the same source as the `route` command, however it's much faster to read this file than to call `route`. If it fails for whatever reason, we can fall back on the system commands (e.g for a platform that has a route command, but maybe doesn't...
def js_distance(p, q): """Compute the Jensen-Shannon distance between two discrete distributions. NOTE: JS divergence is not a metric but the sqrt of JS divergence is a metric and is called the JS distance. Parameters ---------- p : np.array probability mass array (sums to 1) q : n...
Compute the Jensen-Shannon distance between two discrete distributions. NOTE: JS divergence is not a metric but the sqrt of JS divergence is a metric and is called the JS distance. Parameters ---------- p : np.array probability mass array (sums to 1) q : np.array probability ma...
def play(self, **kwargs): """Trigger a job explicitly. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobPlayError: If the job could not be triggered """ ...
Trigger a job explicitly. Args: **kwargs: Extra options to send to the server (e.g. sudo) Raises: GitlabAuthenticationError: If authentication is not correct GitlabJobPlayError: If the job could not be triggered
def clear_cached_data(self): """Clear any internally cached BLE device data. Necessary in some cases to prevent issues with stale device data getting cached by the OS. """ # Go through and remove any device that isn't currently connected. for device in self.list_devices(): ...
Clear any internally cached BLE device data. Necessary in some cases to prevent issues with stale device data getting cached by the OS.
def get_theming_attribute(self, mode, name, part=None): """ looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec """ colours = ...
looks up theming attribute :param mode: ui-mode (e.g. `search`,`thread`...) :type mode: str :param name: identifier of the atttribute :type name: str :rtype: urwid.AttrSpec
def getLogger(name): """Return a logger from a given name. If the name does not have a log handler, this will create one for it based on the module name which will log everything to a log file in a location the executing user will have access to. :param name: ``str`` :return: ``object`` ""...
Return a logger from a given name. If the name does not have a log handler, this will create one for it based on the module name which will log everything to a log file in a location the executing user will have access to. :param name: ``str`` :return: ``object``
def build_network_settings(**settings): ''' Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings> ''' changes = [] # Read current configuration and store default values current_network_settings = _parse_current_networ...
Build the global network script. CLI Example: .. code-block:: bash salt '*' ip.build_network_settings <settings>
def get_library_citation(): '''Return a descriptive string and reference data for what users of the library should cite''' all_ref_data = api.get_reference_data() lib_refs_data = {k: all_ref_data[k] for k in _lib_refs} return (_lib_refs_desc, lib_refs_data)
Return a descriptive string and reference data for what users of the library should cite
def parse_field(self, field_data, index=0): """Parse field and add missing options""" field = { '__index__': index, } if isinstance(field_data, str): field.update(self.parse_string_field(field_data)) elif isinstance(field_data, dict): field.up...
Parse field and add missing options
def grant_permissions(self, proxy_model): """ Create the default permissions for the just added proxy model """ ContentType = apps.get_model('contenttypes', 'ContentType') try: Permission = apps.get_model('auth', 'Permission') except LookupError: r...
Create the default permissions for the just added proxy model
def default_image_loader(filename, flags, **kwargs): """ This default image loader just returns filename, rect, and any flags """ def load(rect=None, flags=None): return filename, rect, flags return load
This default image loader just returns filename, rect, and any flags
def script(self, sql_script, split_algo='sql_split', prep_statements=True, dump_fails=True): """Wrapper method providing access to the SQLScript class's methods and properties.""" return Execute(sql_script, split_algo, prep_statements, dump_fails, self)
Wrapper method providing access to the SQLScript class's methods and properties.
def run_radia(job, bams, univ_options, radia_options, chrom): """ This module will run radia on the RNA and DNA bams ARGUMENTS 1. bams: Dict of bams and their indexes bams |- 'tumor_rna': <JSid> |- 'tumor_rnai': <JSid> |- 'tumor_dna': <JSid> |- 'tumor_dnai': ...
This module will run radia on the RNA and DNA bams ARGUMENTS 1. bams: Dict of bams and their indexes bams |- 'tumor_rna': <JSid> |- 'tumor_rnai': <JSid> |- 'tumor_dna': <JSid> |- 'tumor_dnai': <JSid> |- 'normal_dna': <JSid> +- 'normal_dnai': <JSid> ...
def coverage_region_detailed_stats(target_name, bed_file, data, out_dir): """ Calculate coverage at different completeness cutoff for region in coverage option. """ if bed_file and utils.file_exists(bed_file): ready_depth = tz.get_in(["depth", target_name], data) if ready_depth: ...
Calculate coverage at different completeness cutoff for region in coverage option.
def create_dset_to3d(prefix,file_list,file_order='zt',num_slices=None,num_reps=None,TR=None,slice_order='alt+z',only_dicoms=True,sort_filenames=False): '''manually create dataset by specifying everything (not recommended, but necessary when autocreation fails) If `num_slices` or `num_reps` is omitted, it will ...
manually create dataset by specifying everything (not recommended, but necessary when autocreation fails) If `num_slices` or `num_reps` is omitted, it will be inferred by the number of images. If both are omitted, it assumes that this it not a time-dependent dataset :only_dicoms: filter the given li...
def configure_sessionmaker(graph): """ Create the SQLAlchemy session class. """ engine_routing_strategy = getattr(graph, graph.config.sessionmaker.engine_routing_strategy) if engine_routing_strategy.supports_multiple_binds: ScopedFactory.infect(graph, "postgres") class RoutingSession(...
Create the SQLAlchemy session class.
def generate_variants(unresolved_spec): """Generates variants from a spec (dict) with unresolved values. There are two types of unresolved values: Grid search: These define a grid search over values. For example, the following grid search values in a spec will produce six distinct vari...
Generates variants from a spec (dict) with unresolved values. There are two types of unresolved values: Grid search: These define a grid search over values. For example, the following grid search values in a spec will produce six distinct variants in combination: "activation":...
def _create_opt_rule(self, rulename): """ Given a rule name, creates an optional ply.yacc rule for it. The name of the optional rule is <rulename>_opt """ optname = rulename + '_opt' def optrule(self, p): p[0] = p[1] optrule.__doc__ = '%s : e...
Given a rule name, creates an optional ply.yacc rule for it. The name of the optional rule is <rulename>_opt
def view_set(method_name): """ Creates a setter that will call the view method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the view. @type method_name: str """ def view_set(value, context, **_params): ...
Creates a setter that will call the view method with the context's key as first parameter and the value as second parameter. @param method_name: the name of a method belonging to the view. @type method_name: str