code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def serve(config): "Serve the app with Gevent" from gevent.pywsgi import WSGIServer app = make_app(config=config) host = app.config.get("HOST", '127.0.0.1') port = app.config.get("PORT", 5000) http_server = WSGIServer((host, port), app) http_server.serve_forever()
Serve the app with Gevent
def conn_is_open(conn): """Tests sqlite3 connection, returns T/F""" if conn is None: return False try: get_table_names(conn) return True # # Idea taken from # # http: // stackoverflow.com / questions / 1981392 / how - to - tell - if -python - sqlite - data...
Tests sqlite3 connection, returns T/F
def getTopRight(self): """ Retrieves a tuple with the x,y coordinates of the upper right point of the rect. Requires the coordinates, width, height to be numbers """ return (float(self.get_x()) + float(self.get_width()), float(self.get_y()) + float(self.get_height()))
Retrieves a tuple with the x,y coordinates of the upper right point of the rect. Requires the coordinates, width, height to be numbers
def send_headers(self): """Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this. """ hkeys = [key.lower() for key, value in self.outheaders] status = int(self.status[:3]) if status...
Assert, process, and send the HTTP response message-headers. You must set self.status, and self.outheaders before calling this.
def _init_params(self, amplitude, length_scale, validate_args): """Shared init logic for `amplitude` and `length_scale` params. Args: amplitude: `Tensor` (or convertible) or `None` to convert, validate. length_scale: `Tensor` (or convertible) or `None` to convert, validate. validate_args: If ...
Shared init logic for `amplitude` and `length_scale` params. Args: amplitude: `Tensor` (or convertible) or `None` to convert, validate. length_scale: `Tensor` (or convertible) or `None` to convert, validate. validate_args: If `True`, parameters are checked for validity despite possibly de...
def set_secure_boot_mode(irmc_info, enable): """Enable/Disable secure boot on the server. :param irmc_info: node info :param enable: True, if secure boot needs to be enabled for next boot, else False. """ bios_config_data = { 'Server': { '@Version': '1.01', ...
Enable/Disable secure boot on the server. :param irmc_info: node info :param enable: True, if secure boot needs to be enabled for next boot, else False.
def free_symbols(self): """Set of all free symbols""" return set([ sym for sym in self.term.free_symbols if sym not in self.bound_symbols])
Set of all free symbols
def _register(self, defaults=None, **kwargs): """Fetch (update or create) an instance, lazily. We're doing this lazily, so that it becomes possible to define custom enums in your code, even before the Django ORM is fully initialized. Domain.objects.SHOPPING = Domain.objects.re...
Fetch (update or create) an instance, lazily. We're doing this lazily, so that it becomes possible to define custom enums in your code, even before the Django ORM is fully initialized. Domain.objects.SHOPPING = Domain.objects.register( ref='shopping', name='Web...
def fit(self, X, y=None, **kwargs): """ The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m ...
The fit method is the primary drawing input for the visualization since it has both the X and y data required for the viz and the transform method does not. Parameters ---------- X : ndarray or DataFrame of shape n x m A matrix of n instances with m features ...
def from_data(cls, data): """Create gyroscope stream from data array Parameters ------------------- data : (N, 3) ndarray Data array of angular velocities (rad/s) Returns ------------------- GyroStream Stream object """ if...
Create gyroscope stream from data array Parameters ------------------- data : (N, 3) ndarray Data array of angular velocities (rad/s) Returns ------------------- GyroStream Stream object
def initialize(self, config, context): """Implements Pulsar Spout's initialize method""" self.logger.info("Initializing PulsarSpout with the following") self.logger.info("Component-specific config: \n%s" % str(config)) self.logger.info("Context: \n%s" % str(context)) self.emit_count = 0 self.ac...
Implements Pulsar Spout's initialize method
def _set_session_ldp_stats(self, v, load=False): """ Setter method for session_ldp_stats, mapped from YANG variable /mpls_state/ldp/ldp_session/session_ldp_stats (container) If this variable is read-only (config: false) in the source YANG file, then _set_session_ldp_stats is considered as a private ...
Setter method for session_ldp_stats, mapped from YANG variable /mpls_state/ldp/ldp_session/session_ldp_stats (container) If this variable is read-only (config: false) in the source YANG file, then _set_session_ldp_stats is considered as a private method. Backends looking to populate this variable should ...
def _sb_short_word(self, term, r1_prefixes=None): """Return True iff term is a short word. (...according to the Porter2 specification.) Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ...
Return True iff term is a short word. (...according to the Porter2 specification.) Parameters ---------- term : str The term to examine r1_prefixes : set Prefixes to consider Returns ------- bool True iff term is a sh...
def facts(puppet=False): ''' Run facter and return the results CLI Example: .. code-block:: bash salt '*' puppet.facts ''' ret = {} opt_puppet = '--puppet' if puppet else '' cmd_ret = __salt__['cmd.run_all']('facter {0}'.format(opt_puppet)) if cmd_ret['retcode'] != 0: ...
Run facter and return the results CLI Example: .. code-block:: bash salt '*' puppet.facts
def query_obj(self): """Returns the query object for this visualization""" d = super().query_obj() d['row_limit'] = self.form_data.get( 'row_limit', int(config.get('VIZ_ROW_LIMIT'))) numeric_columns = self.form_data.get('all_columns_x') if numeric_columns is None: ...
Returns the query object for this visualization
def config(_config=None, **kwargs): """ A decorator for setting the default kwargs of `BaseHandler.crawl`. Any self.crawl with this callback will use this config. """ if _config is None: _config = {} _config.update(kwargs) def wrapper(func): func._config = _config re...
A decorator for setting the default kwargs of `BaseHandler.crawl`. Any self.crawl with this callback will use this config.
def request_token(): """ 通过帐号,密码请求token,返回一个dict { "user_info": { "ck": "-VQY", "play_record": { "fav_chls_count": 4, "liked": 802, "banned": 162, "played": 28368 }, "is_new_user": 0, "uid": "taizilongxu", "t...
通过帐号,密码请求token,返回一个dict { "user_info": { "ck": "-VQY", "play_record": { "fav_chls_count": 4, "liked": 802, "banned": 162, "played": 28368 }, "is_new_user": 0, "uid": "taizilongxu", "third_party_info": null, "...
def modelSetCompleted(self, modelID, completionReason, completionMsg, cpuTime=0, useConnectionID=True): """ Mark a model as completed, with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client (connection_id doesn't match)...
Mark a model as completed, with the given completionReason and completionMsg. This will fail if the model does not currently belong to this client (connection_id doesn't match). Parameters: ---------------------------------------------------------------- modelID: model ID of model to mo...
async def send_initial_metadata(self, *, metadata=None): """Coroutine to send headers with initial metadata to the client. In gRPC you can send initial metadata as soon as possible, because gRPC doesn't use `:status` pseudo header to indicate success or failure of the current request. g...
Coroutine to send headers with initial metadata to the client. In gRPC you can send initial metadata as soon as possible, because gRPC doesn't use `:status` pseudo header to indicate success or failure of the current request. gRPC uses trailers for this purpose, and trailers are sent du...
def get_route_lines_route(self, **kwargs): """Obtain itinerary for one or more lines in the given date. Args: day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. ...
Obtain itinerary for one or more lines in the given date. Args: day (int): Day of the month in format DD. The number is automatically padded if it only has one digit. month (int): Month number in format MM. The number is automatically padded if it only ha...
def _is_viable_phone_number(number): """Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance ...
Checks to see if a string could possibly be a phone number. At the moment, checks to see that the string begins with at least 2 digits, ignoring any punctuation commonly found in phone numbers. This method does not require the number to be normalized in advance - but does assume that leading non-numbe...
def create(self, friendly_name, event_callback_url=values.unset, events_filter=values.unset, multi_task_enabled=values.unset, template=values.unset, prioritize_queue_order=values.unset): """ Create a new WorkspaceInstance :param unicode friendly_name: Human readabl...
Create a new WorkspaceInstance :param unicode friendly_name: Human readable description of this workspace :param unicode event_callback_url: If provided, the Workspace will publish events to this URL. :param unicode events_filter: Use this parameter to receive webhooks on EventCallbackUrl for s...
def show_tooltip(self, pos, tooltip, _sender_deco=None): """ Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use on...
Show a tool tip at the specified position :param pos: Tooltip position :param tooltip: Tooltip text :param _sender_deco: TextDecoration which is the sender of the show tooltip request. (for internal use only).
def set_cores_massive(self,filename='core_masses_massive.txt'): ''' Uesse function cores in nugridse.py ''' core_info=[] minis=[] for i in range(len(self.runs_H5_surf)): sefiles=se(self.runs_H5_out[i]) mini=sefiles.get('mini') minis.append(mini) incycle=in...
Uesse function cores in nugridse.py
def read_uic1tag(fh, byteorder, dtype, count, offsetsize, planecount=None): """Read MetaMorph STK UIC1Tag from file and return as dict. Return empty dictionary if planecount is unknown. """ assert dtype in ('2I', '1I') and byteorder == '<' result = {} if dtype == '2I': # pre MetaMorph ...
Read MetaMorph STK UIC1Tag from file and return as dict. Return empty dictionary if planecount is unknown.
def create_space(deployment_name, space_name, security_policy='public', events_retention_days=0, metrics_retention_days=0, token_manager=None, app_url=defaults.APP_URL): """ create a space within the deployment...
create a space within the deployment specified and with the various rentention values set
def _clean_html(html): """\ Removes links (``<a href="...">...</a>``) from the provided HTML input. Further, it replaces "&#x000A;" with ``\n`` and removes "¶" from the texts. """ content = html.replace(u'&#x000A;', u'\n').replace(u'¶', '') content = _LINK_PATTERN.sub(u'', content) content =...
\ Removes links (``<a href="...">...</a>``) from the provided HTML input. Further, it replaces "&#x000A;" with ``\n`` and removes "¶" from the texts.
def add(name, mac, mtu=1500): ''' Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add s...
Add a new nictag name : string name of new nictag mac : string mac of parent interface or 'etherstub' to create a ether stub mtu : int MTU (ignored for etherstubs) CLI Example: .. code-block:: bash salt '*' nictagadm.add storage0 etherstub salt '*' nictaga...
def from_yamlfile(cls, fp, selector_handler=None, strict=False, debug=False): """ Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ...
Create a Parselet instance from a file containing the Parsley script as a YAML object >>> import parslepy >>> with open('parselet.yml') as fp: ... parslepy.Parselet.from_yamlfile(fp) ... <parslepy.base.Parselet object at 0x2014e50> :param file fp: an open fi...
def _managePsets(configobj, section_name, task_name, iparsobj=None, input_dict=None): """ Read in parameter values from PSET-like configobj tasks defined for source-finding algorithms, and any other PSET-like tasks under this task, and merge those values into the input configobj dictionary. """ ...
Read in parameter values from PSET-like configobj tasks defined for source-finding algorithms, and any other PSET-like tasks under this task, and merge those values into the input configobj dictionary.
def parse(self, stream): """ Parse the given stream """ lines = re.sub("[\r\n]+", "\n", stream.read()).split("\n") for line in lines: self.parseline(line)
Parse the given stream
def packageRootPath(path): """ Returns the root file path that defines a Python package from the inputted path. :param path | <str> :return <str> """ path = nstr(path) if os.path.isfile(path): path = os.path.dirname(path) parts = os.path.normpath(path).spl...
Returns the root file path that defines a Python package from the inputted path. :param path | <str> :return <str>
def transform(transform_func): """Apply a transformation to a functions return value""" def decorator(func): @wraps(func) def f(*args, **kwargs): return transform_func( func(*args, **kwargs) ) return f return decorator
Apply a transformation to a functions return value
def parse_csv_headers(dataset_id): """Return the first row of a CSV as a list of headers.""" data = Dataset.objects.get(pk=dataset_id) with open(data.dataset_file.path, 'r') as datasetFile: csvReader = reader(datasetFile, delimiter=',', quotechar='"') headers = next(csvReader) # prin...
Return the first row of a CSV as a list of headers.
def populate_results_dict(self, sample, gene, total_mismatches, genome_pos, amplicon_length, contig, primer_set): """ Populate the results dictionary with the required key: value pairs :param sample: type MetadataObject: Current metadata sample to process :param gene: type STR: Gene of i...
Populate the results dictionary with the required key: value pairs :param sample: type MetadataObject: Current metadata sample to process :param gene: type STR: Gene of interest :param total_mismatches: type INT: Number of mismatches between primer pairs and subject sequence :param genom...
def highlights_worker(work_unit): '''coordinate worker wrapper around :func:`maybe_create_highlights` ''' if 'config' not in work_unit.spec: raise coordinate.exceptions.ProgrammerError( 'could not run `create_highlights` without global config') web_conf = Config() unitconf = wor...
coordinate worker wrapper around :func:`maybe_create_highlights`
def get_closest_points(self, mesh): """ For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values. """ ...
For each point in ``mesh`` find the closest surface element, and return the corresponding closest point. See :meth:`superclass method <.base.BaseSurface.get_closest_points>` for spec of input and result values.
def get_assessment_admin_session_for_bank(self, bank_id): """Gets the ``OsidSession`` associated with the assessment admin service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentAdminSession) - ``an _assessment_admin_s...
Gets the ``OsidSession`` associated with the assessment admin service for the given bank. arg: bank_id (osid.id.Id): the ``Id`` of the bank return: (osid.assessment.AssessmentAdminSession) - ``an _assessment_admin_session`` raise: NotFound - ``bank_id`` not found rai...
def get_next_assessment_part_id(self, assessment_part_id=None): """This supports the basic simple sequence case. Can be overriden in a record for other cases""" if assessment_part_id is None: part_id = self.get_id() else: part_id = assessment_part_id return get_ne...
This supports the basic simple sequence case. Can be overriden in a record for other cases
def _lookup_generic_scalar(self, obj, as_of_date, country_code, matches, missing): """ Convert asset_convertible to an asset. On success, ap...
Convert asset_convertible to an asset. On success, append to matches. On failure, append to missing.
def _add_current_usage(self, value, maximum=None, resource_id=None, aws_type=None): """ Add a new current usage value for this limit. Creates a new :py:class:`~.AwsLimitUsage` instance and appends it to the internal list. If more than one usage value i...
Add a new current usage value for this limit. Creates a new :py:class:`~.AwsLimitUsage` instance and appends it to the internal list. If more than one usage value is given to this service, they should have ``id`` and ``aws_type`` set. This method should only be called from the ...
def get_ngrok_public_url(): """Get the ngrok public HTTP URL from the local client API.""" try: response = requests.get(url=NGROK_CLIENT_API_BASE_URL + "/tunnels", headers={'content-type': 'application/json'}) response.raise_for_status() except request...
Get the ngrok public HTTP URL from the local client API.
def predict(self, X): """Predict the class labels for the provided data Parameters ---------- X : array-like, shape (n_query, n_features). Test samples. Returns ------- y : array of shape [n_samples] Class labels for each data sample. ...
Predict the class labels for the provided data Parameters ---------- X : array-like, shape (n_query, n_features). Test samples. Returns ------- y : array of shape [n_samples] Class labels for each data sample.
def create(self, chat_id=None, name=None, owner=None, user_list=None): """ 创建群聊会话 详情请参考 https://work.weixin.qq.com/api/doc#90000/90135/90245 限制说明: 只允许企业自建应用调用,且应用的可见范围必须是根部门; 群成员人数不可超过管理端配置的“群成员人数上限”,且最大不可超过500人; 每企业创建群数不可超过1000/天; :param chat_i...
创建群聊会话 详情请参考 https://work.weixin.qq.com/api/doc#90000/90135/90245 限制说明: 只允许企业自建应用调用,且应用的可见范围必须是根部门; 群成员人数不可超过管理端配置的“群成员人数上限”,且最大不可超过500人; 每企业创建群数不可超过1000/天; :param chat_id: 群聊的唯一标志,不能与已有的群重复;字符串类型,最长32个字符。只允许字符0-9及字母a-zA-Z。如果不填,系统会随机生成群id :param name: 群...
def commit_signature(vcs, user_config, signature): """Add `signature` to the list of committed signatures The signature must already be staged Args: vcs (easyci.vcs.base.Vcs) user_config (dict) signature (basestring) Raises: NotStagedError AlreadyCommittedError...
Add `signature` to the list of committed signatures The signature must already be staged Args: vcs (easyci.vcs.base.Vcs) user_config (dict) signature (basestring) Raises: NotStagedError AlreadyCommittedError
def delete(self): """ Delete this source """ r = self._client.request('DELETE', self.url) logger.info("delete(): %s", r.status_code)
Delete this source
def lineup_user(self,userid): '''Get user lineup using a ID''' headers = {"Content-type": "application/x-www-form-urlencoded","Accept": "text/plain",'Referer': 'http://'+self.domain+'/standings.phtml',"User-Agent": user_agent} req = self.session.get('http://'+self.domain+'/playerInfo.phtml?pid='...
Get user lineup using a ID
def main(): """ NAME dia_vgp.py DESCRIPTION converts declination inclination alpha95 to virtual geomagnetic pole, dp and dm SYNTAX dia_vgp.py [-h] [-i] [-f FILE] [< filename] OPTIONS -h prints help message and quits -i interactive data entry -f...
NAME dia_vgp.py DESCRIPTION converts declination inclination alpha95 to virtual geomagnetic pole, dp and dm SYNTAX dia_vgp.py [-h] [-i] [-f FILE] [< filename] OPTIONS -h prints help message and quits -i interactive data entry -f FILE to specify file na...
def title_from_content(content): """ Try and extract the first sentence from a block of test to use as a title. """ for end in (". ", "?", "!", "<br />", "\n", "</p>"): if end in content: content = content.split(end)[0] + end break return strip_tags(content)
Try and extract the first sentence from a block of test to use as a title.
def from_config(cls, cp, section, variable_args): """Returns a distribution based on a configuration file. The section must have the names of the polar and azimuthal angles in the tag part of the section header. For example: .. code-block:: ini [prior-theta+phi] ...
Returns a distribution based on a configuration file. The section must have the names of the polar and azimuthal angles in the tag part of the section header. For example: .. code-block:: ini [prior-theta+phi] name = uniform_solidangle If nothing else is provi...
def _validate(self): """ Enforce some structure to the config file """ # This could be done with a default config # Check that specific keys exist sections = odict([ ('catalog',['dirname','basename', 'lon_field','lat_field','objid_field', ...
Enforce some structure to the config file
def LoadSecondaryConfig(self, filename=None, parser=None): """Loads an additional configuration file. The configuration system has the concept of a single Primary configuration file, and multiple secondary files. The primary configuration file is the main file that is used by the program. Any writeback...
Loads an additional configuration file. The configuration system has the concept of a single Primary configuration file, and multiple secondary files. The primary configuration file is the main file that is used by the program. Any writebacks will only be made to the primary configuration file. Seconda...
def limit(self, limit): """Sets `sysparm_limit` :param limit: Size limit (int) """ if not isinstance(limit, int) or isinstance(limit, bool): raise InvalidUsage("limit size must be of type integer") self._sysparms['sysparm_limit'] = limit
Sets `sysparm_limit` :param limit: Size limit (int)
def set_default(sld, tld): ''' Sets domain to use namecheap default DNS servers. Required for free services like Host record management, URL forwarding, email forwarding, dynamic DNS and other value added services. sld SLD of the domain name tld TLD of the domain name Retu...
Sets domain to use namecheap default DNS servers. Required for free services like Host record management, URL forwarding, email forwarding, dynamic DNS and other value added services. sld SLD of the domain name tld TLD of the domain name Returns ``True`` if the domain was successf...
def execute(self): """ Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution """ ...
Execute the job, that is, execute all of its tasks. Each produced sync map will be stored inside the corresponding task object. :raises: :class:`~aeneas.executejob.ExecuteJobExecutionError`: if there is a problem during the job execution
def circuit_to_pyquil(circuit: Circuit) -> pyquil.Program: """Convert a QuantumFlow circuit to a pyQuil program""" prog = pyquil.Program() for elem in circuit.elements: if isinstance(elem, Gate) and elem.name in QUIL_GATES: params = list(elem.params.values()) if elem.params else [] ...
Convert a QuantumFlow circuit to a pyQuil program
def get_expiration_date(self, fn): """ Reads the expiration date of a local crt file. """ r = self.local_renderer r.env.crt_fn = fn with hide('running'): ret = r.local('openssl x509 -noout -in {ssl_crt_fn} -dates', capture=True) matches = re.findall('n...
Reads the expiration date of a local crt file.
def to_unicode(sorb, allow_eval=False): r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever...
r"""Ensure that strings are unicode (UTF-8 encoded). Evaluate bytes literals that are sometimes accidentally created by str(b'whatever') >>> to_unicode(b'whatever') 'whatever' >>> to_unicode(b'b"whatever"') 'whatever' >>> to_unicode(repr(b'b"whatever"')) 'whatever' >>> to_unicode(str(b...
def edit_txt(filename, substitutions, newname=None): """Primitive text file stream editor. This function can be used to edit free-form text files such as the topology file. By default it does an **in-place edit** of *filename*. If *newname* is supplied then the edited file is written to *newname*. ...
Primitive text file stream editor. This function can be used to edit free-form text files such as the topology file. By default it does an **in-place edit** of *filename*. If *newname* is supplied then the edited file is written to *newname*. :Arguments: *filename* input text fil...
def league_info(): """Returns a dictionary of league information""" league = __get_league_object() output = {} for x in league.attrib: output[x] = league.attrib[x] return output
Returns a dictionary of league information
def _bn(editor, force=False): """ Go to next buffer. """ eb = editor.window_arrangement.active_editor_buffer if not force and eb.has_unsaved_changes: editor.show_message(_NO_WRITE_SINCE_LAST_CHANGE_TEXT) else: editor.window_arrangement.go_to_next_buffer()
Go to next buffer.
def term(self): """ term: atom (('*' | '/' | '//') atom)* """ node = self.atom() while self.token.nature in (Nature.MUL, Nature.DIV, Nature.INT_DIV): token = self.token if token.nature == Nature.MUL: self._process(Nature.MUL) e...
term: atom (('*' | '/' | '//') atom)*
def get_project_name(project_id, projects): """Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match """ for project in projects: if project_id == project.id: return...
Retrieves project name for given project id Args: projects: List of projects project_id: project id Returns: Project name or None if there is no match
def get_url(self, name, view_name, kwargs, request): """ Given a name, view name and kwargs, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf. """ ...
Given a name, view name and kwargs, return the URL that hyperlinks to the object. May raise a `NoReverseMatch` if the `view_name` and `lookup_field` attributes are not configured to correctly match the URL conf.
def attach(self, instance_id, device): """ Attach this EBS volume to an EC2 instance. :type instance_id: str :param instance_id: The ID of the EC2 instance to which it will be attached. :type device: str :param device: The device on the insta...
Attach this EBS volume to an EC2 instance. :type instance_id: str :param instance_id: The ID of the EC2 instance to which it will be attached. :type device: str :param device: The device on the instance through which the volume will be...
def register_agent(self, host, sweep_id=None, project_name=None): """Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep """ mutatio...
Register a new agent Args: host (str): hostname persistent (bool): long running or oneoff sweep (str): sweep id project_name: (str): model that contains sweep
def activate(self, profile_name=NotSet): """ Sets <PROFILE_ROOT>_PROFILE environment variable to the name of the current profile. """ if profile_name is NotSet: profile_name = self.profile_name self._active_profile_name = profile_name
Sets <PROFILE_ROOT>_PROFILE environment variable to the name of the current profile.
def _relation(self, id, join_on, join_to, level=None, featuretype=None, order_by=None, reverse=False, completely_within=False, limit=None): # The following docstring will be included in the parents() and # children() docstrings to maintain consistency, since they bot...
Parameters ---------- id : string or a Feature object level : None or int If `level=None` (default), then return all children regardless of level. If `level` is an integer, then constrain to just that level. {_method_doc} Returns -...
def _enough_time_has_passed(self, FPS): '''For limiting how often frames are computed.''' if FPS == 0: return False else: earliest_time = self.last_update_time + (1.0 / FPS) return time.time() >= earliest_time
For limiting how often frames are computed.
def scale(config=None, name=None, replicas=None): """ Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas:...
Scales the number of pods in the specified K8sReplicationController to the desired replica count. :param config: an instance of K8sConfig :param name: the name of the ReplicationController we want to scale. :param replicas: the desired number of replicas. :return: An instance of K8sR...
def image_exists(self, id=None, tag=None): """ Check if specified image exists """ exists = False if id and self.image_by_id(id): exists = True elif tag and self.image_by_tag(tag): exists = True return exists
Check if specified image exists
def iter_transport_opts(opts): ''' Yield transport, opts for all master configured transports ''' transports = set() for transport, opts_overrides in six.iteritems(opts.get('transport_opts', {})): t_opts = dict(opts) t_opts.update(opts_overrides) t_opts['transport'] = transp...
Yield transport, opts for all master configured transports
def date_time_this_month( self, before_now=True, after_now=False, tzinfo=None): """ Gets a DateTime object for the current month. :param before_now: include days in current month before today :param after_now: include days in current month...
Gets a DateTime object for the current month. :param before_now: include days in current month before today :param after_now: include days in current month after today :param tzinfo: timezone, instance of datetime.tzinfo subclass :example DateTime('2012-04-04 11:02:02') :return ...
async def register_user(self, password, **kwds): """ This function is used to provide a sessionToken for later requests. Args: uid (str): The """ # so make one user = await self._create_remote_user(password=password, **kwds) # if there is ...
This function is used to provide a sessionToken for later requests. Args: uid (str): The
def missing_some(data, min_required, args): """Implements the missing_some operator for finding missing variables.""" if min_required < 1: return [] found = 0 not_found = object() ret = [] for arg in args: if get_var(data, arg, not_found) is not_found: ret.append(arg)...
Implements the missing_some operator for finding missing variables.
def _build(self, one_hot_input_sequence): """Builds the deep LSTM model sub-graph. Args: one_hot_input_sequence: A Tensor with the input sequence encoded as a one-hot representation. Its dimensions should be `[truncation_length, batch_size, output_size]`. Returns: Tuple of the ...
Builds the deep LSTM model sub-graph. Args: one_hot_input_sequence: A Tensor with the input sequence encoded as a one-hot representation. Its dimensions should be `[truncation_length, batch_size, output_size]`. Returns: Tuple of the Tensor of output logits for the batch, with dimen...
def get_param_type_indexes(self, data, name=None, prev=None): """Get from a docstring a parameter type indexes. In javadoc style it is after @type. :param data: string to parse :param name: the name of the parameter (Default value = None) :param prev: index after the previous el...
Get from a docstring a parameter type indexes. In javadoc style it is after @type. :param data: string to parse :param name: the name of the parameter (Default value = None) :param prev: index after the previous element (param or param's description) (Default value = None) :retu...
def lifter(cepstra, L=22): """Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. :param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size. :param L: the liftering coefficient to use. Default is 22. L ...
Apply a cepstral lifter the the matrix of cepstra. This has the effect of increasing the magnitude of the high frequency DCT coeffs. :param cepstra: the matrix of mel-cepstra, will be numframes * numcep in size. :param L: the liftering coefficient to use. Default is 22. L <= 0 disables lifter.
def style(self): """Function to apply some styles to the layers.""" LOGGER.info('ANALYSIS : Styling') classes = generate_classified_legend( self.analysis_impacted, self.exposure, self.hazard, self.use_rounding, self.debug_mode) ...
Function to apply some styles to the layers.
def find_frametype(self, gpstime=None, frametype_match=None, host=None, port=None, return_all=False, allow_tape=True): """Find the containing frametype(s) for this `Channel` Parameters ---------- gpstime : `int` a reference GPS t...
Find the containing frametype(s) for this `Channel` Parameters ---------- gpstime : `int` a reference GPS time at which to search for frame files frametype_match : `str` a regular expression string to use to down-select from the list of all available ...
def split(self, length, vertical=True): """ Returns two bounding boxes representing the current bounds split into two smaller boxes. Parameters ------------- length: float, length to split vertical: bool, if True will split box vertically Returns ...
Returns two bounding boxes representing the current bounds split into two smaller boxes. Parameters ------------- length: float, length to split vertical: bool, if True will split box vertically Returns ------------- box: (2,4) float, two bounding boxe...
def wait_for_response(client, timeout, path='/', expected_status_code=None): """ Try make a GET request with an HTTP client against a certain path and return once any response has been received, ignoring any errors. :param ContainerHttpClient client: The HTTP client to use to connect to the con...
Try make a GET request with an HTTP client against a certain path and return once any response has been received, ignoring any errors. :param ContainerHttpClient client: The HTTP client to use to connect to the container. :param timeout: Timeout value in seconds. :param path: HT...
def call(self, task, decorators=None): """ Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / Tas...
Call given task on service layer. :param task: task to be called. task will be decorated with TaskDecorator's contained in 'decorators' list :type task: instance of Task class :param decorators: list of TaskDecorator's / TaskResultDecorator's inherited classes :t...
def parse_metric_family(buf): """ Parse the binary buffer in input, searching for Prometheus messages of type MetricFamily [0] delimited by a varint32 [1]. [0] https://github.com/prometheus/client_model/blob/086fe7ca28bde6cec2acd5223423c1475a362858/metrics.proto#L76-%20%20L81 # noqa: E501 [1] http...
Parse the binary buffer in input, searching for Prometheus messages of type MetricFamily [0] delimited by a varint32 [1]. [0] https://github.com/prometheus/client_model/blob/086fe7ca28bde6cec2acd5223423c1475a362858/metrics.proto#L76-%20%20L81 # noqa: E501 [1] https://developers.google.com/protocol-buffers...
def add_matches(self): """Adds all regular expressions declared in guake.globals.TERMINAL_MATCH_EXPRS to the terminal to make vte highlight text that matches them. """ try: # NOTE: PCRE2_UTF | PCRE2_NO_UTF_CHECK | PCRE2_MULTILINE # reference from vte/bindi...
Adds all regular expressions declared in guake.globals.TERMINAL_MATCH_EXPRS to the terminal to make vte highlight text that matches them.
def south_field_triple(self): """ Returns a suitable description of this field for South. """ # We'll just introspect the _actual_ field. from south.modelsinspector import introspector try: # Check if the field provides its own 'field_class': field...
Returns a suitable description of this field for South.
def get_thellier_gui_meas_mapping(input_df, output=2): """ Get the appropriate mapping for translating measurements in Thellier GUI. This requires special handling for treat_step_num/measurement/measurement_number. Parameters ---------- input_df : pandas DataFrame MagIC records outp...
Get the appropriate mapping for translating measurements in Thellier GUI. This requires special handling for treat_step_num/measurement/measurement_number. Parameters ---------- input_df : pandas DataFrame MagIC records output : int output to this MagIC data model (2 or 3) Outp...
def parse_import_directory(self, rva, size): """Walk and parse the import directory.""" import_descs = [] while True: try: # If the RVA is invalid all would blow up. Some EXEs seem to be # specially nasty and have an invalid RVA. ...
Walk and parse the import directory.
def _succeed(self, request_id, reply, duration): """Publish a CommandSucceededEvent.""" self.listeners.publish_command_success( duration, reply, self.name, request_id, self.sock_info.address, self.op_id)
Publish a CommandSucceededEvent.
async def get_resource(self, resource_id: int) -> dict: """Get a single resource. :raises PvApiError when a hub connection occurs.""" resource = await self.request.get( join_path(self._base_path, str(resource_id)) ) self._sanitize_resource(self._get_to_actual_data(re...
Get a single resource. :raises PvApiError when a hub connection occurs.
def _get_item(self, package, flavor): """Returns the item for ordering a dedicated host.""" for item in package['items']: if item['keyName'] == flavor: return item raise SoftLayer.SoftLayerError("Could not find valid item for: '%s'" % flavor)
Returns the item for ordering a dedicated host.
def apply_T7(word): '''If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as].''' WORD = _split_consonants_and_vowels(word) for k, v in WORD.iteritems(): if len(v) == 3 and is_v...
If a VVV-sequence does not contain a potential /i/-final diphthong, there is a syllable boundary between the second and third vowels, e.g. [kau.an], [leu.an], [kiu.as].
def make_target(url, extra_opts=None): """Factory that creates `_Target` objects from URLs. FTP targets must begin with the scheme ``ftp://`` or ``ftps://`` for TLS. Note: TLS is only supported on Python 2.7/3.2+. Args: url (str): extra_opts (dict, optional): Passed to Target c...
Factory that creates `_Target` objects from URLs. FTP targets must begin with the scheme ``ftp://`` or ``ftps://`` for TLS. Note: TLS is only supported on Python 2.7/3.2+. Args: url (str): extra_opts (dict, optional): Passed to Target constructor. Default: None. Returns: ...
def delete(self, save=True): """ Deletes the original, plus any thumbnails. Fails silently if there are errors deleting the thumbnails. """ for thumb in self.field.thumbs: thumb_name, thumb_options = thumb thumb_filename = self._calc_thumb_filename(thumb_n...
Deletes the original, plus any thumbnails. Fails silently if there are errors deleting the thumbnails.
def create(self): """ Creates the current document in the remote database and if successful, updates the locally cached Document object with the ``_id`` and ``_rev`` returned as part of the successful response. """ # Ensure that an existing document will not be "updated"...
Creates the current document in the remote database and if successful, updates the locally cached Document object with the ``_id`` and ``_rev`` returned as part of the successful response.
def _get_register_specs(bit_labels): """Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register na...
Get the number and size of unique registers from bit_labels list. Args: bit_labels (list): this list is of the form:: [['reg1', 0], ['reg1', 1], ['reg2', 0]] which indicates a register named "reg1" of size 2 and a register named "reg2" of size 1. This is the ...
def _render_log(): """Totally tap into Towncrier internals to get an in-memory result. """ config = load_config(ROOT) definitions = config['types'] fragments, fragment_filenames = find_fragments( pathlib.Path(config['directory']).absolute(), config['sections'], None, ...
Totally tap into Towncrier internals to get an in-memory result.
def sort_against(list1, list2, reverse=False): """ Arrange items of list1 in the same order as sorted(list2). In other words, apply to list1 the permutation which takes list2 to sorted(list2, reverse). """ try: return [item for _, item in sorted(zip(list2, list1), key=...
Arrange items of list1 in the same order as sorted(list2). In other words, apply to list1 the permutation which takes list2 to sorted(list2, reverse).
def copy(self, memo=None, which=None): """ Returns a (deep) copy of the current parameter handle. All connections to parents of the copy will be cut. :param dict memo: memo for deepcopy :param Parameterized which: parameterized object which started the copy process [default: se...
Returns a (deep) copy of the current parameter handle. All connections to parents of the copy will be cut. :param dict memo: memo for deepcopy :param Parameterized which: parameterized object which started the copy process [default: self]
def _balance_braces(tokens, filename=None): """Raises syntax errors if braces aren't balanced""" depth = 0 for token, line, quoted in tokens: if token == '}' and not quoted: depth -= 1 elif token == '{' and not quoted: depth += 1 # raise error if we ever hav...
Raises syntax errors if braces aren't balanced