code
stringlengths
75
104k
docstring
stringlengths
1
46.9k
def as_string(self, chars, current_linkable=False, class_current="active_link"): """ It returns menu as string """ return self.__do_menu("as_string", current_linkable, class_current, chars)
It returns menu as string
def full_name(self): """Return full package/distribution name, w/version""" if self.requested_version is not None: return '%s-%s' % (self.name, self.requested_version) return self.name
Return full package/distribution name, w/version
def get_dash(self): """Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect. """ dashes = ffi.new('double[]', cairo.cairo_get_dash_count(sel...
Return the current dash pattern. :returns: A ``(dashes, offset)`` tuple of a list and a float. :obj:`dashes` is a list of floats, empty if no dashing is in effect.
def get_available_references(self, datas): """ Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (d...
Get available manifest reference names. Every rules starting with prefix from ``nomenclature.RULE_REFERENCE`` are available references. Only name validation is performed on these references. Arguments: datas (dict): Data where to search for reference declarations. ...
def hkdf(self, chaining_key, input_key_material, dhlen=64): """Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequence...
Hash-based key derivation function Takes a ``chaining_key'' byte sequence of len HASHLEN, and an ``input_key_material'' byte sequence with length either zero bytes, 32 bytes or dhlen bytes. Returns two byte sequences of length HASHLEN
def _read_hdf_columns(path_or_buf, columns, num_splits, kwargs): # pragma: no cover """Use a Ray task to read columns from HDF5 into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path_or_buf: The path of the HDF5 file. columns: The list ...
Use a Ray task to read columns from HDF5 into a Pandas DataFrame. Note: Ray functions are not detected by codecov (thus pragma: no cover) Args: path_or_buf: The path of the HDF5 file. columns: The list of column names to read. num_splits: The number of partitions to split the column in...
def create_weekmatrices(user, split_interval=60): """ Computes raw indicators (e.g. number of outgoing calls) for intervals of ~1 hour across each week of user data. These "week-matrices" are returned in a nested list with each sublist containing [user.name, channel, weekday, section, value]. P...
Computes raw indicators (e.g. number of outgoing calls) for intervals of ~1 hour across each week of user data. These "week-matrices" are returned in a nested list with each sublist containing [user.name, channel, weekday, section, value]. Parameters ---------- user : object The user to...
def check_install(): """ Try to detect the two most common installation errors: 1. Installing on macOS using a Homebrew version of Python 2. Installing on Linux using Python 2 when GDB is linked with Python 3 """ if platform.system() == 'Darwin' and sys.executable != '/usr/bin/python': ...
Try to detect the two most common installation errors: 1. Installing on macOS using a Homebrew version of Python 2. Installing on Linux using Python 2 when GDB is linked with Python 3
def mv(source, target): ''' Move synchronized directory. ''' if os.path.isfile(target) and len(source) == 1: if click.confirm("Are you sure you want to overwrite %s?" % target): err_msg = cli_syncthing_adapter.mv_edge_case(source, target) # Edge case: to match Bash 'mv' behavior and overwrite file...
Move synchronized directory.
def waitForCreation(self, timeout=10, notification='AXCreated'): """Convenience method to wait for creation of some UI element. Returns: The element created """ callback = AXCallbacks.returnElemCallback retelem = None args = (retelem,) return self.waitFor(timeou...
Convenience method to wait for creation of some UI element. Returns: The element created
def properties(self): """ Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager """ if self._property_manager is None: self._property_manager = PropertyManager(sessi...
Property for accessing :class:`PropertyManager` instance, which is used to manage properties of the jobs. :rtype: yagocd.resources.property.PropertyManager
def _make_jsmin(python_only=False): """ Generate JS minifier based on `jsmin.c by Douglas Crockford`_ .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c :Parameters: `python_only` : ``bool`` Use only the python variant. If true, the c extension is not ev...
Generate JS minifier based on `jsmin.c by Douglas Crockford`_ .. _jsmin.c by Douglas Crockford: http://www.crockford.com/javascript/jsmin.c :Parameters: `python_only` : ``bool`` Use only the python variant. If true, the c extension is not even tried to be loaded. :Return: Min...
def print_progress_bar(iteration, total, prefix='', suffix='', decimals=1, length=100, fill='█'): """ Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : p...
Call in a loop to create terminal progress bar @params: iteration - Required : current iteration (Int) total - Required : total iterations (Int) prefix - Optional : prefix string (Str) suffix - Optional : suffix string (Str) decimals - Optional : pos...
def QWidget_factory(ui_file=None, *args, **kwargs): """ Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords ...
Defines a class factory creating `QWidget <http://doc.qt.nokia.com/qwidget.html>`_ classes using given ui file. :param ui_file: Ui file. :type ui_file: unicode :param \*args: Arguments. :type \*args: \* :param \*\*kwargs: Keywords arguments. :type \*\*kwargs: \*\* :return: QWidget class...
def remove(self, fieldspec): """ Removes fields or subfields according to `fieldspec`. If a non-control field subfield removal leaves no other subfields, delete the field entirely. """ pattern = r'(?P<field>[^.]+)(.(?P<subfield>[^.]+))?' match = re.match(pattern...
Removes fields or subfields according to `fieldspec`. If a non-control field subfield removal leaves no other subfields, delete the field entirely.
def lockToColumn(self, index): """ Sets the column that the tree view will lock to. If None is supplied, then locking will be removed. :param index | <int> || None """ self._lockColumn = index if index is None: self.__...
Sets the column that the tree view will lock to. If None is supplied, then locking will be removed. :param index | <int> || None
def server(request): """ Respond to requests for the server's primary web page. """ return direct_to_template( request, 'server/index.html', {'user_url': getViewURL(request, idPage), 'server_xrds_url': getViewURL(request, idpXrds), })
Respond to requests for the server's primary web page.
def discover(language): ''' Discovers all registered scrapers to be used for the generic scraping interface. ''' debug('Discovering scrapers for \'%s\'...' % (language,)) global scrapers, discovered for language in scrapers.iterkeys(): discovered[language] = {} for scraper in scrapers[language]: blacklist =...
Discovers all registered scrapers to be used for the generic scraping interface.
def check_bidi(data): """Checks if sting is valid for bidirectional printing.""" has_l = False has_ral = False for char in data: if stringprep.in_table_d1(char): has_ral = True elif stringprep.in_table_d2(char): has_l = True ...
Checks if sting is valid for bidirectional printing.
def handle_battery_level(msg): """Process an internal battery level message.""" if not msg.gateway.is_sensor(msg.node_id): return None msg.gateway.sensors[msg.node_id].battery_level = msg.payload msg.gateway.alert(msg) return None
Process an internal battery level message.
def getScans(self, modifications=True, fdr=True): """ get a random scan """ if not self.scans: for i in self: yield i else: for i in self.scans.values(): yield i yield None
get a random scan
def _vote_disagreement(self, votes): """ Return the disagreement measurement of the given number of votes. It uses the vote vote to measure the disagreement. Parameters ---------- votes : list of int, shape==(n_samples, n_students) The predictions that each s...
Return the disagreement measurement of the given number of votes. It uses the vote vote to measure the disagreement. Parameters ---------- votes : list of int, shape==(n_samples, n_students) The predictions that each student gives to each sample. Returns ---...
def describe(self, **kwargs): """ :returns: A hash containing attributes of the project or container. :rtype: dict Returns a hash with key-value pairs as specified by the API specification for the `/project-xxxx/describe <https://wiki.dnanexus.com/API-Specification-v1.0....
:returns: A hash containing attributes of the project or container. :rtype: dict Returns a hash with key-value pairs as specified by the API specification for the `/project-xxxx/describe <https://wiki.dnanexus.com/API-Specification-v1.0.0/Projects#API-method%3A-%2Fproject-xxxx%2Fdescrib...
async def stop(self): """ Stop discarding media. """ for task in self.__tracks.values(): if task is not None: task.cancel() self.__tracks = {}
Stop discarding media.
def ko_model(model, field_names=None, data=None): """ Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data. """ try: if isinstance(model, str): modelName = model else: modelName = model.__class__.__name__ ...
Given a model, returns the Knockout Model and the Knockout ViewModel. Takes optional field names and data.
def _get_cpu_info_from_registry(): ''' FIXME: Is missing many of the newer CPU flags like sse3 Returns the CPU info gathered from the Windows Registry. Returns {} if not on Windows. ''' try: # Just return {} if not on Windows if not DataSource.is_windows: return {} # Get the CPU name processor_brand =...
FIXME: Is missing many of the newer CPU flags like sse3 Returns the CPU info gathered from the Windows Registry. Returns {} if not on Windows.
def index(): """ This is not served anywhere in the web application. It is used explicitly in the context of generating static files since flask-frozen requires url_for's to crawl content. url_for's are not used with result.show_result directly and are instead dynamically generated through javas...
This is not served anywhere in the web application. It is used explicitly in the context of generating static files since flask-frozen requires url_for's to crawl content. url_for's are not used with result.show_result directly and are instead dynamically generated through javascript for performance pur...
def list_resource_commands(self): """Returns a list of multi-commands for each resource type. """ resource_path = os.path.abspath(os.path.join( os.path.dirname(__file__), os.pardir, 'resources' )) answer = set([]) for _, name, _ in pkgu...
Returns a list of multi-commands for each resource type.
def patch_namespaced_horizontal_pod_autoscaler_status(self, name, namespace, body, **kwargs): """ partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True ...
partially update status of the specified HorizontalPodAutoscaler This method makes a synchronous HTTP request by default. To make an asynchronous HTTP request, please pass async_req=True >>> thread = api.patch_namespaced_horizontal_pod_autoscaler_status(name, namespace, body, async_req=True) ...
def command_max_delay(self, event=None): """ CPU burst max running time - self.runtime_cfg.max_delay """ try: max_delay = self.max_delay_var.get() except ValueError: max_delay = self.runtime_cfg.max_delay if max_delay < 0: max_delay = self.runtime_cfg...
CPU burst max running time - self.runtime_cfg.max_delay
def _read_to_buffer(self) -> Optional[int]: """Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception...
Reads from the socket and appends the result to the read buffer. Returns the number of bytes read. Returns 0 if there is nothing to read (i.e. the read returns EWOULDBLOCK or equivalent). On error closes the socket and raises an exception.
def upload(ctx, product, git_ref, dirname, aws_id, aws_secret, ci_env, on_travis_push, on_travis_pr, on_travis_api, on_travis_cron, skip_upload): """Upload a new site build to LSST the Docs. """ logger = logging.getLogger(__name__) if skip_upload: click.echo('Skipping ltd ...
Upload a new site build to LSST the Docs.
def serial_ports(): """ Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-p...
Lists serial port names :raises EnvironmentError: On unsupported or unknown platforms :returns: A list of the serial ports available on the system Courtesy: Thomas ( http://stackoverflow.com/questions/12090503 /listing-available-com-ports-with-python )
def build_asset_array(assets_by_site, tagnames=(), time_event=None): """ :param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol` """ for assets in assets_by_site: if len(assets): first_asset = assets[0] b...
:param assets_by_site: a list of lists of assets :param tagnames: a list of tag names :returns: an array `assetcol`
def is_successful(self, retry=False): """ If the instance runs successfully. :return: True if successful else False :rtype: bool """ if not self.is_terminated(retry=retry): return False retry_num = options.retry_times while retry_num > 0: ...
If the instance runs successfully. :return: True if successful else False :rtype: bool
def add_report(self, specification_name, report): """ Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specif...
Adds a given report with the given specification_name as key to the reports list and computes the number of success, failures and errors Args: specification_name: string representing the specification (with ".spec") report: The
def parse(self): """Parse show subcommand.""" parser = self.subparser.add_parser( "show", help="Show workspace details", description="Show workspace details.") group = parser.add_mutually_exclusive_group(required=True) group.add_argument('--all', acti...
Parse show subcommand.
def squeeze(attrs, inputs, proto_obj): """Remove single-dimensional entries from the shape of a tensor.""" new_attrs = translation_utils._fix_attribute_names(attrs, {'axes' : 'axis'}) return 'squeeze', new_attrs, inputs
Remove single-dimensional entries from the shape of a tensor.
def get_chart(self, id, **kwargs): """"Retrieve a (v2) chart by id. """ resp = self._get_object_by_name(self._CHART_ENDPOINT_SUFFIX, id, **kwargs) return resp
Retrieve a (v2) chart by id.
def p_multiplicative_expr(self, p): """multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr """ if len(p) == 2:...
multiplicative_expr : unary_expr | multiplicative_expr MULT unary_expr | multiplicative_expr DIV unary_expr | multiplicative_expr MOD unary_expr
def get_text(self): """Get the text in its current state.""" return u''.join(u'{0}'.format(b) for b in self.text)
Get the text in its current state.
def just_find_proxy(pacfile, url, host=None): """ This function is a wrapper around init, parse_pac, find_proxy and cleanup. This is the function to call if you want to find proxy just for one url. """ if not os.path.isfile(pacfile): raise IOError('Pac file does not exist: {}'.format(pacfile)) init() ...
This function is a wrapper around init, parse_pac, find_proxy and cleanup. This is the function to call if you want to find proxy just for one url.
def _runcog(options, files, uncog=False): """Common function for the cog and runcog tasks.""" options.order('cog', 'sphinx', add_rest=True) c = Cog() if uncog: c.options.bNoGenerate = True c.options.bReplace = True c.options.bDeleteCode = options.get("delete_code", False) includedir ...
Common function for the cog and runcog tasks.
def print_object_results(obj_result): """Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance. """ print_results_header(obj_result.object_id, obj_result.is_valid) if obj_result.warnings: print_warning_results(obj_result, 1) if obj_re...
Print the results of validating an object. Args: obj_result: An ObjectValidationResults instance.
def parse_summary(self, contents): """Parses summary file into a dictionary of counts.""" lines = contents.strip().split('\n') data = {} for row in lines[1:]: split = row.strip().split('\t') sample = split[0] data[sample] = { 'speci...
Parses summary file into a dictionary of counts.
def _onError(self, message): """Memorizies a parser error message""" self.isOK = False if message.strip() != "": self.errors.append(message)
Memorizies a parser error message
def _import_lua_dependencies(lua, lua_globals): """ Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson ...
Imports lua dependencies that are supported by redis lua scripts. The current implementation is fragile to the target platform and lua version and may be disabled if these imports are not needed. Included: - cjson lib. Pending: - base lib. - table li...
def transpose(self, rows): """ Transposes the grid to allow for cols """ res = OrderedDict() for row, cols in rows.items(): for col, cell in cols.items(): if col not in res: res[col] = OrderedDict() res[col][row] = c...
Transposes the grid to allow for cols
def _example_from_allof(self, prop_spec): """Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict """ example_dict = {} for definition in prop_spec['allOf']: ...
Get the examples from an allOf section. Args: prop_spec: property specification you want an example of. Returns: An example dict
def patchURL(self, url, headers, body): """ Request a URL using the HTTP method PATCH. """ return self._load_resource("PATCH", url, headers, body)
Request a URL using the HTTP method PATCH.
def _get_position(self): """ 获取雪球持仓 :return: """ portfolio_code = self.account_config["portfolio_code"] portfolio_info = self._get_portfolio_info(portfolio_code) position = portfolio_info["view_rebalancing"] # 仓位结构 stocks = position["holdings"] # 持仓股票 ...
获取雪球持仓 :return:
def serialize_filesec(self): """ Return the file Element for this file, appropriate for use in a fileSec. If this is not an Item or has no use, return None. :return: fileSec element for this FSEntry """ if ( self.type.lower() not in ("item", "archival inform...
Return the file Element for this file, appropriate for use in a fileSec. If this is not an Item or has no use, return None. :return: fileSec element for this FSEntry
def gradient_factory(name): """Create gradient `Functional` for some ufuncs.""" if name == 'sin': def gradient(self): """Return the gradient operator.""" return cos(self.domain) elif name == 'cos': def gradient(self): """Return the gradient operator.""" ...
Create gradient `Functional` for some ufuncs.
def register_hooks(app): """Register hooks.""" @app.before_request def before_request(): g.user = get_current_user() if g.user and g.user.is_admin: g._before_request_time = time.time() @app.after_request def after_request(response): if hasattr(g, '_before_reques...
Register hooks.
def issue_add_comment(self, issue_key, comment, visibility=None): """ Add comment into Jira issue :param issue_key: :param comment: :param visibility: OPTIONAL :return: """ url = 'rest/api/2/issue/{issueIdOrKey}/comment'.format(issueIdOrKey=issue_key) ...
Add comment into Jira issue :param issue_key: :param comment: :param visibility: OPTIONAL :return:
def on_change(self, path, event_type): """Respond to changes in the file system This method will be given the path to a file that has changed on disk. We need to reload the keywords from that file """ # I can do all this work in a sql statement, but # for debuggi...
Respond to changes in the file system This method will be given the path to a file that has changed on disk. We need to reload the keywords from that file
def get_full_durable_object(arn, event_time, durable_model): """ Utility method to fetch items from the Durable table if they are too big for SNS/SQS. :param record: :param durable_model: :return: """ LOG.debug(f'[-->] Item with ARN: {arn} was too big for SNS -- fetching it from the Durable...
Utility method to fetch items from the Durable table if they are too big for SNS/SQS. :param record: :param durable_model: :return:
def tz_localize(self, tz, ambiguous='raise', nonexistent='raise', errors=None): """ Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. I...
Localize tz-naive Datetime Array/Index to tz-aware Datetime Array/Index. This method takes a time zone (tz) naive Datetime Array/Index object and makes this time zone aware. It does not move the time to another time zone. Time zone localization helps to switch from time zone awa...
def to_dict(self): """Generate a dict for this object's attributes. :return: A dict representing an :class:`Asset` """ rv = {'code': self.code} if not self.is_native(): rv['issuer'] = self.issuer rv['type'] = self.type else: rv['type']...
Generate a dict for this object's attributes. :return: A dict representing an :class:`Asset`
def apply_reactions(self, user): """ Set active topics and limits after a response has been triggered :param user: The user triggering the response :type user: agentml.User """ # User attributes if self.global_limit: self._log.info('Enforcing Global T...
Set active topics and limits after a response has been triggered :param user: The user triggering the response :type user: agentml.User
def js_extractor(response): """Extract js files from the response body""" # Extract .js files matches = rscript.findall(response) for match in matches: match = match[2].replace('\'', '').replace('"', '') verb('JS file', match) bad_scripts.add(match)
Extract js files from the response body
def unpack_value(format_string, stream): """Helper function to unpack struct data from a stream and update the signature verifier. :param str format_string: Struct format string :param stream: Source data stream :type stream: io.BytesIO :returns: Unpacked values :rtype: tuple """ messag...
Helper function to unpack struct data from a stream and update the signature verifier. :param str format_string: Struct format string :param stream: Source data stream :type stream: io.BytesIO :returns: Unpacked values :rtype: tuple
def prepare_files(self, finder): """ Prepare process. Create temp directories, download and/or unpack files. """ from pip.index import Link unnamed = list(self.unnamed_requirements) reqs = list(self.requirements.values()) while reqs or unnamed: if unn...
Prepare process. Create temp directories, download and/or unpack files.
def make_serializable(data, mutable=True, key_stringifier=lambda x:x, simplify_midnight_datetime=True): r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures. If mutable=False then return tuples for all iterables, except basestrings (strs), ...
r"""Make sure the data structure is json serializable (json.dumps-able), all they way down to scalars in nested structures. If mutable=False then return tuples for all iterables, except basestrings (strs), so that they can be used as keys in a Mapping (dict). >>> from collections import OrderedDict ...
def build_from_token_counts(self, token_counts, min_count, num_iterations=4): """Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_...
Train a SubwordTextTokenizer based on a dictionary of word counts. Args: token_counts: a dictionary of Unicode strings to int. min_count: an integer - discard subtokens with lower counts. num_iterations: an integer; how many iterations of refinement.
def get(self, buffer_type, offset): """Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outside of this en...
Get a reading from the buffer at offset. Offset is specified relative to the start of the data buffer. This means that if the buffer rolls over, the offset for a given item will appear to change. Anyone holding an offset outside of this engine object will need to be notified when rollo...
def update(self, report): """ Add the items from the given report. """ self.tp.extend(pack_boxes(report.tp, self.title)) self.fp.extend(pack_boxes(report.fp, self.title)) self.fn.extend(pack_boxes(report.fn, self.title))
Add the items from the given report.
def plot_hurst_hist(): """ Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``. """ # local import to avoid dependency for non-debug use import matplotlib.pyplot as plt hs = [nolds.hurst_rs(np.random.random(...
Plots a histogram of values obtained for the hurst exponent of uniformly distributed white noise. This function requires the package ``matplotlib``.
def enable_vxlan_feature(self, nexus_host, nve_int_num, src_intf): """Enable VXLAN on the switch.""" # Configure the "feature" commands and NVE interface # (without "member" subcommand configuration). # The Nexus 9K will not allow the "interface nve" configuration # until the "f...
Enable VXLAN on the switch.
def delete_repository(self, repository, params=None): """ Removes a shared file system repository. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_ :arg repository: A comma-separated list of repository names :arg master_timeout: Explicit...
Removes a shared file system repository. `<http://www.elastic.co/guide/en/elasticsearch/reference/current/modules-snapshots.html>`_ :arg repository: A comma-separated list of repository names :arg master_timeout: Explicit operation timeout for connection to master node :arg ...
def example_describe_configs(a, args): """ describe configs """ resources = [ConfigResource(restype, resname) for restype, resname in zip(args[0::2], args[1::2])] fs = a.describe_configs(resources) # Wait for operation to finish. for res, f in fs.items(): try: ...
describe configs
def get_version(self, paths=None, default="unknown"): """Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the va...
Get version number of installed module, 'None', or 'default' Search 'paths' for module. If not found, return 'None'. If found, return the extracted version attribute, or 'default' if no version attribute was specified, or the value cannot be determined without importing the module. T...
def calc_stress_tf(self, lin, lout, damped): """Compute the stress transfer function. Parameters ---------- lin : :class:`~site.Location` Location of input lout : :class:`~site.Location` Location of output. Note that this would typically be midheight ...
Compute the stress transfer function. Parameters ---------- lin : :class:`~site.Location` Location of input lout : :class:`~site.Location` Location of output. Note that this would typically be midheight of the layer.
def _intertext_score(full_text): '''returns tuple of scored sentences in order of appearance Note: Doing an A/B test to compare results, reverting to original algorithm.''' sentences = sentence_tokenizer(full_text) norm = _normalize(sentences) similarity_matrix = pairwise_k...
returns tuple of scored sentences in order of appearance Note: Doing an A/B test to compare results, reverting to original algorithm.
def constrains(self): """ returns a list of parameters that are constrained by this parameter """ params = [] for constraint in self.in_constraints: for var in constraint._vars: param = var.get_parameter() if param.component == constrai...
returns a list of parameters that are constrained by this parameter
def check_ns_run_threads(run): """Check thread labels and thread_min_max have expected properties. Parameters ---------- run: dict Nested sampling run to check. Raises ------ AssertionError If run does not have expected properties. """ assert run['thread_labels'].dt...
Check thread labels and thread_min_max have expected properties. Parameters ---------- run: dict Nested sampling run to check. Raises ------ AssertionError If run does not have expected properties.
def get_appium_sessionId(self): """Returns the current session ID as a reference""" self._info("Appium Session ID: " + self._current_application().session_id) return self._current_application().session_id
Returns the current session ID as a reference
def git_pull(repo_dir, remote="origin", ref=None, update_head_ok=False): """Do a git pull of `ref` from `remote`.""" command = ['git', 'pull'] if update_head_ok: command.append('--update-head-ok') command.append(pipes.quote(remote)) if ref: command.append(ref) return execute_git_...
Do a git pull of `ref` from `remote`.
def encode(locations): """ :param locations: locations list containig (lat, lon) two-tuples :return: encoded polyline string """ encoded = ( (_encode_value(lat, prev_lat), _encode_value(lon, prev_lon)) for (prev_lat, prev_lon), (lat, lon) in _iterate_with_previous(locations, ...
:param locations: locations list containig (lat, lon) two-tuples :return: encoded polyline string
def confd_state_internal_callpoints_typepoint_registration_type_range_range_daemon_error(self, **kwargs): """Auto Generated Code """ config = ET.Element("config") confd_state = ET.SubElement(config, "confd-state", xmlns="http://tail-f.com/yang/confd-monitoring") internal = ET.Sub...
Auto Generated Code
def _get_file_by_alias(part, files): """ Given a command part, find the file it represents. If not found, then returns a new token representing that file. :throws ValueError: if the value is not a command file alias. """ # Make Output if _is_output(part): return Output.from_string(part.p...
Given a command part, find the file it represents. If not found, then returns a new token representing that file. :throws ValueError: if the value is not a command file alias.
def averageConvergencePoint(self, prefix, minOverlap, maxOverlap, settlingTime=1, firstStat=0, lastStat=None): """ For each object, compute the convergence time - the first point when all L2 columns have converged. Return the average convergence time and accuracy across a...
For each object, compute the convergence time - the first point when all L2 columns have converged. Return the average convergence time and accuracy across all objects. Using inference statistics for a bunch of runs, locate all traces with the given prefix. For each trace locate the iteration where it...
def get_orm_column_names(cls: Type, sort: bool = False) -> List[str]: """ Gets column names (that is, database column names) from an SQLAlchemy ORM class. """ colnames = [col.name for col in get_orm_columns(cls)] return sorted(colnames) if sort else colnames
Gets column names (that is, database column names) from an SQLAlchemy ORM class.
def expr(args): """ %prog expr block exp layout napus.bed Plot a composite figure showing synteny and the expression level between homeologs in two tissues - total 4 lists of values. block file contains the gene pairs between AN and CN. """ from jcvi.graphics.base import red_purple as defau...
%prog expr block exp layout napus.bed Plot a composite figure showing synteny and the expression level between homeologs in two tissues - total 4 lists of values. block file contains the gene pairs between AN and CN.
def area(self): r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice th...
r"""The area of the current surface. For surfaces in :math:`\mathbf{R}^2`, this computes the area via Green's theorem. Using the vector field :math:`\mathbf{F} = \left[-y, x\right]^T`, since :math:`\partial_x(x) - \partial_y(-y) = 2` Green's theorem says twice the area is equal to ...
def crypto_box_seal_open(ciphertext, pk, sk): """ Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender...
Decrypts and returns an encrypted message ``ciphertext``, using the recipent's secret key ``sk`` and the sender's ephemeral public key embedded in the sealed box. The box contruct nonce is derived from the recipient's public key ``pk`` and the sender's public key. :param ciphertext: bytes :param pk...
def _get_query(self, order=None, filters=None): """ This method is just to evade code duplication in count() and get_content, since they do basically the same thing""" order = self._get_order(order) return self.posts.all().order_by(order)
This method is just to evade code duplication in count() and get_content, since they do basically the same thing
def _value_iterator(self, task_name, param_name): """ Yield the parameter values, with optional deprecation warning as second tuple value. The parameter value will be whatever non-_no_value that is yielded first. """ cp_parser = CmdlineParser.get_instance() if cp_parser:...
Yield the parameter values, with optional deprecation warning as second tuple value. The parameter value will be whatever non-_no_value that is yielded first.
def enumerate_global_imports(tokens): """ Returns a list of all globally imported modules (skips modules imported inside of classes, methods, or functions). Example:: >>> enumerate_global_modules(tokens) ['sys', 'os', 'tokenize', 're'] .. note:: Does not enumerate imports usi...
Returns a list of all globally imported modules (skips modules imported inside of classes, methods, or functions). Example:: >>> enumerate_global_modules(tokens) ['sys', 'os', 'tokenize', 're'] .. note:: Does not enumerate imports using the 'from' or 'as' keywords.
def chdir(self, path, timeout=shutit_global.shutit_global_object.default_timeout, note=None, loglevel=logging.DEBUG): """How to change directory will depend on whether we are in delivery mode bash or docker. @param path: Path to send file to. @param timeout: ...
How to change directory will depend on whether we are in delivery mode bash or docker. @param path: Path to send file to. @param timeout: Timeout on response @param note: See send()
def infomax(data, weights=None, l_rate=None, block=None, w_change=1e-12, anneal_deg=60., anneal_step=0.9, extended=False, n_subgauss=1, kurt_size=6000, ext_blocks=1, max_iter=200, random_state=None, verbose=None): """Run the (extended) Infomax ICA decomposition on raw data b...
Run the (extended) Infomax ICA decomposition on raw data based on the publications of Bell & Sejnowski 1995 (Infomax) and Lee, Girolami & Sejnowski, 1999 (extended Infomax) Parameters ---------- data : np.ndarray, shape (n_samples, n_features) The data to unmix. w_init : np.ndarray, sh...
def from_iter(cls, data, name=None): """Convenience method for loading data from an iterable. Defaults to numerical indexing for x-axis. Parameters ---------- data: iterable An iterable of data (list, tuple, dict of key/val pairs) name: string, default None ...
Convenience method for loading data from an iterable. Defaults to numerical indexing for x-axis. Parameters ---------- data: iterable An iterable of data (list, tuple, dict of key/val pairs) name: string, default None Name of the data set. If None (defau...
def astype(self, dtype, undefined_on_failure=False): """ Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.dat...
Create a new SArray with all values cast to the given type. Throws an exception if the types are not castable to the given type. Parameters ---------- dtype : {int, float, str, list, array.array, dict, datetime.datetime} The type to cast the elements to in SArray un...
def convert_svhn(which_format, directory, output_directory, output_filename=None): """Converts the SVHN dataset to HDF5. Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible with :class:`fuel.datasets.SVHN`. The converted dataset is saved as 'svhn_format_1.hdf5' or 'svhn_form...
Converts the SVHN dataset to HDF5. Converts the SVHN dataset [SVHN] to an HDF5 dataset compatible with :class:`fuel.datasets.SVHN`. The converted dataset is saved as 'svhn_format_1.hdf5' or 'svhn_format_2.hdf5', depending on the `which_format` argument. .. [SVHN] Yuval Netzer, Tao Wang, Adam Coate...
def flesh_out(X, W, embed_dim, CC_labels, dist_mult=2.0, angle_thresh=0.2, min_shortcircuit=4, max_degree=5, verbose=False): '''Given a connected graph adj matrix (W), add edges to flesh it out.''' W = W.astype(bool) assert np.all(W == W.T), 'graph given to flesh_out must be symmetric' D = pa...
Given a connected graph adj matrix (W), add edges to flesh it out.
def compare(orderby_item1, orderby_item2): """compares the two orderby item pairs. :param dict orderby_item1: :param dict orderby_item2: :return: Integer comparison result. The comparator acts such that - if the types are different we get: ...
compares the two orderby item pairs. :param dict orderby_item1: :param dict orderby_item2: :return: Integer comparison result. The comparator acts such that - if the types are different we get: Undefined value < Null < booleans < Numbers < St...
def local_fehdist(feh): """feh PDF based on local SDSS distribution From Jo Bovy: https://github.com/jobovy/apogee/blob/master/apogee/util/__init__.py#L3 2D gaussian fit based on Casagrande (2011) """ fehdist= 0.8/0.15*np.exp(-0.5*(feh-0.016)**2./0.15**2.)\ +0.2/0.22*np.exp(-0.5*(fe...
feh PDF based on local SDSS distribution From Jo Bovy: https://github.com/jobovy/apogee/blob/master/apogee/util/__init__.py#L3 2D gaussian fit based on Casagrande (2011)
def set_status(self, action, target): """ Sets query status with format: "{domain} ({action}) {target}" """ try: target = unquote(target) except (AttributeError, TypeError): pass status = "%s (%s) %s" % (self.domain, action, target) status...
Sets query status with format: "{domain} ({action}) {target}"
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None): """ Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: ...
Connect to AWS ec2 :type region: str :param region: AWS region to connect to :type access_key: str :param access_key: AWS access key id :type secret_key: str :param secret_key: AWS secret access key :returns: boto.ec2.connection.EC2Connection -- EC2 connection
def raise_205(instance): """Abort the current request with a 205 (Reset Content) response code. Clears out the body of the response. :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException`...
Abort the current request with a 205 (Reset Content) response code. Clears out the body of the response. :param instance: Resource instance (used to access the response) :type instance: :class:`webob.resource.Resource` :raises: :class:`webob.exceptions.ResponseException` of status 205