code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def _process_counter_example(self, mma, w_string): """" Process a counterexample in the Rivest-Schapire way. Args: mma (DFA): The hypothesis automaton w_string (str): The examined string to be consumed Returns: None """ diff = len(w_str...
Process a counterexample in the Rivest-Schapire way. Args: mma (DFA): The hypothesis automaton w_string (str): The examined string to be consumed Returns: None
def _set_options_headers(self, methods): """ Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for request...
Set proper headers. Sets following headers: Allow Access-Control-Allow-Methods Access-Control-Allow-Headers Arguments: :methods: Sequence of HTTP method names that are value for requested URI
def observed_data_to_xarray(self): """Convert observed_data to xarray.""" data = self.observed_data if not isinstance(data, dict): raise TypeError("DictConverter.observed_data is not a dictionary") if self.dims is None: dims = {} else: dims = s...
Convert observed_data to xarray.
def locale(self) -> tornado.locale.Locale: """The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` ...
The locale for the current session. Determined by either `get_user_locale`, which you can override to set the locale based on, e.g., a user preference stored in a database, or `get_browser_locale`, which uses the ``Accept-Language`` header. .. versionchanged: 4.1 Add...
def _power_mismatch_dc(self, buses, generators, B, Pbusinj, base_mva): """ Returns the power mismatch constraint (B*Va + Pg = Pd). """ nb, ng = len(buses), len(generators) # Negative bus-generator incidence matrix. gen_bus = array([g.bus._i for g in generators]) neg_Cg = ...
Returns the power mismatch constraint (B*Va + Pg = Pd).
def parse_params(self, n_samples=None, dx_min=-0.1, dx_max=0.1, n_dxs=2, dy_min=-0.1, dy_max=0.1, n_dys=2, angle_min=-30, angle_max=30, ...
Take in a dictionary of parameters and applies attack-specific checks before saving them as attributes. :param n_samples: (optional) The number of transformations sampled to construct the attack. Set it to None to run full grid attack. :param dx_min: (optional flo...
def p_text(self, text): '''text : TEXT PARBREAK | TEXT | PARBREAK''' item = text[1] text[0] = item if item[0] != "\n" else u"" if len(text) > 2: text[0] += "\n"
text : TEXT PARBREAK | TEXT | PARBREAK
def participant_ids(self): """:class:`~hangups.user.UserID` of users involved (:class:`list`).""" return [user.UserID(chat_id=id_.chat_id, gaia_id=id_.gaia_id) for id_ in self._event.membership_change.participant_ids]
:class:`~hangups.user.UserID` of users involved (:class:`list`).
def get_log_entry_mdata(): """Return default mdata map for LogEntry""" return { 'priority': { 'element_label': { 'text': 'priority', 'languageTypeId': str(DEFAULT_LANGUAGE_TYPE), 'scriptTypeId': str(DEFAULT_SCRIPT_TYPE), 'format...
Return default mdata map for LogEntry
def center (self): """center() -> (x, y) Returns the center (of mass) point of this Polygon. See http://en.wikipedia.org/wiki/Polygon Examples: >>> p = Polygon() >>> p.vertices = [ Point(3, 8), Point(6, 4), Point(0, 3) ] >>> p.center() Point(2.89285714286, 4.82142857143) """ ...
center() -> (x, y) Returns the center (of mass) point of this Polygon. See http://en.wikipedia.org/wiki/Polygon Examples: >>> p = Polygon() >>> p.vertices = [ Point(3, 8), Point(6, 4), Point(0, 3) ] >>> p.center() Point(2.89285714286, 4.82142857143)
def _get_managed_files(self): ''' Build a in-memory data of all managed files. ''' if self.grains_core.os_data().get('os_family') == 'Debian': return self.__get_managed_files_dpkg() elif self.grains_core.os_data().get('os_family') in ['Suse', 'redhat']: re...
Build a in-memory data of all managed files.
def consume_texture_coordinates(self): """Consume all consecutive texture coordinates""" # The first iteration processes the current/first vt statement. # The loop continues until there are no more vt-statements or StopIteration is raised by generator while True: yield ( ...
Consume all consecutive texture coordinates
def update_last_wm_layers(self, service_id, num_layers=10): """ Update and index the last added and deleted layers (num_layers) in WorldMap service. """ from hypermap.aggregator.models import Service LOGGER.debug( 'Updating the index the last %s added and %s deleted layers in WorldMap servi...
Update and index the last added and deleted layers (num_layers) in WorldMap service.
def rmon_alarm_entry_alarm_rising_threshold(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") rmon = ET.SubElement(config, "rmon", xmlns="urn:brocade.com:mgmt:brocade-rmon") alarm_entry = ET.SubElement(rmon, "alarm-entry") alarm_index_key = ET.SubE...
Auto Generated Code
def stringClade(taxrefs, name, at): '''Return a Newick string from a list of TaxRefs''' string = [] for ref in taxrefs: # distance is the difference between the taxonomic level of the ref # and the current level of the tree growth d = float(at-ref.level) # ensure no spaces i...
Return a Newick string from a list of TaxRefs
def recovery(self, using=None, **kwargs): """ The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged. """ return self._get_connection(...
The indices recovery API provides insight into on-going shard recoveries for the index. Any additional keyword arguments will be passed to ``Elasticsearch.indices.recovery`` unchanged.
def getObjectByPid(self, pid): """ Args: pid : str Returns: str : URIRef of the entry identified by ``pid``.""" self._check_initialized() opid = rdflib.term.Literal(pid) res = [o for o in self.subjects(predicate=DCTERMS.identifier, object=opid)] return res[0]
Args: pid : str Returns: str : URIRef of the entry identified by ``pid``.
def vm_snapshot_create(vm_name, kwargs=None, call=None): ''' Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example...
Creates a new virtual machine snapshot from the provided VM. .. versionadded:: 2016.3.0 vm_name The name of the VM from which to create the snapshot. snapshot_name The name of the snapshot to be created. CLI Example: .. code-block:: bash salt-cloud -a vm_snapshot_create...
def port(self, value=None): """ Return or set the port :param string value: the new port to use :returns: string or new :class:`URL` instance """ if value is not None: return URL._mutate(self, port=value) return self._tuple.port
Return or set the port :param string value: the new port to use :returns: string or new :class:`URL` instance
def check_is_spam(content, content_object, request, backends=None): """ Return True if the content is a spam, else False. """ if backends is None: backends = SPAM_CHECKER_BACKENDS for backend_path in backends: spam_checker = get_spam_checker(backend_path) i...
Return True if the content is a spam, else False.
def module_ids(self, rev=False): """Gets a list of module ids guaranteed to be sorted by run_order, ignoring conn modules (run order < 0). """ shutit_global.shutit_global_object.yield_to_draw() ids = sorted(list(self.shutit_map.keys()),key=lambda module_id: self.shutit_map[module_id].run_order) if rev: r...
Gets a list of module ids guaranteed to be sorted by run_order, ignoring conn modules (run order < 0).
def create_environment(component_config): """ Create a modified environment. Arguments component_config - The configuration for a component. """ ret = os.environ.copy() for env in component_config.get_list("dp.env_list"): real_env = env.upper() value = os.environ.get(real_en...
Create a modified environment. Arguments component_config - The configuration for a component.
def run(self, endpoint: str, loop: AbstractEventLoop = None): """ Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method) """ if not loop: loop...
Run server main task. :param endpoint: Socket endpoint to listen to, e.g. "tcp://*:1234" :param loop: Event loop to run server in (alternatively just use run_async method)
def sorted_enums(self) -> List[Tuple[str, int]]: """Return list of enum items sorted by value.""" return sorted(self.enum.items(), key=lambda x: x[1])
Return list of enum items sorted by value.
def attribute_path(self, attribute, missing=None, visitor=None): """ Generates a list of values of the `attribute` of all ancestors of this node (as well as the node itself). If a value is ``None``, then the optional value of `missing` is used (by default ``None``). By defau...
Generates a list of values of the `attribute` of all ancestors of this node (as well as the node itself). If a value is ``None``, then the optional value of `missing` is used (by default ``None``). By default, the ``getattr(node, attribute, None) or missing`` mechanism i...
def create_comment(self, access_token, video_id, content, reply_id=None, captcha_key=None, captcha_text=None): """doc: http://open.youku.com/docs/doc?id=41 """ url = 'https://openapi.youku.com/v2/comments/create.json' data = { 'client_id': self.client_i...
doc: http://open.youku.com/docs/doc?id=41
def elcm_profile_set(irmc_info, input_data): """send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { ...
send an eLCM request to set param values To apply param values, a new session is spawned with status 'running'. When values are applied or error, the session ends. :param irmc_info: node info :param input_data: param values to apply, eg. { 'Server': { 'SystemCon...
def open_buffer(self, location=None, show_in_current_window=False): """ Open/create a file, load it, and show it in a new buffer. """ eb = self._get_or_create_editor_buffer(location) if show_in_current_window: self.show_editor_buffer(eb)
Open/create a file, load it, and show it in a new buffer.
def to_api_repr(self): """Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource """ resource = {self.entity_type: self.entity_id} if self.role is not None: resource["role"] =...
Construct the API resource representation of this access entry Returns: Dict[str, object]: Access entry represented as an API resource
def copy_and_run(config, src_dir): ''' Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Ret...
Local-only operation of the executor. Intended for validation script developers, and the test suite. Please not that this function only works correctly if the validator has one of the following names: - validator.py - validator.zip Returns True when a job was prepared and executed....
def maxlike(self,nseeds=50): """Returns the best-fit parameters, choosing the best of multiple starting guesses :param nseeds: (optional) Number of starting guesses, uniformly distributed throughout allowed ranges. Default=50. :return: list of best-fit para...
Returns the best-fit parameters, choosing the best of multiple starting guesses :param nseeds: (optional) Number of starting guesses, uniformly distributed throughout allowed ranges. Default=50. :return: list of best-fit parameters: ``[m,age,feh,[distance,A_V]]``. ...
def get_repositories(self, digests): """ Build the repositories metadata :param digests: dict, image -> digests """ if self.workflow.push_conf.pulp_registries: # If pulp was used, only report pulp images registries = self.workflow.push_conf.pulp_registrie...
Build the repositories metadata :param digests: dict, image -> digests
def read_handshake(self): """Read and process an initial handshake message from Storm.""" msg = self.read_message() pid_dir, _conf, _context = msg["pidDir"], msg["conf"], msg["context"] # Write a blank PID file out to the pidDir open(join(pid_dir, str(self.pid)), "w").close() ...
Read and process an initial handshake message from Storm.
def _login(self, max_tries=2): """Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts. """ i...
Logs in to Kindle Cloud Reader. Args: max_tries: The maximum number of login attempts that will be made. Raises: BrowserError: If method called when browser not at a signin URL. LoginError: If login unsuccessful after `max_tries` attempts.
def sort_topologically(dag): """Sort the dag breath first topologically. Only the nodes inside the dag are returned, i.e. the nodes that are also keys. Returns: a topological ordering of the DAG. Raises: an error if this is not possible (graph is not valid). """ dag = copy.de...
Sort the dag breath first topologically. Only the nodes inside the dag are returned, i.e. the nodes that are also keys. Returns: a topological ordering of the DAG. Raises: an error if this is not possible (graph is not valid).
def connect(self): """Connect to the Redis server if necessary. :rtype: :class:`~tornado.concurrent.Future` :raises: :class:`~tredis.exceptions.ConnectError` :class:`~tredis.exceptinos.RedisError` """ future = concurrent.Future() if self.connected: ...
Connect to the Redis server if necessary. :rtype: :class:`~tornado.concurrent.Future` :raises: :class:`~tredis.exceptions.ConnectError` :class:`~tredis.exceptinos.RedisError`
def _read_credential_file(self, cfg): """ Implements the default (keystone) behavior. """ self.username = cfg.get("keystone", "username") self.password = cfg.get("keystone", "password", raw=True) self.tenant_id = cfg.get("keystone", "tenant_id")
Implements the default (keystone) behavior.
def get_readwrite_instance(cls, working_dir, restore=False, restore_block_height=None): """ Get a read/write instance to the db, without the singleton check. Used for low-level operations like db restore. Not used in the steady state behavior of the system. """ log.warnin...
Get a read/write instance to the db, without the singleton check. Used for low-level operations like db restore. Not used in the steady state behavior of the system.
def purge_old_files(date_time, directory_path, custom_prefix="backup"): """ Takes a datetime object and a directory path, runs through files in the directory and deletes those tagged with a date from before the provided datetime. If your backups have a custom_prefix that is not the defau...
Takes a datetime object and a directory path, runs through files in the directory and deletes those tagged with a date from before the provided datetime. If your backups have a custom_prefix that is not the default ("backup"), provide it with the "custom_prefix" kwarg.
def index(config): # pragma: no cover """Display group info in raw format.""" client = Client() client.prepare_connection() group_api = API(client) print(group_api.index())
Display group info in raw format.
def afterqc_general_stats_table(self): """ Take the parsed stats from the Afterqc report and add it to the General Statistics table at the top of the report """ headers = OrderedDict() headers['pct_good_bases'] = { 'title': '% Good Bases', 'description': 'Percent...
Take the parsed stats from the Afterqc report and add it to the General Statistics table at the top of the report
def _set_buttons(self, chat, bot): """ Helper methods to set the buttons given the input sender and chat. """ if isinstance(self.reply_markup, ( types.ReplyInlineMarkup, types.ReplyKeyboardMarkup)): self._buttons = [[ MessageButton(self._client...
Helper methods to set the buttons given the input sender and chat.
def get_place_tags(index_page, domain): #: TODO geoip to docstring """ Return list of `place` tags parsed from `meta` and `whois`. Args: index_page (str): HTML content of the page you wisht to analyze. domain (str): Domain of the web, without ``http://`` or other parts. Returns: ...
Return list of `place` tags parsed from `meta` and `whois`. Args: index_page (str): HTML content of the page you wisht to analyze. domain (str): Domain of the web, without ``http://`` or other parts. Returns: list: List of :class:`.SourceString` objects.
def create_resource(output_model, rtype, unique, links, existing_ids=None, id_helper=None): ''' General-purpose routine to create a new resource in the output model, based on data provided output_model - Versa connection to model to be updated rtype - Type IRI for the new resource, set wit...
General-purpose routine to create a new resource in the output model, based on data provided output_model - Versa connection to model to be updated rtype - Type IRI for the new resource, set with Versa type unique - list of key/value pairs for determining a unique hash for the new res...
def dec2dms(dec): """ ADW: This should really be replaced by astropy """ DEGREE = 360. HOUR = 24. MINUTE = 60. SECOND = 3600. dec = float(dec) sign = np.copysign(1.0,dec) fdeg = np.abs(dec) deg = int(fdeg) fminute = (fdeg - deg)*MINUTE minute = int(fminute) ...
ADW: This should really be replaced by astropy
def load_params_from_file(self, fname: str): """ Loads and sets model parameters from file. :param fname: Path to load parameters from. """ utils.check_condition(os.path.exists(fname), "No model parameter file found under %s. " ...
Loads and sets model parameters from file. :param fname: Path to load parameters from.
def __del_running_bp(self, tid, bp): "Auxiliary method." self.__runningBP[tid].remove(bp) if not self.__runningBP[tid]: del self.__runningBP[tid]
Auxiliary method.
def to_det_oid(self, det_id_or_det_oid): """Convert det OID or ID to det OID""" try: int(det_id_or_det_oid) except ValueError: return det_id_or_det_oid else: return self.get_det_oid(det_id_or_det_oid)
Convert det OID or ID to det OID
def install_sql(self, site=None, database='default', apps=None, stop_on_error=0, fn=None): """ Installs all custom SQL. """ #from burlap.db import load_db_set stop_on_error = int(stop_on_error) site = site or ALL name = database r = self.local_renderer...
Installs all custom SQL.
def updateTable(self, networkId, tableType, body, class_, verbose=None): """ Updates the table specified by the `tableType` and `networkId` parameters. New columns will be created if they do not exist in the target table. Current limitations: * Numbers are handled as Double ...
Updates the table specified by the `tableType` and `networkId` parameters. New columns will be created if they do not exist in the target table. Current limitations: * Numbers are handled as Double * List column is not supported in this version :param networkId: SUID containin...
def _check_endings(self): """Check begin/end of slug, raises Error if malformed.""" if self.slug.startswith("/") and self.slug.endswith("/"): raise InvalidSlugError( _("Invalid slug. Did you mean {}, without the leading and trailing slashes?".format(self.slug.strip("/")))) ...
Check begin/end of slug, raises Error if malformed.
def _default_verify_function(instance, answer, result_host, atol, verbose): """default verify function based on numpy.allclose""" #first check if the length is the same if len(instance.arguments) != len(answer): raise TypeError("The length of argument list and provided results do not match.") #...
default verify function based on numpy.allclose
def Drop(self: dict, n): """ [ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ] """ n = len(self) - n if n <= 0: yield from self.items() else: for i, e in enumerate(self.items()): ...
[ { 'self': [1, 2, 3, 4, 5], 'n': 3, 'assert': lambda ret: list(ret) == [1, 2] } ]
def ToPath(self): """Converts a reference into a VFS file path.""" if self.path_type == PathInfo.PathType.OS: return os.path.join("fs", "os", *self.path_components) elif self.path_type == PathInfo.PathType.TSK: return os.path.join("fs", "tsk", *self.path_components) elif self.path_type == P...
Converts a reference into a VFS file path.
def run(self): """Sends extracted metadata in json format to stdout if stdout option is specified, assigns metadata dictionary to class_metadata variable otherwise. """ if self.stdout: sys.stdout.write("extracted json data:\n" + json.dumps( self.metada...
Sends extracted metadata in json format to stdout if stdout option is specified, assigns metadata dictionary to class_metadata variable otherwise.
def query(ra ,dec, rad=0.1, query=None): """Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image L...
Query the CADC TAP service to determine the list of images for the NewHorizons Search. Things to determine: a- Images to have the reference subtracted from. b- Image to use as the 'REFERENCE' image. c- Images to be used for input into the reference image Logic: Given a particular Image/CCD find all the ...
def delete_guest(userid): """ Destroy a virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8 """ # Check if the guest exists. guest_list_info = client.send_request('guest_list') # the string 'userid' need to be coded as 'u'userid' in case of py2 i...
Destroy a virtual machine. Input parameters: :userid: USERID of the guest, last 8 if length > 8
def add_key_filter(self, *args): """ Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce` """ if self._input_mode == 'query': raise ValueError('Key filters are not supported in a query.') ...
Add a single key filter to the inputs. :param args: a filter :type args: list :rtype: :class:`RiakMapReduce`
def GroupsUsersPost(self, parameters, group_id): """ Add users to a group in CommonSense. @param parameters (dictonary) - Dictionary containing the users to add. @return (bool) - Boolean indicating whether GroupsPost was...
Add users to a group in CommonSense. @param parameters (dictonary) - Dictionary containing the users to add. @return (bool) - Boolean indicating whether GroupsPost was successful.
def _run_incremental_transforms(self, si, transforms): ''' Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None. ''' ## operate each transform on this one Strea...
Run transforms on stream item. Item may be discarded by some transform. Writes successful items out to current self.t_chunk Returns transformed item or None.
def hour(self, value=None): """Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a miss...
Corresponds to IDD Field `hour` Args: value (int): value for IDD Field `hour` value >= 1 value <= 24 if `value` is None it will not be checked against the specification and is assumed to be a missing value Raises: ...
def write_config_value_to_file(key, value, config_path=None): """Write key/value pair to config file. """ if config_path is None: config_path = DEFAULT_CONFIG_PATH # Get existing config. config = _get_config_dict_from_file(config_path) # Add/update the key/value pair. config[key] =...
Write key/value pair to config file.
def _client_builder(self): """Build Elasticsearch client.""" client_config = self.app.config.get('SEARCH_CLIENT_CONFIG') or {} client_config.setdefault( 'hosts', self.app.config.get('SEARCH_ELASTIC_HOSTS')) client_config.setdefault('connection_class', RequestsHttpConnection) ...
Build Elasticsearch client.
def get_bool_value(self, section, option, default=True): """Get the bool value of an option, if it exists.""" try: return self.parser.getboolean(section, option) except NoOptionError: return bool(default)
Get the bool value of an option, if it exists.
def begin(self, **options): '''Begin a new :class:`Transaction`. If this :class:`Session` is already in a :ref:`transactional state <transactional-state>`, an error will occur. It returns the :attr:`transaction` attribute. This method is mostly used within a ``with`` statement block:: with session....
Begin a new :class:`Transaction`. If this :class:`Session` is already in a :ref:`transactional state <transactional-state>`, an error will occur. It returns the :attr:`transaction` attribute. This method is mostly used within a ``with`` statement block:: with session.begin() as t: t.add(...) ...
def send_notification(self, method, *args): """Send a JSON-RPC notification. The notification *method* is sent with positional arguments *args*. """ message = self._version.create_request(method, args, notification=True) self.send_message(message)
Send a JSON-RPC notification. The notification *method* is sent with positional arguments *args*.
def _ReadFloatingPointDataTypeDefinition( self, definitions_registry, definition_values, definition_name, is_member=False): """Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_valu...
Reads a floating-point data type definition. Args: definitions_registry (DataTypeDefinitionsRegistry): data type definitions registry. definition_values (dict[str, object]): definition values. definition_name (str): name of the definition. is_member (Optional[bool]): True if the d...
def longitude(self, value=0.0): """Corresponds to IDD Field `longitude` - is West, + is East, degree minutes represented in decimal (i.e. 30 minutes is .5) Args: value (float): value for IDD Field `longitude` Unit: deg Default value: 0.0 ...
Corresponds to IDD Field `longitude` - is West, + is East, degree minutes represented in decimal (i.e. 30 minutes is .5) Args: value (float): value for IDD Field `longitude` Unit: deg Default value: 0.0 value >= -180.0 value <...
def parser_factory(fake_args=None): """Return a proper contextual OptionParser""" parser = ArgumentParser(description='aomi') subparsers = parser.add_subparsers(dest='operation', help='Specify the data ' ' or extraction operation'...
Return a proper contextual OptionParser
def read_mda(attribute): """Read HDFEOS metadata and return a dict with all the key/value pairs.""" lines = attribute.split('\n') mda = {} current_dict = mda path = [] prev_line = None for line in lines: if not line: continue ...
Read HDFEOS metadata and return a dict with all the key/value pairs.
def get_all_subdomains(offset=0, count=100, proxy=None, hostport=None): """ Get all subdomains within the given range. Return the list of names on success Return {'error': ...} on failure """ assert proxy or hostport, 'Need proxy or hostport' if proxy is None: proxy = connect_hostpor...
Get all subdomains within the given range. Return the list of names on success Return {'error': ...} on failure
def check_subdomain_transition(cls, existing_subrec, new_subrec): """ Given an existing subdomain record and a (newly-discovered) new subdomain record, determine if we can use the new subdomain record (i.e. is its signature valid? is it in the right sequence?) Return True if so R...
Given an existing subdomain record and a (newly-discovered) new subdomain record, determine if we can use the new subdomain record (i.e. is its signature valid? is it in the right sequence?) Return True if so Return False if not
def _strict_match(self, struct1, struct2, fu, s1_supercell=True, use_rms=False, break_on_match=False): """ Matches struct2 onto struct1 (which should contain all sites in struct2). Args: struct1, struct2 (Structure): structures to be matched ...
Matches struct2 onto struct1 (which should contain all sites in struct2). Args: struct1, struct2 (Structure): structures to be matched fu (int): size of supercell to create s1_supercell (bool): whether to create the supercell of struct1 (vs struct2) ...
def authenticate_nova_user(self, keystone, user, password, tenant): """Authenticates a regular user with nova-api.""" self.log.debug('Authenticating nova user ({})...'.format(user)) ep = keystone.service_catalog.url_for(service_type='identity', inter...
Authenticates a regular user with nova-api.
def _setup(self): "Resets the state and prepares for running the example." self.example.error = None self.example.traceback = '' # inject function contexts from parent functions c = Context(parent=self.context) #for parent in reversed(self.example.parents): # c...
Resets the state and prepares for running the example.
def chartbeat_top(parser, token): """ Top Chartbeat template tag. Render the top Javascript code for Chartbeat. """ bits = token.split_contents() if len(bits) > 1: raise TemplateSyntaxError("'%s' takes no arguments" % bits[0]) return ChartbeatTopNode()
Top Chartbeat template tag. Render the top Javascript code for Chartbeat.
def _is_executable_file(path): """Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012,...
Checks that path is an executable regular file, or a symlink towards one. This is roughly ``os.path isfile(path) and os.access(path, os.X_OK)``. This function was forked from pexpect originally: Copyright (c) 2013-2014, Pexpect development team Copyright (c) 2012, Noah Spurrier <[email protected]> PE...
def render(directory, opt): """Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles""" if not os.path.exists(directory) and not os.path.isdir(directory): os.mkdir(directory) a_secretfile = render_secretfile(opt) s_path = "%s/Secretfile" % director...
Render any provided template. This includes the Secretfile, Vault policies, and inline AWS roles
def xform_key(self, key): '''we transform cache keys by taking their sha1 hash so that we don't need to worry about cache keys containing invalid characters''' newkey = hashlib.sha1(key.encode('utf-8')) return newkey.hexdigest()
we transform cache keys by taking their sha1 hash so that we don't need to worry about cache keys containing invalid characters
def is_classmethod(meth): """Detects if the given callable is a classmethod. """ if inspect.ismethoddescriptor(meth): return isinstance(meth, classmethod) if not inspect.ismethod(meth): return False if not inspect.isclass(meth.__self__): return False if not hasattr(meth._...
Detects if the given callable is a classmethod.
def get(self, key, timeout=None): """Given a key, returns an element from the redis table""" key = self.pre_identifier + key # Check to see if we have this key unpickled_entry = self.client.get(key) if not unpickled_entry: # No hit, return nothing return N...
Given a key, returns an element from the redis table
def find_connected_atoms(struct, tolerance=0.45, ldict=JmolNN().el_radius): """ Finds the list of bonded atoms. Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) +...
Finds the list of bonded atoms. Args: struct (Structure): Input structure tolerance: length in angstroms used in finding bonded atoms. Two atoms are considered bonded if (radius of atom 1) + (radius of atom 2) + (tolerance) < (distance between atoms 1 and 2). Default value = 0.45, the value used by...
def cmd(send, msg, args): """Reports the difference between now and some specified time. Syntax: {command} <time> """ parser = arguments.ArgParser(args['config']) parser.add_argument('date', nargs='*', action=arguments.DateParser) try: cmdargs = parser.parse_args(msg) except argume...
Reports the difference between now and some specified time. Syntax: {command} <time>
def _normalize(value): """ Normalize handle values. """ if hasattr(value, 'value'): value = value.value if value is not None: value = long(value) return value
Normalize handle values.
def frictional_resistance_coef(length, speed, **kwargs): """ Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could...
Flat plate frictional resistance of the ship according to ITTC formula. ref: https://ittc.info/media/2021/75-02-02-02.pdf :param length: metres length of the vehicle :param speed: m/s speed of the vehicle :param kwargs: optional could take in temperature to take account change of water property :re...
def check(self, instance): """ Process both the istio_mesh instance and process_mixer instance associated with this instance """ # Get the config for the istio_mesh instance istio_mesh_endpoint = instance.get('istio_mesh_endpoint') istio_mesh_config = self.config_map[ist...
Process both the istio_mesh instance and process_mixer instance associated with this instance
def is_success(self): ''' check all sessions to see if they have completed successfully ''' for _session in self._sessions.values(): if not _session.is_success(): return False return True
check all sessions to see if they have completed successfully
def store_vdp_vsi(self, port_uuid, mgrid, typeid, typeid_ver, vsiid_frmt, vsiid, filter_frmt, gid, mac, vlan, new_network, reply, oui_id, oui_data, vsw_cb_fn, vsw_cb_data, reason): """Stores the vNIC specific info for VDP Refresh. :param...
Stores the vNIC specific info for VDP Refresh. :param uuid: vNIC UUID :param mgrid: MGR ID :param typeid: Type ID :param typeid_ver: Version of the Type ID :param vsiid_frmt: Format of the following VSI argument :param vsiid: VSI value :param filter_frmt: Filter ...
async def whowas(self, nickname): """ Return information about offline user. This is an blocking asynchronous method: it has to be called from a coroutine, as follows: info = await self.whowas('Nick') """ # Same treatment as nicknames in whois. if protocol.AR...
Return information about offline user. This is an blocking asynchronous method: it has to be called from a coroutine, as follows: info = await self.whowas('Nick')
def output_paas(gandi, paas, datacenters, vhosts, output_keys, justify=11): """ Helper to output a paas information.""" output_generic(gandi, paas, output_keys, justify) if 'sftp_server' in output_keys: output_line(gandi, 'sftp_server', paas['ftp_server'], justify) if 'vhost' in output_keys: ...
Helper to output a paas information.
def rot90(img): ''' rotate one or multiple grayscale or color images 90 degrees ''' s = img.shape if len(s) == 3: if s[2] in (3, 4): # color image out = np.empty((s[1], s[0], s[2]), dtype=img.dtype) for i in range(s[2]): out[:, :, i] = np.rot...
rotate one or multiple grayscale or color images 90 degrees
async def inline_query(self, bot, query, *, offset=None, geo_point=None): """ Makes the given inline query to the specified bot i.e. ``@vote My New Poll`` would be as follows: >>> client = ... >>> client.inline_query('vote', 'My New Poll') Args: bot (`entity...
Makes the given inline query to the specified bot i.e. ``@vote My New Poll`` would be as follows: >>> client = ... >>> client.inline_query('vote', 'My New Poll') Args: bot (`entity`): The bot entity to which the inline query should be made. quer...
def GetInput(self): "Build the INPUT structure for the action" actions = 1 # if both up and down if self.up and self.down: actions = 2 inputs = (INPUT * actions)() vk, scan, flags = self._get_key_info() for inp in inputs: inp.type = INPU...
Build the INPUT structure for the action
def _reconnect_delay(self): """ Calculate reconnection delay. """ if self.RECONNECT_ON_ERROR and self.RECONNECT_DELAYED: if self._reconnect_attempts >= len(self.RECONNECT_DELAYS): return self.RECONNECT_DELAYS[-1] else: return self.RECONNECT_DELAYS[...
Calculate reconnection delay.
def hash(value, arg): """ Returns a hex-digest of the passed in value for the hash algorithm given. """ arg = str(arg).lower() if sys.version_info >= (3,0): value = value.encode("utf-8") if not arg in get_available_hashes(): raise TemplateSyntaxError("The %s hash algorithm does n...
Returns a hex-digest of the passed in value for the hash algorithm given.
def stem(self, text): """Stem each word of the Latin text.""" stemmed_text = '' for word in text.split(' '): if word not in self.stops: # remove '-que' suffix word, in_que_pass_list = self._checkremove_que(word) if not in_que_pass_li...
Stem each word of the Latin text.
def query(usr, pwd, *hpo_terms): """ Query the phenomizer web tool Arguments: usr (str): A username for phenomizer pwd (str): A password for phenomizer hpo_terms (list): A list with hpo terms yields: parsed_term (dict): A dictionary with the parsed information ...
Query the phenomizer web tool Arguments: usr (str): A username for phenomizer pwd (str): A password for phenomizer hpo_terms (list): A list with hpo terms yields: parsed_term (dict): A dictionary with the parsed information from phenomizer
def _bss_decomp_mtifilt_images(reference_sources, estimated_source, j, flen, Gj=None, G=None): """Decomposition of an estimated source image into four components representing respectively the true source image, spatial (or filtering) distortion, interference and artifacts, der...
Decomposition of an estimated source image into four components representing respectively the true source image, spatial (or filtering) distortion, interference and artifacts, derived from the true source images using multichannel time-invariant filters. Adapted version to work with multichannel sources...
def _close_holding(self, trade): """ 应用平仓,并计算平仓盈亏 买平: delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier 卖平: delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier ...
应用平仓,并计算平仓盈亏 买平: delta_realized_pnl = sum of ((trade_price - cost_price)* quantity) of closed trades * contract_multiplier 卖平: delta_realized_pnl = sum of ((cost_price - trade_price)* quantity) of closed trades * contract_multiplier :param trade: rqalpha.model.trade.Trade ...
def domain_delete(domain, logger): """libvirt domain undefinition. @raise: libvirt.libvirtError. """ if domain is not None: try: if domain.isActive(): domain.destroy() except libvirt.libvirtError: logger.exception("Unable to destroy the domain.")...
libvirt domain undefinition. @raise: libvirt.libvirtError.