code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def init_db_conn( connection_name, HOST=None, PORT=None, DB=None, PASSWORD=None): """ Initialize a redis connection by each connection string defined in the configuration file """ rpool = redis.ConnectionPool( host=HOST, port=PORT, db=DB, password=PASSWORD) r = redis.Redis(connec...
Initialize a redis connection by each connection string defined in the configuration file
def build_seasonal_transition_matrix( num_seasons, is_last_day_of_season, dtype, basis_change_matrix=None, basis_change_matrix_inv=None): """Build a function computing transitions for a seasonal effect model.""" with tf.compat.v1.name_scope('build_seasonal_transition_matrix'): # If the season is changi...
Build a function computing transitions for a seasonal effect model.
def tee_output_python(): """Duplicate sys.stdout and sys.stderr to new StringIO.""" buffer = StringIO() out = CapturedStdout(buffer) orig_stdout, orig_stderr = sys.stdout, sys.stderr flush() sys.stdout = TeeingStreamProxy(sys.stdout, buffer) sys.stderr = TeeingStreamProxy(sys.stderr, buffer)...
Duplicate sys.stdout and sys.stderr to new StringIO.
def to_slice(arr): """Test whether `arr` is an integer array that can be replaced by a slice Parameters ---------- arr: numpy.array Numpy integer array Returns ------- slice or None If `arr` could be converted to an array, this is returned, otherwise `None` is retur...
Test whether `arr` is an integer array that can be replaced by a slice Parameters ---------- arr: numpy.array Numpy integer array Returns ------- slice or None If `arr` could be converted to an array, this is returned, otherwise `None` is returned See Also ----...
def b58ToC32(b58check, version=-1): """ >>> b58ToC32('1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> b58ToC32('3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y') 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G' >>> b58ToC32('mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8') 'ST2J6ZY48G...
>>> b58ToC32('1FzTxL9Mxnm2fdmnQEArfhzJHevwbvcH6d') 'SP2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKNRV9EJ7' >>> b58ToC32('3GgUssdoWh5QkoUDXKqT6LMESBDf8aqp2y') 'SM2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQVX8X0G' >>> b58ToC32('mvWRFPELmpCHSkFQ7o9EVdCd9eXeUTa9T8') 'ST2J6ZY48GV1EZ5V2V5RB9MP66SW86PYKKQYAC0RQ' >>> b58ToC3...
def reset_kernel(self): """Reset kernel of current client.""" client = self.get_current_client() if client is not None: self.switch_to_plugin() client.reset_namespace()
Reset kernel of current client.
def cg(f_Ax, b, cg_iters=10, callback=None, verbose=False, residual_tol=1e-10): """ Demmel p 312 """ p = b.copy() r = b.copy() x = np.zeros_like(b) rdotr = r.dot(r) fmtstr = "%10i %10.3g %10.3g" titlestr = "%10s %10s %10s" if verbose: print(titlestr % ("iter", "residual norm",...
Demmel p 312
def spladder(job, inputs, bam_id, bai_id): """ Run SplAdder to detect and quantify alternative splicing events :param JobFunctionWrappingJob job: passed by Toil automatically :param Namespace inputs: Stores input arguments (see main) :param str bam_id: FileStore ID of bam :param str bai_id: Fil...
Run SplAdder to detect and quantify alternative splicing events :param JobFunctionWrappingJob job: passed by Toil automatically :param Namespace inputs: Stores input arguments (see main) :param str bam_id: FileStore ID of bam :param str bai_id: FileStore ID of bam index file :return: FileStore ID o...
def get_stp_mst_detail_output_msti_port_interface_type(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") get_stp_mst_detail = ET.Element("get_stp_mst_detail") config = get_stp_mst_detail output = ET.SubElement(get_stp_mst_detail, "output") ...
Auto Generated Code
def getAttributeName(self, index): """ Returns the String which represents the attribute name """ offset = self._get_attribute_offset(index) name = self.m_attributes[offset + const.ATTRIBUTE_IX_NAME] res = self.sb[name] # If the result is a (null) string, we need...
Returns the String which represents the attribute name
def load_script(browser, url): """Ensure that JavaScript at a given URL is available to the browser.""" if browser.current_url.startswith('file:'): url = 'https:' + url browser.execute_script(""" var script_tag = document.createElement("script"); script_tag.setAttribute("type", "text/javascr...
Ensure that JavaScript at a given URL is available to the browser.
def logout(current): """ Log out view. Simply deletes the session object. For showing logout message: 'show_logout_message' field should be True in current.task_data, Message should be sent in current.task_data with 'logout_message' field. Message title should be sent in current....
Log out view. Simply deletes the session object. For showing logout message: 'show_logout_message' field should be True in current.task_data, Message should be sent in current.task_data with 'logout_message' field. Message title should be sent in current.task_data with 'logout_title' fie...
def partition_asymmetry(bif_point): '''Calculate the partition asymmetry at a bifurcation point as defined in https://www.ncbi.nlm.nih.gov/pubmed/18568015 The number of nodes in each child tree is counted. The partition is defined as the ratio of the absolute difference and the sum of the number of...
Calculate the partition asymmetry at a bifurcation point as defined in https://www.ncbi.nlm.nih.gov/pubmed/18568015 The number of nodes in each child tree is counted. The partition is defined as the ratio of the absolute difference and the sum of the number of bifurcations in the two daughter subtrees ...
def unsubscribe(self): """ Completly stop all pubnub operations. """ _LOGGER.info("PubNub unsubscribing") self._pubnub.unsubscribe_all() self._pubnub.stop() self._pubnub = None
Completly stop all pubnub operations.
def dump(context=os.environ): """Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment. """ output = {} for key, value in context.iteritems(): if not key.startswith("BE_"): continu...
Dump current environment as a dictionary Arguments: context (dict, optional): Current context, defaults to the current environment.
def directories_in_directory(db, user_id, db_dirname): """ Return subdirectories of a directory. """ fields = _directory_default_fields() rows = db.execute( select( fields, ).where( _is_in_directory(directories, user_id, db_dirname), ) ) return...
Return subdirectories of a directory.
def env(**kwargs: Union[Dict[str, str], None]) -> ContextManager: """Context handler to temporarily alter environment. If you supply a value of ``None``, then the associated key will be deleted from the environment. Args: kwargs: Environment variables to override Yields: Execution...
Context handler to temporarily alter environment. If you supply a value of ``None``, then the associated key will be deleted from the environment. Args: kwargs: Environment variables to override Yields: Execution context with modified environment
def printTPRegionParams(tpregion): """ Note: assumes we are using TemporalMemory/TPShim in the TPRegion """ tm = tpregion.getSelf()._tfdr print "------------PY TemporalMemory Parameters ------------------" print "numberOfCols =", tm.columnDimensions print "cellsPerColumn =", tm.cell...
Note: assumes we are using TemporalMemory/TPShim in the TPRegion
def forward(self, X, training=False, device='cpu'): """Gather and concatenate the output from forward call with input data. The outputs from ``self.module_.forward`` are gathered on the compute device specified by ``device`` and then concatenated using PyTorch :func:`~torch.cat`...
Gather and concatenate the output from forward call with input data. The outputs from ``self.module_.forward`` are gathered on the compute device specified by ``device`` and then concatenated using PyTorch :func:`~torch.cat`. If multiple outputs are returned by ``self.module_.fo...
def allocate(self): """Builds the context and the Hooks.""" self.logger.debug("Allocating environment.") self._allocate() self.logger.debug("Environment successfully allocated.")
Builds the context and the Hooks.
def read_lsm_floatpairs(fh): """Read LSM sequence of float pairs from file and return as list.""" size = struct.unpack('<i', fh.read(4))[0] return fh.read_array('<2f8', count=size)
Read LSM sequence of float pairs from file and return as list.
def attr_membership(attr_val, value_set, attr_type=basestring, modifier_fn=lambda x: x): """ Helper function passed to netCDF4.Dataset.get_attributes_by_value Checks that `attr_val` exists, has the same type as `attr_type`, and is contained in `value_set` attr_val: The valu...
Helper function passed to netCDF4.Dataset.get_attributes_by_value Checks that `attr_val` exists, has the same type as `attr_type`, and is contained in `value_set` attr_val: The value of the attribute being checked attr_type: A type object that the `attr_val` is expected to have the same t...
def next_child(self, child_pid): """Get the next child PID in the PID relation.""" relation = self._get_child_relation(child_pid) if relation.index is not None: return self.children.filter( PIDRelation.index > relation.index ).ordered(ord='asc').first() ...
Get the next child PID in the PID relation.
def battery_voltage(self): """ Returns voltage in mV """ msb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_MSB_REG) lsb = self.bus.read_byte_data(AXP209_ADDRESS, BATTERY_VOLTAGE_LSB_REG) voltage_bin = msb << 4 | lsb & 0x0f return voltage_bin * 1.1
Returns voltage in mV
def getfield(f): """convert values from cgi.Field objects to plain values.""" if isinstance(f, list): return [getfield(x) for x in f] else: return f.value
convert values from cgi.Field objects to plain values.
def get_matches(self, code, start=0, end=None, skip=None): """Search for `code` in source and return a list of `Match`\es `code` can contain wildcards. ``${name}`` matches normal names and ``${?name} can match any expression. You can use `Match.get_ast()` for getting the node that has...
Search for `code` in source and return a list of `Match`\es `code` can contain wildcards. ``${name}`` matches normal names and ``${?name} can match any expression. You can use `Match.get_ast()` for getting the node that has matched a given pattern.
def build_request_relationship(type, ids): """Build a relationship list. A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API. Args: type(str...
Build a relationship list. A relationship list is used to update relationships between two resources. Setting sensors on a label, for example, uses this function to construct the list of sensor ids to pass to the Helium API. Args: type(string): The resource type for the ids in the relatio...
def build_body(self): ''' Builds the body of a syslog-ng configuration object. ''' _increase_indent() body_array = [x.build() for x in self.iterable] nl = '\n' if self.append_extra_newline else '' if len(self.iterable) >= 1: body = self.join_body_on....
Builds the body of a syslog-ng configuration object.
def format_docstring(*args, **kwargs): """ Decorator for clean docstring formatting """ def decorator(func): func.__doc__ = getdoc(func).format(*args, **kwargs) return func return decorator
Decorator for clean docstring formatting
def do_find(self, params): """ \x1b[1mNAME\x1b[0m find - Find znodes whose path matches a given text \x1b[1mSYNOPSIS\x1b[0m find [path] [match] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * match: the string to match in the paths (default: '') \x1b[1mEXAMPLES\x1b[0m ...
\x1b[1mNAME\x1b[0m find - Find znodes whose path matches a given text \x1b[1mSYNOPSIS\x1b[0m find [path] [match] \x1b[1mOPTIONS\x1b[0m * path: the path (default: cwd) * match: the string to match in the paths (default: '') \x1b[1mEXAMPLES\x1b[0m > find / foo /foo2 ...
def _get_or_add(self, prop_name): """ Return element returned by 'get_or_add_' method for *prop_name*. """ get_or_add_method_name = 'get_or_add_%s' % prop_name get_or_add_method = getattr(self, get_or_add_method_name) element = get_or_add_method() return element
Return element returned by 'get_or_add_' method for *prop_name*.
def prettyname(cls, attrib_name): """ Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str`` """ if attr...
Returns the "pretty name" (capitalized, etc) of an attribute, by looking it up in ``cls.COLUMN_NAMES`` if it exists there. :param attrib_name: An attribute name. :type attrib_name: ``str`` :rtype: ``str``
def in_memory(self, value): """Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory. """ self_class = self.__class__ memory = Annotation.__ANNOTATIONS_IN_MEMORY__ if value: annotations_memory = memory.set...
Add or remove self from global memory. :param bool value: if True(False) ensure self is(is not) in memory.
def set_ntp_servers(primary_server=None, secondary_server=None, deploy=False): ''' Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server...
Set the NTP servers of the Palo Alto proxy minion. A commit will be required before this is processed. CLI Example: Args: primary_server(str): The primary NTP server IP address or FQDN. secondary_server(str): The secondary NTP server IP address or FQDN. deploy (bool): If true then co...
def browserfamilies(self, tag=None, fromdate=None, todate=None): """ Gets an overview of the browsers used to open links in your emails. This is only recorded when Link Tracking is enabled for that email. """ return self.call("GET", "/stats/outbound/clicks/browserfamilies", tag=t...
Gets an overview of the browsers used to open links in your emails. This is only recorded when Link Tracking is enabled for that email.
async def article( self, title, description=None, *, url=None, thumb=None, content=None, id=None, text=None, parse_mode=(), link_preview=True, geo=None, period=60, contact=None, game=False, buttons=None ): """ Creates new inline result of article type....
Creates new inline result of article type. Args: title (`str`): The title to be shown for this result. description (`str`, optional): Further explanation of what this result means. url (`str`, optional): The URL to be shown f...
def _getCellForNewSegment(self, colIdx): """ Return the index of a cell in this column which is a good candidate for adding a new segment. When we have fixed size resources in effect, we insure that we pick a cell which does not already have the max number of allowed segments. If none exists, w...
Return the index of a cell in this column which is a good candidate for adding a new segment. When we have fixed size resources in effect, we insure that we pick a cell which does not already have the max number of allowed segments. If none exists, we choose the least used segment in the column to re-a...
def get_op_traceback(self, op_name): """Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given...
Get the traceback of an op in the latest version of the TF graph. Args: op_name: Name of the op. Returns: Creation traceback of the op, in the form of a list of 2-tuples: (file_path, lineno) Raises: ValueError: If the op with the given name cannot be found in the latest ...
def get_pending_reboot(): ''' Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot ''' # Order the c...
Determine whether there is a reboot pending. .. versionadded:: 2016.11.0 Returns: bool: ``True`` if the system is pending reboot, otherwise ``False`` CLI Example: .. code-block:: bash salt '*' system.get_pending_reboot
def get_all_security_groups(groupnames=None, group_ids=None, filters=None, region=None, key=None, keyid=None, profile=None): ''' Return a list of all Security Groups matching the given criteria and filters. Note that the 'groupnames' argument only functions correctly for EC2 Cla...
Return a list of all Security Groups matching the given criteria and filters. Note that the 'groupnames' argument only functions correctly for EC2 Classic and default VPC Security Groups. To find groups by name in other VPCs you'll want to use the 'group-name' filter instead. Valid keys for the filte...
def _unpack_token_json(token): """ Unpack a JSON-serialized JWT Returns (headers, payload, signatures) on success Raises DecodeError on bad input """ if not isinstance(token, dict): raise DecodeError("Not a dict") if not token.has_key('payload'): raise DecodeError("Missing '...
Unpack a JSON-serialized JWT Returns (headers, payload, signatures) on success Raises DecodeError on bad input
def FunctionTimer(on_done=None): ''' To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(details) .....
To check execution time of a function borrowed from https://medium.com/pythonhive/python-decorator-to-measure-the-execution-time-of-methods-fa04cb6bb36d >>> def logger(details, args, kwargs): #some function that uses the time output ... print(details) ... >>> @FunctionTimer(on_done= logger) ...
def checkPermissions(permissions=[], obj=None): """ Checks if a user has permissions for a given object. Args: permissions: The permissions the current user must be compliant with obj: The object for which the permissions apply Returns: 1 if the user complies with all the permi...
Checks if a user has permissions for a given object. Args: permissions: The permissions the current user must be compliant with obj: The object for which the permissions apply Returns: 1 if the user complies with all the permissions for the given object. Otherwise, it returns e...
def getcolor(spec): """ Turn optional color string spec into an array. """ if isinstance(spec, str): from matplotlib import colors return asarray(colors.hex2color(colors.cnames[spec])) else: return spec
Turn optional color string spec into an array.
def ensure_session_key(request): """ Given a request return a session key that will be used. There may already be a session key associated, but if there is not, we force the session to create itself and persist between requests for the client behind the given request. """ key = request.sessi...
Given a request return a session key that will be used. There may already be a session key associated, but if there is not, we force the session to create itself and persist between requests for the client behind the given request.
def get(self, obj, key): """ Retrieve 'key' from an instance of a class which previously exposed it. @param key: a hashable object, previously passed to L{Exposer.expose}. @return: the object which was exposed with the given name on obj's key. @raise MethodNotExposed: when the...
Retrieve 'key' from an instance of a class which previously exposed it. @param key: a hashable object, previously passed to L{Exposer.expose}. @return: the object which was exposed with the given name on obj's key. @raise MethodNotExposed: when the key in question was not exposed with ...
def get_storage_credentials(key, read_only=False): """Authenticates a service account for reading and/or writing on a bucket. This uses the `google.oauth2.service_account` module to obtain "scoped credentials". These can be used with the `google.storage` module. TODO: docstring""" if read_only...
Authenticates a service account for reading and/or writing on a bucket. This uses the `google.oauth2.service_account` module to obtain "scoped credentials". These can be used with the `google.storage` module. TODO: docstring
def set_from_json(self, obj, json, models=None, setter=None): ''' Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to t...
Sets the value of this property from a JSON value. This method first separately extracts and removes any ``units`` field in the JSON, and sets the associated units property directly. The remaining JSON is then passed to the superclass ``set_from_json`` to be handled. Args: ...
def stop(self, bIgnoreExceptions = True): """ Stops debugging all processes. If the kill on exit mode is on, debugged processes are killed when the debugger is stopped. Otherwise when the debugger stops it detaches from all debugged processes and leaves them running (default). F...
Stops debugging all processes. If the kill on exit mode is on, debugged processes are killed when the debugger is stopped. Otherwise when the debugger stops it detaches from all debugged processes and leaves them running (default). For more details see: L{__init__} @note: This ...
def get_history_item_for_tree_iter(self, child_tree_iter): """Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item: ...
Hands history item for tree iter and compensate if tree item is a dummy item :param Gtk.TreeIter child_tree_iter: Tree iter of row :rtype rafcon.core.execution.execution_history.HistoryItem: :return history tree item:
def get_form(self, request, obj=None, **kwargs): """Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself. """ if obj is not None and obj.parent is not None: self.previous_parent = obj.parent previous_parent_id = self.previ...
Returns modified form for TreeItem model. 'Parent' field choices are built by sitetree itself.
def load_file(self, filename): """Load file into treeview""" self.counter.clear() # python2 issues try: etree = ET.parse(filename) except ET.ParseError: parser = ET.XMLParser(encoding='UTF-8') etree = ET.parse(filename, parser) eroot =...
Load file into treeview
def Henry_H_at_T(T, H, Tderiv, T0=None, units=None, backend=None): """ Evaluate Henry's constant H at temperature T Parameters ---------- T: float Temperature (with units), assumed to be in Kelvin if ``units == None`` H: float Henry's constant Tderiv: float (optional) dl...
Evaluate Henry's constant H at temperature T Parameters ---------- T: float Temperature (with units), assumed to be in Kelvin if ``units == None`` H: float Henry's constant Tderiv: float (optional) dln(H)/d(1/T), assumed to be in Kelvin if ``units == None``. T0: float ...
def simxGetStringParameter(clientID, paramIdentifier, operationMode): ''' Please have a look at the function description/documentation in the V-REP user manual ''' paramValue = ct.POINTER(ct.c_char)() ret = c_GetStringParameter(clientID, paramIdentifier, ct.byref(paramValue), operationMode) ...
Please have a look at the function description/documentation in the V-REP user manual
def get_recent_files(self): """Return a list of files opened by the project.""" try: recent_files = self.CONF[WORKSPACE].get('main', 'recent_files', default=[]) except EnvironmentError: return [] for rec...
Return a list of files opened by the project.
def load_file(self): ''' Loads combined SAR format logfile in ASCII format. :return: ``True`` if loading and parsing of file went fine, \ ``False`` if it failed (at any point) ''' daychunks = self.__split_file() if (daychunks): maxcount = len...
Loads combined SAR format logfile in ASCII format. :return: ``True`` if loading and parsing of file went fine, \ ``False`` if it failed (at any point)
def get_loggers(self): '''Return a list of the logger methods: (debug, info, warn, error)''' return self.log.debug, self.log.info, self.log.warn, self.log.error
Return a list of the logger methods: (debug, info, warn, error)
def update(self, action: torch.Tensor) -> 'ChecklistStatelet': """ Takes an action index, updates checklist and returns an updated state. """ checklist_addition = (self.terminal_actions == action).float() new_checklist = self.checklist + checklist_addition new_checklist_s...
Takes an action index, updates checklist and returns an updated state.
def delete_by_hash(self, file_hash): """ Remove file/archive by it's `file_hash`. Args: file_hash (str): Hash, which is used to find the file in storage. Raises: IOError: If the file for given `file_hash` was not found in \ storage. ...
Remove file/archive by it's `file_hash`. Args: file_hash (str): Hash, which is used to find the file in storage. Raises: IOError: If the file for given `file_hash` was not found in \ storage.
def _cram_to_fastq_regions(regions, cram_file, dirs, data): """Convert CRAM files to fastq, potentially within sub regions. Returns multiple fastq files that can be merged back together. """ base_name = utils.splitext_plus(os.path.basename(cram_file))[0] work_dir = utils.safe_makedir(os.path.join(d...
Convert CRAM files to fastq, potentially within sub regions. Returns multiple fastq files that can be merged back together.
def dtypes(self): """ Return the dtypes in the DataFrame. This returns a Series with the data type of each column. The result's index is the original DataFrame's columns. Columns with mixed types are stored with the ``object`` dtype. See :ref:`the User Guide <basics.dtyp...
Return the dtypes in the DataFrame. This returns a Series with the data type of each column. The result's index is the original DataFrame's columns. Columns with mixed types are stored with the ``object`` dtype. See :ref:`the User Guide <basics.dtypes>` for more. Returns ...
def _read_as_dict(self): """ Read the data contained in all entries as a list of dictionaries with the headers as the dictionary keys :return: list of dicts containing all tabular data """ data = list() for row in self._rows: row_data = OrderedDict() ...
Read the data contained in all entries as a list of dictionaries with the headers as the dictionary keys :return: list of dicts containing all tabular data
def epoch_to_human_time(epoch_time): """Converts an epoch timestamp to human readable time. This essentially converts an output of get_current_epoch_time to an output of get_current_human_time Args: epoch_time: An integer representing an epoch timestamp in milliseconds. Returns: A...
Converts an epoch timestamp to human readable time. This essentially converts an output of get_current_epoch_time to an output of get_current_human_time Args: epoch_time: An integer representing an epoch timestamp in milliseconds. Returns: A time string representing the input time. ...
def execute_sync(self, message): """ Respond when the server indicates that the client is out of sync. The server can request a sync when this client sends a message that fails the check() on the server. If the reason for the failure isn't very serious, then the server can de...
Respond when the server indicates that the client is out of sync. The server can request a sync when this client sends a message that fails the check() on the server. If the reason for the failure isn't very serious, then the server can decide to send it as usual in the interest of ...
def create_assessment(self, assessment_form): """Creates a new ``Assessment``. arg: assessment_form (osid.assessment.AssessmentForm): the form for this ``Assessment`` return: (osid.assessment.Assessment) - the new ``Assessment`` raise: IllegalState - ``assessment_for...
Creates a new ``Assessment``. arg: assessment_form (osid.assessment.AssessmentForm): the form for this ``Assessment`` return: (osid.assessment.Assessment) - the new ``Assessment`` raise: IllegalState - ``assessment_form`` already used in a create transaction ...
def set_token(self, token): """ Set token in authentification for next requests :param token: str. token to set in auth. If None, reinit auth """ if token: auth = HTTPBasicAuth(token, '') self._token = token self.authenticated = True # TODO: R...
Set token in authentification for next requests :param token: str. token to set in auth. If None, reinit auth
def event_info(self, event): """Get a dict of info for the artist selected by "event".""" def default_func(event): return {} registry = { AxesImage : [pick_info.image_props], PathCollection : [pick_info.scatter_props, self._contour_info, ...
Get a dict of info for the artist selected by "event".
def redirect( to, headers=None, status=302, content_type="text/html; charset=utf-8" ): """Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified URL to redirect to :param headers: optional dict of headers to include in the new request :param status: status code (i...
Abort execution and cause a 302 redirect (by default). :param to: path or fully qualified URL to redirect to :param headers: optional dict of headers to include in the new request :param status: status code (int) of the new request, defaults to 302 :param content_type: the content type (string) of the ...
def csv( self, filepath=None ): """*Render the data in CSV format* **Key Arguments:** - ``filepath`` -- path to the file to write the csv content to. Default *None* **Return:** - ``renderedData`` -- the data rendered in csv format **Usage:**...
*Render the data in CSV format* **Key Arguments:** - ``filepath`` -- path to the file to write the csv content to. Default *None* **Return:** - ``renderedData`` -- the data rendered in csv format **Usage:** To render the data set as csv: .. co...
def wait(timeout=None, flush=True): """Wait for an event. Args: timeout (Optional[int]): The time in seconds that this function will wait before giving up and returning None. With the default value of None, this will block forever. flush (bool): If True a call to :any:`...
Wait for an event. Args: timeout (Optional[int]): The time in seconds that this function will wait before giving up and returning None. With the default value of None, this will block forever. flush (bool): If True a call to :any:`tdl.flush` will be made before ...
def cancel(self, workflow_id): """Cancels a running workflow. Args: workflow_id (str): Workflow id. Returns: Nothing """ self.logger.debug('Canceling workflow: ' + workflow_id) url = '%(wf_url)s/%(wf_id)s/cancel' % { 'wf_u...
Cancels a running workflow. Args: workflow_id (str): Workflow id. Returns: Nothing
def get_running_race(self, race_id): """ Gets a running race for a given identifier.t http://strava.github.io/api/v3/running_races/#list :param race_id: id for the race :rtype: :class:`stravalib.model.RunningRace` """ raw = self.protocol.get('/running_r...
Gets a running race for a given identifier.t http://strava.github.io/api/v3/running_races/#list :param race_id: id for the race :rtype: :class:`stravalib.model.RunningRace`
def as_hyperbola(self, rotated=False): """ Hyperbolic error area """ idx = N.diag_indices(3) _ = 1/self.covariance_matrix[idx] d = list(_) d[-1] *= -1 arr = N.identity(4)*-1 arr[idx] = d hyp = conic(arr) if rotated: R =...
Hyperbolic error area
def chmod(path, mode=None, user=None, group=None, other=None, recursive=False): """Changes file mode permissions. >>> if chmod('/tmp/one', 0755): ... print('OK') OK NOTE: The precending ``0`` is required when using a numerical mode. """ successful = True mode = _ops_mode(mode...
Changes file mode permissions. >>> if chmod('/tmp/one', 0755): ... print('OK') OK NOTE: The precending ``0`` is required when using a numerical mode.
def rgamma(alpha, beta, size=None): """ Random gamma variates. """ return np.random.gamma(shape=alpha, scale=1. / beta, size=size)
Random gamma variates.
def initialize_ui(self): """ Initializes the Component ui. :return: Method success. :rtype: bool """ LOGGER.debug("> Initializing '{0}' Component ui.".format(self.__class__.__name__)) self.__model = ProjectsProxyModel(self) self.__model.setSourceModel(se...
Initializes the Component ui. :return: Method success. :rtype: bool
def PrependENVPath(self, name, newpath, envname = 'ENV', sep = os.pathsep, delete_existing=1): """Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to hel...
Prepend path elements to the path 'name' in the 'ENV' dictionary for this environment. Will only add any particular path once, and will normpath and normcase all paths to help assure this. This can also handle the case where the env variable is a list instead of a string. If d...
def initialize(self, config): """ Create the physical storage for this job store, allocate a workflow ID and persist the given Toil configuration to the store. :param toil.common.Config config: the Toil configuration to initialize this job store with. The given configurat...
Create the physical storage for this job store, allocate a workflow ID and persist the given Toil configuration to the store. :param toil.common.Config config: the Toil configuration to initialize this job store with. The given configuration will be updated with the newly allocated workf...
def climb_stairs(n): """ :type n: int :rtype: int """ arr = [1, 1] for _ in range(1, n): arr.append(arr[-1] + arr[-2]) return arr[-1]
:type n: int :rtype: int
def surface(self, param): """Return the detector surface point corresponding to ``param``. For parameter value ``p``, the surface point is given by :: surf = p[0] * axes[0] + p[1] * axes[1] Parameters ---------- param : `array-like` or sequence Paramete...
Return the detector surface point corresponding to ``param``. For parameter value ``p``, the surface point is given by :: surf = p[0] * axes[0] + p[1] * axes[1] Parameters ---------- param : `array-like` or sequence Parameter value(s) at which to evaluate. A se...
def roll_mean(input, window): '''Apply a rolling mean function to an array. This is a simple rolling aggregation.''' nobs, i, j, sum_x = 0,0,0,0. N = len(input) if window > N: raise ValueError('Out of bound') output = np.ndarray(N-window+1,dtype=input.dtype) for val in inpu...
Apply a rolling mean function to an array. This is a simple rolling aggregation.
def _generate_limit_items(lower, upper): """Yield key, value pairs for limits dictionary. Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``. A key, value pair is emitted if the bounds are not None. """ # Use value + 0 to convert any -0.0 to 0.0 which looks better. if lowe...
Yield key, value pairs for limits dictionary. Yield pairs of key, value where key is ``lower``, ``upper`` or ``fixed``. A key, value pair is emitted if the bounds are not None.
def generate_matrices(dim = 40): """ Generates the matrices that positive and negative samples are multiplied with. The matrix for positive samples is randomly drawn from a uniform distribution, with elements in [-1, 1]. The matrix for negative examples is the sum of the positive matrix with a matrix drawn ...
Generates the matrices that positive and negative samples are multiplied with. The matrix for positive samples is randomly drawn from a uniform distribution, with elements in [-1, 1]. The matrix for negative examples is the sum of the positive matrix with a matrix drawn from a normal distribution with mean 0 ...
def list(self, id=None): """ List all running jobs :param id: optional ID for the job to list """ args = {'id': id} self._job_chk.check(args) return self._client.json('job.list', args)
List all running jobs :param id: optional ID for the job to list
def wait_command(self, start_func, turns=1, end_func=None): """Call ``start_func``, wait ``turns``, and then call ``end_func`` if provided Disables input for the duration. :param start_func: function to call just after disabling input :param turns: number of turns to wait :para...
Call ``start_func``, wait ``turns``, and then call ``end_func`` if provided Disables input for the duration. :param start_func: function to call just after disabling input :param turns: number of turns to wait :param end_func: function to call just before re-enabling input :ret...
def add_to_dumper(dumper: Type, classes: List[Type]) -> None: """Register user-defined classes with the Dumper. This enables the Dumper to write objects of your classes to a \ YAML file. Note that all the arguments are types, not instances! Args: dumper: Your dumper class(!), derived from yati...
Register user-defined classes with the Dumper. This enables the Dumper to write objects of your classes to a \ YAML file. Note that all the arguments are types, not instances! Args: dumper: Your dumper class(!), derived from yatiml.Dumper classes: One or more classes to add.
def get_wrapped_stream(stream, encoding=None, errors="replace"): """ Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :param str encoding: The encoding to use for the stream :param str errors: The error handler to use, def...
Given a stream, wrap it in a `StreamWrapper` instance and return the wrapped stream. :param stream: A stream instance to wrap :param str encoding: The encoding to use for the stream :param str errors: The error handler to use, default "replace" :returns: A new, wrapped stream :rtype: :class:`Stream...
def get_aggregates(self, request): """ Implements the Get aggregates (total number of objects filtered) maps to PATCH /api/object_name/get_aggregates/ in rest semantics :param request: rip.Request :return: rip.Response """ pipeline = crud_pipeline_factory.get_agg...
Implements the Get aggregates (total number of objects filtered) maps to PATCH /api/object_name/get_aggregates/ in rest semantics :param request: rip.Request :return: rip.Response
def raise_from_response(resp): """Turn a failed request response into a BackendError. Handy for reflecting HTTP errors from farther back in the call chain. Parameters ---------- resp: :class:`requests.Response` Raises ------ :class:`apikit.BackendError` If `resp.status_code` i...
Turn a failed request response into a BackendError. Handy for reflecting HTTP errors from farther back in the call chain. Parameters ---------- resp: :class:`requests.Response` Raises ------ :class:`apikit.BackendError` If `resp.status_code` is equal to or greater than 400.
def add_alarm_action(self, action_arn=None): """ Adds an alarm action, represented as an SNS topic, to this alarm. What do do when alarm is triggered. :type action_arn: str :param action_arn: SNS topics to which notification should be sent if the ala...
Adds an alarm action, represented as an SNS topic, to this alarm. What do do when alarm is triggered. :type action_arn: str :param action_arn: SNS topics to which notification should be sent if the alarm goes to state ALARM.
def get_time_slide_id(xmldoc, time_slide, create_new = None, superset_ok = False, nonunique_ok = False): """ Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_s...
Return the time_slide_id corresponding to the offset vector described by time_slide, a dictionary of instrument/offset pairs. Example: >>> get_time_slide_id(xmldoc, {"H1": 0, "L1": 0}) 'time_slide:time_slide_id:10' This function is a wrapper around the .get_time_slide_id() method of the pycbc_glue.ligolw.lscta...
def get_evpn_table(self): """Returns global EVPN table. Creates the table if it does not exist. """ evpn_table = self._global_tables.get(RF_L2_EVPN) # Lazy initialization of the table. if not evpn_table: evpn_table = EvpnTable(self._core_service, self._signal...
Returns global EVPN table. Creates the table if it does not exist.
def delete(self): """Del or Backspace pressed. Delete selection""" with self._qpart: for cursor in self.cursors(): if cursor.hasSelection(): cursor.deleteChar()
Del or Backspace pressed. Delete selection
def similarity_matrix(self, x_subjects=None, y_subjects=None, symmetric=False): """ Query for similarity matrix between groups of subjects Return a list of intersection result objects with keys: - x : term from x - y : term from y - c : count of intersection ...
Query for similarity matrix between groups of subjects Return a list of intersection result objects with keys: - x : term from x - y : term from y - c : count of intersection - j : jaccard score
def build_groetzch_graph(): """Makes a new Groetzsch graph. Ref: http://mathworld.wolfram.com/GroetzschGraph.html""" # Because the graph is so complicated, we want to # build it via adjacency matrix specification # -- Initialize the matrix to all zeros adj = [[0 for _ in range(11)] for _...
Makes a new Groetzsch graph. Ref: http://mathworld.wolfram.com/GroetzschGraph.html
def cprint(self, cstr): """ Clear line, then reprint on same line :param cstr: string to print on current line """ cstr = str(cstr) # Force it to be a string cstr_len = len(cstr) prev_cstr_len = len(self._prev_cstr) num_spaces = 0 if cstr_len < pr...
Clear line, then reprint on same line :param cstr: string to print on current line
def generate_idx(maxlen, nedit): """ generate all possible nedit edits of a string. each item has the form ((index1, index2), 'A', 'G') for nedit=2 index1 will be replaced by 'A', index2 by 'G' this covers all edits < nedit as well since some of the specified substitutions will not change the ...
generate all possible nedit edits of a string. each item has the form ((index1, index2), 'A', 'G') for nedit=2 index1 will be replaced by 'A', index2 by 'G' this covers all edits < nedit as well since some of the specified substitutions will not change the base
def mt_modelform_register_clean_method(form_self, field_name, func, nomaster=False): """ You can add clean_<field_name> for each translated field. For example: class MyModelForm(models.ModelForm): class Meta: model = MyModel _mt_fields = mt_fields(('title', 'description'), n...
You can add clean_<field_name> for each translated field. For example: class MyModelForm(models.ModelForm): class Meta: model = MyModel _mt_fields = mt_fields(('title', 'description'), nomaster=True) fields = _mt_fields def __init__(self, *args, **kwargs): ...
def on_batch_end(self, iteration:int, smooth_loss:TensorOrNumber, **kwargs:Any)->None: "Determine if loss has runaway and we should stop." if iteration==0 or smooth_loss < self.best_loss: self.best_loss = smooth_loss self.opt.lr = self.sched.step() if self.sched.is_done or (self.stop_div...
Determine if loss has runaway and we should stop.
def write(self, image, options, thumbnail): """ Wrapper for ``_write`` """ format_ = options['format'] quality = options['quality'] image_info = options.get('image_info', {}) # additional non-default-value options: progressive = options.get('progressive', ...
Wrapper for ``_write``