text
stringlengths
81
112k
Returns all hooks of repository with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository :return: a list of hooks for...
Creates a new hook, and returns the created hook. :param auth.Authentication auth: authentication object, must be admin-level :param str repo_name: the name of the repo for which we create the hook :param str hook_type: The type of webhook, either "gogs" or "slack" :param dict config: S...
Updates hook with id ``hook_id`` according to ``update``. :param auth.Authentication auth: authentication object :param str repo_name: repo of the hook to update :param int hook_id: id of the hook to update :param GogsHookUpdate update: a ``GogsHookUpdate`` object describing the request...
Deletes the hook with id ``hook_id`` for repo with name ``repo_name`` owned by the user with username ``username``. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: name of repository of hook to delete ...
Creates a new organization, and returns the created organization. :param auth.Authentication auth: authentication object, must be admin-level :param str owner_name: Username of organization owner :param str org_name: Organization name :param str full_name: Full name of organization ...
Creates a new team of the organization. :param auth.Authentication auth: authentication object, must be admin-level :param str org_name: Organization user name :param str name: Full name of the team :param str description: Description of the team :param str permission: Team perm...
Add user to team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be added to team :raises NetworkFailure: if there is an error communicating with the server :raises ApiFailure...
Remove user from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str username: Username of the user to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :rais...
Add or update repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be added to the team :raises NetworkFailure: if there is an error communicating with the server :rais...
Remove repo from team. :param auth.Authentication auth: authentication object, must be admin-level :param str team_id: Team's id :param str repo_name: Name of the repo to be removed from the team :raises NetworkFailure: if there is an error communicating with the server :raises ...
List deploy keys for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :return: a list of deploy keys for the repo :rtype: List[GogsRepo.DeployKey] :r...
Get a deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :return: the deploy key :rtype: GogsRepo.D...
Add a deploy key to the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param str title: title of the key to add :param str key_content: content of the key to ...
Remove deploy key for the specified repo. :param auth.Authentication auth: authentication object :param str username: username of owner of repository :param str repo_name: the name of the repo :param int key_id: the id of the key :raises NetworkFailure: if there is an error comm...
Manually make a DELETE request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-request...
Manually make a GET request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.o...
Manually make a PATCH request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests...
Manually make a POST request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests....
Manually make a PUT request. :param str path: relative url of the request (e.g. `/users/username`) :param auth.Authentication auth: authentication object :param kwargs dict: Extra arguments for the request, as supported by the `requests <http://docs.python-requests.o...
Raise an ApiFailure pertaining to the given response def _fail(response): """ Raise an ApiFailure pertaining to the given response """ message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url) try: message += ", message:{}".f...
Set a function to call when run() is called, before the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. def setStartAction(self, action, *args, **kwargs): """ ...
Set a function to call when run() is stopping, after the main action is called. Parameters ---------- action: function pointer The function to call. *args Positional arguments to pass to action. **kwargs: Keyword arguments to pass to action. def setStopAction(self, action, *args, **kwargs): """ ...
Calls the defined action every $interval seconds. Optionally calls an action before the main loop, and an action when stopping, if these are defined. Exceptions in the main loop will NOT cause the thread to die. def run(self): """ Calls the defined action every $interval seconds. Optionally calls an action be...
Prints items with a timestamp. def Printer(open_file=sys.stdout, closing=False): """ Prints items with a timestamp. """ try: while True: logstr = (yield) open_file.write(logstr) open_file.write('\n') # new line except GeneratorExit: if closing: ...
Opens the given file and returns a printer to it. def FilePrinter(filename, mode='a', closing=True): path = os.path.abspath(os.path.expanduser(filename)) """ Opens the given file and returns a printer to it. """ f = open(path, mode) return Printer(f, closing)
Writes messages to a socket/host. def SocketWriter(host, port, af=None, st=None): """ Writes messages to a socket/host. """ import socket if af is None: af = socket.AF_INET if st is None: st = socket.SOCK_STREAM message = '({0}): {1}' s = socket.socket(af, st) s.connect(host...
Sends messages as emails to the given list of recipients. def Emailer(recipients, sender=None): """ Sends messages as emails to the given list of recipients. """ import smtplib hostname = socket.gethostname() if not sender: sender = 'lggr@{0}'.format(hostname) smtp = smtplib...
Sends messages as emails to the given list of recipients, from a GMail account. def GMailer(recipients, username, password, subject='Log message from lggr.py'): """ Sends messages as emails to the given list of recipients, from a GMail account. """ import smtplib srvr = smtplib.SMTP('smtp.g...
Given a list or tuple of logging levels, add a logger instance to each. def add(self, levels, logger): """ Given a list or tuple of logging levels, add a logger instance to each. """ if isinstance(levels, (list, tuple)): for lvl in levels: self.config...
Given a level, remove a given logger function if it is a member of that level, closing the logger function either way. def remove(self, level, logger): """ Given a level, remove a given logger function if it is a member of that level, closing the logger function ...
Remove all logger functions from a given level. def clear(self, level): """ Remove all logger functions from a given level. """ for item in self.config[level]: item.close() self.config[level].clear()
Create a 'record' (a dictionary) with information to be logged. def _make_record(self, level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc): """ Create ...
Send a log message to all of the logging functions for a given level as well as adding the message to this logger instance's history. def _log(self, level, fmt, args=None, extra=None, exc_info=None, inc_stackinfo=Fals...
Do logging, but handle error suppression. def log(self, *args, **kwargs): """ Do logging, but handle error suppression. """ if self.suppress_errors: try: self._log(*args, **kwargs) return True except: return False else: ...
Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included. def debug(self, msg, *args, **kwargs): """ Log a message with DEBUG level. Automatically includes stack info unless it is specifically not included. """ kwargs.setdefault('inc_stack...
Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included. def error(self, msg, *args, **kwargs): """ Log a message with ERROR level. Automatically includes stack and process info unless they are specifically not included. """ ...
Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included. def critical(self, msg, *args, **kwargs): """ Log a message with CRITICAL level. Automatically includes stack and process info unless they are specifically not included. "...
Log a message at multiple levels def multi(self, lvl_list, msg, *args, **kwargs): """ Log a message at multiple levels""" for level in lvl_list: self.log(level, msg, args, **kwargs)
Log a message at every known log level def all(self, msg, *args, **kwargs): """ Log a message at every known log level """ self.multi(ALL, msg, args, **kwargs)
Find the stack frame of the caller so that we can note the source file name, line number, and function name. def _find_caller(self): """ Find the stack frame of the caller so that we can note the source file name, line number, and function name. """ rv = ('(unknown file)...
Maps a raw deserialized row to proper types def _map_value(self, value): ''' Maps a raw deserialized row to proper types ''' # TODO: Once we've gotten here, we've done the following: # -> Recieve the full response, copy it from network buffer it into a ByteBuffer (copy 1) # -> Copy all ...
gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs def get_deprecated_gene_ids(filename): """ gets a dict of the gene IDs used during in DDD datasets that have been deprecated in favour of other gene IDs """ deprecated = {} with op...
finds the protein length for ensembl transcript IDs for a gene Args: ensembl: EnsemblRequest object to request sequences and data from the ensembl REST API transcript_ids: list of transcript IDs for a single gene Returns: dictionary of lengths (in amino acids), inde...
creates an Transcript object for a gene from ensembl databases Args: ensembl: EnsemblRequest object to request data from ensembl transcript_id: string for an Ensembl transcript ID Returns: a Transcript object, containing transcript coordinates and gene and transcript se...
get the de novos within the coding sequence of a transcript Args: transcript: Transcript object, which defines the transcript coordinates de_novos: list of chromosome sequence positions for de novo events Returns: list of de novo positions found within the transcript def get_d...
gets transcript IDs for a gene. Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene Returns: dictionary of transcript ID: transcript lengths for all transcripts for a given HGNC symbol. def get_transcript_ids(ensembl, gene_id...
sort out all the necessary sequences and positions for a gene Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene de_novos: list of de novo positions, so we can check they all fit in the gene transcript Returns: ...
count de novos in transcripts for a gene. Args: ensembl: EnsemblRequest object to request data from ensembl gene_id: HGNC symbol for gene de_novos: list of de novo positions, so we can check they all fit in the gene transcript Returns: dictionary of leng...
get a set of minimal transcripts to contain all the de novos. We identify the minimal number of transcripts to contain all de novos. This allows for de novos on mutually exclusive transcripts. The transcripts are selected on the basis of containing the most number of de novos, while also being the ...
Dumps a SimpleDb as string in the following format: <key>: <json-encoded string> def dump_simple_db(path): """ Dumps a SimpleDb as string in the following format: <key>: <json-encoded string> """ output = [] simpledb = SimpleDb(path, mode="r", sync=False) with simpledb as db: for key in db: output.append(...
Retrieve a required variable from the current environment variables. Raises a ValueError if the env variable is not found or has no value. def required_from_env(key): """ Retrieve a required variable from the current environment variables. Raises a ValueError if the env variable is not found or has n...
Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. def get(self, url): """ Make a HTTP GET request to the Reader API. :param url: url to which to make a GET request. """ logger.debug('Making GET request to %s', url) retur...
Make a HTTP POST request to the Reader API. :param url: url to which to make a POST request. :param post_params: parameters to be sent in the request's body. def post(self, url, post_params=None): """ Make a HTTP POST request to the Reader API. :param url: url to which to make...
Make a HTTP DELETE request to the Readability API. :param url: The url to which to send a DELETE request. def delete(self, url): """ Make a HTTP DELETE request to the Readability API. :param url: The url to which to send a DELETE request. """ logger.debug('Making DELET...
Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve. def get_article(self, article_id): """ Get a single article represented by `article_id`. :param article_id: ID of the article to retrieve. """ url = self._generate_url('...
Get Bookmarks for the current user. Filters: :param archive: Filter Bookmarks returned by archived status. :param favorite: Filter Bookmarks returned by favorite status. :param domain: Filter Bookmarks returned by a domain. :param added_since: Filter bookmarks by date added (si...
Get a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to retrieve. def get_bookmark(self, bookmark_id): """ Get a single bookmark represented by `bookmark_id`. The requested bookmark ...
Adds given bookmark to the authenticated user. :param url: URL of the article to bookmark :param favorite: whether or not the bookmark should be favorited :param archive: whether or not the bookmark should be archived :param allow_duplicates: whether or not to allow duplicate bookmarks ...
Updates given bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to update. :param favorite (optional): Whether this article is favorited or not. :param archive (optional): Whether this article is archived or not. :param read...
Delete a single bookmark represented by `bookmark_id`. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. def delete_bookmark(self, bookmark_id): """ Delete a single bookmark represented by `bookmark_id`. The requested bo...
Retrieve tags that have been applied to a bookmark. The requested bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. def get_bookmark_tags(self, bookmark_id): """ Retrieve tags that have been applied to a bookmark. The requested bookma...
Add tags to to a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. :param tags: Comma separated tags to be applied. def add_tags_to_bookmark(self, bookmark_id, tags): """ Add tags to to a bookmark. The...
Remove a single tag from a bookmark. The identified bookmark must belong to the current user. :param bookmark_id: ID of the bookmark to delete. def delete_tag_from_bookmark(self, bookmark_id, tag_id): """ Remove a single tag from a bookmark. The identified bookmark must belon...
Get a single tag represented by `tag_id`. The requested tag must belong to the current user. :param tag_id: ID fo the tag to retrieve. def get_tag(self, tag_id): """ Get a single tag represented by `tag_id`. The requested tag must belong to the current user. :param t...
Make an HTTP POST request to the Parser API. :param url: url to which to make the request :param post_params: POST data to send along. Expected to be a dict. def post(self, url, post_params=None): """ Make an HTTP POST request to the Parser API. :param url: url to which to mak...
Build the url to resource. :param resource: Name of the resource that is being called. Options are `''` (empty string) for root resource, `'parser'`, `'confidence'`. :param query_params: Data to be passed as query parameters. def _generate_url(self, resource, query_params=None): """ ...
Send a GET request to the `parser` endpoint of the parser API to get back the representation of an article. The article can be identified by either a URL or an id that exists in Readability. Note that either the `url` or `article_id` param should be passed. :param url (optiona...
POST content to be parsed to the Parser API. Note: Even when POSTing content, a url must still be provided. :param content: the content to be parsed :param url: the url that represents the content :param max_pages (optional): the maximum number of pages to parse and combine...
Send a HEAD request to the `parser` endpoint to the parser API to get the articles status. Returned is a `requests.Response` object. The id and status for the article can be extracted from the `X-Article-Id` and `X-Article-Status` headers. Note that either the `url` or `article...
Send a GET request to the `confidence` endpoint of the Parser API. Note that either the `url` or `article_id` param should be passed. :param url (optional): The url of an article whose content is wanted. :param article_id (optional): The id of an article in the Readability system w...
Decorator for priming co-routines that use (yield) def coroutine(func): """ Decorator for priming co-routines that use (yield) """ def wrapper(*args, **kwargs): c = func(*args, **kwargs) c.next() # prime it for iteration return c return wrapper
Save word embedding file. Args: f (File): File to write the vectors. File should be open for writing ascii. arr (numpy.array): Numpy array with ``float`` dtype. vocab (iterable): Each element is pair of a word (``bytes``) and ``arr`` index (``int``). Word should be e...
Convert pretrained word embedding file in one format to another. def convert(outputfile, inputfile, to_format, from_format): """ Convert pretrained word embedding file in one format to another. """ emb = word_embedding.WordEmbedding.load( inputfile, format=_input_choices[from_format][1], ...
Check format of inputfile. def check_format(inputfile): """ Check format of inputfile. """ t = word_embedding.classify_format(inputfile) if t == word_embedding._glove: _echo_format_result('glove') elif t == word_embedding._word2vec_bin: _echo_format_result('word2vec-binary') ...
List available format. def list(): """ List available format. """ choice_len = max(map(len, _input_choices.keys())) tmpl = " {:<%d}: {}\n" % choice_len text = ''.join(map( lambda k_v: tmpl.format(k_v[0], k_v[1][0]), six.iteritems(_input_choices))) click.echo(text)
Do the default action of `twitter` command. def main(): """Do the default action of `twitter` command.""" from twitter.cmdline import Action, OPTIONS twitter = Twitter.from_oauth_file() Action()(twitter, OPTIONS)
Get an object bound to the Twitter API using your own credentials. The `twitter` library ships with a `twitter` command that uses PIN OAuth. Generate your own OAuth credentials by running `twitter` from the shell, which will open a browser window to authenticate you. Once successfully r...
Search twitter for ``q``, return `results`__ directly from twitter. __ https://dev.twitter.com/rest/reference/get/search/tweets def search(self, q=None, **kw): """Search twitter for ``q``, return `results`__ directly from twitter. __ https://dev.twitter.com/rest/reference/get/search/tweets ...
Perform :meth:`lookup` on return value of :meth:`search`. def lookup_search_result(self, result, **kw): """Perform :meth:`lookup` on return value of :meth:`search`.""" return self.lookup(s['id_str'] for s in result['statuses'], **kw)
Lookup list of statuses, return `results`__ directly from twitter. Input can be any sequence of numeric or string values representing twitter status IDs. __ https://dev.twitter.com/rest/reference/get/statuses/lookup def lookup(self, id_list, **kw): """Lookup list of statuses, return `...
Parameters ---------- mea axis xlim ylim Returns ------- def plot_probe(mea, ax=None, xlim=None, ylim=None, color_currents=False, top=None, bottom=None, cmap='viridis', type='shank', alpha_elec=0.7, alpha_prb=0.3): ''' Parameters ---------- mea axis ...
Get version without import, which avoids dependency issues. def get_version(filepath='src/birding/version.py'): """Get version without import, which avoids dependency issues.""" with open(get_abspath(filepath)) as version_file: return re.search( r"""__version__\s+=\s+(['"])(?P<version>.+?)\...
Search Gnip for given query, returning deserialized response. def search(self, q, **kw): """Search Gnip for given query, returning deserialized response.""" url = '{base_url}/search/{stream}'.format(**vars(self)) params = { 'q': q, } params.update(self.params) ...
Dump result into a string, useful for debugging. def dump(result): """Dump result into a string, useful for debugging.""" if isinstance(result, dict): # Result is a search result. statuses = result['results'] else: # Result is a lookup result. sta...
Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as defined in :mod:`birding.config`. def shelf_from_config(config, **default_init): """Get a `Shelf` instance dynamically based on config. `config` is a dictionary containing ``shelf_*`` keys as d...
Unpack and return value only if it is fresh. def unpack(self, key, value): """Unpack and return value only if it is fresh.""" value, freshness = value if not self.is_fresh(freshness): raise KeyError('{} (stale)'.format(key)) return value
Return False if given freshness value has expired, else True. def is_fresh(self, freshness): """Return False if given freshness value has expired, else True.""" if self.expire_after is None: return True return self.freshness() - freshness <= self.expire_after
Django form errors do not obey natural field order, this template tag returns non-field and field-specific errors :param form: the form instance def get_form_errors(form): """ Django form errors do not obey natural field order, this template tag returns non-field and field-specific errors :para...
Sub-nav displayed below proposition header - creates alternate language links if SHOW_LANGUAGE_SWITCH is set - takes "breadcrumbs" from the context - takes "breadcrumbs_back" from the context to show a back link *instead* of breadcrumbs def sub_nav(context): """ Sub-nav displayed below proposition ...
Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. def is_first_instance_aws(): """ Returns True if the current instance is the first instance in the ASG group, sorted by instance_id. """ try: # get instance id and aws region inst...
Returns True if the current pod is the first replica in Kubernetes cluster. def is_first_instance_k8s(current_pod_name=None): """ Returns True if the current pod is the first replica in Kubernetes cluster. """ current_pod_name = current_pod_name or os.environ.get('POD_NAME') if not current_pod_name...
This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool def splitarg(args): ''' This function will split arguments separated by spaces or commas to be backwards compatible with the original ArcGet command line tool '''...
Displays the login form and handles the login action. def login(request, template_name=None, redirect_field_name=REDIRECT_FIELD_NAME, authentication_form=AuthenticationForm, current_app=None, extra_context=None): """ Displays the login form and handles the login action. """ ...
Logs out the user. def logout(request, template_name=None, next_page=None, redirect_field_name=REDIRECT_FIELD_NAME, current_app=None, extra_context=None): """ Logs out the user. """ auth_logout(request) if next_page is not None: next_page = resolve_url(next...
Get a dict for the current birding configuration. The resulting dictionary is fully populated with defaults, such that all valid keys will resolve to valid values. Invalid and extra values in the configuration result in an exception. See :ref:`config` (module-level docstring) for discussion on how bir...
Get a file object with YAML data of configuration defaults. Arguments are passed through to :func:`get_defaults_str`. def get_defaults_file(*a, **kw): """Get a file object with YAML data of configuration defaults. Arguments are passed through to :func:`get_defaults_str`. """ fd = StringIO() f...
Get the string YAML representation of configuration defaults. def get_defaults_str(raw=None, after='Defaults::'): """Get the string YAML representation of configuration defaults.""" if raw is None: raw = __doc__ return unicode(textwrap.dedent(raw.split(after)[-1]).strip())
Return the overlay of `upper` dict onto `lower` dict. This operation is similar to `dict.update`, but recurses when it encounters a dict/mapping, as to allow nested leaf values in the lower collection which are not in the upper collection. Whenever the upper collection has a value, its value is used. ...
Import an object based on the dotted string. >>> import_name('textwrap') # doctest: +ELLIPSIS <module 'textwrap' from '...'> >>> import_name('birding.config') # doctest: +ELLIPSIS <module 'birding.config' from '...'> >>> import_name('birding.config.get_config') # doctest: +ELLIPSIS <function ge...
Read kafka config, then dispatch to `follow_topic`. def follow_topic_from_config(): """Read kafka config, then dispatch to `follow_topic`.""" config = get_config()['ResultTopicBolt'] kafka_class = import_name(config['kafka_class']) return follow_topic(kafka_class, config['topic'], **config['kafka_init'...