code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def unproxy(possible_proxy): ''' Unwrap and return the object referenced by a proxy. This function is very similar to :func:`get_reference`, but works for both proxies and regular objects. If the specified object is a proxy, its reference is extracted with ``get_reference`` and ...
Unwrap and return the object referenced by a proxy. This function is very similar to :func:`get_reference`, but works for both proxies and regular objects. If the specified object is a proxy, its reference is extracted with ``get_reference`` and returned. If it is not a proxy, it is ret...
def serialize_symbol(ctx, document, el, root): "Serialize special symbols." span = etree.SubElement(root, 'span') span.text = el.value() fire_hooks(ctx, document, el, span, ctx.get_hook('symbol')) return root
Serialize special symbols.
def hash_sha512(self): """Calculates sha512 fingerprint.""" fp_plain = hashlib.sha512(self._decoded_key).digest() return (b"SHA512:" + base64.b64encode(fp_plain).replace(b"=", b"")).decode("utf-8")
Calculates sha512 fingerprint.
def truncate(self, max_length): """Truncate this vector so it's length does not exceed max.""" if self.length() > max_length: # If it's longer than the max_length, scale to the max_length. self.scale(max_length / self.length())
Truncate this vector so it's length does not exceed max.
def _scope_vars(scope, trainable_only=False): """ Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were...
Get variables inside a scope The scope can be specified as a string Parameters ---------- scope: str or VariableScope scope in which the variables reside. trainable_only: bool whether or not to return only the variables that were marked as trainable. Returns ------- v...
def SA_ellipsoidal_head(D, a): r'''Calculates the surface area of an ellipsoidal head according to [1]_. Formula below is for the full shape, the result of which is halved. The formula also does not support `D` being larger than `a`; this is ensured by simply swapping the variables if necessary, as geom...
r'''Calculates the surface area of an ellipsoidal head according to [1]_. Formula below is for the full shape, the result of which is halved. The formula also does not support `D` being larger than `a`; this is ensured by simply swapping the variables if necessary, as geometrically the result is the sam...
def get_issue_by_ref(self, ref): """ Get a :class:`Issue` by ref. :param ref: :class:`Issue` reference """ response = self.requester.get( '/{endpoint}/by_ref?ref={us_ref}&project={project_id}', endpoint=Issue.endpoint, us_ref=ref, ...
Get a :class:`Issue` by ref. :param ref: :class:`Issue` reference
def friend_addRow(self, rowNum, row): """used only by parser: adds a row of columns""" self[rowNum] = row if (rowNum > self.maxRow): self.maxRow = rowNum for cellNum in row.keys(): if cellNum > self.m...
used only by parser: adds a row of columns
def set_system_date_time(years=None, months=None, days=None, hours=None, minutes=None, seconds=None, utc_offset=None): ''' Set the system date and time. Each argu...
Set the system date and time. Each argument is an element of the date, but not required. If an element is not passed, the current system value for that element will be used. For example, if you don't pass the year, the current system year will be used. (Used by set_system_date and set_system_time) ...
def _get_sof_terms(self, C, rake): """ Returns the style-of-faulting scaling parameters """ if rake >= 45.0 and rake <= 135.0: # Reverse faulting return C["b0R"], C["b1R"] elif rake <= -45. and rake >= -135.0: # Normal faulting retu...
Returns the style-of-faulting scaling parameters
def add_node(self, tax_id, parent_id, rank, names, source_name, children=None, is_valid=True, execute=True, **ignored): """Add a node to the taxonomy. ``source_name`` is added to table "source" if necessary. """ if ignored: log.info('some arguments were ig...
Add a node to the taxonomy. ``source_name`` is added to table "source" if necessary.
def click(self) -> None: """Send click event.""" if self.connected: self.js_exec('click') else: # Web上に表示されてれば勝手にブラウザ側からクリックイベント発生する # のでローカルのクリックイベント不要 msg = {'proto': '', 'type': 'click', 'currentTarget': {'id': self.wdom_id}, ...
Send click event.
def add_node(self, transformer, name=None, children=None, parent=None, parameters={}, return_node=False): ''' Adds a node to the current graph. Args: transformer (str, Transformer): The pliers Transformer to use at the to-be-added node. Either a case-insensi...
Adds a node to the current graph. Args: transformer (str, Transformer): The pliers Transformer to use at the to-be-added node. Either a case-insensitive string giving the name of a Transformer class, or an initialized Transformer instance. ...
def create(cls, domain, source, destinations): """Create a domain mail forward.""" cls.echo('Creating mail forward %s@%s' % (source, domain)) options = {'destinations': list(destinations)} result = cls.call('domain.forward.create', domain, source, options) return result
Create a domain mail forward.
def state_transition( mediator_state: Optional[MediatorTransferState], state_change: StateChange, channelidentifiers_to_channels: ChannelMap, nodeaddresses_to_networkstates: NodeNetworkStateMap, pseudo_random_generator: random.Random, block_number: BlockNumber, bl...
State machine for a node mediating a transfer.
def http_basic_auth(request): """ Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request ...
Extracts the credentials of a client using HTTP Basic Auth. Expects the ``client_id`` to be the username and the ``client_secret`` to be the password part of the Authorization header. :param request: The incoming request :type request: oauth2.web.Request :return: A tuple in the format of (<CLIENT...
def confidence_interval_hazard_(self): """ The confidence interval of the hazard. """ return self._compute_confidence_bounds_of_transform(self._hazard, self.alpha, self._ci_labels)
The confidence interval of the hazard.
def _get_configs_path(): """Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files """ paths...
Get a list of possible configuration files, from the following sources: 1. All files that exists in constants.CONFS_PATH. 2. All XDG standard config files for "lago.conf", in reversed order of importance. Returns: list(str): list of files
def send_frame(self, frame): """ Sends a frame to connected socket client. @param frame: The frame to send. @type frame: C{stompclient.frame.Frame} """ packed = frame.pack() if self.debug: # pragma: no cover self.log.debug("SEND: %r" % packed) self.r...
Sends a frame to connected socket client. @param frame: The frame to send. @type frame: C{stompclient.frame.Frame}
def setDisallowed(self, laneID, disallowedClasses): """setDisallowed(string, list) -> None Sets a list of disallowed vehicle classes. """ if isinstance(disallowedClasses, str): disallowedClasses = [disallowedClasses] self._connection._beginMessage(tc.CMD_SET_LANE_VAR...
setDisallowed(string, list) -> None Sets a list of disallowed vehicle classes.
def close(self): """Close the pooled shared connection.""" # Instead of actually closing the connection, # unshare it and/or return it to the pool. if self._con: self._pool.unshare(self._shared_con) self._shared_con = self._con = None
Close the pooled shared connection.
def dict_from_file(filename, key_type=str): """Load a text file and parse the content as a dict. Each line of the text file will be two or more columns splited by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Args: ...
Load a text file and parse the content as a dict. Each line of the text file will be two or more columns splited by whitespaces or tabs. The first column will be parsed as dict keys, and the following columns will be parsed as dict values. Args: filename(str): Filename. key_type(type):...
def simDeath(self): ''' Trivial function that returns boolean array of all False, as there is no death. Parameters ---------- None Returns ------- which_agents : np.array(bool) Boolean array of size AgentCount indicating which agents die. ...
Trivial function that returns boolean array of all False, as there is no death. Parameters ---------- None Returns ------- which_agents : np.array(bool) Boolean array of size AgentCount indicating which agents die.
def bed(args): """ %prog bed fastafile kmer.dump.txt Map kmers on FASTA. """ from jcvi.formats.fasta import rc, parse_fasta p = OptionParser(bed.__doc__) opts, args = p.parse_args(args) if len(args) != 2: sys.exit(not p.print_help()) fastafile, dumpfile = args fp = op...
%prog bed fastafile kmer.dump.txt Map kmers on FASTA.
def escapeUnderscores(self): """ Escape underscores so that the markdown is correct """ new_metrics = [] for m in self.metrics: m['name'] = m['name'].replace("_", "\_") new_metrics.append(m) self.metrics = new_metrics
Escape underscores so that the markdown is correct
def convert_to_shape(self, origin_x=0, origin_y=0): """Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. ...
Return new freeform shape positioned relative to specified offset. *origin_x* and *origin_y* locate the origin of the local coordinate system in slide coordinates (EMU), perhaps most conveniently by use of a |Length| object. Note that this method may be called more than once to add mul...
def remover(self, id_equipment, id_environment): """Remove Related Equipment with Environment from by the identifier. :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :param id_environment: Identifier of the Environment. Integer value and greater than zero....
Remove Related Equipment with Environment from by the identifier. :param id_equipment: Identifier of the Equipment. Integer value and greater than zero. :param id_environment: Identifier of the Environment. Integer value and greater than zero. :return: None :raise InvalidParameterErro...
def write_samples(self, samples, parameters=None, last_iteration=None): """Writes samples to the given file. Results are written to ``samples_group/{vararg}``, where ``{vararg}`` is the name of a model params. The samples are written as an ``nwalkers x niterations`` array. If samples al...
Writes samples to the given file. Results are written to ``samples_group/{vararg}``, where ``{vararg}`` is the name of a model params. The samples are written as an ``nwalkers x niterations`` array. If samples already exist, the new samples are appended to the current. If the c...
def ws025(self, value=None): """ Corresponds to IDD Field `ws025` Wind speed corresponding to 2.5% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws025` Unit: m/s if `value` is None it will not be checked against ...
Corresponds to IDD Field `ws025` Wind speed corresponding to 2.5% annual cumulative frequency of occurrence Args: value (float): value for IDD Field `ws025` Unit: m/s if `value` is None it will not be checked against the specification and is a...
def from_text(text, origin = None, rdclass = dns.rdataclass.IN, relativize = True, zone_factory=Zone, filename=None, allow_include=False, check_origin=True): """Build a zone object from a master file format string. @param text: the master file format input @type text: string. ...
Build a zone object from a master file format string. @param text: the master file format input @type text: string. @param origin: The origin of the zone; if not specified, the first $ORIGIN statement in the master file will determine the origin of the zone. @type origin: dns.name.Name object o...
def parse(self): '''parse is the base function for parsing the recipe, whether it be a Dockerfile or Singularity recipe. The recipe is read in as lines, and saved to a list if needed for the future. If the client has it, the recipe type specific _parse function is called. ...
parse is the base function for parsing the recipe, whether it be a Dockerfile or Singularity recipe. The recipe is read in as lines, and saved to a list if needed for the future. If the client has it, the recipe type specific _parse function is called. Instructions for makin...
def dumps(obj, **kwargs): """ Serialize `obj`, which may contain :class:`JsonRef` objects, to a JSON formatted string. `JsonRef` objects will be dumped as the original reference object they were created from. :param obj: Object to serialize :param kwargs: Keyword arguments are the same as to :f...
Serialize `obj`, which may contain :class:`JsonRef` objects, to a JSON formatted string. `JsonRef` objects will be dumped as the original reference object they were created from. :param obj: Object to serialize :param kwargs: Keyword arguments are the same as to :func:`json.dumps`
def get_hoisted(dct, child_name): """Pulls all of a child's keys up to the parent, with the names unchanged.""" child = dct[child_name] del dct[child_name] dct.update(child) return dct
Pulls all of a child's keys up to the parent, with the names unchanged.
def do_py(self, arg): """ :: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive pyth...
:: Usage: py py COMMAND Arguments: COMMAND the command to be executed Description: The command without a parameter will be executed and the interactive python mode is entered. The python mode can be...
def fromFile(cls, filename): """From File Loads a JSON file and creates a Node instance from it Args: filename (str): The filename to load Returns: _NodeInterface """ # Load the file oFile = open(filename) # Convert it to a dictionary dDetails = JSON.decodef(oFile) # Create and return th...
From File Loads a JSON file and creates a Node instance from it Args: filename (str): The filename to load Returns: _NodeInterface
def massradius(age, planetdist, coremass, mass='massjupiter', radius='radiusjupiter'): '''This function gets the Fortney mass-radius relation for planets. Parameters ---------- age : float This should be one of: 0.3, 1.0, 4.5 [in Gyr]. planetdist : float ...
This function gets the Fortney mass-radius relation for planets. Parameters ---------- age : float This should be one of: 0.3, 1.0, 4.5 [in Gyr]. planetdist : float This should be one of: 0.02, 0.045, 0.1, 1.0, 9.5 [in AU] coremass : int This should be one of: 0, 10, 25, ...
def StopTiming(self, profile_name): """Stops timing CPU time. Args: profile_name (str): name of the profile to sample. """ measurements = self._profile_measurements.get(profile_name) if measurements: measurements.SampleStop() sample = '{0:f}\t{1:s}\t{2:f}\n'.format( mea...
Stops timing CPU time. Args: profile_name (str): name of the profile to sample.
def save_request_token(self, token, request): """Save request token to database. A grantsetter is required, which accepts a token and request parameters:: def grantsetter(token, request): grant = Grant( token=token['oauth_token'], ...
Save request token to database. A grantsetter is required, which accepts a token and request parameters:: def grantsetter(token, request): grant = Grant( token=token['oauth_token'], secret=token['oauth_token_secret'], ...
def plot_cdf(self, n=(0, 1, 2, 3), d_min=None, d_max=None, pts=500, method='logarithmic'): # pragma: no cover r'''Plot the cumulative distribution function of the particle size distribution. The plotted range can be specified using `d_min` and `d_max`, or estimated automatic...
r'''Plot the cumulative distribution function of the particle size distribution. The plotted range can be specified using `d_min` and `d_max`, or estimated automatically. One or more order can be plotted, by providing an iterable of ints as the value of `n` or just one int. ...
def run(arguments: List[str], execution_directory: str=None, execution_environment: Dict=None) -> str: """ Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory). :param arguments: the CLI arguments to run :param execution_directory: the directory...
Runs the given arguments from the given directory (if given, else resorts to the (undefined) current directory). :param arguments: the CLI arguments to run :param execution_directory: the directory to execute the arguments in :param execution_environment: the environment to execute in :return: what is w...
def calculate_bar_widths(self, size, bardata): """ Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol. """ (maxcol, _) = size if self.bar_width...
Return a list of bar widths, one for each bar in data. If self.bar_width is None this implementation will stretch the bars across the available space specified by maxcol.
def _allocate_channel(self): """ Allocate a new AMQP channel. Raises: NoFreeChannels: If this connection has reached its maximum number of channels. """ try: channel = yield self.channel() except pika.exceptions.NoFreeChannels: raise N...
Allocate a new AMQP channel. Raises: NoFreeChannels: If this connection has reached its maximum number of channels.
def write(self, data: bytes) -> None: """ Write the data. """ if self.finished(): if self._exc: raise self._exc raise WriteAfterFinishedError if not data: return try: self._delegate.write_data(data, finish...
Write the data.
def concat(cartesians, ignore_index=False, keys=None): """Join list of cartesians into one molecule. Wrapper around the :func:`pandas.concat` function. Default values are the same as in the pandas function except for ``verify_integrity`` which is set to true in case of this library. Args: ...
Join list of cartesians into one molecule. Wrapper around the :func:`pandas.concat` function. Default values are the same as in the pandas function except for ``verify_integrity`` which is set to true in case of this library. Args: ignore_index (sequence, bool, int): If it is a boolean, it ...
def reset_password(self, token, new_password): """Reset password using a token received in email then logs user in.""" user = self.validated_user( token, purpose=HashPurpose.PASSWORD_RESET, minutes_valid=HASH_MINUTES_VALID[HashPurpose.PASSWORD_RESET], ) user.set_p...
Reset password using a token received in email then logs user in.
def join_sources(source_module: DeploymentModule, contract_name: str): """ Use join-contracts.py to concatenate all imported Solidity files. Args: source_module: a module name to look up contracts_source_path() contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc. """ joined_file...
Use join-contracts.py to concatenate all imported Solidity files. Args: source_module: a module name to look up contracts_source_path() contract_name: 'TokenNetworkRegistry', 'SecretRegistry' etc.
def struct_from_value( cls, name, volume, channel_list=None, mute=False, device=None ): 'Same arguments as with class instance init.' chan_map = c.PA_CHANNEL_MAP() if not channel_list: c.pa.channel_map_init_mono(chan_map) else: if not is_str(channel_list): channel_list = b','.join(map(c.force_bytes, c...
Same arguments as with class instance init.
def scopes(self, scopes): """Set scopes. :param scopes: The list of scopes. """ validate_scopes(scopes) self._scopes = " ".join(set(scopes)) if scopes else ""
Set scopes. :param scopes: The list of scopes.
def get_json(self, instance=True, origin='openconfig'): '''get_json High-level api: get_json returns json_val of the config node. Parameters ---------- instance : `bool` True if only one instance of list or leaf-list is required. False if all instances ...
get_json High-level api: get_json returns json_val of the config node. Parameters ---------- instance : `bool` True if only one instance of list or leaf-list is required. False if all instances of list or leaf-list are needed. Returns ------- ...
def value_percent(self): """ [float] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围[0, 1] """ accounts = Environment.get_instance().portfolio.accounts if DEFAULT_ACCOUNT_TYPE.STOCK.name not in accounts: return 0 total_value = accounts[DEFAULT_ACCOUNT_TYPE.STOCK.name].total_v...
[float] 获得该持仓的实时市场价值在股票投资组合价值中所占比例,取值范围[0, 1]
def ancestor(qobject, classType): """ Looks up the ancestor of the inputed QObject based on the given class type. :param qobject | <QObject> classType | <subclass of QObject> || <str> :return <subclass of QObject> || None """ parent = qobject is...
Looks up the ancestor of the inputed QObject based on the given class type. :param qobject | <QObject> classType | <subclass of QObject> || <str> :return <subclass of QObject> || None
def _compat_get_str_key_for_index(self, indexedField, val): ''' _compat_get_str_key_for_index - Return the key name as a string, even if it is a hashed index field. This is used in converting unhashed fields to a hashed index (called by _compat_rem_str_id_from_index which is called by compat_convertHashedInde...
_compat_get_str_key_for_index - Return the key name as a string, even if it is a hashed index field. This is used in converting unhashed fields to a hashed index (called by _compat_rem_str_id_from_index which is called by compat_convertHashedIndexes) @param inde @param indexedField - string of field name ...
def isfile_strict(path): """Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html """ try: st = os.stat(path) except OSError: err = sys.exc_info()[1] if err.errno in (errno.EPERM, er...
Same as os.path.isfile() but does not swallow EACCES / EPERM exceptions, see: http://mail.python.org/pipermail/python-dev/2012-June/120787.html
def fetch_recent_submissions(self, max_duration): """Fetch recent submissions in subreddit with boundaries. Does not include posts within the last day as their scores may not be representative. :param max_duration: When set, specifies the number of days to include """ ...
Fetch recent submissions in subreddit with boundaries. Does not include posts within the last day as their scores may not be representative. :param max_duration: When set, specifies the number of days to include
def get_headers_lang (headers): """Return preferred supported language in given HTTP headers.""" if 'Accept-Language' not in headers: return default_language languages = headers['Accept-Language'].split(",") # sort with preference values pref_languages = [] for lang in languages: ...
Return preferred supported language in given HTTP headers.
def QuickAddEvent(self, event_text, reminders=None): """Wrapper around Google Calendar API's quickAdd""" if not event_text: raise GcalcliError('event_text is required for a quickAdd') if len(self.cals) != 1: # TODO: get a better name for this exception class ...
Wrapper around Google Calendar API's quickAdd
def init(opts): ''' This function gets called when the proxy starts up. ''' if 'host' not in opts['proxy']: log.critical('No \'host\' key found in pillar for this proxy.') return False if 'username' not in opts['proxy']: log.critical('No \'username\' key found in pillar for t...
This function gets called when the proxy starts up.
def get_default_config(self): """ Return default config for the handler """ config = super(DatadogHandler, self).get_default_config() config.update({ 'api_key': '', 'queue_size': '', }) return config
Return default config for the handler
def get_device_info(self): """Parse deviceInfo into dictionary.""" device_info = {} url = '%s/ISAPI/System/deviceInfo' % self.root_url using_digest = False try: response = self.hik_request.get(url, timeout=CONNECT_TIMEOUT) if response.status_code == reque...
Parse deviceInfo into dictionary.
def update(self, cache): """ Update self cache from other. """ self.cache['delims'] = cache.get('delims') self.cache['opts'].update(cache.get('opts')) self.cache['rset'].update(cache.get('rset')) self.cache['mix'].update(cache.get('mix')) map(self.set_var, cache['...
Update self cache from other.
def decode_file_iter(file_obj, codec_options=DEFAULT_CODEC_OPTIONS): """Decode bson data from a file to multiple documents as a generator. Works similarly to the decode_all function, but reads from the file object in chunks and parses bson in chunks, yielding one document at a time. :Parameters: ...
Decode bson data from a file to multiple documents as a generator. Works similarly to the decode_all function, but reads from the file object in chunks and parses bson in chunks, yielding one document at a time. :Parameters: - `file_obj`: A file object containing BSON data. - `codec_options` (...
def get_authorizations_by_genus_type(self, authorization_genus_type): """Gets an ``AuthorizationList`` corresponding to the given authorization genus ``Type`` which does not include authorizations of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known ...
Gets an ``AuthorizationList`` corresponding to the given authorization genus ``Type`` which does not include authorizations of genus types derived from the specified ``Type``. In plenary mode, the returned list contains all known authorizations or an error results. Otherwise, the returned list ...
def _construct_lookup_table(self, polynomial): """Precomputes a CRC-64 lookup table seeded from the supplied polynomial. No return value. """ self._lookup_table = [] for i in range(0, 256): lookup_value = i for _ in range(0, 8): if lo...
Precomputes a CRC-64 lookup table seeded from the supplied polynomial. No return value.
def protect(self, password=None, read_protect=False, protect_from=0): """The implementation of :meth:`nfc.tag.Tag.protect` for a generic type 1 tag is limited to setting the NDEF data read-only for tags that are already NDEF formatted. """ return super(Type1Tag, self).protect( ...
The implementation of :meth:`nfc.tag.Tag.protect` for a generic type 1 tag is limited to setting the NDEF data read-only for tags that are already NDEF formatted.
def process_js_mod(self, data, name, idx, sub_idx): """ Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return: """ if isinstance(data, (int, long)): js = collections.OrderedDict() js['t...
Processes one moduli from JSON :param data: :param name: :param idx: :param sub_idx: :return:
def _evaluate(self,R,z,phi=0.,t=0.): """ NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) ...
NAME: _evaluate PURPOSE: evaluate the potential at R,z INPUT: R - Galactocentric cylindrical radius z - vertical height phi - azimuth t - time OUTPUT: Phi(R,z) HISTORY: 2015-02-07 - Written - Bovy (IA...
def stop(self): """Close websocket connection.""" self.state = STATE_STOPPED if self.transport: self.transport.close()
Close websocket connection.
def generate_nodes(tpm, cm, network_state, indices, node_labels=None): """Generate |Node| objects for a subsystem. Args: tpm (np.ndarray): The system's TPM cm (np.ndarray): The corresponding CM. network_state (tuple): The state of the network. indices (tuple[int]): Indices to ge...
Generate |Node| objects for a subsystem. Args: tpm (np.ndarray): The system's TPM cm (np.ndarray): The corresponding CM. network_state (tuple): The state of the network. indices (tuple[int]): Indices to generate nodes for. Keyword Args: node_labels (|NodeLabels|): Textu...
def get_handlers(self, component_context, instance): """ Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component """ ...
Sets up service providers for the given component :param component_context: The ComponentContext bean :param instance: The component instance :return: The list of handlers associated to the given component
def trcnam(index, namlen=_default_len_out): """ Return the name of the module having the specified position in the trace representation. The first module to check in is at index 0. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcnam_c.html :param index: The position of the requested...
Return the name of the module having the specified position in the trace representation. The first module to check in is at index 0. http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/trcnam_c.html :param index: The position of the requested module name. :type index: int :param namlen: Av...
def addRule(self, field, regExpPattern): '''Adds new rule for checking whether a value of the field matches given regular expression regExpPattern; Parameters ---------- field: str keyword, e.g. 'partofspeech', 'root', 'text' etc ...
Adds new rule for checking whether a value of the field matches given regular expression regExpPattern; Parameters ---------- field: str keyword, e.g. 'partofspeech', 'root', 'text' etc regExpPattern: str a regular ...
def print_ctx(ctx): """ Print given context's info. :param ctx: Context object. :return: None. """ # Print title print_title('ctx attributes') # Print context object's attributes print_text(dir(ctx)) # Print end title print_title('ctx attributes', is_end=True) # Prin...
Print given context's info. :param ctx: Context object. :return: None.
async def api_neighbourhood(request): """ Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code. """ postcode: Optional[str] = request.match_info.get('postcode', None) try: postcode = (await get_postcode_random()) if...
Gets police data about a neighbourhood. :param request: The aiohttp request. :return: The police data for that post code.
def config(): # type: () -> dict[str, Any] """ Return the current git configuration. Returns: dict[str, Any]: The current git config taken from ``git config --list``. """ out = shell.run( 'git config --list', capture=True, never_pretend=True ).stdout.strip() ...
Return the current git configuration. Returns: dict[str, Any]: The current git config taken from ``git config --list``.
def multiline_push(self, code, lines): """Send a multi-message to the peer (using the correct SMTP line terminators (usually only called from the SMTPSession).""" for line in lines[:-1]: answer = '%s-%s' % (code, line) self.push(answer) self.push(code, lines[-1])
Send a multi-message to the peer (using the correct SMTP line terminators (usually only called from the SMTPSession).
def find_file(path, saltenv='base', **kwargs): ''' Search the environment for the relative path ''' fnd = {'path': '', 'rel': ''} for container in __opts__.get('azurefs', []): if container.get('saltenv', 'base') != saltenv: continue full = os.path.join(_get_con...
Search the environment for the relative path
def exports(self): """ Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name. """ ...
Return the information exported by this distribution. :return: A dictionary of exports, mapping an export category to a dict of :class:`ExportEntry` instances describing the individual export entries, and keyed by name.
def report(self, output_file=sys.stdout): """Print human readable report of model.""" cpu_perf = self.results['cpu bottleneck']['performance throughput'] if self.verbose >= 3: print('{}'.format(pformat(self.results)), file=output_file) if self.verbose >= 1: prin...
Print human readable report of model.
def create_client_for_kernel(self): """Create a client connected to an existing kernel""" connect_output = KernelConnectionDialog.get_connection_parameters(self) (connection_file, hostname, sshkey, password, ok) = connect_output if not ok: return else: ...
Create a client connected to an existing kernel
def requestMarketDepth(self, contracts=None, num_rows=10): """ Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdepth.htm """ if num_rows > 10: num_rows = 10 if contracts == None: co...
Register to streaming market data updates https://www.interactivebrokers.com/en/software/api/apiguide/java/reqmktdepth.htm
def _spikes_per_cluster(spike_clusters, spike_ids=None): """Return a dictionary {cluster: list_of_spikes}.""" if spike_clusters is None or not len(spike_clusters): return {} if spike_ids is None: spike_ids = np.arange(len(spike_clusters)).astype(np.int64) # NOTE: this sort method is stab...
Return a dictionary {cluster: list_of_spikes}.
def html(self, data=None, template=None): """ Send html document to user. Args: - data: Dict to render template, or string with rendered HTML. - template: Name of template to render HTML document with passed data. """ if data is None: data = {} ...
Send html document to user. Args: - data: Dict to render template, or string with rendered HTML. - template: Name of template to render HTML document with passed data.
def _load_contract_page(self, contract_url): """Load the profile page of a specific contract when we have multiple contracts.""" try: yield from self._session.get(contract_url, timeout=self._timeout) except OSError: raise PyHydroQu...
Load the profile page of a specific contract when we have multiple contracts.
def response_helper(self, response, **kwargs): """Response component helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` in response definition. :param dict parameter: response fields. May contain a marshmallow Schema class or instance. """ se...
Response component helper that allows using a marshmallow :class:`Schema <marshmallow.Schema>` in response definition. :param dict parameter: response fields. May contain a marshmallow Schema class or instance.
def can_solve(cls, filter_): """Tells if the solver is able to resolve the given filter. Arguments --------- filter_ : subclass of dataql.resources.BaseFilter The subclass or ``BaseFilter`` to check if it is solvable by the current solver class. Returns ----...
Tells if the solver is able to resolve the given filter. Arguments --------- filter_ : subclass of dataql.resources.BaseFilter The subclass or ``BaseFilter`` to check if it is solvable by the current solver class. Returns ------- boolean ``True``...
def temp_output_dir(prefix="tmp", suffix="", dir=None, make_parents=False, always_clean=False): """ A context manager for convenience in creating a temporary directory, which is deleted when exiting the context. Usage: with temp_output_dir() as dirname: ... """ return _temp_output(True, prefix=pr...
A context manager for convenience in creating a temporary directory, which is deleted when exiting the context. Usage: with temp_output_dir() as dirname: ...
def _get_factors(self, element): """ Get factors for categorical axes. """ gdim = None sdim = None if element.ndims == 1: pass elif not (self.stacked or self.stack_index): gdim = element.get_dimension(1) else: sdim = ele...
Get factors for categorical axes.
def _state(self, variable, num): """ Generic method to randomly determine if state is reached """ value = getattr(self, variable) if value is None: return False if value is True: return True if random.randint(1, num) == num: ...
Generic method to randomly determine if state is reached
def get_options(silent=False, hook=True): """ Generate a query string with the appropriate options. :param silent: If set to true, the object will not be bumped up in the stream and notifications will not be generated. :type silent: bool :param hook: True ...
Generate a query string with the appropriate options. :param silent: If set to true, the object will not be bumped up in the stream and notifications will not be generated. :type silent: bool :param hook: True if hooks should be executed for the change, false otherwise. ...
def get_instance(self, payload): """ Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.cr...
Build an instance of CredentialInstance :param dict payload: Payload response from the API :returns: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance :rtype: twilio.rest.api.v2010.account.sip.credential_list.credential.CredentialInstance
def p_lpartselect_lpointer_plus(self, p): 'lpartselect : pointer LBRACKET expression PLUSCOLON expression RBRACKET' p[0] = Partselect(p[1], p[3], Plus(p[3], p[5]), lineno=p.lineno(1)) p.set_lineno(0, p.lineno(1))
lpartselect : pointer LBRACKET expression PLUSCOLON expression RBRACKET
def _already_in(self, option): """ Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise """ for opt in self._options: if option.number == opt.numbe...
Check if an option is already in the message. :type option: Option :param option: the option to be checked :return: True if already present, False otherwise
def scrub(data, units=False): """ For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed. """ units = [i.unit if hasattr(i, 'unit') else 1 for i in data] data = [np.asarray(i.value if hasattr(i, 'unit') else i, dtype=...
For input data [w,f,e] or [w,f] returns the list with NaN, negative, and zero flux (and corresponding wavelengths and errors) removed.
def repo_name(self): """ Returns a DataFrame of the repo names present in this project directory :return: DataFrame """ ds = [[x.repo_name] for x in self.repos] df = pd.DataFrame(ds, columns=['repository']) return df
Returns a DataFrame of the repo names present in this project directory :return: DataFrame
def json_repr(self, minimal=False): """Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict """ if minimal: return {to_camel_case(k): v for k, ...
Construct a JSON-friendly representation of the object. :param bool minimal: Construct a minimal representation of the object (ignore nulls and empty collections) :rtype: dict
def run_transgene(job, snpeffed_file, rna_bam, univ_options, transgene_options, tumor_dna_bam=None, fusion_calls=None): """ Run transgene on an input snpeffed vcf file and return the peptides for MHC prediction. :param toil.fileStore.FileID snpeffed_file: fsID for snpeffed vcf :param...
Run transgene on an input snpeffed vcf file and return the peptides for MHC prediction. :param toil.fileStore.FileID snpeffed_file: fsID for snpeffed vcf :param dict rna_bam: The dict of bams returned by running star :param dict univ_options: Dict of universal options used by almost all tools :param d...
def is_absolute(self): """ Validates that uri contains all parts except version """ return self.namespace and self.ext and self.scheme and self.path
Validates that uri contains all parts except version
def _process_degradation(self, another_moc, order_op): """ Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order Parameters ---------- another_moc : `~mocpy.tmoc.TimeMoc` order_op : int the order in which self and ``another_moc`` will be down...
Degrade (down-sampling) self and ``another_moc`` to ``order_op`` order Parameters ---------- another_moc : `~mocpy.tmoc.TimeMoc` order_op : int the order in which self and ``another_moc`` will be down-sampled to. Returns ------- result : (`~mocpy.tmo...
def flat_map(self, column_names, fn, column_types='auto', seed=None): """ Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of...
Map each row of the SFrame to multiple rows in a new SFrame via a function. The output of `fn` must have type List[List[...]]. Each inner list will be a single row in the new output, and the collection of these rows within the outer list make up the data for the output SFrame. ...
def setListDoc(self, list): """update all nodes in the list to point to the right document """ if list is None: list__o = None else: list__o = list._o libxml2mod.xmlSetListDoc(list__o, self._o)
update all nodes in the list to point to the right document