text
stringlengths
81
112k
Returns highest available version for a package in a list of versions Uses pkg_resources to parse the versions @param versions: List of PyPI package versions @type versions: List of strings @returns: string of a PyPI package version def get_highest_version(versions): """ Returns highest avail...
Yield installed packages @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @param pkg_name: PyPI project name @type pkg_name: string @param version: project's PyPI version @type version: string ...
Return list of alphabetized packages @param pkg_name: PyPI project name @type pkg_name: string @param version: project's PyPI version @type version: string @returns: Alphabetized list of tuples. Each tuple contains a string and a pkg_resources Distribution ob...
Return list of Distributions filtered by active status or all @param show: Type of package(s) to show; active, non-active or all @type show: string: "active", "non-active", "all" @returns: list of pkg_resources Distribution objects def get_packages(self, show): """ Return list...
Return case-sensitive package name given any-case package name @param project_name: PyPI project name @type project_name: string def case_sensitive_name(self, package_name): """ Return case-sensitive package name given any-case package name @param project_name: PyPI project na...
Non-atomic cache increment operation. Not optimal but consistent across different cache backends. def cache_incr(self, key): """ Non-atomic cache increment operation. Not optimal but consistent across different cache backends. """ cache.set(key, cache.get(key, 0) + 1, se...
Call all method on plugins in list, that define it, with provided arguments. The first response that is not None is returned. def call_plugins(plugins, method, *arg, **kw): """Call all method on plugins in list, that define it, with provided arguments. The first response that is not None is returned. "...
Load plugins, either builtin, others, or both. def load_plugins(builtin=True, others=True): """Load plugins, either builtin, others, or both. """ for entry_point in pkg_resources.iter_entry_points('yolk.plugins'): #LOG.debug("load plugin %s" % entry_point) try: plugin = entry_po...
Returns a Boto connection to the provided S3 bucket. def s3_connect(bucket_name, s3_access_key_id, s3_secret_key): """ Returns a Boto connection to the provided S3 bucket. """ conn = connect_s3(s3_access_key_id, s3_secret_key) try: return conn.get_bucket(bucket_name) except S3ResponseError as e...
Lists the contents of the S3 bucket that end in .tbz and match the passed prefix, if any. def s3_list(s3_bucket, s3_access_key_id, s3_secret_key, prefix=None): """ Lists the contents of the S3 bucket that end in .tbz and match the passed prefix, if any. """ bucket = s3_connect(s3_bucket, s3_acc...
Downloads the file matching the provided key, in the provided bucket, from Amazon S3. If s3_file_key is none, it downloads the last file from the provided bucket with the .tbz extension, filtering by prefix if it is provided. def s3_download(output_file_path, s3_bucket, s3_acce...
Uploads the to Amazon S3 the contents of the provided file, keyed with the name of the file. def s3_upload(source_file_path, bucket_name, s3_access_key_id, s3_secret_key): """ Uploads the to Amazon S3 the contents of the provided file, keyed with the name of the file. """ key = s3_key(bucket_na...
Attempt to remedy: https://www.riverbankcomputing.com/pipermail/pyqt/2016-February/037015.html def fix_pyqt5_QGraphicsItem_itemChange(): """ Attempt to remedy: https://www.riverbankcomputing.com/pipermail/pyqt/2016-February/037015.html """ from PyQt5.QtWidgets import QGraphicsObject, QGraphicsI...
Setup the optparser @returns: opt_parser.OptionParser def setup_opt_parser(): """ Setup the optparser @returns: opt_parser.OptionParser """ #pylint: disable-msg=C0301 #line too long usage = "usage: %prog [options]" opt_parser = optparse.OptionParser(usage=usage) opt_parser....
Check parse options that require pkg_spec @returns: pkg_spec def validate_pypi_opts(opt_parser): """ Check parse options that require pkg_spec @returns: pkg_spec """ (options, remaining_args) = opt_parser.parse_args() options_pkg_specs = [ options.versions_available, options...
Write a line to stdout if it isn't in a blacklist Try to get the name of the calling module to see if we want to filter it. If there is no calling module, use current frame in case there's a traceback before there is any calling module def write(self, inline): """ Write a line ...
Return plugin object if CLI option is activated and method exists @param method: name of plugin's method we're calling @type method: string @returns: list of plugins with `method` def get_plugin(self, method): """ Return plugin object if CLI option is activated and method exis...
Set log level according to command-line options @returns: logger object def set_log_level(self): """ Set log level according to command-line options @returns: logger object """ if self.options.debug: self.logger.setLevel(logging.DEBUG) elif self.op...
Perform actions based on CLI options @returns: status code def run(self): """ Perform actions based on CLI options @returns: status code """ opt_parser = setup_opt_parser() (self.options, remaining_args) = opt_parser.parse_args() logger = self.set_log_l...
Check installed packages for available updates on PyPI @param project_name: optional package name to check; checks every installed pacakge if none specified @type project_name: string @returns: None def show_updates(self): """ Check installed packa...
Show list of installed activated OR non-activated packages @param show: type of pkgs to show (all, active or nonactive) @type show: string @returns: None or 2 if error def show_distributions(self, show): """ Show list of installed activated OR non-activated packages @...
Print out formatted metadata @param metadata: package's metadata @type metadata: pkg_resources Distribution obj @param develop: path to pkg if its deployed in development mode @type develop: string @param active: show if package is activated or not @type active: boolea...
Show dependencies for package(s) @returns: 0 - sucess 1 - No dependency info supplied def show_deps(self): """ Show dependencies for package(s) @returns: 0 - sucess 1 - No dependency info supplied """ pkgs = pkg_resources.Environment() for pkg in pkgs[self....
Show detailed PyPI ChangeLog for the last `hours` @returns: 0 = sucess or 1 if failed to retrieve from XML-RPC server def show_pypi_changelog(self): """ Show detailed PyPI ChangeLog for the last `hours` @returns: 0 = sucess or 1 if failed to retrieve from XML-RPC server """ ...
Show PyPI releases for the last number of `hours` @returns: 0 = success or 1 if failed to retrieve from XML-RPC server def show_pypi_releases(self): """ Show PyPI releases for the last number of `hours` @returns: 0 = success or 1 if failed to retrieve from XML-RPC server """ ...
Query PyPI for pkg download URI for a packge @returns: 0 def show_download_links(self): """ Query PyPI for pkg download URI for a packge @returns: 0 """ #In case they specify version as 'dev' instead of using -T svn, #don't show three svn URI's if self...
@param version: version number or 'dev' for svn @type version: string @param source: download source or egg @type source: boolean @returns: None def print_download_uri(self, version, source): """ @param version: version number or 'dev' for svn @type version: st...
Download a package @returns: 0 = success or 1 if failed download def fetch(self): """ Download a package @returns: 0 = success or 1 if failed download """ #Default type to download source = True directory = "." if self.options.file_type == "sv...
Use ``urllib.urlretrieve`` to download package to file in sandbox dir. @param directory: directory to download to @type directory: string @param uri: uri to download @type uri: string @returns: 0 = success or 1 for failed download def fetch_uri(self, directory, uri): ...
Fetch subversion repository @param svn_uri: subversion repository uri to check out @type svn_uri: string @param directory: directory to download to @type directory: string @returns: 0 = success or 1 for failed download def fetch_svn(self, svn_uri, directory): """ ...
Launch web browser at project's homepage @param browser: name of web browser to use @type browser: string @returns: 0 if homepage found, 1 if no homepage found def browse_website(self, browser=None): """ Launch web browser at project's homepage @param browser: name of...
Show pkg metadata queried from PyPI @returns: 0 def query_metadata_pypi(self): """ Show pkg metadata queried from PyPI @returns: 0 """ if self.version and self.version in self.all_versions: metadata = self.pypi.release_data(self.project_name, self.version)...
Query PyPI for a particular version or all versions of a package @returns: 0 if version(s) found or 1 if none found def versions_available(self): """ Query PyPI for a particular version or all versions of a package @returns: 0 if version(s) found or 1 if none found """ ...
Parse search args and return spec dict for PyPI * Owwww, my eyes!. Re-write this. @param spec: Cheese Shop package search spec e.g. name=Cheetah license=ZPL license=ZPL AND name=Cheetah @type spec: string ...
Search PyPI by metadata keyword e.g. yolk -S name=yolk AND license=GPL @param spec: Cheese Shop search spec @type spec: list of strings spec examples: ["name=yolk"] ["license=GPL"] ["name=yolk", "AND", "license=GPL"] @returns: 0 on success or 1 if...
Show entry map for a package @param dist: package @param type: srting @returns: 0 for success or 1 if error def show_entry_map(self): """ Show entry map for a package @param dist: package @param type: srting @returns: 0 for success or 1 if error ...
Show entry points for a module @returns: 0 for success or 1 if error def show_entry_points(self): """ Show entry points for a module @returns: 0 for success or 1 if error """ found = False for entry_point in \ pkg_resources.iter_entry_points(se...
Return tuple with project_name and version from CLI args If the user gave the wrong case for the project name, this corrects it @param want_installed: whether package we want is installed or not @type want_installed: boolean @returns: tuple(project_name, version, all_versions) def par...
Install a backport import hook for Qt4 api Parameters ---------- api : str The Qt4 api whose structure should be intercepted ('pyqt4' or 'pyside'). Example ------- >>> install_backport_hook("pyqt4") >>> import PyQt4 Loaded module AnyQt._backport as a substitute for PyQt...
Install a deny import hook for Qt api. Parameters ---------- api : str The Qt api whose import should be prevented Example ------- >>> install_deny_import("pyqt4") >>> import PyQt4 Traceback (most recent call last):... ImportError: Import of PyQt4 is denied. def install_de...
Run command and return its return status code and its output def run_command(cmd, env=None, max_timeout=None): """ Run command and return its return status code and its output """ arglist = cmd.split() output = os.tmpfile() try: pipe = Popen(arglist, stdout=output, stderr=STDOUT, env=...
Iterate over a slack API method supporting pagination When using :class:`slack.methods` the request is made `as_json` if available Args: url: :class:`slack.methods` or url string data: JSON encodable MutableMapping headers: limit: Maximum number of resul...
Connect and discard incoming RTM event if necessary. :param url: Websocket url :param bot_id: Bot ID :return: Incoming events async def _incoming_from_rtm( self, url: str, bot_id: str ) -> AsyncIterator[events.Event]: """ Connect and discard incoming RTM event if ne...
Displays the login form and handles the login action. def login(request, template_name='registration/login.html', redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the log...
Returns True if package manager 'owns' file Returns False if package manager does not 'own' file There is currently no way to determine if distutils or setuptools installed a package. A future feature of setuptools will make a package manifest which can be checked. '...
If the environmental variable 'HTTP_PROXY' is set, it will most likely be in one of these forms: proxyhost:8080 http://proxyhost:8080 urlllib2 requires the proxy URL to start with 'http://' This routine does that, and returns the transport for xmlrpc. def check_proxy_setting(): ""...
Returns URL of specified file type 'source', 'egg', or 'all' def filter_url(pkg_type, url): """ Returns URL of specified file type 'source', 'egg', or 'all' """ bad_stuff = ["?modtime", "#md5="] for junk in bad_stuff: if junk in url: url = url.split(junk)[0] ...
Send xml-rpc request using proxy def request(self, host, handler, request_body, verbose): '''Send xml-rpc request using proxy''' #We get a traceback if we don't have this attribute: self.verbose = verbose url = 'http://' + host + handler request = urllib2.Request(url) re...
Get a package name list from disk cache or PyPI def get_cache(self): """ Get a package name list from disk cache or PyPI """ #This is used by external programs that import `CheeseShop` and don't #want a cache file written to ~/.pypi and query PyPI every time. if self.no_...
Returns PyPI's XML-RPC server instance def get_xmlrpc_server(self): """ Returns PyPI's XML-RPC server instance """ check_proxy_setting() if os.environ.has_key('XMLRPC_DEBUG'): debug = 1 else: debug = 0 try: return xmlrpclib.Ser...
Fetch list of available versions for a package from The CheeseShop def query_versions_pypi(self, package_name): """Fetch list of available versions for a package from The CheeseShop""" if not package_name in self.pkg_list: self.logger.debug("Package %s not in cache, querying PyPI..." \ ...
Return list of pickled package names from PYPI def query_cached_package_list(self): """Return list of pickled package names from PYPI""" if self.debug: self.logger.debug("DEBUG: reading pickled cache file") return cPickle.load(open(self.pkg_cache_file, "r"))
Fetch and cache master list of package names from PYPI def fetch_pkg_list(self): """Fetch and cache master list of package names from PYPI""" self.logger.debug("DEBUG: Fetching package name list from PyPI") package_list = self.list_packages() cPickle.dump(package_list, open(self.pkg_cac...
Query PYPI via XMLRPC interface using search spec def search(self, spec, operator): '''Query PYPI via XMLRPC interface using search spec''' return self.xmlrpc.search(spec, operator.lower())
Query PYPI via XMLRPC interface for a pkg's metadata def release_data(self, package_name, version): """Query PYPI via XMLRPC interface for a pkg's metadata""" try: return self.xmlrpc.release_data(package_name, version) except xmlrpclib.Fault: #XXX Raises xmlrpclib.Fault ...
Query PYPI via XMLRPC interface for a pkg's available versions def package_releases(self, package_name): """Query PYPI via XMLRPC interface for a pkg's available versions""" if self.debug: self.logger.debug("DEBUG: querying PyPI for versions of " \ + package_name) ...
Query PyPI for pkg download URI for a packge def get_download_urls(self, package_name, version="", pkg_type="all"): """Query PyPI for pkg download URI for a packge""" if version: versions = [version] else: #If they don't specify version, show em all. (pack...
Clone the event Returns: :class:`slack.events.Event` def clone(self) -> "Event": """ Clone the event Returns: :class:`slack.events.Event` """ return self.__class__(copy.deepcopy(self.event), copy.deepcopy(self.metadata))
Create an event with data coming from the RTM API. If the event type is a message a :class:`slack.events.Message` is returned. Args: raw_event: JSON decoded data from the RTM API Returns: :class:`slack.events.Event` or :class:`slack.events.Message` def from_rtm(cls, r...
Create an event with data coming from the HTTP Event API. If the event type is a message a :class:`slack.events.Message` is returned. Args: raw_body: Decoded body of the Event API request verification_token: Slack verification token used to verify the request came from slack ...
Create a response message. Depending on the incoming message the response can be in a thread. By default the response follow where the incoming message was posted. Args: in_thread (boolean): Overwrite the `threading` behaviour Returns: a new :class:`slack.even...
Serialize the message for sending to slack API Returns: serialized message def serialize(self) -> dict: """ Serialize the message for sending to slack API Returns: serialized message """ data = {**self} if "attachments" in self: ...
Register a new handler for a specific :class:`slack.events.Event` `type` (See `slack event types documentation <https://api.slack.com/events>`_ for a list of event types). The arbitrary keyword argument is used as a key/value pair to compare against what is in the incoming :class:`slack.events....
Yields handlers matching the routing of the incoming :class:`slack.events.Event`. Args: event: :class:`slack.events.Event` Yields: handler def dispatch(self, event: Event) -> Iterator[Any]: """ Yields handlers matching the routing of the incoming :class:`slack....
Register a new handler for a specific :class:`slack.events.Message`. The routing is based on regex pattern matching the message text and the incoming slack channel. Args: pattern: Regex pattern matching the message text. handler: Callback flags: Regex flags. ...
Yields handlers matching the routing of the incoming :class:`slack.events.Message` Args: message: :class:`slack.events.Message` Yields: handler def dispatch(self, message: Message) -> Iterator[Any]: """ Yields handlers matching the routing of the incoming :clas...
Query the slack API When using :class:`slack.methods` the request is made `as_json` if available Args: url: :class:`slack.methods` or url string data: JSON encodable MutableMapping headers: Custom headers as_json: Post JSON to the slack API Retur...
Iterate over event from the RTM API Args: url: Websocket connection url bot_id: Connecting bot ID Returns: :class:`slack.events.Event` or :class:`slack.events.Message` def rtm( # type: ignore self, url: Optional[str] = None, bot_id: Optional[str] = None ...
Displays the login form for the given HttpRequest. def login(self, request, extra_context=None): """ Displays the login form for the given HttpRequest. """ context = { 'title': _('Log in'), 'app_path': request.get_full_path(), } if (REDIRECT_FIELD...
Get configuration from a file. def get_config(config_file): """Get configuration from a file.""" def load(fp): try: return yaml.safe_load(fp) except yaml.YAMLError as e: sys.stderr.write(text_type(e)) sys.exit(1) # TODO document exit codes if config_fil...
Figure out what options to use based on the four places it can come from. Order of precedence: * cli_options specified by the user at the command line * local_options specified in the config file for the metric * config_options specified in the config file at the base * DEFAULT_OPTIONS h...
Output the results to stdout. TODO: add AMPQ support for efficiency def output_results(results, metric, options): """ Output the results to stdout. TODO: add AMPQ support for efficiency """ formatter = options['Formatter'] context = metric.copy() # XXX might need to sanitize this try...
This method is analogous to "gsutil cp gsuri localpath", but in a programatically accesible way. The only difference is that we have to make a guess about the encoding of the file to not upset downstream file operations. If you are downloading a VCF, then "False" is great. If this is a B...
Accurate float rounding from http://stackoverflow.com/a/15398691. def round_float(f, digits, rounding=ROUND_HALF_UP): """ Accurate float rounding from http://stackoverflow.com/a/15398691. """ return Decimal(str(f)).quantize(Decimal(10) ** (-1 * digits), rounding=roun...
Returns a string representing a float, where the number of significant digits is min_digits unless it takes more digits to hit a non-zero digit (and the number is 0 < x < 1). We stop looking for a non-zero digit after max_digits. def float_str(f, min_digits=2, max_digits=6): """ Returns a string re...
Returns full name (first and last) if name is available. If not, returns username if available. If not available too, returns the user id as a string. def default_format(self): """ Returns full name (first and last) if name is available. If not, returns username if available. ...
Returns the first and last name of the user separated by a space. def full_name(self): """ Returns the first and last name of the user separated by a space. """ formatted_user = [] if self.user.first_name is not None: formatted_user.append(self.user.first_name) ...
Returns the full name (first and last parts), and the username between brackets if the user has it. If there is no info about the user, returns the user id between < and >. def full_format(self): """ Returns the full name (first and last parts), and the username between brackets if the user has...
Returns all the info available for the user in the following format: name [username] <id> (locale) bot_or_user If any data is not available, it is not added. def full_data(self): """ Returns all the info available for the user in the following format: name [username] <id...
Returns all the info available for the chat in the following format: title [username] (type) <id> If any data is not available, it is not added. def full_data(self): """ Returns all the info available for the chat in the following format: title [username] (type) <id> ...
Decorator for functions that should automatically fall back to the Cohort-default filter_fn and normalized_per_mb if not specified. def use_defaults(func): """ Decorator for functions that should automatically fall back to the Cohort-default filter_fn and normalized_per_mb if not specified. """ ...
Decorator for functions that return a collection (technically a dict of collections) that should be counted up. Also automatically falls back to the Cohort-default filter_fn and normalized_per_mb if not specified. def count_function(func): """ Decorator for functions that return a collection (technical...
Creates a function that counts variants that are filtered by the provided filterable_variant_function. The filterable_variant_function is a function that takes a filterable_variant and returns True or False. Users of this builder need not worry about applying e.g. the Cohort's default `filter_fn`. That will be...
Create a function that counts effects that are filtered by the provided filterable_effect_function. The filterable_effect_function is a function that takes a filterable_effect and returns True or False. Users of this builder need not worry about applying e.g. the Cohort's default `filter_fn`. That will be appl...
Estimate purity based on 2 * median VAF. Even if the Cohort has a default filter_fn, ignore it: we want to use all variants for this estimate. def median_vaf_purity(row, cohort, **kwargs): """ Estimate purity based on 2 * median VAF. Even if the Cohort has a default filter_fn, ignore it: we want ...
Calculate the boostrapped AUC for a given col trying to predict a pred_col. Parameters ---------- df : pandas.DataFrame col : str column to retrieve the values from pred_col : str the column we're trying to predict n_boostrap : int the number of bootstrap samples Re...
:param are_async: True if the callbacks execute asynchronously, posting any heavy work to another thread. def set_callbacks(self, worker_start_callback: callable, worker_end_callback: callable, are_async: bool = False): """ :param are_async: True if the callbacks execute asynchronously, posting any hea...
Can be safely called multiple times on the same worker (for workers that support it) to start a new thread for it. def _start_worker(self, worker: Worker): """ Can be safely called multiple times on the same worker (for workers that support it) to start a new thread for it. """ ...
Creates a new Worker and start a new Thread with it. Returns the Worker. def new_worker(self, name: str): """Creates a new Worker and start a new Thread with it. Returns the Worker.""" if not self.running: return self.immediate_worker worker = self._new_worker(name) self._st...
Creates a new worker pool and starts it. Returns the Worker that schedules works to the pool. def new_worker_pool(self, name: str, min_workers: int = 0, max_workers: int = 1, max_seconds_idle: int = DEFAULT_WORKER_POOL_MAX_SECONDS_IDLE): """ Creates a new worker pool and...
Return this Cohort as a DataFrame, and optionally include additional columns using `on`. on : str or function or list or dict, optional - A column name. - Or a function that creates a new column for comparison, e.g. count.snv_count. - Or a list of column-generating f...
Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just directly load a particular DataFrame. def load_dataframe(self, df_loader_name): """ Instead of joining a DataFrameJoiner with the Cohort in `as_dataframe`, sometimes we may want to just...
Return name of function, using default value if function not defined def _get_function_name(self, fn, default="None"): """ Return name of function, using default value if function not defined """ if fn is None: fn_name = default else: fn_name = fn.__name__ ...
Load a dictionary of patient_id to varcode.VariantCollection Parameters ---------- patients : str, optional Filter to a subset of patients filter_fn : function Takes a FilterableVariant and returns a boolean. Only variants returning True are preserved. ...
Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely depending on filter fn values def _hash_filter_fn(self, filter_fn, **kwargs): """ Construct string representing state of filter_fn Used to cache filtered variants or effects uniquely dep...
Load filtered, merged variants for a single patient, optionally using cache Note that filtered variants are first merged before filtering, and each step is cached independently. Turn on debug statements for more details about cached files. Use `_load_single_pati...
Load merged variants for a single patient, optionally using cache Note that merged variants are not filtered. Use `_load_single_patient_variants` to get filtered variants def _load_single_patient_merged_variants(self, patient, use_cache=True): """ Load merged variants for a single pati...
Load a dataframe containing polyphen2 annotations for all variants Parameters ---------- database_file : string, sqlite Path to the WHESS/Polyphen2 SQLite database. Can be downloaded and bunzip2"ed from http://bit.ly/208mlIU filter_fn : function Takes...
Load a dictionary of patient_id to varcode.EffectCollection Note that this only loads one effect per variant. Parameters ---------- patients : str, optional Filter to a subset of patients only_nonsynonymous : bool, optional If true, load only nonsynonymo...
Load Kallisto transcript quantification data for a cohort Parameters ---------- Returns ------- kallisto_data : Pandas dataframe Pandas dataframe with Kallisto data for all patients columns include patient_id, gene_name, est_counts def load_kallisto(sel...