code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def check_exclamations_ppm(text): """Make sure that the exclamation ppm is under 30.""" err = "leonard.exclamation.30ppm" msg = u"More than 30 ppm of exclamations. Keep them under control." regex = r"\w!" count = len(re.findall(regex, text)) num_words = len(text.split(" ")) ppm = (count*1...
Make sure that the exclamation ppm is under 30.
def sign_more(self, bucket, cos_path, expired): """多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表) :param bucket: bucket名称 :param cos_path: 要操作的cos路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串 """ return self.app_sign(bucket, ...
多次签名(针对上传文件,创建目录, 获取文件目录属性, 拉取目录列表) :param bucket: bucket名称 :param cos_path: 要操作的cos路径, 以'/'开始 :param expired: 签名过期时间, UNIX时间戳, 如想让签名在30秒后过期, 即可将expired设成当前时间加上30秒 :return: 签名字符串
def recommend(self, client_data, limit, extra_data={}): """ Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight. """ preinsta...
Hybrid recommendations simply select half recommendations from the ensemble recommender, and half from the curated one. Duplicate recommendations are accomodated by rank ordering by weight.
def populate(self, priority, address, rtr, data): """ :return: None """ assert isinstance(data, bytes) self.needs_high_priority(priority) self.needs_no_rtr(rtr) self.needs_data(data, 4) self.set_attributes(priority, address, rtr) # 00000011 = chann...
:return: None
def _add_video_timing(self, pic): """Add a `p:video` element under `p:sld/p:timing`. The element will refer to the specified *pic* element by its shape id, and cause the video play controls to appear for that video. """ sld = self._spTree.xpath('/p:sld')[0] childTnLst = ...
Add a `p:video` element under `p:sld/p:timing`. The element will refer to the specified *pic* element by its shape id, and cause the video play controls to appear for that video.
def new_evaluation_result(self, has_improved: bool) -> bool: """ Returns true if the parameters should be reset to the ones with the best validation score. :param has_improved: Whether the model improved on held-out validation data. :return: True if parameters should be reset to the one...
Returns true if the parameters should be reset to the ones with the best validation score. :param has_improved: Whether the model improved on held-out validation data. :return: True if parameters should be reset to the ones with best validation score.
def getFlaskResponse(responseString, httpStatus=200): """ Returns a Flask response object for the specified data and HTTP status. """ return flask.Response(responseString, status=httpStatus, mimetype=MIMETYPE)
Returns a Flask response object for the specified data and HTTP status.
def which(program, ignore_own_venv=False): """ :param str|None program: Program name to find via env var PATH :param bool ignore_own_venv: If True, do not resolve to executables in current venv :return str|None: Full path to program, if one exists and is executable """ if not program: re...
:param str|None program: Program name to find via env var PATH :param bool ignore_own_venv: If True, do not resolve to executables in current venv :return str|None: Full path to program, if one exists and is executable
def trim(self, lower=None, upper=None): """Trim upper values in accordance with :math:`EQI2 \\leq EQI1 \\leq EQB`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb.value = 3.0 >>> eqi2.value = 1.0 >>> eqi1(0.0) >>> eqi1 eqi1(1....
Trim upper values in accordance with :math:`EQI2 \\leq EQI1 \\leq EQB`. >>> from hydpy.models.lland import * >>> parameterstep('1d') >>> eqb.value = 3.0 >>> eqi2.value = 1.0 >>> eqi1(0.0) >>> eqi1 eqi1(1.0) >>> eqi1(1.0) >>> eqi1 e...
def _build_biomart_gene_query(self, taxid, cols_to_fetch): """ Building url to fetch equivalent identifiers via Biomart Restful API. Documentation at http://uswest.ensembl.org/info/data/biomart/biomart_restful.html :param taxid: :param array of ensembl biomart attributes ...
Building url to fetch equivalent identifiers via Biomart Restful API. Documentation at http://uswest.ensembl.org/info/data/biomart/biomart_restful.html :param taxid: :param array of ensembl biomart attributes to include :return:
def parse_command_line_parameters(): """ Parses command line arguments """ usage = 'usage: %prog [options] fasta_filepath' version = 'Version: %prog 0.1' parser = OptionParser(usage=usage, version=version) # A binary 'verbose' flag parser.add_option('-p', '--is_protein', action='store_true', ...
Parses command line arguments
def fit_left_censoring( self, durations, event_observed=None, timeline=None, label=None, alpha=None, ci_labels=None, show_progress=False, entry=None, weights=None, ): # pylint: disable=too-many-arguments """ Fit the mod...
Fit the model to a left-censored dataset Parameters ---------- durations: an array, or pd.Series length n, duration subject was observed for event_observed: numpy array or pd.Series, optional length n, True if the the death was observed, False if the event was lost (...
def _absorb_z_into_w(moment_index: int, op: ops.Operation, state: _OptimizerState) -> None: """Absorbs a Z^t gate into a W(a) flip. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(a)───Z^t─── ≡ ───W(a)────...
Absorbs a Z^t gate into a W(a) flip. [Where W(a) is shorthand for PhasedX(phase_exponent=a).] Uses the following identity: ───W(a)───Z^t─── ≡ ───W(a)───────────Z^t/2──────────Z^t/2─── (split Z) ≡ ───W(a)───W(a)───Z^-t/2───W(a)───Z^t/2─── (flip Z) ≡ ───W(a)───W(a)──────────W(a+t...
def make_subscriber(self, my_args=None): """ not implemented :return: """ LOGGER.debug("zeromq.Driver.make_subscriber") if my_args is None: raise exceptions.ArianeConfError('subscriber arguments') if not self.configuration_OK or self.connection_args is...
not implemented :return:
def apply_filter(self, strings): """ Apply the text filter filter to the given list of strings. :param list strings: the list of input strings """ result = strings for filt in self.filters: result = filt.apply_filter(result) self.log([u"Applying regex...
Apply the text filter filter to the given list of strings. :param list strings: the list of input strings
def _get_login_manager(self, app: FlaskUnchained, anonymous_user: AnonymousUser, ) -> LoginManager: """ Get an initialized instance of Flask Login's :class:`~flask_login.LoginManager`. """ login_mana...
Get an initialized instance of Flask Login's :class:`~flask_login.LoginManager`.
def set_end_date(self, date): """Sets the end date. arg: date (osid.calendaring.DateTime): the new date raise: InvalidArgument - ``date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``date`` is ``null`` *compliance: mand...
Sets the end date. arg: date (osid.calendaring.DateTime): the new date raise: InvalidArgument - ``date`` is invalid raise: NoAccess - ``Metadata.isReadOnly()`` is ``true`` raise: NullArgument - ``date`` is ``null`` *compliance: mandatory -- This method must be implemented....
def example_exc_handler(tries_remaining, exception, delay): """Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised. """ print >> stderr, "Caught '{0}', {1} tries remaining, \ sleeping for {2} ...
Example exception handler; prints a warning to stderr. tries_remaining: The number of tries remaining. exception: The exception instance which was raised.
def build_notification_message(template_context, template_configuration=None): """ Create HTML and plaintext message bodies for a notification. We receive a context with data we can use to render, as well as an optional site template configration - if we don't get a template configuration, we'll use th...
Create HTML and plaintext message bodies for a notification. We receive a context with data we can use to render, as well as an optional site template configration - if we don't get a template configuration, we'll use the standard, built-in template. Arguments: template_context (dict): A set o...
def scan_file(self, filename, apikey): """ Sends a file to virus total for assessment """ url = self.base_url + "file/scan" params = {'apikey': apikey} scanfile = {"file": open(filename, 'rb')} response = requests.post(url, files=scanfile, params=params) r...
Sends a file to virus total for assessment
def check_docstring(cls): """ Asserts that the class has a docstring, returning it if successful. """ docstring = inspect.getdoc(cls) if not docstring: breadcrumbs = " -> ".join(t.__name__ for t in inspect.getmro(cls)[:-1][::-1]) msg = "docstring required ...
Asserts that the class has a docstring, returning it if successful.
def schunk(string, size): """Splits string into n sized chunks.""" return [string[i:i+size] for i in range(0, len(string), size)]
Splits string into n sized chunks.
def __get_favorites(self, favorite_type, start=0, max_items=100): """ Helper method for `get_favorite_radio_*` methods. Args: favorite_type (str): Specify either `RADIO_STATIONS` or `RADIO_SHOWS`. start (int): Which number to start the retrieval from. Used for ...
Helper method for `get_favorite_radio_*` methods. Args: favorite_type (str): Specify either `RADIO_STATIONS` or `RADIO_SHOWS`. start (int): Which number to start the retrieval from. Used for paging. max_items (int): The total number of results...
def get_fetch_headers(self, method, headers): """merge class headers with passed in headers :param method: string, (eg, GET or POST), this is passed in so you can customize headers based on the method that you are calling :param headers: dict, all the headers passed into the fetch m...
merge class headers with passed in headers :param method: string, (eg, GET or POST), this is passed in so you can customize headers based on the method that you are calling :param headers: dict, all the headers passed into the fetch method :returns: passed in headers merged with glo...
def reinterpretBits(self, sigOrVal, toType): """ Cast object of same bit size between to other type (f.e. bits to struct, union or array) """ if isinstance(sigOrVal, Value): return reinterpretBits__val(self, sigOrVal, toType) elif isinstance(toType, Bits): return fitTo_t(sigOrVal...
Cast object of same bit size between to other type (f.e. bits to struct, union or array)
def coord_pyramids(coords, zoom_start, zoom_stop): """ generate full pyramid for coords Generate the full pyramid for the list of coords. Note that zoom_stop is exclusive. """ for coord in coords: for child in coord_pyramid(coord, zoom_start, zoom_stop): yield child
generate full pyramid for coords Generate the full pyramid for the list of coords. Note that zoom_stop is exclusive.
def _filter_properties(obj, property_list): """ Remove properties from an instance or class that aren't in the plist parameter obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance): The class or instance from which properties are to be filtered property_list...
Remove properties from an instance or class that aren't in the plist parameter obj(:class:`~pywbem.CIMClass` or :class:`~pywbem.CIMInstance): The class or instance from which properties are to be filtered property_list(list of :term:`string`): List of properties which a...
def simulated_annealing(objective_function, initial_array, initial_temperature=10 ** 4, cooldown_rate=0.7, acceptance_criteria=None, lower_bound=-float('inf'), max_iterations=1...
Implement a simulated annealing algorithm with exponential cooling Has two stopping conditions: 1. Maximum number of iterations; 2. A known lower bound, a none is passed then this is not used. Note that starting with an initial_temperature corresponds to a hill climbing algorithm
def configure(self, options, conf): """Turn style-forcing on if bar-forcing is on. It'd be messy to position the bar but still have the rest of the terminal capabilities emit ''. """ super(ProgressivePlugin, self).configure(options, conf) if (getattr(options, 'verbosity...
Turn style-forcing on if bar-forcing is on. It'd be messy to position the bar but still have the rest of the terminal capabilities emit ''.
async def set_mode(self, mode, timeout=OTGW_DEFAULT_TIMEOUT): """ Set the operating mode to either "Gateway" mode (:mode: = OTGW_MODE_GATEWAY or 1) or "Monitor" mode (:mode: = OTGW_MODE_MONITOR or 0), or use this method to reset the device (:mode: = OTGW_MODE_RESET). Retu...
Set the operating mode to either "Gateway" mode (:mode: = OTGW_MODE_GATEWAY or 1) or "Monitor" mode (:mode: = OTGW_MODE_MONITOR or 0), or use this method to reset the device (:mode: = OTGW_MODE_RESET). Return the newly activated mode, or the full renewed status dict after a reset...
def could_scope_out(self): """ could bubble up from current scope :return: """ return not self.waiting_for or \ isinstance(self.waiting_for, callable.EndOfStory) or \ self.is_breaking_a_loop()
could bubble up from current scope :return:
def toDict(self): """To Dict Returns the Parent as a dictionary in the same format as is used in constructing it Returns: dict """ # Get the parents dict as the starting point of our return dRet = super(Parent,self).toDict() # Go through each field and add it to the return for k,v in iteritems(...
To Dict Returns the Parent as a dictionary in the same format as is used in constructing it Returns: dict
def remove_unit_rules(grammar, inplace=False): # type: (Grammar, bool) -> Grammar """ Remove unit rules from the grammar. :param grammar: Grammar where remove the rules. :param inplace: True if transformation should be performed in place. False by default. :return: Grammar without unit rules. ...
Remove unit rules from the grammar. :param grammar: Grammar where remove the rules. :param inplace: True if transformation should be performed in place. False by default. :return: Grammar without unit rules.
def semantic_similarity(go_id1, go_id2, godag, branch_dist=None): ''' Finds the semantic similarity (inverse of the semantic distance) between two GO terms. ''' dist = semantic_distance(go_id1, go_id2, godag, branch_dist) if dist is not None: return 1.0 / float(dist)
Finds the semantic similarity (inverse of the semantic distance) between two GO terms.
def model_performance(self, test_data=None, train=False, valid=False, xval=False): """ Generate model metrics for this model on test_data. :param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train, valid and xval arguments are ignored ...
Generate model metrics for this model on test_data. :param H2OFrame test_data: Data set for which model metrics shall be computed against. All three of train, valid and xval arguments are ignored if test_data is not None. :param bool train: Report the training metrics for the model. ...
def _smixins(self, name): """Inner wrapper to search for mixins by name. """ return (self._mixins[name] if name in self._mixins else False)
Inner wrapper to search for mixins by name.
def get_hostfirmware(self,callb=None): """Convenience method to request the device firmware info from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device a...
Convenience method to request the device firmware info from the device This method will check whether the value has already been retrieved from the device, if so, it will simply return it. If no, it will request the information from the device and request that callb be executed when a response ...
def add_host(kwargs=None, call=None): ''' Add a host system to the specified cluster or datacenter in this VMware environment .. note:: To use this function, you need to specify ``esxi_host_user`` and ``esxi_host_password`` under your provider configuration set up at ``/etc/salt/cl...
Add a host system to the specified cluster or datacenter in this VMware environment .. note:: To use this function, you need to specify ``esxi_host_user`` and ``esxi_host_password`` under your provider configuration set up at ``/etc/salt/cloud.providers`` or ``/etc/salt/cloud.providers.d/v...
def plotOptMod(verNObg3gray, VERgray): """ called from either readTranscar.py or hist-feasibility/plotsnew.py """ if VERgray is None and verNObg3gray is None: return fg = figure() ax2 = fg.gca() # summed (as camera would see) if VERgray is not None: z = VERgray.alt_km Ek =...
called from either readTranscar.py or hist-feasibility/plotsnew.py
def remover(self, id_interface): """Remove an interface by its identifier. :param id_interface: Interface identifier. :return: None :raise InterfaceNaoExisteError: Interface doesn't exist. :raise InterfaceError: Interface is linked to another interface. :raise InvalidP...
Remove an interface by its identifier. :param id_interface: Interface identifier. :return: None :raise InterfaceNaoExisteError: Interface doesn't exist. :raise InterfaceError: Interface is linked to another interface. :raise InvalidParameterError: The interface identifier is i...
def parse(self, text): """Call the server and return the raw results.""" if isinstance(text, bytes): text = text.decode("ascii") text = re.sub("\s+", " ", unidecode(text)) return self.communicate(text + "\n")
Call the server and return the raw results.
def _scale(x, min_x_value, max_x_value, output_min, output_max): """Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. R...
Scale a column to [output_min, output_max]. Assumes the columns's range is [min_x_value, max_x_value]. If this is not true at training or prediction time, the output value of this scale could be outside the range [output_min, output_max]. Raises: ValueError: if min_x_value = max_x_value, as the column is ...
def get_scripts(): """Get custom npm scripts.""" proc = Popen(['npm', 'run-script'], stdout=PIPE) should_yeild = False for line in proc.stdout.readlines(): line = line.decode() if 'available via `npm run-script`:' in line: should_yeild = True continue if ...
Get custom npm scripts.
def DeserializeUnsignedWithoutType(self, reader): """ Deserialize object without reading transaction type data. Args: reader (neo.IO.BinaryReader): """ self.Version = reader.ReadByte() self.DeserializeExclusiveData(reader) self.Attributes = reader.Rea...
Deserialize object without reading transaction type data. Args: reader (neo.IO.BinaryReader):
def _tp_finder(self, dcycle): # Private routine """ Routine to find thermal pulses in given star and returns an index vector that gives the cycle number in which the thermal pulse occure. The routine looks for the C/O ratio jumping up and up, so only useful in TP-AGB s...
Routine to find thermal pulses in given star and returns an index vector that gives the cycle number in which the thermal pulse occure. The routine looks for the C/O ratio jumping up and up, so only useful in TP-AGB star. A vector is given back that indicates the position of th...
def getBlock(self, block_identifier, full_transactions=False): """ `eth_getBlockByHash` `eth_getBlockByNumber` """ method = select_method_for_block_identifier( block_identifier, if_predefined='eth_getBlockByNumber', if_hash='eth_getBlockByHash'...
`eth_getBlockByHash` `eth_getBlockByNumber`
def get_summary(self): """ Return the function summary Returns: (str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries) """ func_summaries = [f.get_summary() for f in self.functions] modif_summaries = [f.get_summary() for ...
Return the function summary Returns: (str, list, list, list, list): (name, inheritance, variables, fuction summaries, modifier summaries)
async def reset_webhook(self, check=True) -> bool: """ Reset webhook :param check: check before deleting :return: """ if check: wh = await self.bot.get_webhook_info() if not wh.url: return False return await self.bot.delet...
Reset webhook :param check: check before deleting :return:
def MobileDeviceProvisioningProfile(self, data=None, subset=None): """{dynamic_docstring}""" return self.factory.get_object( jssobjects.MobileDeviceProvisioningProfile, data, subset)
{dynamic_docstring}
def convert_uuid(self, in_uuid: str = str, mode: bool = 0): """Convert a metadata UUID to its URI equivalent. And conversely. :param str in_uuid: UUID or URI to convert :param int mode: conversion direction. Options: * 0 to HEX * 1 to URN (RFC4122) * 2 to URN (Iso...
Convert a metadata UUID to its URI equivalent. And conversely. :param str in_uuid: UUID or URI to convert :param int mode: conversion direction. Options: * 0 to HEX * 1 to URN (RFC4122) * 2 to URN (Isogeo specific style)
def url_defaults(self, fn): """ Callback function for URL defaults for this bundle. It's called with the endpoint and values and should update the values passed in place. """ self._defer(lambda bp: bp.url_defaults(fn)) return fn
Callback function for URL defaults for this bundle. It's called with the endpoint and values and should update the values passed in place.
def readB1header(filename): """Read beamline B1 (HASYLAB, Hamburg) header data Input ----- filename: string the file name. If ends with ``.gz``, it is fed through a ``gunzip`` filter Output ------ A header dictionary. Examples -------- read header data from 'OR...
Read beamline B1 (HASYLAB, Hamburg) header data Input ----- filename: string the file name. If ends with ``.gz``, it is fed through a ``gunzip`` filter Output ------ A header dictionary. Examples -------- read header data from 'ORG000123.DAT':: header=read...
def extract_entry(self, e, decompress='auto'): """Yield blocks of data for this entry from this MAR file. Args: e (:obj:`mardor.format.index_entry`): An index_entry object that refers to this file's size and offset inside the MAR file. path (str): Where on disk t...
Yield blocks of data for this entry from this MAR file. Args: e (:obj:`mardor.format.index_entry`): An index_entry object that refers to this file's size and offset inside the MAR file. path (str): Where on disk to extract this file to. decompress (str, optio...
def category(self, category_id, country=None, locale=None): """Get a single category used to tag items in Spotify. Parameters ---------- category_id : str The Spotify category ID for the category. country : COUNTRY_TP COUNTRY locale : LOCALE_TP ...
Get a single category used to tag items in Spotify. Parameters ---------- category_id : str The Spotify category ID for the category. country : COUNTRY_TP COUNTRY locale : LOCALE_TP LOCALE
def read_config(self): """ reads config """ # multi-options self.ssl = self.get_option("ssl") self.tank_type = self.get_option("tank_type") # TODO: refactor. Maybe we should decide how to interact with # StepperWrapper here. # self.instances = self.get_option('ins...
reads config
def arrow_get(string): '''this function exists because ICS uses ISO 8601 without dashes or colons, i.e. not ISO 8601 at all.''' # replace slashes with dashes if '/' in string: string = string.replace('/', '-') # if string contains dashes, assume it to be proper ISO 8601 if '-' in strin...
this function exists because ICS uses ISO 8601 without dashes or colons, i.e. not ISO 8601 at all.
def _process_diseasegene(self, limit): """ :param limit: :return: """ if self.test_mode: graph = self.testgraph else: graph = self.graph line_counter = 0 model = Model(graph) myfile = '/'.join((self.rawdir, self.files['dis...
:param limit: :return:
def filter(self, data, collection, **kwargs): """Filter given collection.""" if not data or self.filters is None: return None, collection filters = {} for f in self.filters: if f.name not in data: continue ops, collection = f.filter(co...
Filter given collection.
def is_valid_python(tkn: str) -> bool: """Determine whether tkn is a valid python identifier :param tkn: :return: """ try: root = ast.parse(tkn) except SyntaxError: return False return len(root.body) == 1 and isinstance(root.body[0], ast.Expr) and isinstance(root.body[0].val...
Determine whether tkn is a valid python identifier :param tkn: :return:
def _convert_connected_app(self): """Convert Connected App to service""" if self.services and "connected_app" in self.services: # already a service return connected_app = self.get_connected_app() if not connected_app: # not configured retur...
Convert Connected App to service
def _handle_upsert(self, parts, unwritten_lobs=()): """Handle reply messages from INSERT or UPDATE statements""" self.description = None self._received_last_resultset_part = True # set to 'True' so that cursor.fetch*() returns just empty list for part in parts: if part.kind...
Handle reply messages from INSERT or UPDATE statements
def get_form(self, **kwargs): """Returns the form for registering or inviting a user""" if not hasattr(self, "form_class"): raise AttributeError(_("You must define a form_class")) return self.form_class(**kwargs)
Returns the form for registering or inviting a user
def _selection_by_callable(self, view, num_slices, non_empty_slices): """Returns all the slices selected by the given callable.""" selected = [sl for sl in non_empty_slices if self._sampler(self._get_axis(self._image, view, sl))] return selected[:num_slices]
Returns all the slices selected by the given callable.
def transform(self, X): """ if already fit, can add new points and see where they fall""" iclustup = [] dims = self.n_components if hasattr(self, 'isort1'): if X.shape[1] == self.v.shape[0]: # reduce dimensionality of X X = X @ self.v ...
if already fit, can add new points and see where they fall
def resize(self, dims): """Resize our drawing area to encompass a space defined by the given dimensions. """ width, height = dims[:2] self.dims = (width, height) self.logger.debug("renderer reconfigured to %dx%d" % ( width, height)) # create cv surfac...
Resize our drawing area to encompass a space defined by the given dimensions.
def database_caller_creator(self, host, port, name=None): '''creates a redis connection object which will be later used to modify the db ''' name = name or 0 client = redis.StrictRedis(host=host, port=port, db=name) pipe = client.pipeline(transaction=False) retur...
creates a redis connection object which will be later used to modify the db
def get_mac_address_table(self): """ Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (...
Returns a lists of dictionaries. Each dictionary represents an entry in the MAC Address Table, having the following keys * mac (string) * interface (string) * vlan (int) * active (boolean) * static (boolean) * moves (int) * last...
def image_member(self): """ Returns a json-schema document that represents an image member entity. (a container of member entities). """ uri = "/%s/member" % self.uri_base resp, resp_body = self.api.method_get(uri) return resp_body
Returns a json-schema document that represents an image member entity. (a container of member entities).
def _get_route_args(self, namespace, route, tag=False): # pylint: disable=unused-argument """Returns a list of name / value string pairs representing the arguments for a particular route.""" data_type, _ = unwrap_nullable(route.arg_data_type) if is_struct_type(data_type): ar...
Returns a list of name / value string pairs representing the arguments for a particular route.
def _parse_action(action): """ Parses a single action item, for instance one of the following: m; m(); m(True); m(*) The brackets must match. """ i_open = action.find('(') if i_open is -1: # return action name, finished return {'name': action, 'args': [], 'event_args': ...
Parses a single action item, for instance one of the following: m; m(); m(True); m(*) The brackets must match.
def findattr(self, name, resolved=True): """ Find an attribute type definition. @param name: An attribute name. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: ...
Find an attribute type definition. @param name: An attribute name. @type name: basestring @param resolved: A flag indicating that the fully resolved type should be returned. @type resolved: boolean @return: The found schema I{type} @rtype: L{xsd.sxbase.SchemaO...
def _preprocess_Y(self, Y, k): """Convert Y to prob labels if necessary""" Y = Y.clone() # If preds, convert to probs if Y.dim() == 1 or Y.shape[1] == 1: Y = pred_to_prob(Y.long(), k=k) return Y
Convert Y to prob labels if necessary
def get_totals_by_payee(self, account, start_date=None, end_date=None): """ Returns transaction totals grouped by Payee. """ qs = Transaction.objects.filter(account=account, parent__isnull=True) qs = qs.values('payee').annotate(models.Sum('value_gross')) qs = qs.order_by...
Returns transaction totals grouped by Payee.
def get_response_object(self, service_id, version_number, name): """Gets the specified Response Object.""" content = self._fetch("/service/%s/version/%d/response_object/%s" % (service_id, version_number, name)) return FastlyResponseObject(self, content)
Gets the specified Response Object.
def tv_to_rdf(infile_name, outfile_name): """ Convert a SPDX file from tag/value format to RDF format. Return True on sucess, False otherwise. """ parser = Parser(Builder(), StandardLogger()) parser.build() with open(infile_name) as infile: data = infile.read() document, erro...
Convert a SPDX file from tag/value format to RDF format. Return True on sucess, False otherwise.
def from_mongo(cls, doc): """Convert data coming in from the MongoDB wire driver into a Document instance.""" if doc is None: # To support simplified iterative use, None should return None. return None if isinstance(doc, Document): # No need to perform processing on existing Document instances. retu...
Convert data coming in from the MongoDB wire driver into a Document instance.
def reload_configuration(self, event): """Event triggered configuration reload""" if event.target == self.uniquename: self.log('Reloading configuration') self._read_config()
Event triggered configuration reload
def setValue(self, newText): """Sets a text value (string) into the text field.""" newText = str(newText) # attempt to convert to string (might be int or float ...) if self.text == newText: return # nothing to change self.text = newText # save the new text ...
Sets a text value (string) into the text field.
def select(self, key=None, val=None, touch=None, log='any', out=int): """ Return the indices of the rays matching selection criteria The criterion can be of two types: - a key found in self.dchans, with a matching value - a touch tuple (indicating which element in self.config is...
Return the indices of the rays matching selection criteria The criterion can be of two types: - a key found in self.dchans, with a matching value - a touch tuple (indicating which element in self.config is touched by the desired rays) Parameters --------...
def read_detections(fname): """ Read detections from a file to a list of Detection objects. :type fname: str :param fname: File to read from, must be a file written to by \ Detection.write. :returns: list of :class:`eqcorrscan.core.match_filter.Detection` :rtype: list .. note:: ...
Read detections from a file to a list of Detection objects. :type fname: str :param fname: File to read from, must be a file written to by \ Detection.write. :returns: list of :class:`eqcorrscan.core.match_filter.Detection` :rtype: list .. note:: :class:`eqcorrscan.core.match_filt...
def set_role(username, role): ''' Assign role to username .. code-block:: bash salt '*' onyx.cmd set_role username=daniel role=vdc-admin ''' try: sendline('config terminal') role_line = 'username {0} role {1}'.format(username, role) ret = sendline(role_line) ...
Assign role to username .. code-block:: bash salt '*' onyx.cmd set_role username=daniel role=vdc-admin
def _sanity_check_block_pairwise_constraints(ir_blocks): """Assert that adjacent blocks obey all invariants.""" for first_block, second_block in pairwise(ir_blocks): # Always Filter before MarkLocation, never after. if isinstance(first_block, MarkLocation) and isinstance(second_block, Filter): ...
Assert that adjacent blocks obey all invariants.
def _select_next_server(self): """ Looks up in the server pool for an available server and attempts to connect. """ while True: if len(self._server_pool) == 0: self._current_server = None raise ErrNoServers now = time.mono...
Looks up in the server pool for an available server and attempts to connect.
def getLVstats(self, *args): """Returns I/O stats for LV. @param args: Two calling conventions are implemented: - Passing two parameters vg and lv. - Passing only one parameter in 'vg-lv' format. @return: Dict of stats. ""...
Returns I/O stats for LV. @param args: Two calling conventions are implemented: - Passing two parameters vg and lv. - Passing only one parameter in 'vg-lv' format. @return: Dict of stats.
def add_to_env(self, content): """ add content to the env script. """ if not self.rewrite_config: raise DirectoryException("Error! Directory was not intialized w/ rewrite_config.") if not self.env_file: self.env_path, self.env_file = self.__get_env_handle(...
add content to the env script.
def CreateTask(self, session_identifier): """Creates a task. Args: session_identifier (str): the identifier of the session the task is part of. Returns: Task: task attribute container. """ task = tasks.Task(session_identifier) logger.debug('Created task: {0:s}.'.format(ta...
Creates a task. Args: session_identifier (str): the identifier of the session the task is part of. Returns: Task: task attribute container.
def coge(args): """ %prog coge cogefile Convert CoGe file to anchors file. """ p = OptionParser(coge.__doc__) opts, args = p.parse_args(args) if len(args) != 1: sys.exit(not p.print_help()) cogefile, = args fp = must_open(cogefile) cogefile = cogefile.replace(".gz", ""...
%prog coge cogefile Convert CoGe file to anchors file.
def on_step_end(self, **kwargs): "Put the LR back to its value if necessary." if not self.learn.gan_trainer.gen_mode: self.learn.opt.lr /= self.mult_lr
Put the LR back to its value if necessary.
def compute_xy( self, projection: Union[pyproj.Proj, crs.Projection, None] = None ): """Computes x and y columns from latitudes and longitudes. The source projection is WGS84 (EPSG 4326). The default destination projection is a Lambert Conformal Conical projection centered o...
Computes x and y columns from latitudes and longitudes. The source projection is WGS84 (EPSG 4326). The default destination projection is a Lambert Conformal Conical projection centered on the data inside the dataframe. For consistency reasons with pandas DataFrame, a new Traffic struc...
def generate_documentation(schema): """ Generates reStructuredText documentation from a Confirm file. :param schema: Dictionary representing the Confirm schema. :returns: String representing the reStructuredText documentation. """ documentation_title = "Configuration documentation" docume...
Generates reStructuredText documentation from a Confirm file. :param schema: Dictionary representing the Confirm schema. :returns: String representing the reStructuredText documentation.
def add_ospf_area(self, ospf_area, ospf_interface_setting=None, network=None, communication_mode='NOT_FORCED', unicast_ref=None): """ Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment...
Add OSPF Area to this routing node. Communication mode specifies how the interface will interact with the adjacent OSPF environment. Please see SMC API documentation for more in depth information on each option. If the interface has multiple networks nested below, all networks ...
def create_mosaic(tiles, nodata=0): """ Create a mosaic from tiles. Tiles must be connected (also possible over Antimeridian), otherwise strange things can happen! Parameters ---------- tiles : iterable an iterable containing tuples of a BufferedTile and an array nodata : integer or...
Create a mosaic from tiles. Tiles must be connected (also possible over Antimeridian), otherwise strange things can happen! Parameters ---------- tiles : iterable an iterable containing tuples of a BufferedTile and an array nodata : integer or float raster nodata value to initialize...
def get_loc_level(self, key, level=0, drop_level=True): """ Get both the location for the requested label(s) and the resulting sliced index. Parameters ---------- key : label or sequence of labels level : int/level name or list thereof, optional drop_leve...
Get both the location for the requested label(s) and the resulting sliced index. Parameters ---------- key : label or sequence of labels level : int/level name or list thereof, optional drop_level : bool, default True if ``False``, the resulting index will no...
def to_dict(self, omit=()): """ Return a (shallow) copy of self cast to a dictionary, optionally omitting some key/value pairs. """ result = dict(self) for key in omit: if key in result: del result[key] return result
Return a (shallow) copy of self cast to a dictionary, optionally omitting some key/value pairs.
def pickle_load(cls, filepath): """ Loads the object from a pickle file. Args: filepath: Filename or directory name. It filepath is a directory, we scan the directory tree starting from filepath and we read the first pickle database. Raise RuntimeErro...
Loads the object from a pickle file. Args: filepath: Filename or directory name. It filepath is a directory, we scan the directory tree starting from filepath and we read the first pickle database. Raise RuntimeError if multiple databases are found.
def get_stream(self, session_id, stream_id): """ Returns an Stream object that contains information of an OpenTok stream: -id: The stream ID -videoType: "camera" or "screen" -name: The stream name (if one was set when the client published the stream) -layoutClassList: It...
Returns an Stream object that contains information of an OpenTok stream: -id: The stream ID -videoType: "camera" or "screen" -name: The stream name (if one was set when the client published the stream) -layoutClassList: It's an array of the layout classes for the stream
def get_service_inspect(self, stack, service): """查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} ...
查看服务 查看指定名称服务的属性。 Args: - stack: 服务所属的服务组名称 - service: 服务名 Returns: 返回一个tuple对象,其格式为(<result>, <ResponseInfo>) - result 成功返回服务信息,失败返回{"error": "<errMsg string>"} - ResponseInfo 请求的Response信息
def should_we_load(kls): """ should we load this class as a check? """ # we don't load abstract classes if kls.__name__.endswith("AbstractCheck"): return False # and we only load checks if not kls.__name__.endswith("Check"): return False mro = kls.__mro__ # and the class need...
should we load this class as a check?
def _set_show_zoning_enabled_configuration(self, v, load=False): """ Setter method for show_zoning_enabled_configuration, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_zoning_enabl...
Setter method for show_zoning_enabled_configuration, mapped from YANG variable /brocade_zone_rpc/show_zoning_enabled_configuration (rpc) If this variable is read-only (config: false) in the source YANG file, then _set_show_zoning_enabled_configuration is considered as a private method. Backends looking to p...
def score(self, X, y=None, sample_weight=None): """ Apply transforms, and score with the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. y : iterable, default=No...
Apply transforms, and score with the final estimator Parameters ---------- X : iterable Data to predict on. Must fulfill input requirements of first step of the pipeline. y : iterable, default=None Targets used for scoring. Must fulfill label requirem...