code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def pair(args): """ %prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments. """ p = OptionParser(pair.__doc__) p.set_sep(sep=None, help="Separator in name to reduce to clone id" +\ "e.g. GFNQ33242/1 us...
%prog pair fastafile Generate .pairs.fasta and .fragments.fasta by matching records into the pairs and the rest go to fragments.
def char_range(starting_char, ending_char): """ Create a range generator for chars """ assert isinstance(starting_char, str), 'char_range: Wrong argument/s type' assert isinstance(ending_char, str), 'char_range: Wrong argument/s type' for char in range(ord(starting_char), ord(ending_char) + 1):...
Create a range generator for chars
def _cleanup(self): """ Cleanup open channels and handlers """ for channel in self._open_channels: try: self.disconnect_channel(channel) except Exception: # pylint: disable=broad-except pass for handler in self._handlers.values(): ...
Cleanup open channels and handlers
def trimSegments(self, minPermanence=None, minNumSyns=None): """ This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. Parameters: -------------------------------------------------------------- mi...
This method deletes all synapses whose permanence is less than minPermanence and deletes any segments that have less than minNumSyns synapses remaining. Parameters: -------------------------------------------------------------- minPermanence: Any syn whose permamence is 0 or < minPermanence wi...
def map_pixel(self, point_x, point_y): ''' geo.map_pixel(point_x, point_y) Return value of raster in location Note: (point_x, point_y) must belong to the geographic coordinate system and the coverage of the raster ''' row, col = map_pixel(point_x, point_y, ...
geo.map_pixel(point_x, point_y) Return value of raster in location Note: (point_x, point_y) must belong to the geographic coordinate system and the coverage of the raster
def sizeClassifier(path, min_size=DEFAULTS['min_size']): """Sort a file into a group based on on-disk size. :param paths: See :func:`fastdupes.groupify` :param min_size: Files smaller than this size (in bytes) will be ignored. :type min_size: :class:`__builtins__.int` :returns: See :func:`fastdup...
Sort a file into a group based on on-disk size. :param paths: See :func:`fastdupes.groupify` :param min_size: Files smaller than this size (in bytes) will be ignored. :type min_size: :class:`__builtins__.int` :returns: See :func:`fastdupes.groupify` .. todo:: Rework the calling of :func:`~os.sta...
def to_dict(mapreduce_yaml): """Converts a MapReduceYaml file into a JSON-encodable dictionary. For use in user-visible UI and internal methods for interfacing with user code (like param validation). as a list Args: mapreduce_yaml: The Pyton representation of the mapreduce.yaml document. Re...
Converts a MapReduceYaml file into a JSON-encodable dictionary. For use in user-visible UI and internal methods for interfacing with user code (like param validation). as a list Args: mapreduce_yaml: The Pyton representation of the mapreduce.yaml document. Returns: A list of configuration...
def xml_to_metrics(xmlstr, object_type): '''Converts xml response to service bus metrics objects The xml format for MetricProperties <entry> <id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id> <title/> <updated>2014-10-09T11:56:50Z</updated> <author> <name/> </au...
Converts xml response to service bus metrics objects The xml format for MetricProperties <entry> <id>https://sbgm.windows.net/Metrics(\'listeners.active\')</id> <title/> <updated>2014-10-09T11:56:50Z</updated> <author> <name/> </author> <content type="application/xml"> <...
def create(self, alert_config, occurrence_frequency_count=None, occurrence_frequency_unit=None, alert_frequency_count=None, alert_frequency_unit=None): """ Create a new alert :param alert_config: A list of AlertConfig cl...
Create a new alert :param alert_config: A list of AlertConfig classes (Ex: ``[EmailAlertConfig('me@mydomain.com')]``) :type alert_config: list of :class:`PagerDutyAlertConfig<logentries_api.alerts.PagerDutyAlertConfig>`, :class:`WebHookAlertConfig<logentries_api.aler...
def save(): """ Apply configuration changes on all the modules """ from .models import ModuleInfo logger = logging.getLogger(__name__) logger.info("Saving changes") # Save + restart for module in modules(): if module.enabled: if module.changed: modul...
Apply configuration changes on all the modules
def work(self): """ Use a blocking <sleep> call to periodically trigger a signal. """ import time for val in range(200): time.sleep(0.1) self.sigUpdate.emit(val + 1)
Use a blocking <sleep> call to periodically trigger a signal.
def transform(self, data): """ :param data: :type data: dict :return: :rtype: """ out=[] keys = sorted(data.keys()) for k in keys: out.append("%s=%s" % (k, data[k])) return "\n".join(out)
:param data: :type data: dict :return: :rtype:
def next(self, fetch: bool = False, next_symbol: _NextSymbol = DEFAULT_NEXT_SYMBOL) -> _Next: """Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL. ...
Attempts to find the next page, if there is one. If ``fetch`` is ``True`` (default), returns :class:`HTML <HTML>` object of next page. If ``fetch`` is ``False``, simply returns the next URL.
def run(self, *args): """Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file. """ params = self.parser.parse_args(args) with params.outfile as outfile: ...
Export data from the registry. By default, it writes the data to the standard output. If a positional argument is given, it will write the data on that file.
def forward_remote( self, remote_port, local_port=None, remote_host="127.0.0.1", local_host="localhost", ): """ Open a tunnel connecting ``remote_port`` to the local environment. For example, say you're running a daemon in development mode on your ...
Open a tunnel connecting ``remote_port`` to the local environment. For example, say you're running a daemon in development mode on your workstation at port 8080, and want to funnel traffic to it from a production or staging environment. In most situations this isn't possible as your of...
def _version_string(): """ Gets the output for `trytravis --version`. """ platform_system = platform.system() if platform_system == 'Linux': os_name, os_version, _ = platform.dist() else: os_name = platform_system os_version = platform.version() python_version = platform.pyth...
Gets the output for `trytravis --version`.
def select_eep(self, rorg_func, rorg_type, direction=None, command=None): ''' Set EEP based on FUNC and TYPE ''' # set EEP profile self.rorg_func = rorg_func self.rorg_type = rorg_type self._profile = self.eep.find_profile(self._bit_data, self.rorg, rorg_func, rorg_type, directio...
Set EEP based on FUNC and TYPE
def project_invite(object_id, input_params={}, always_retry=False, **kwargs): """ Invokes the /project-xxxx/invite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Finvite """ return DXHTTPRequest('/%s/...
Invokes the /project-xxxx/invite API method. For more info, see: https://wiki.dnanexus.com/API-Specification-v1.0.0/Project-Permissions-and-Sharing#API-method%3A-%2Fproject-xxxx%2Finvite
def update_many(self, **kwargs): """ Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw). """ db_object...
Update multiple objects from collection. First ES is queried, then the results are used to query DB. This is done to make sure updated objects are those filtered by ES in the 'index' method (so user updates what he saw).
def from_triple(cls, triple): """ Create a Target instance for the given triple (a string). """ with ffi.OutputString() as outerr: target = ffi.lib.LLVMPY_GetTargetFromTriple(triple.encode('utf8'), outerr) if...
Create a Target instance for the given triple (a string).
def table_exists(self, table): """Returns whether the given table exists. :param table: :type table: BQTable """ if not self.dataset_exists(table.dataset): return False try: self.client.tables().get(projectId=table.project_id, ...
Returns whether the given table exists. :param table: :type table: BQTable
def read_probes(self, key = None): """ function is overloaded: - read_probes() - read_probes(key) Args: key: name of requested value Returns: - if called without argument: returns the values of all probes in dictionary form - ...
function is overloaded: - read_probes() - read_probes(key) Args: key: name of requested value Returns: - if called without argument: returns the values of all probes in dictionary form - if called with argument: returns the value the requeste...
def _check_restart_params(self, restart_strategy, min_beta, s_greedy, xi_restart): r""" Check restarting parameters This method checks that the restarting parameters are set and satisfy the correct assumptions. It also checks that the current mode is regula...
r""" Check restarting parameters This method checks that the restarting parameters are set and satisfy the correct assumptions. It also checks that the current mode is regular (as opposed to CD for now). Parameters ---------- restart_strategy: str or None na...
def _noneload(l: Loader, value, type_) -> None: """ Loads a value that can only be None, so it fails if it isn't """ if value is None: return None raise TypedloadValueError('Not None', value=value, type_=type_)
Loads a value that can only be None, so it fails if it isn't
async def close_async(self, context, reason): """ Called by processor host to indicate that the event processor is being stopped. :param context: Information about the partition :type context: ~azure.eventprocessorhost.PartitionContext """ logger.info("Connection closed (...
Called by processor host to indicate that the event processor is being stopped. :param context: Information about the partition :type context: ~azure.eventprocessorhost.PartitionContext
def attributes(self) -> Sequence[bytes]: """The mailbox attributes that should be returned with the mailbox in a ``LIST`` response, e.g. ``\\Noselect``. See Also: `RFC 3348 <https://tools.ietf.org/html/rfc3348>`_ """ ret: List[bytes] = [] if not self.exists:...
The mailbox attributes that should be returned with the mailbox in a ``LIST`` response, e.g. ``\\Noselect``. See Also: `RFC 3348 <https://tools.ietf.org/html/rfc3348>`_
def activate(self, *, filter_func=None): ''' Activate the type safety checker. After the call all functions that need to be checked will be. ''' if self.active: raise RuntimeError("Type safety check already active") self.__module_finder = ModuleFinder(Valida...
Activate the type safety checker. After the call all functions that need to be checked will be.
def __init(self): """ initializes all the properties """ params = { "f" : "json" } json_dict = self._get(url=self._url, param_dict=params, securityHandler=self._securityHandler, proxy_url=self._proxy_url, ...
initializes all the properties
def is_reached(self, uid=None): """ is_reached is to be called for every object that counts towards the limit. - When called with no uid, the Limiter assumes this is a new object and unconditionally increments the counter (less CPU and memory usage). - When a given object can be ...
is_reached is to be called for every object that counts towards the limit. - When called with no uid, the Limiter assumes this is a new object and unconditionally increments the counter (less CPU and memory usage). - When a given object can be passed multiple times, a uid must be provided to ...
def PhenomModel(self, r): """Fit to field map A phenomenological fit by Ryan Bayes (Glasgow) to a field map generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated January 30th, 2012. Not defined for r <= 0""" if r <= 0: raise ValueError fiel...
Fit to field map A phenomenological fit by Ryan Bayes (Glasgow) to a field map generated by Bob Wands (FNAL). It assumes a 1 cm plate. This is dated January 30th, 2012. Not defined for r <= 0
def plot(x, fmt='-', marker=None, markers=None, linestyle=None, linestyles=None, color=None, colors=None, palette='hls', group=None, hue=None, labels=None, legend=None, title=None, size=None, elev=10, azim=-60, ndims=3, model=None, model_params=None, reduce='IncrementalPCA', cluster=...
Plots dimensionality reduced data and parses plot arguments Parameters ---------- x : Numpy array, DataFrame, String, Geo or mixed list Data for the plot. The form should be samples (rows) by features (cols). fmt : str or list of strings A list of format strings. All matplotlib format...
def delete_group(self, group_id): """ Remove a group from your team :param group_id: Id of group """ url = self.TEAM_GROUPS_ID_URL % group_id connection = Connection(self.token) connection.set_url(self.production, url) return connection.delete_request()
Remove a group from your team :param group_id: Id of group
def ensure_chosen_alternatives_are_in_user_alt_ids(choice_col, wide_data, availability_vars): """ Ensures that all chosen alternatives in `wide_df` are present in the `availability_vars` dict. Raises a help...
Ensures that all chosen alternatives in `wide_df` are present in the `availability_vars` dict. Raises a helpful ValueError if not. Parameters ---------- choice_col : str. Denotes the column in `wide_data` that contains a one if the alternative pertaining to the given row was the observe...
def labels(self): """Tuple of labels.""" return tuple(_Label(label.get('id'), label.get('color'), label.text) for label in self.root.iter('label'))
Tuple of labels.
def show(self): '''Output for command sos show''' textWidth = max(60, shutil.get_terminal_size((80, 20)).columns) text = f' {self.step_name() + ":":<21} ' + self.comment print('\n'.join( textwrap.wrap( text, width=textWidth, in...
Output for command sos show
def get(key, default=-1): """Backport support for original codes.""" if isinstance(key, int): return NotifyMessage(key) if key not in NotifyMessage._member_map_: extend_enum(NotifyMessage, key, default) return NotifyMessage[key]
Backport support for original codes.
def evaluate(self, node: InstanceNode) -> XPathValue: """Evaluate the receiver and return the result. Args: node: Context node for XPath evaluation. Raises: XPathTypeError: If a subexpression of the receiver is of a wrong type. """ return...
Evaluate the receiver and return the result. Args: node: Context node for XPath evaluation. Raises: XPathTypeError: If a subexpression of the receiver is of a wrong type.
def xor(key, data): """ Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``data`` with. ...
Perform cyclical exclusive or operations on ``data``. The ``key`` can be a an integer *(0 <= key < 256)* or a byte sequence. If the key is smaller than the provided ``data``, the ``key`` will be repeated. Args: key(int or bytes): The key to xor ``data`` with. data(bytes): The data to p...
def _setattr_url_map(self): ''' Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs. ''' if self.apiopts.get('enable_sessions', True) is False: url_blacklist = ['login', 'logout', 'minions', 'jobs'] ...
Set an attribute on the local instance for each key/val in url_map CherryPy uses class attributes to resolve URLs.
def macro_network(): """A network of micro elements which has greater integrated information after coarse graining to a macro scale. """ tpm = np.array([[0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 0.3, 0.3], [0.3, 0.3, 1.0, 1.0], ...
A network of micro elements which has greater integrated information after coarse graining to a macro scale.
def screen_resolution(): """ Returns the current screen's resolution. Should be multi-platform. :return: A tuple containing the width and height of the screen. """ w = 0 h = 0 try: # Windows import ctypes user32 = ctypes.windll.user32 w, h = user32.GetSy...
Returns the current screen's resolution. Should be multi-platform. :return: A tuple containing the width and height of the screen.
def add(self, source, email=None, name=None, username=None, uuid=None, matching=None, interactive=False): """Add an identity to the registry. This method adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. ...
Add an identity to the registry. This method adds a new identity to the registry. By default, a new unique identity will be also added an associated to the new identity. When <uuid> parameter is set, it only creates a new identity that will be associated to a unique identity defined by ...
def q(self, x, q0): """ Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`. """ y1_0 = q0 y0_0 = 0 y0 = [y0_0, y1_0] y = _sp.integrate.odeint(self._func, y0, x, Dfun=self._gradient, rtol=self.rtol, atol=self.at...
Numerically solved trajectory function for initial conditons :math:`q(0) = q_0` and :math:`q'(0) = 0`.
def has_perm(self, user, perm, obj=None, *args, **kwargs): """Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type...
Test user permissions for a single action and object. :param user: The user to test. :type user: ``User`` :param perm: The action to test. :type perm: ``str`` :param obj: The object path to test. :type obj: ``tutelary.engine.Object`` :returns: ``bool`` -- is the ...
def authenticate(self, name, password, mechanism="DEFAULT"): """ Send an authentication command for this database. mostly stolen from pymongo """ if not isinstance(name, (bytes, unicode)): raise TypeError("TxMongo: name must be an instance of basestring.") if ...
Send an authentication command for this database. mostly stolen from pymongo
def p_new_expr(self, p): """new_expr : member_expr | NEW new_expr """ if len(p) == 2: p[0] = p[1] else: p[0] = ast.NewExpr(p[2])
new_expr : member_expr | NEW new_expr
def parse(query_string, unquote=True, normalized=False, encoding=DEFAULT_ENCODING): ''' Main parse function @param query_string: @param unquote: unquote html query string ? @param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a d...
Main parse function @param query_string: @param unquote: unquote html query string ? @param encoding: An optional encoding used to decode the keys and values. Defaults to utf-8, which the W3C declares as a defaul in the W3C algorithm for encoding. @see http://www.w3.org/TR/html5/forms.html#applicati...
def tuple_search(t, i, v): """ Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value """ for e in t: if e[i] == v: return e retur...
Search tuple array by index and value :param t: tuple array :param i: index of the value in each tuple :param v: value :return: the first tuple in the array with the specific index / value
def sites(c): """ Build both doc sites w/ maxed nitpicking. """ # TODO: This is super lolzy but we haven't actually tackled nontrivial # in-Python task calling yet, so we do this to get a copy of 'our' context, # which has been updated with the per-collection config data of the # docs/www su...
Build both doc sites w/ maxed nitpicking.
def reads(err_log): """ Parse the outputs from bbmerge to extract the total number of reads, as well as the number of reads that could be paired :param err_log: bbmerge outputs the stats in the error file :return: num_reads, the total number of reads, paired_reads, number of pair...
Parse the outputs from bbmerge to extract the total number of reads, as well as the number of reads that could be paired :param err_log: bbmerge outputs the stats in the error file :return: num_reads, the total number of reads, paired_reads, number of paired readds
def extract_to(self, *, stream=None, fileprefix=''): """Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the da...
Attempt to extract the image directly to a usable image file If possible, the compressed data is extracted and inserted into a compressed image file format without transcoding the compressed content. If this is not possible, the data will be decompressed and extracted to an appropriate ...
def DoubleClick(cls): ''' 左键点击2次 ''' element = cls._element() action = ActionChains(Web.driver) action.double_click(element) action.perform()
左键点击2次
def add_pr_curve(self, tag, labels, predictions, num_thresholds, global_step=None, weights=None): """Adds precision-recall curve. Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs. Since `asnumpy()` is a blocking function call, this function would ...
Adds precision-recall curve. Note: This function internally calls `asnumpy()` for MXNet `NDArray` inputs. Since `asnumpy()` is a blocking function call, this function would block the main thread till it returns. It may consequently affect the performance of async execution of the MXNet ...
def delete(self): """Deletes the bucket. Raises: Exception if there was an error deleting the bucket. """ if self.exists(): try: self._api.buckets_delete(self._name) except Exception as e: raise e
Deletes the bucket. Raises: Exception if there was an error deleting the bucket.
def connections_from_object(self, from_obj): """ Returns a ``Connection`` query set matching all connections with the given object as a source. """ self._validate_ctypes(from_obj, None) return self.connections.filter(from_pk=from_obj.pk)
Returns a ``Connection`` query set matching all connections with the given object as a source.
def throw(self, method, args={}, nowait=False, **kwargs): """Call method on one of the agents in round robin. See :meth:`call_or_cast` for a full list of supported arguments. If the keyword argument `nowait` is false (default) it will block and return the reply. """ ...
Call method on one of the agents in round robin. See :meth:`call_or_cast` for a full list of supported arguments. If the keyword argument `nowait` is false (default) it will block and return the reply.
def clear_mask(self): """Clear mask from image. This does not clear loaded masks from memory.""" if self.masktag: try: self.canvas.delete_object_by_tag(self.masktag, redraw=False) except Exception: pass if self.maskhltag: ...
Clear mask from image. This does not clear loaded masks from memory.
def results_tc(self, key, value): """Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The da...
Write data to results_tc file in TcEX specified directory. The TcEx platform support persistent values between executions of the App. This method will store the values for TC to read and put into the Database. Args: key (string): The data key to be stored. value (strin...
def __get_average_intra_cluster_distance(self, entry): """! @brief Calculates average intra cluster distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Average intra...
! @brief Calculates average intra cluster distance between current and specified clusters. @param[in] entry (cfentry): Clustering feature to which distance should be obtained. @return (double) Average intra cluster distance.
def read_from_file(self, filename): """Read from an existing json file. :param filename: The file to be written to. :type filename: basestring, str :returns: Success status. -1 for unsuccessful 0 for success :rtype: int """ if not exists(filename): r...
Read from an existing json file. :param filename: The file to be written to. :type filename: basestring, str :returns: Success status. -1 for unsuccessful 0 for success :rtype: int
def Parse(self): """Parse program output.""" (start_line, lang) = self.ParseDesc() if start_line < 0: return if 'python' == lang: self.ParsePythonFlags(start_line) elif 'c' == lang: self.ParseCFlags(start_line) elif 'java' == lang: self.ParseJavaFlags(start_line)
Parse program output.
def addFeatureToGraph( self, add_region=True, region_id=None, feature_as_class=False): """ We make the assumption here that all features are instances. The features are located on a region, which begins and ends with faldo:Position The feature locations leverage the F...
We make the assumption here that all features are instances. The features are located on a region, which begins and ends with faldo:Position The feature locations leverage the Faldo model, which has a general structure like: Triples: feature_id a feature_type (individual)...
def getMibSymbol(self): """Returns MIB variable symbolic identification. Returns ------- str MIB module name str MIB variable symbolic name : :py:class:`~pysnmp.proto.rfc1902.ObjectName` class instance representing MIB variable inst...
Returns MIB variable symbolic identification. Returns ------- str MIB module name str MIB variable symbolic name : :py:class:`~pysnmp.proto.rfc1902.ObjectName` class instance representing MIB variable instance index. Raises ...
def verify_system_status(self): """Verify system status.""" if not sys.platform.startswith('linux'): raise InstallError('Supported platform is Linux only.') if self.python.is_system_python(): if self.python.is_python_binding_installed(): message = ''' RPM...
Verify system status.
def subnet_range(ip_net, cidr): """ Function to return a subnet range value from a IP address and CIDR pair Args: ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 1 to 32 Returns: returns a dictionary of info """ ...
Function to return a subnet range value from a IP address and CIDR pair Args: ip_net: Unicast or Multicast IP address or subnet in the following format 192.168.1.1, 239.1.1.1 cidr: CIDR value of 1 to 32 Returns: returns a dictionary of info
def parse_name(cls, name: str, default: T = None) -> T: """Parse specified name for IntEnum; return default if not found.""" if not name: return default name = name.lower() return next((item for item in cls if name == item.name.lower()), default)
Parse specified name for IntEnum; return default if not found.
def m2i(self, pkt, s): """ The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. However, safedec prevents the r...
The good thing about safedec is that it may still decode ASN1 even if there is a mismatch between the expected tag (self.ASN1_tag) and the actual tag; the decoded ASN1 object will simply be put into an ASN1_BADTAG object. However, safedec prevents the raising of exceptions needed for ASN...
def ProfileRunValidationOutputFromOptions(feed, options): """Run RunValidationOutputFromOptions, print profile and return exit code.""" import cProfile import pstats # runctx will modify a dict, but not locals(). We need a way to get rv back. locals_for_exec = locals() cProfile.runctx('rv = RunValidationOut...
Run RunValidationOutputFromOptions, print profile and return exit code.
def set_bind(self): """ Sets key bindings -- we need this more than once """ RangedInt.set_bind(self) self.unbind('<Next>') self.unbind('<Prior>') self.bind('<Next>', lambda e: self.set(self._min())) self.bind('<Prior>', lambda e: self.set(self._max()))
Sets key bindings -- we need this more than once
def GET(self, courseid, taskid, path): # pylint: disable=arguments-differ """ GET request """ try: course = self.course_factory.get_course(courseid) if not self.user_manager.course_is_open_to_user(course): return self.template_helper.get_renderer().course_unavail...
GET request
def parser(self): """return the parser for the current name""" module = self.module subcommands = self.subcommands if subcommands: module_desc = inspect.getdoc(module) parser = Parser(description=module_desc, module=module) subparsers = parser.add_sub...
return the parser for the current name
def flock(path): """Attempt to acquire a POSIX file lock. """ with open(path, "w+") as lf: try: fcntl.flock(lf, fcntl.LOCK_EX | fcntl.LOCK_NB) acquired = True yield acquired except OSError: acquired = False yield acquired ...
Attempt to acquire a POSIX file lock.
def assets(self, asset_code=None, asset_issuer=None, cursor=None, order='asc', limit=10): """This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are ...
This endpoint represents all assets. It will give you all the assets in the system along with various statistics about each. See the documentation below for details on query parameters that are available. `GET /assets{?asset_code,asset_issuer,cursor,limit,order} <https://www.st...
def update(self): """ Update the PopupWindow if it is currently showing. This avoids calling update during initialization. """ if not self.showing: return d = self.declaration self.set_show(d.show)
Update the PopupWindow if it is currently showing. This avoids calling update during initialization.
def read_excel(file_name, offset=1, sheet_index=0): """ 读取 Excel :param sheet_index: :param file_name: :param offset: 偏移,一般第一行是表头,不需要读取数据 :return: """ try: workbook = xlrd.open_workbook(file_name) except Exception as e: return None if len(workbook.sheets()) <= 0:...
读取 Excel :param sheet_index: :param file_name: :param offset: 偏移,一般第一行是表头,不需要读取数据 :return:
def main(): """ Entry point """ rc_settings = read_rcfile() parser = ArgumentParser(description='Millipede generator') parser.add_argument('-s', '--size', type=int, nargs="?", help='the size of the millipede') parser.add...
Entry point
def get_requests(self): """ Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest) """ safe = self.get_safe_struct() self.download_list = [] self.structure_recursion(safe...
Creates product structure and returns list of files for download :return: list of download requests :rtype: list(download.DownloadRequest)
def text(self): """Formatted Command declaration. This is the C declaration for the command. """ params = ', '.join(x.text for x in self.params) return '{0} ({1})'.format(self.proto_text, params)
Formatted Command declaration. This is the C declaration for the command.
def _combine_out_files(chr_files, work_dir, data): """Concatenate all CNV calls into a single file. """ out_file = "%s.bed" % sshared.outname_from_inputs(chr_files) if not utils.file_exists(out_file): with file_transaction(data, out_file) as tx_out_file: with open(tx_out_file, "w") a...
Concatenate all CNV calls into a single file.
def status_unreblog(self, id): """ Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged. """ id = self.__unpack_id(id) url = '/api/v1/statuses/{0}/unreblog'.format(str(id)) return self.__api_request('POST', url)
Un-reblog a status. Returns a `toot dict`_ with the status that used to be reblogged.
def create(sub_array_id): """Create / register a Scheduling Block instance with SDP.""" config = request.data config['sub_array_id'] = 'subarray-{:02d}'.format(sub_array_id) return add_scheduling_block(config)
Create / register a Scheduling Block instance with SDP.
def depends_on_helper(obj): """ Handles using .title if the given object is a troposphere resource. If the given object is a troposphere resource, use the `.title` attribute of that resource. If it's a string, just use the string. This should allow more pythonic use of DependsOn. """ if isinsta...
Handles using .title if the given object is a troposphere resource. If the given object is a troposphere resource, use the `.title` attribute of that resource. If it's a string, just use the string. This should allow more pythonic use of DependsOn.
def p_contextualize_item(self, t): """contextualize_item : SYSTEM VAR CONFIGURE VAR | SYSTEM VAR CONFIGURE VAR STEP NUMBER | SYSTEM VAR CONFIGURE VAR WITH VAR""" if len(t) == 5: t[0] = contextualize_item(t[2], t[4], line=t.lineno(1...
contextualize_item : SYSTEM VAR CONFIGURE VAR | SYSTEM VAR CONFIGURE VAR STEP NUMBER | SYSTEM VAR CONFIGURE VAR WITH VAR
def main(http_port, peer_name, node_name, app_id): """ Runs the framework :param http_port: HTTP port to listen to :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Application ID """ # Create the framework framework = ...
Runs the framework :param http_port: HTTP port to listen to :param peer_name: Name of the peer :param node_name: Name (also, UID) of the node hosting the peer :param app_id: Application ID
def gen(self, text, start=0): """Return the source code in text, filled with autogenerated code starting at start. """ for cc in self.chunkComment(text, start): c = self.extractChunkContent(cc) cc = ''.join(cc) m = self.matchComment(c) id...
Return the source code in text, filled with autogenerated code starting at start.
def patch_ast(node, source, sorted_children=False): """Patches the given node After calling, each node in `node` will have a new field named `region` that is a tuple containing the start and end offsets of the code that generated it. If `sorted_children` is true, a `sorted_children` field will ...
Patches the given node After calling, each node in `node` will have a new field named `region` that is a tuple containing the start and end offsets of the code that generated it. If `sorted_children` is true, a `sorted_children` field will be created for each node, too. It is a list containing ch...
def set(self, x): """ Set variable values via a dictionary mapping name to value. """ for name, value in iter(x.items()): if hasattr(value, "ndim"): if self[name].value.ndim < value.ndim: self[name].value.itemset(value.squeeze()) ...
Set variable values via a dictionary mapping name to value.
def set_decade_lims(axis=None,direction=None): r''' Set limits the the floor/ceil values in terms of decades. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. **direction** ([``None``] | ``'x'`` | ``'y'``) Limit the application to a certain direction (default: b...
r''' Set limits the the floor/ceil values in terms of decades. :options: **axis** ([``plt.gca()``] | ...) Specify the axis to which to apply the limits. **direction** ([``None``] | ``'x'`` | ``'y'``) Limit the application to a certain direction (default: both).
def best_match(desired_language: {str, Language}, supported_languages: list, min_score: int=75) -> (str, int): """ You have software that supports any of the `supported_languages`. You want to use `desired_language`. This function lets you choose the right language, even if there isn't an...
You have software that supports any of the `supported_languages`. You want to use `desired_language`. This function lets you choose the right language, even if there isn't an exact match. Returns: - The best-matching language code, which will be one of the `supported_languages` or 'und' - Th...
def loads(cls, json_data): """description of load""" try: return cls(**cls.MARSHMALLOW_SCHEMA.loads(json_data)) except marshmallow.exceptions.ValidationError as exc: raise ValidationError("Failed to load message", extra=exc.args[0])
description of load
def join(*args, **kwargs): """Join parts of a path together""" import os.path if _is_list(args[0]): return os.path.join(*args[0]) return os.path.join(*args, **kwargs)
Join parts of a path together
def send(data, channels=None, push_time=None, expiration_time=None, expiration_interval=None, where=None, cql=None): """ 发送推送消息。返回结果为此条推送对应的 _Notification 表中的对象,但是如果需要使用其中的数据,需要调用 fetch() 方法将数据同步至本地。 :param channels: 需要推送的频道 :type channels: list or tuple :param push_time: 推送的时间 :type push_time:...
发送推送消息。返回结果为此条推送对应的 _Notification 表中的对象,但是如果需要使用其中的数据,需要调用 fetch() 方法将数据同步至本地。 :param channels: 需要推送的频道 :type channels: list or tuple :param push_time: 推送的时间 :type push_time: datetime :param expiration_time: 消息过期的绝对日期时间 :type expiration_time: datetime :param expiration_interval: 消息过期的相对时间,从...
def markup_description(description): """ Apply HTML markup to the given description. """ if apply_markdown: description = apply_markdown(description) else: description = escape(description).replace('\n', '<br />') description = '<p>' + description + '</p>' return mark_saf...
Apply HTML markup to the given description.
def _augment_file(self, f): """ Augment a FileRecord with methods to get the data URL and to download, returning the updated file for use in generator functions :internal: """ def get_url(target): if target.file_size is None: return None ...
Augment a FileRecord with methods to get the data URL and to download, returning the updated file for use in generator functions :internal:
def add_state_errors(self, errors): """ Add state errors Accepts a list of errors (or a single Error) coming from validators applied to entity as whole that are used for entity state validation The errors will exist on a __state__ property of the errors object. :param e...
Add state errors Accepts a list of errors (or a single Error) coming from validators applied to entity as whole that are used for entity state validation The errors will exist on a __state__ property of the errors object. :param errors: list or Error, list of entity state validation er...
def to_serializable_dict(self, attrs_to_serialize=None, rels_to_expand=None, rels_to_serialize=None, key_modifications=None): """ An alias for `todict` """ return self.todict( attrs_to_seri...
An alias for `todict`
def render_mail_template(subject_template, body_template, context): """ Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result. """ try: subject = strip_spaces(render_to_string(subject_template, context)) body = render_to_strin...
Renders both the subject and body templates in the given context. Returns a tuple (subject, body) of the result.
def tplot_save(names, filename=None): """ This function will save tplot variables into a single file by using the python "pickle" function. This file can then be "restored" using tplot_restore. This is useful if you want to end the pytplot session, but save all of your data/options. All variables and ...
This function will save tplot variables into a single file by using the python "pickle" function. This file can then be "restored" using tplot_restore. This is useful if you want to end the pytplot session, but save all of your data/options. All variables and plot options can be read back into tplot with the ...
def send_select_and_operate_command_set(self, command_set, callback=asiodnp3.PrintingCommandCallback.Get(), config=opendnp3.TaskConfig().Default()): """ Select and operate a set of commands :param command_set: set of command headers :param...
Select and operate a set of commands :param command_set: set of command headers :param callback: callback that will be invoked upon completion or failure :param config: optional configuration that controls normal callbacks and allows the user to be specified for SA
def get_ref_dict(self, schema): """Method to create a dictionary containing a JSON reference to the schema in the spec """ schema_key = make_schema_key(schema) ref_schema = build_reference( "schema", self.openapi_version.major, self.refs[schema_key] ) ...
Method to create a dictionary containing a JSON reference to the schema in the spec