code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def drape(raster, feature): """Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate feature (dict): fiona feature record to convert Returns: result (Point or Linestring): shapely Point or LineString of xyz coord...
Convert a 2D feature to a 3D feature by sampling a raster Parameters: raster (rasterio): raster to provide the z coordinate feature (dict): fiona feature record to convert Returns: result (Point or Linestring): shapely Point or LineString of xyz coordinate triples
def get_access_id(self): """ Gets the application access id. The value can be stored in parameters "access_id" pr "client_id" :return: the application access id. """ access_id = self.get_as_nullable_string("access_id") access_id = access_id if access_id != None else self...
Gets the application access id. The value can be stored in parameters "access_id" pr "client_id" :return: the application access id.
def is_safe(self): """ Check if the option is safe. :rtype : bool :return: True, if option is safe """ if self._number == defines.OptionRegistry.URI_HOST.number \ or self._number == defines.OptionRegistry.URI_PORT.number \ or self._number ...
Check if the option is safe. :rtype : bool :return: True, if option is safe
def _build_number_type(var, property_path=None): """ Builds schema definitions for number type values. :param var: The number type value :param List[str] property_path: The property path of the current type, defaults to None, optional :param property_path: [type], optional :return: The buil...
Builds schema definitions for number type values. :param var: The number type value :param List[str] property_path: The property path of the current type, defaults to None, optional :param property_path: [type], optional :return: The built schema definition :rtype: Dict[str, Any]
def Tm_depression_eutectic(Tm, Hm, x=None, M=None, MW=None): r'''Returns the freezing point depression caused by a solute in a solvent. Can use either the mole fraction of the solute or its molality and the molecular weight of the solvent. Assumes ideal system behavior. .. math:: \Delta T_m = \...
r'''Returns the freezing point depression caused by a solute in a solvent. Can use either the mole fraction of the solute or its molality and the molecular weight of the solvent. Assumes ideal system behavior. .. math:: \Delta T_m = \frac{R T_m^2 x}{\Delta H_m} \Delta T_m = \frac{R T_m^2 (...
def copy_file_content(self, file_id, source_file): '''Copy file content from source file to target file. Args: file_id (str): The UUID of the file whose content is written. source_file (str): The UUID of the file whose content is copied. Returns: None ...
Copy file content from source file to target file. Args: file_id (str): The UUID of the file whose content is written. source_file (str): The UUID of the file whose content is copied. Returns: None Raises: StorageArgumentException: Invalid arguments...
def __prepare_resource(data): """Prepare the resourcepart of the JID. :Parameters: - `data`: Resourcepart of the JID :raise JIDError: if the resource name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the resourcepart fails Resourceprep preparati...
Prepare the resourcepart of the JID. :Parameters: - `data`: Resourcepart of the JID :raise JIDError: if the resource name is too long. :raise pyxmpp.xmppstringprep.StringprepError: if the resourcepart fails Resourceprep preparation.
def plot_signal_sum_colorplot(ax, params, fname='LFPsum.h5', unit='mV', N=1, ylabels = True, T=[800, 1000], ylim=[-1500, 0], fancy=False, colorbar=True, cmap='spectral_r', absmax=None, transient=200, rasterized=True): ''' on colorplot and as background...
on colorplot and as background plot the summed CSD contributions args: :: ax : matplotlib.axes.AxesSubplot object T : list, [tstart, tstop], which timeinterval ylims : list, set range of yaxis to scale with other plots fancy : bool, N : integer, set to number of LFP...
def start(self, timeout=None): """Start the process going Args: timeout (float): Maximum amount of time to wait for each spawned process. None means forever """ assert self.state == STOPPED, "Process already started" self.state = STARTING shou...
Start the process going Args: timeout (float): Maximum amount of time to wait for each spawned process. None means forever
def match_description(self, description, string_match_type=DEFAULT_STRING_MATCH_TYPE, match=True): """Adds a description name to match. Multiple description matches can be added to perform a boolean ``OR`` among them. arg: description (string): description to match arg: s...
Adds a description name to match. Multiple description matches can be added to perform a boolean ``OR`` among them. arg: description (string): description to match arg: string_match_type (osid.type.Type): the string match type arg: match (boolean): ``tr...
def update_total(self, n=1): """Increment total pbar value.""" with self._lock: self._pbar.total += n self.refresh()
Increment total pbar value.
def tds7_process_result(self): """ Reads and processes COLMETADATA stream This stream contains a list of returned columns. Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx """ self.log_response_message('got COLMETADATA') r = self._reader ...
Reads and processes COLMETADATA stream This stream contains a list of returned columns. Stream format link: http://msdn.microsoft.com/en-us/library/dd357363.aspx
def construct(parent=None, defaults=None, **kwargs): """ Random variable constructor. Args: cdf: Cumulative distribution function. Optional if ``parent`` is used. bnd: Boundary interval. Optional if ``parent`` is used. parent (Dist): Distribution ...
Random variable constructor. Args: cdf: Cumulative distribution function. Optional if ``parent`` is used. bnd: Boundary interval. Optional if ``parent`` is used. parent (Dist): Distribution used as basis for new distribution. Any other argument ...
def _set_ldp_params(self, v, load=False): """ Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_params is considered as a private ...
Setter method for ldp_params, mapped from YANG variable /mpls_config/router/mpls/mpls_cmds_holder/mpls_interface/ldp_params (container) If this variable is read-only (config: false) in the source YANG file, then _set_ldp_params is considered as a private method. Backends looking to populate this variable sh...
def __store_processing_state(self): """ Stores the processing state. """ steps = self.Application_Progress_Status_processing.Processing_progressBar.maximum() value = self.Application_Progress_Status_processing.Processing_progressBar.value() message = self.Application_Pro...
Stores the processing state.
def send_produce_request(self, payloads=(), acks=1, timeout=1000, fail_on_error=True, callback=None): """ Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of respo...
Encode and send some ProduceRequests ProduceRequests will be grouped by (topic, partition) and then sent to a specific broker. Output is a list of responses in the same order as the list of payloads specified Arguments: payloads (list of ProduceRequest): produce requests to...
def get_matches(self, src, src_idx): """Get elements equal to the idx'th in src from the other list. e.g. get_matches(self, 'l1', 0) will return all elements from self.l2 matching with self.l1[0] """ if src not in ('l1', 'l2'): raise ValueError('Must have one of "l1"...
Get elements equal to the idx'th in src from the other list. e.g. get_matches(self, 'l1', 0) will return all elements from self.l2 matching with self.l1[0]
def SynchronizedClassMethod(*locks_attr_names, **kwargs): # pylint: disable=C1801 """ A synchronizer decorator for class methods. An AttributeError can be raised at runtime if the given lock attribute doesn't exist or if it is None. If a parameter ``sorted`` is found in ``kwargs`` and its value is ...
A synchronizer decorator for class methods. An AttributeError can be raised at runtime if the given lock attribute doesn't exist or if it is None. If a parameter ``sorted`` is found in ``kwargs`` and its value is True, then the list of locks names will be sorted before locking. :param locks_attr_names...
def normalizeFilePath(value): """ Normalizes file path. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string """ if not isinstance(value, basestring): raise TypeError("File paths must be strings, not %s." % type(value).__n...
Normalizes file path. * **value** must be a :ref:`type-string`. * Returned value is an unencoded ``unicode`` string
def pipe_strtransform(context=None, _INPUT=None, conf=None, **kwargs): """A string module that splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : {'transformation': {value': <'swa...
A string module that splits a string into tokens delimited by separators. Loopable. Parameters ---------- context : pipe2py.Context object _INPUT : iterable of items or strings conf : {'transformation': {value': <'swapcase'>}} Returns ------- _OUTPUT : generator of tokenized string...
def divine_format(text): """Guess the format of the notebook, based on its content #148""" try: nbformat.reads(text, as_version=4) return 'ipynb' except nbformat.reader.NotJSONError: pass lines = text.splitlines() for comment in ['', '#'] + _COMMENT_CHARS: metadata, ...
Guess the format of the notebook, based on its content #148
def construct_channel(self, *args, **kwargs): """ Create ChannelNode and build topic tree. """ channel = self.get_channel(*args, **kwargs) # creates ChannelNode from data in self.channel_info city_topic = TopicNode(source_id="List_of_largest_cities", title="Cities!") cha...
Create ChannelNode and build topic tree.
def main(): """ What will be executed when running as a stand alone program. """ args = parse_args() try: s = pyhsm.base.YHSM(device=args.device, debug=args.debug) get_entropy(s, args.iterations, args.ratio) return 0 except pyhsm.exception.YHSM_Error as e: sys.st...
What will be executed when running as a stand alone program.
def generalize_sql(sql): """ Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str """ if sql is None: return None # multiple spaces sql = re.sub(r'\s{2,}', ' ', s...
Removes most variables from an SQL query and replaces them with X or N for numbers. Based on Mediawiki's DatabaseBase::generalizeSQL :type sql str|None :rtype: str
def show_rules(): """ Show the list of available rules and quit :return: """ from rules.loader import import_rules from rules.rule_list import all_rules rules = import_rules(all_rules) print("") for name, rule in rules.iteritems(): heading = "{} (`{}`)".format(rule.descriptio...
Show the list of available rules and quit :return:
def assign(self, role): '''Assign :class:`Role` ``role`` to this :class:`Subject`. If this :class:`Subject` is the :attr:`Role.owner`, this method does nothing.''' if role.owner_id != self.id: return self.roles.add(role)
Assign :class:`Role` ``role`` to this :class:`Subject`. If this :class:`Subject` is the :attr:`Role.owner`, this method does nothing.
def submit(self, code: str, results: str ="html", prompt: dict = None) -> dict: ''' This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary. code - the SAS statements you want to execute results - format of results, HTML is default, TEXT is the altern...
This method is used to submit any SAS code. It returns the Log and Listing as a python dictionary. code - the SAS statements you want to execute results - format of results, HTML is default, TEXT is the alternative prompt - dict of names:flags to prompt for; create macro variables (used in submitt...
def balanced_accuracy(y_true, y_pred): """Default scoring function: balanced accuracy. Balanced accuracy computes each class' accuracy on a per-class basis using a one-vs-rest encoding, then computes an unweighted average of the class accuracies. Parameters ---------- y_true: numpy.ndarray {n_...
Default scoring function: balanced accuracy. Balanced accuracy computes each class' accuracy on a per-class basis using a one-vs-rest encoding, then computes an unweighted average of the class accuracies. Parameters ---------- y_true: numpy.ndarray {n_samples} True class labels y_pred:...
def tweet(self, status, images): # time.sleep(10) template = "%s #soyprice" """ if not images: self.twitter.update_status(status=template % status) else: medias = map(lambda i: self.upload_media(i), images) self.twitter.post('/statuses/update_w...
if not images: self.twitter.update_status(status=template % status) else: medias = map(lambda i: self.upload_media(i), images) self.twitter.post('/statuses/update_with_media', params={'status': template % status, 'me...
def _get_element_by_names(source, names): """ Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (list): list of attribute names """ if source is Non...
Given a dict and path '/' or '.' separated. Digs into de dict to retrieve the specified element. Args: source (dict): set of nested objects in which the data will be searched path (list): list of attribute names
def tryCComment(self, block): """C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment """ indentation = None prevNonEmptyBloc...
C comment checking. If the previous line begins with a "/*" or a "* ", then return its leading white spaces + ' *' + the white spaces after the * return: filler string or null, if not in a C comment
def parse(self, group_by_stmt): """ Extract the data resolution of a query in seconds E.g. "group by time(99s)" => 99 :param group_by_stmt: A raw InfluxDB group by statement """ if not group_by_stmt: return Resolution.MAX_RESOLUTION m = self.GROUP_BY...
Extract the data resolution of a query in seconds E.g. "group by time(99s)" => 99 :param group_by_stmt: A raw InfluxDB group by statement
def element(self, inp=None, order=None, **kwargs): """Create an element from ``inp`` or from scratch. Parameters ---------- inp : optional Input used to initialize the new element. The following options are available: - ``None``: an empty element is ...
Create an element from ``inp`` or from scratch. Parameters ---------- inp : optional Input used to initialize the new element. The following options are available: - ``None``: an empty element is created with no guarantee of its state (memory a...
def find_nearby_pores(self, pores, r, flatten=False, include_input=False): r""" Find all pores within a given radial distance of the input pore(s) regardless of whether or not they are toplogically connected. Parameters ---------- pores : array_like The list ...
r""" Find all pores within a given radial distance of the input pore(s) regardless of whether or not they are toplogically connected. Parameters ---------- pores : array_like The list of pores for whom nearby neighbors are to be found r : scalar ...
def parse_roadmap_gwas(fn): """ Read Roadmap GWAS file and filter for unique, significant (p < 1e-5) SNPs. Parameters ---------- fn : str Path to (subset of) GRASP database. Returns ------- df : pandas.DataFrame Pandas dataframe with de-duplicated, significa...
Read Roadmap GWAS file and filter for unique, significant (p < 1e-5) SNPs. Parameters ---------- fn : str Path to (subset of) GRASP database. Returns ------- df : pandas.DataFrame Pandas dataframe with de-duplicated, significant SNPs. The index is of the for...
def is_up_url(url, allow_redirects=False, timeout=5): r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "ht...
r""" Check URL to see if it is a valid web page, return the redirected location if it is Returns: None if ConnectionError False if url is invalid (any HTTP error code) cleaned up URL (following redirects and possibly adding HTTP schema "http://") >>> is_up_url("duckduckgo.com") # a more pri...
def identifier_director(**kwargs): """Direct how to handle the identifier element.""" ark = kwargs.get('ark', None) domain_name = kwargs.get('domain_name', None) # Set default scheme if it is None or is not supplied. scheme = kwargs.get('scheme') or 'http' qualifier = kwargs.get('qualifier', Non...
Direct how to handle the identifier element.
def _flush_aggregated_objects(self): """ method inserts aggregated objects into MongoDB :return number_of_aggregated_objects """ if len(self.aggregated_objects) == 0: # nothing to do return 0 number_of_aggregated_objects = len(self.aggregated_objects) ...
method inserts aggregated objects into MongoDB :return number_of_aggregated_objects
def create_add_on(self, add_on): """Make the given `AddOn` available to subscribers on this plan.""" url = urljoin(self._url, '/add_ons') return add_on.post(url)
Make the given `AddOn` available to subscribers on this plan.
def IsFile(path): ''' :param unicode path: Path to a file (local or ftp) :raises NotImplementedProtocol: If checking for a non-local, non-ftp file :rtype: bool :returns: True if the file exists .. seealso:: FTP LIMITATIONS at this module's doc for performance issues in...
:param unicode path: Path to a file (local or ftp) :raises NotImplementedProtocol: If checking for a non-local, non-ftp file :rtype: bool :returns: True if the file exists .. seealso:: FTP LIMITATIONS at this module's doc for performance issues information
def get_file_contents(self, project, provider_name, service_endpoint_id=None, repository=None, commit_or_branch=None, path=None, **kwargs): """GetFileContents. [Preview API] Gets the contents of a file in the given source code repository. :param str project: Project ID or project name :p...
GetFileContents. [Preview API] Gets the contents of a file in the given source code repository. :param str project: Project ID or project name :param str provider_name: The name of the source provider. :param str service_endpoint_id: If specified, the ID of the service endpoint to query....
def _process_results(): """Process the results from an Async job.""" async = get_current_async() callbacks = async.get_callbacks() if not isinstance(async.result.payload, AsyncException): callback = callbacks.get('success') else: callback = callbacks.get('error') if not cal...
Process the results from an Async job.
def timesince(self, now=None): """ Shortcut for the ``django.utils.timesince.timesince`` function of the current timestamp. """ return djtimesince(self.timestamp, now).encode('utf8').replace(b'\xc2\xa0', b' ').decode('utf8')
Shortcut for the ``django.utils.timesince.timesince`` function of the current timestamp.
def matching_fpaths(dpath_list, include_patterns, exclude_dirs=[], greater_exclude_dirs=[], exclude_patterns=[], recursive=True): r""" walks dpath lists returning all directories that match the requested pattern. Args: dpath_list (list): inc...
r""" walks dpath lists returning all directories that match the requested pattern. Args: dpath_list (list): include_patterns (str): exclude_dirs (None): recursive (bool): References: # TODO: fix names and behavior of exclude_dirs and greater_exc...
def resplit(prev, pattern, *args, **kw): """The resplit pipe split previous pipe input by regular expression. Use 'maxsplit' keyword argument to limit the number of split. :param prev: The previous iterator of pipe. :type prev: Pipe :param pattern: The pattern which used to split string. :type...
The resplit pipe split previous pipe input by regular expression. Use 'maxsplit' keyword argument to limit the number of split. :param prev: The previous iterator of pipe. :type prev: Pipe :param pattern: The pattern which used to split string. :type pattern: str|unicode
def send_request(self, request): '''Send a Request. Return a (message, event) pair. The message is an unframed message to send over the network. Wait on the event for the response; which will be in the "result" attribute. Raises: ProtocolError if the request violates the proto...
Send a Request. Return a (message, event) pair. The message is an unframed message to send over the network. Wait on the event for the response; which will be in the "result" attribute. Raises: ProtocolError if the request violates the protocol in some way..
def vars(self): """Alternative naming, you can use `node.vars.name` instead of `node.v_name`""" if self._vars is None: self._vars = NNTreeNodeVars(self) return self._vars
Alternative naming, you can use `node.vars.name` instead of `node.v_name`
def _dt_to_epoch_ns(dt_series): """Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch. """ ...
Convert a timeseries into an Int64Index of nanoseconds since the epoch. Parameters ---------- dt_series : pd.Series The timeseries to convert. Returns ------- idx : pd.Int64Index The index converted to nanoseconds since the epoch.
def to_one(dest_class, type=RelationType.DIRECT, resource_classes=None, reverse=None, reverse_type=RelationType.DIRECT, writable=False): """Create a one to one relation to a given target :class:`Resource`. Args: dest_class(Resource): The *target* class for the relationship K...
Create a one to one relation to a given target :class:`Resource`. Args: dest_class(Resource): The *target* class for the relationship Keyword Args: type(RelationType): The relationship approach to use. reverse(to_may or to_one): An *optional* reverse relationship. reverse_typ...
def _comparator_approximate_star(filter_value, tested_value): """ Tests if the filter value, which contains a joker, is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms """ lower_filter_value = filter_value.lower() ...
Tests if the filter value, which contains a joker, is nearly equal to the tested value. If the tested value is a string or an array of string, it compares their lower case forms
def compile_patterns_in_dictionary(dictionary): """ Replace all strings in dictionary with compiled version of themselves and return dictionary. """ for key, value in dictionary.items(): if isinstance(value, str): dictionary[key] = re.compile(value) elif isinstance(value,...
Replace all strings in dictionary with compiled version of themselves and return dictionary.
def setMaxSpeedLat(self, typeID, speed): """setMaxSpeedLat(string, double) -> None Sets the maximum lateral speed of this type. """ self._connection._sendDoubleCmd( tc.CMD_SET_VEHICLETYPE_VARIABLE, tc.VAR_MAXSPEED_LAT, typeID, speed)
setMaxSpeedLat(string, double) -> None Sets the maximum lateral speed of this type.
def set_advanced_configs(vm_name, datacenter, advanced_configs, service_instance=None): ''' Appends extra config parameters to a virtual machine advanced config list vm_name Virtual machine name datacenter Datacenter name where the virtual machine is available ...
Appends extra config parameters to a virtual machine advanced config list vm_name Virtual machine name datacenter Datacenter name where the virtual machine is available advanced_configs Dictionary with advanced parameter key value pairs service_instance vCenter servic...
def shuffled_batches(self, batch_size): """ Generate randomized batches of data """ if batch_size >= self.size: yield self else: batch_splits = math_util.divide_ceiling(self.size, batch_size) indices = list(range(self.size)) np.random.shuffle(indic...
Generate randomized batches of data
def load_image(file) -> DataAndMetadata.DataAndMetadata: """ Loads the image from the file-like object or string file. If file is a string, the file is opened and then read. Returns a numpy ndarray of our best guess for the most important image in the file. """ if isinstance(file, str) or is...
Loads the image from the file-like object or string file. If file is a string, the file is opened and then read. Returns a numpy ndarray of our best guess for the most important image in the file.
def get_user_group(self, user=None, group=None): """ Get the user and group information. Parameters ---------- user : str User name or user id (default is the `os.getuid()`). group : str Group name or group id (default is the group of `user`). ...
Get the user and group information. Parameters ---------- user : str User name or user id (default is the `os.getuid()`). group : str Group name or group id (default is the group of `user`). Returns ------- user : pwd.struct_passwd ...
def get_single(self, key, lang=None): """ Returns a single triple related to this node. :param key: Predicate of the triple :param lang: Language of the triple if applicable :rtype: Literal or BNode or URIRef """ if not isinstance(key, URIRef): key = URIRef(k...
Returns a single triple related to this node. :param key: Predicate of the triple :param lang: Language of the triple if applicable :rtype: Literal or BNode or URIRef
def auto_find_instance_path(self) -> Path: """Locates the instace_path if it was not provided """ prefix, package_path = find_package(self.import_name) if prefix is None: return package_path / "instance" return prefix / "var" / f"{self.name}-instance"
Locates the instace_path if it was not provided
def _find_volumes(self, volume_system, vstype='detect'): """Finds all volumes based on the pytsk3 library.""" try: # noinspection PyUnresolvedReferences import pytsk3 except ImportError: logger.error("pytsk3 not installed, could not detect volumes") ...
Finds all volumes based on the pytsk3 library.
def sort_top_level_items(self, key): """Sorting tree wrt top level items""" self.save_expanded_state() items = sorted([self.takeTopLevelItem(0) for index in range(self.topLevelItemCount())], key=key) for index, item in enumerate(items): self.inse...
Sorting tree wrt top level items
def _validate_argument(self, arg): """Validate a type or matcher argument to the constructor.""" if arg is None: return arg if isinstance(arg, type): return InstanceOf(arg) if not isinstance(arg, BaseMatcher): raise TypeError( "argumen...
Validate a type or matcher argument to the constructor.
def src_to_dst(self, src_uri): """Return the dst filepath from the src URI. Returns None on failure, destination path on success. """ m = re.match(self.src_uri + "/(.*)$", src_uri) if (m is None): return(None) rel_path = m.group(1) return(self.dst_pat...
Return the dst filepath from the src URI. Returns None on failure, destination path on success.
async def asgi_send(self, message: dict) -> None: """Called by the ASGI instance to send a message.""" if message["type"] == "websocket.accept" and self.state == ASGIWebsocketState.HANDSHAKE: headers = build_and_validate_headers(message.get("headers", [])) raise_if_subprotocol_pr...
Called by the ASGI instance to send a message.
def _real_re_compile(self, *args, **kwargs): """Thunk over to the original re.compile""" try: return re.compile(*args, **kwargs) except re.error as e: # raise ValueError instead of re.error as this gives a # cleaner message to the user. raise Value...
Thunk over to the original re.compile
def roll_dice(spec): """ Perform the dice rolls and replace all roll expressions with lists of the dice faces that landed up. """ if spec[0] == 'c': return spec if spec[0] == 'r': r = spec[1:] if len(r) == 2: return ('r', perform_roll(r[0], r[1])) k = r[3] if r[2] == 'k' else -1 ...
Perform the dice rolls and replace all roll expressions with lists of the dice faces that landed up.
def SavePrivateKey(self, private_key): """Store the new private key on disk.""" self.private_key = private_key config.CONFIG.Set("Client.private_key", self.private_key.SerializeToString()) config.CONFIG.Write()
Store the new private key on disk.
def rotateAboutVectorMatrix(vec, theta_deg): """Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should...
Construct the matrix that rotates vector a about vector vec by an angle of theta_deg degrees Taken from http://en.wikipedia.org/wiki/Rotation_matrix#Rotation_matrix_from_axis_and_angle Input: theta_deg (float) Angle through which vectors should be rotated in degrees Returns:...
def get_parser(): """Return ArgumentParser for pypyr cli.""" parser = argparse.ArgumentParser( allow_abbrev=True, description='pypyr pipeline runner') parser.add_argument('pipeline_name', help='Name of pipeline to run. It should exist in the ' ...
Return ArgumentParser for pypyr cli.
def get_worker_report(self, with_memory=False): """ Returns a dict containing all the data we can about the current status of the worker and its jobs. """ greenlets = [] for greenlet in list(self.gevent_pool): g = {} short_stack = [] stack = trace...
Returns a dict containing all the data we can about the current status of the worker and its jobs.
def get_files_zip(run_id: int, filetype: _FileType): """Send all artifacts or sources of a run as ZIP.""" data = current_app.config["data"] dao_runs = data.get_run_dao() dao_files = data.get_files_dao() run = dao_runs.get(run_id) if filetype == _FileType.ARTIFACT: target_files = run['ar...
Send all artifacts or sources of a run as ZIP.
def point(self, x, y): """Creates a POINT shape.""" shapeType = POINT pointShape = Shape(shapeType) pointShape.points.append([x, y]) self.shape(pointShape)
Creates a POINT shape.
def _options(self): """ Returns a raw options object :rtype: dict """ if self._options_cache is None: target_url = self.client.get_url(self._URL_KEY, 'OPTIONS', 'options') r = self.client.request('OPTIONS', target_url) self._options_cache = r....
Returns a raw options object :rtype: dict
def search(self, pattern="*", raw=True, search_raw=True, output=False): """Search the database using unix glob-style matching (wildcards * and ?). Parameters ---------- pattern : str The wildcarded pattern to matc...
Search the database using unix glob-style matching (wildcards * and ?). Parameters ---------- pattern : str The wildcarded pattern to match when searching search_raw : bool If True, search the raw input, otherwise, the parsed input raw, output : bool ...
def merge_text_nodes_on(self, node): """Merges all consecutive non-translatable text nodes into one""" if not isinstance(node, ContainerNode) or not node.children: return new_children = [] text_run = [] for i in node.children: if isinstance(i, Text) and ...
Merges all consecutive non-translatable text nodes into one
def start_tcp_client(self, ip=None, port=None, name=None, timeout=None, protocol=None, family='ipv4'): """Starts a new TCP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or i...
Starts a new TCP client. Client can be optionally given `ip` and `port` to bind to, as well as `name`, default `timeout` and a `protocol`. `family` can be either ipv4 (default) or ipv6. You should use `Connect` keyword to connect client to a host. Examples: | Start TCP...
def register(self, source_point_cloud, target_point_cloud, source_normal_cloud, target_normal_cloud, matcher, num_iterations=1, compute_total_cost=True, match_centroids=False, vis=False): """ Iteratively register objects to one another using a modified ...
Iteratively register objects to one another using a modified version of point to plane ICP. The cost func is PointToPlane_COST + gamma * PointToPoint_COST. Uses a `stochastic Gauss-Newton step` where on each iteration a smaller number of points is sampled. Parameters ---------- ...
def sys_status_send(self, onboard_control_sensors_present, onboard_control_sensors_enabled, onboard_control_sensors_health, load, voltage_battery, current_battery, battery_remaining, drop_rate_comm, errors_comm, errors_count1, errors_count2, errors_count3, errors_count4, force_mavlink1=False): ''' ...
The general system state. If the system is following the MAVLink standard, the system state is mainly defined by three orthogonal states/modes: The system mode, which is either LOCKED (motors shut down and locked), MANUAL (system under RC control), GUIDED ...
def OnTableChanged(self, event): """Table changed event handler""" if hasattr(event, 'table'): self.Select(event.table) self.EnsureVisible(event.table) event.Skip()
Table changed event handler
def _write_model(self, specification, specification_set): """ Write autogenerate specification file """ filename = "%s%s.py" % (self._class_prefix.lower(), specification.entity_name.lower()) override_content = self._extract_override_content(specification.entity_name) constants ...
Write autogenerate specification file
def _get_key_location(self, key) -> (int, int): """ Return chunk no and 1-based offset of key :param key: :return: """ key = int(key) if key == 0: return 1, 0 remainder = key % self.chunkSize addend = ChunkedFileStore.firstChunkIndex ...
Return chunk no and 1-based offset of key :param key: :return:
def upload(self, filepath, service_path, remove=False): ''' "Upload" a file to a service This copies a file from the local filesystem into the ``DataService``'s filesystem. If ``remove==True``, the file is moved rather than copied. If ``filepath`` and ``service_path`` paths are...
"Upload" a file to a service This copies a file from the local filesystem into the ``DataService``'s filesystem. If ``remove==True``, the file is moved rather than copied. If ``filepath`` and ``service_path`` paths are the same, ``upload`` deletes the file if ``remove==True`` and retur...
def squeeze(self, trits, offset=0, length=HASH_LENGTH): # type: (MutableSequence[int], Optional[int], Optional[int]) -> None """ Squeeze trits from the sponge. :param trits: Sequence that the squeezed trits will be copied to. Note: this object will be modified! ...
Squeeze trits from the sponge. :param trits: Sequence that the squeezed trits will be copied to. Note: this object will be modified! :param offset: Starting offset in ``trits``. :param length: Number of trits to squeeze, default to ``HASH_LENGTH...
def prog(self, s=None): """ Prints the progress indicator """ s = s or self.prog_msg self.printer(s, end='')
Prints the progress indicator
def clean_pdb(pdb_file, out_suffix='_clean', outdir=None, force_rerun=False, remove_atom_alt=True, keep_atom_alt_id='A', remove_atom_hydrogen=True, add_atom_occ=True, remove_res_hetero=True, keep_chemicals=None, keep_res_only=None, add_chain_id_if_empty='X', keep_chains=None): ...
Clean a PDB file. Args: pdb_file (str): Path to input PDB file out_suffix (str): Suffix to append to original filename outdir (str): Path to output directory force_rerun (bool): If structure should be re-cleaned if a clean file exists already remove_atom_alt (bool): Remove a...
def _get_min_max_value(min, max, value=None, step=None): """Return min, max, value given input values with possible None.""" # Either min and max need to be given, or value needs to be given if value is None: if min is None or max is None: raise ValueError('unable to infer range, value f...
Return min, max, value given input values with possible None.
def n_p(self): """ The plasma density in SI units. """ return 2*_sltr.GeV2joule(self.E)*_spc.epsilon_0 / (self.beta*_spc.elementary_charge)**2
The plasma density in SI units.
def metadata_sorter(x, y): """ Sort metadata keys by priority. """ if x == y: return 0 if x in METADATA_SORTER_FIRST and y in METADATA_SORTER_FIRST: return -1 if METADATA_SORTER_FIRST.index(x) < METADATA_SORTER_FIRST.index(y) else 1 elif x in METADATA_SORTER_FIRST: return -1 ...
Sort metadata keys by priority.
def _init_base_objects(self, ssl_version: OpenSslVersionEnum, underlying_socket: Optional[socket.socket]) -> None: """Setup the socket and SSL_CTX objects. """ self._is_handshake_completed = False self._ssl_version = ssl_version self._ssl_ctx = self._NASSL_MODULE.SSL_CTX(ssl_vers...
Setup the socket and SSL_CTX objects.
def correspond(text): """Communicate with the child process without closing stdin.""" subproc.stdin.write(text) subproc.stdin.flush() return drain()
Communicate with the child process without closing stdin.
def rate_limit(limit: int, key=None): """ Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return: """ def decorator(func): setattr(func, 'throttling_rate_limit', limit) if key: setattr(func, 'throttling_key', key) ...
Decorator for configuring rate limit and key in different functions. :param limit: :param key: :return:
def name_parts(self): """Works with PartialNameMixin.clear_dict to set NONE and ANY values.""" default = PartialMixin.ANY return ([(k, default, True) for k, _, _ in PartitionName._name_parts] + [(k, default, True) for k, ...
Works with PartialNameMixin.clear_dict to set NONE and ANY values.
def compute_integrated_acquisition(acquisition,x): ''' Used to compute the acquisition function when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluate...
Used to compute the acquisition function when samples of the hyper-parameters have been generated (used in GP_MCMC model). :param acquisition: acquisition function with GpyOpt model type GP_MCMC. :param x: location where the acquisition is evaluated.
def shutdown(self): ''' shutdown operations on exit, this is run by a finaly statement after the tkinter mainloop ends call root.quit to get here, Note you will still need to call sys.exit() ''' logging.info('Shutdown procedures being run!') for func in self.shutd...
shutdown operations on exit, this is run by a finaly statement after the tkinter mainloop ends call root.quit to get here, Note you will still need to call sys.exit()
def dist_dir(self): '''The dist dir at which to place the finished distribution.''' if self.distribution is None: warning('Tried to access {}.dist_dir, but {}.distribution ' 'is None'.format(self, self)) exit(1) return self.distribution.dist_dir
The dist dir at which to place the finished distribution.
def cds_identifier_validator(record, result): """Ensure that the two records have the same CDS identifier. This is needed because the search is done only for ``external_system_identifiers.value``, which might cause false positives in case the matched record has an identifier with the same ``value`` but...
Ensure that the two records have the same CDS identifier. This is needed because the search is done only for ``external_system_identifiers.value``, which might cause false positives in case the matched record has an identifier with the same ``value`` but ``schema`` different from CDS. Args: ...
def decr(self, stat, count=1, rate=1): """Decrement a stat by `count`.""" self.incr(stat, -count, rate)
Decrement a stat by `count`.
def getSupportedServices(self, only_uids=True): """Return a list with the services supported by this reference sample, those for which there is a valid results range assigned in reference results :param only_uids: returns a list of uids or a list of objects :return: list of uids ...
Return a list with the services supported by this reference sample, those for which there is a valid results range assigned in reference results :param only_uids: returns a list of uids or a list of objects :return: list of uids or AnalysisService objects
def create_api_key(self, api_id, stage_name): """ Create new API key and link it with an api_id and a stage_name """ response = self.apigateway_client.create_api_key( name='{}_{}'.format(stage_name, api_id), description='Api Key for {}'.format(api_id), ...
Create new API key and link it with an api_id and a stage_name
def accept_all(self): ''' Accept all keys in pre ''' keys = self.list_keys() for key in keys[self.PEND]: try: shutil.move( os.path.join( self.opts['pki_dir'], self.PEND, ...
Accept all keys in pre
def get_default(__func: Callable, __arg: str) -> str: """Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for """ return signature(__func).parameters[__arg].default
Fetch default value for a function argument Args: __func: Function to inspect __arg: Argument to extract default value for