code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
response = self.get("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth)
return GogsRepo.DeployKey.from_json(response.json()) | def get_deploy_key(self, auth, username, repo_name, key_id) | 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... | 3.375067 | 2.437992 | 1.384363 |
data = {
"title": title,
"key": key_content
}
response = self.post("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth, data=data)
return GogsRepo.DeployKey.from_json(response.json()) | def add_deploy_key(self, auth, username, repo_name, title, key_content) | 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 ... | 2.865293 | 2.269378 | 1.26259 |
self.delete("/repos/{u}/{r}/keys/{k}".format(u=username, r=repo_name, k=key_id), auth=auth) | def delete_deploy_key(self, auth, username, repo_name, key_id) | 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... | 2.646682 | 3.064511 | 0.863656 |
return self._check_ok(self._delete(path, auth=auth, **kwargs)) | def delete(self, path, auth=None, **kwargs) | 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... | 5.288076 | 9.728161 | 0.543584 |
return self._check_ok(self._get(path, auth=auth, **kwargs)) | def get(self, path, auth=None, **kwargs) | 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... | 5.384245 | 9.909395 | 0.543348 |
return self._check_ok(self._patch(path, auth=auth, **kwargs)) | def patch(self, path, auth=None, **kwargs) | 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... | 5.400463 | 10.730883 | 0.503264 |
return self._check_ok(self._post(path, auth=auth, **kwargs)) | def post(self, path, auth=None, **kwargs) | 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.... | 5.368063 | 10.119801 | 0.530451 |
return self._check_ok(self._put(path, auth=auth, **kwargs)) | def put(self, path, auth=None, **kwargs) | 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... | 5.332031 | 10.262331 | 0.519573 |
message = "Status code: {}-{}, url: {}".format(response.status_code, response.reason, response.url)
try:
message += ", message:{}".format(response.json()["message"])
except (ValueError, KeyError):
pass
raise ApiFailure(message, response.status_code) | def _fail(response) | Raise an ApiFailure pertaining to the given response | 3.779779 | 3.192614 | 1.183914 |
self.init_action = action
self.init_args = args
self.init_kwargs = kwargs | def setStartAction(self, action, *args, **kwargs) | 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. | 3.300109 | 3.289448 | 1.003241 |
self.stop_action = action
self.stop_args = args
self.stop_kwargs = kwargs | def setStopAction(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. | 2.340913 | 2.966014 | 0.789245 |
self.logger.debug("Thread {0} is entering main loop".format(self.name))
if hasattr(self, "init_action"):
self.logger.debug("Thread {0} is calling its init action")
self.init_action(*self.init_args, **self.init_kwargs)
while not self.stop:
self.logger.debug("Delay is {0}".format(self.delay))
if (d... | def run(self) | 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. | 1.911838 | 1.851009 | 1.032863 |
try:
while True:
logstr = (yield)
open_file.write(logstr)
open_file.write('\n') # new line
except GeneratorExit:
if closing:
try: open_file.close()
except: pass | def Printer(open_file=sys.stdout, closing=False) | Prints items with a timestamp. | 3.324124 | 3.70156 | 0.898033 |
path = os.path.abspath(os.path.expanduser(filename))
f = open(path, mode)
return Printer(f, closing) | def FilePrinter(filename, mode='a', closing=True) | Opens the given file and returns a printer to it. | 4.093443 | 4.738887 | 0.863798 |
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, port)
try:
while True:
logstr = (yield)
s.send(logstr)
except GeneratorExit:
... | def SocketWriter(host, port, af=None, st=None) | Writes messages to a socket/host. | 3.011394 | 3.039249 | 0.990835 |
import smtplib
hostname = socket.gethostname()
if not sender:
sender = 'lggr@{0}'.format(hostname)
smtp = smtplib.SMTP('localhost')
try:
while True:
logstr = (yield)
try:
smtp.sendmail(sender, recipients, logstr)
except smtplib... | def Emailer(recipients, sender=None) | Sends messages as emails to the given list
of recipients. | 3.52263 | 3.508608 | 1.003996 |
import smtplib
srvr = smtplib.SMTP('smtp.gmail.com', 587)
srvr.ehlo()
srvr.starttls()
srvr.ehlo()
srvr.login(username, password)
if not (isinstance(recipients, list) or isinstance(recipients, tuple)):
recipients = [recipients]
gmail_sender = '{0}@gmail.com'.format(username... | 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. | 2.425565 | 2.440558 | 0.993857 |
if isinstance(levels, (list, tuple)):
for lvl in levels:
self.config[lvl].add(logger)
else:
self.config[levels].add(logger) | def add(self, levels, logger) | Given a list or tuple of logging levels,
add a logger instance to each. | 2.972624 | 2.706291 | 1.098412 |
self.config[level].discard(logger)
logger.close() | 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 either way. | 10.370747 | 8.93634 | 1.160514 |
for item in self.config[level]:
item.close()
self.config[level].clear() | def clear(self, level) | Remove all logger functions from a given level. | 6.502612 | 5.757957 | 1.129326 |
fn = fname = '(unknown file)'
lno = 0
func = '(unknown function)'
code = '(code not available)'
cc = []
sinfo = None
module = '(unknown module)'
if _srcfile and inc_stackinfo:
#IronPython doesn't track Python frames, so _find_caller t... | def _make_record(self,
level,
fmt,
args,
extra,
exc_info,
inc_stackinfo,
inc_multiproc) | Create a 'record' (a dictionary) with information to be logged. | 4.51875 | 4.511736 | 1.001555 |
if not self.enabled:
return # Fail silently so that logging can easily be removed
log_record = self._make_record(
level, fmt, args, extra, exc_info, inc_stackinfo, inc_multiproc)
logstr = log_record['defaultfmt'].format(**log_record) #whoah.
if self.keep... | def _log(self,
level,
fmt,
args=None,
extra=None,
exc_info=None,
inc_stackinfo=False,
inc_multiproc=False) | 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. | 5.222957 | 5.073979 | 1.029361 |
if self.suppress_errors:
try:
self._log(*args, **kwargs)
return True
except:
return False
else:
self._log(*args, **kwargs)
return True | def log(self, *args, **kwargs) | Do logging, but handle error suppression. | 2.711957 | 2.027415 | 1.337643 |
kwargs.setdefault('inc_stackinfo', True)
self.log(DEBUG, msg, args, **kwargs) | def debug(self, msg, *args, **kwargs) | Log a message with DEBUG level. Automatically includes stack info
unless it is specifically not included. | 7.897558 | 4.858787 | 1.625418 |
kwargs.setdefault('inc_stackinfo', True)
kwargs.setdefault('inc_multiproc', True)
self.log(ERROR, msg, args, **kwargs) | def error(self, msg, *args, **kwargs) | Log a message with ERROR level. Automatically includes stack and
process info unless they are specifically not included. | 8.596642 | 4.882129 | 1.760839 |
kwargs.setdefault('inc_stackinfo', True)
kwargs.setdefault('inc_multiproc', True)
self.log(CRITICAL, msg, args, **kwargs) | def critical(self, msg, *args, **kwargs) | Log a message with CRITICAL level. Automatically includes stack and
process info unless they are specifically not included. | 7.181151 | 4.780352 | 1.502222 |
for level in lvl_list:
self.log(level, msg, args, **kwargs) | def multi(self, lvl_list, msg, *args, **kwargs) | Log a message at multiple levels | 3.475491 | 3.001606 | 1.157877 |
self.multi(ALL, msg, args, **kwargs) | def all(self, msg, *args, **kwargs) | Log a message at every known log level | 21.78359 | 17.093878 | 1.27435 |
rv = ('(unknown file)',
0,
'(unknown function)',
'(code not available)',
[],
None)
f = inspect.currentframe()
while hasattr(f, 'f_code'):
co = f.f_code
filename = os.path.normcase(co.co_filenam... | 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. | 6.688417 | 6.405981 | 1.04409 |
''' 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 the data into a String (copy 2)
# -> Deserialize that string (copy... | def _map_value(self, value) | Maps a raw deserialized row to proper types | 5.321565 | 4.971996 | 1.070308 |
deprecated = {}
with open(filename) as handle:
for line in handle:
line = line.strip().split()
old = line[0]
new = line[1]
deprecated[old] = new
return deprecated | 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 | 2.328304 | 2.405615 | 0.967862 |
transcripts = {}
for transcript_id in transcript_ids:
# get the transcript's protein sequence via the ensembl REST API
try:
seq = ensembl.get_protein_seq_for_transcript(transcript_id)
except ValueError:
continue
transcripts[transcript_id... | def get_transcript_lengths(ensembl, transcript_ids) | 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... | 3.32014 | 3.1738 | 1.046109 |
# get the sequence for the identified transcript
(chrom, start, end, strand, genomic_sequence) = ensembl.get_genomic_seq_for_transcript(transcript_id, expand=10)
cds_sequence = ensembl.get_cds_seq_for_transcript(transcript_id)
# get the locations of the exons and cds from ensembl
cds_... | def construct_gene_object(ensembl, transcript_id) | 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... | 2.568462 | 2.571043 | 0.998996 |
in_transcript = []
for de_novo in de_novos:
# we check if the de novo is within the transcript by converting the
# chromosomal position to a CDS-based position. Variants outside the CDS
# will raise an error, which we catch and pass on. It's better to do
# this, rather ... | def get_de_novos_in_transcript(transcript, de_novos) | 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 | 5.2463 | 5.299591 | 0.989944 |
ensembl_genes = ensembl.get_genes_for_hgnc_id(gene_id)
transcript_ids = ensembl.get_transcript_ids_for_ensembl_gene_ids(ensembl_genes, [gene_id])
# sometimes we get HGNC symbols that do not match the ensembl rest version
# that we are currentl using. We can look for earlier HGNC symbols f... | def get_transcript_ids(ensembl, gene_id) | 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. | 3.613194 | 3.641413 | 0.992251 |
transcripts = minimise_transcripts(ensembl, gene_id, de_novos)
genes = []
for transcript_id in transcripts:
gene = construct_gene_object(ensembl, transcript_id)
genes.append(gene)
if len(genes) == 0:
raise IndexError("{0}: no suitable transcripts".format(gene_... | def load_gene(ensembl, gene_id, de_novos=[]) | 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:
... | 3.511771 | 3.622759 | 0.969364 |
transcripts = get_transcript_ids(ensembl, gene_id)
# TODO: allow for genes without any coding sequence.
if len(transcripts) == 0:
raise IndexError("{0} lacks coding transcripts".format(gene_id))
# count the de novos observed in all transcripts
counts = {}
for key in t... | def count_de_novos_per_transcript(ensembl, gene_id, de_novos=[]) | 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... | 3.865081 | 3.825659 | 1.010305 |
if len(de_novos) == 0:
return {}
counts = count_de_novos_per_transcript(ensembl, gene_id, de_novos)
if len(counts) == 0:
return {}
# find the transcripts with the most de novos
max_count = max( val["n"] for key, val in counts.items() )
transcripts = [ key... | def minimise_transcripts(ensembl, gene_id, de_novos) | 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 ... | 3.017505 | 2.899888 | 1.040559 |
output = []
simpledb = SimpleDb(path, mode="r", sync=False)
with simpledb as db:
for key in db:
output.append("{0}: {1}".format(key, db.dumpvalue(key)))
return "\n".join(output) | def dump_simple_db(path) | Dumps a SimpleDb as string in the following format:
<key>: <json-encoded string> | 3.774366 | 3.337848 | 1.130778 |
val = os.environ.get(key)
if not val:
raise ValueError(
"Required argument '{}' not supplied and not found in environment variables".format(key))
return val | 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 no value. | 4.164197 | 4.867731 | 0.85547 |
logger.debug('Making GET request to %s', url)
return self.oauth_session.get(url) | def get(self, url) | Make a HTTP GET request to the Reader API.
:param url: url to which to make a GET request. | 4.865781 | 6.083568 | 0.799824 |
params = urlencode(post_params)
logger.debug('Making POST request to %s with body %s', url, params)
return self.oauth_session.post(url, data=params) | def post(self, url, post_params=None) | 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. | 3.443851 | 3.991284 | 0.862843 |
logger.debug('Making DELETE request to %s', url)
return self.oauth_session.delete(url) | def delete(self, url) | Make a HTTP DELETE request to the Readability API.
:param url: The url to which to send a DELETE request. | 5.304375 | 6.43197 | 0.824689 |
url = self._generate_url('articles/{0}'.format(article_id))
return self.get(url) | def get_article(self, article_id) | Get a single article represented by `article_id`.
:param article_id: ID of the article to retrieve. | 4.252035 | 5.531378 | 0.768712 |
filter_dict = filter_args_to_dict(filters, ACCEPTED_BOOKMARK_FILTERS)
url = self._generate_url('bookmarks', query_params=filter_dict)
return self.get(url) | def get_bookmarks(self, **filters) | 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... | 4.476324 | 5.613026 | 0.797489 |
url = self._generate_url('bookmarks/{0}'.format(bookmark_id))
return self.get(url) | def get_bookmark(self, bookmark_id) | 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. | 4.052637 | 6.543144 | 0.619371 |
rdb_url = self._generate_url('bookmarks')
params = {
"url": url,
"favorite": int(favorite),
"archive": int(archive),
"allow_duplicates": int(allow_duplicates)
}
return self.post(rdb_url, params) | def add_bookmark(self, url, favorite=False, archive=False, allow_duplicates=True) | 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 ... | 2.722036 | 2.969611 | 0.91663 |
rdb_url = self._generate_url('bookmarks/{0}'.format(bookmark_id))
params = {}
if favorite is not None:
params['favorite'] = 1 if favorite == True else 0
if archive is not None:
params['archive'] = 1 if archive == True else 0
if read_percent is not... | def update_bookmark(self, bookmark_id, favorite=None, archive=None, read_percent=None) | 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... | 2.069538 | 2.261096 | 0.915281 |
url = self._generate_url('bookmarks/{0}'.format(bookmark_id))
return self.delete(url) | def delete_bookmark(self, bookmark_id) | 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. | 4.222171 | 7.000181 | 0.603152 |
url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id))
return self.get(url) | def get_bookmark_tags(self, bookmark_id) | 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. | 3.761662 | 6.413115 | 0.586558 |
url = self._generate_url('bookmarks/{0}/tags'.format(bookmark_id))
params = dict(tags=tags)
return self.post(url, params) | def add_tags_to_bookmark(self, bookmark_id, tags) | 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. | 3.286094 | 4.721895 | 0.695927 |
url = self._generate_url('bookmarks/{0}/tags/{1}'.format(
bookmark_id, tag_id))
return self.delete(url) | def delete_tag_from_bookmark(self, bookmark_id, tag_id) | 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. | 3.208787 | 5.243777 | 0.611923 |
url = self._generate_url('tags/{0}'.format(tag_id))
return self.get(url) | def get_tag(self, tag_id) | 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. | 4.134296 | 6.169489 | 0.67012 |
post_params['token'] = self.token
params = urlencode(post_params)
logger.debug('Making POST request to %s with body %s', url, params)
return requests.post(url, data=params) | def post(self, url, post_params=None) | 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. | 3.167074 | 3.246921 | 0.975408 |
resource = '{resource}?token={token}'.format(resource=resource, token=self.token)
if query_params:
resource += "&{}".format(urlencode(query_params))
return self.base_url_template.format(resource) | def _generate_url(self, resource, query_params=None) | 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. | 3.288462 | 3.963706 | 0.829643 |
query_params = {}
if url is not None:
query_params['url'] = url
if article_id is not None:
query_params['article_id'] = article_id
query_params['max_pages'] = max_pages
url = self._generate_url('parser', query_params=query_params)
return s... | def get_article(self, url=None, article_id=None, max_pages=25) | 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... | 2.156088 | 2.069766 | 1.041706 |
params = {
'doc': content,
'max_pages': max_pages
}
url = self._generate_url('parser', {"url": url})
return self.post(url, post_params=params) | def post_article_content(self, content, url, max_pages=25) | 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... | 5.039389 | 5.781952 | 0.871572 |
query_params = {}
if url is not None:
query_params['url'] = url
if article_id is not None:
query_params['article_id'] = article_id
url = self._generate_url('parser', query_params=query_params)
return self.head(url) | def get_article_status(self, url=None, article_id=None) | 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... | 2.697799 | 2.511957 | 1.073983 |
query_params = {}
if url is not None:
query_params['url'] = url
if article_id is not None:
query_params['article_id'] = article_id
url = self._generate_url('confidence', query_params=query_params)
return self.get(url) | def get_confidence(self, url=None, article_id=None) | 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... | 1.989999 | 2.206737 | 0.901784 |
def wrapper(*args, **kwargs):
c = func(*args, **kwargs)
c.next() # prime it for iteration
return c
return wrapper | def coroutine(func) | Decorator for priming co-routines that use (yield) | 4.077947 | 3.857848 | 1.057052 |
itr = iter(vocab)
# Avoid empty line at the end
word, idx = next(itr)
_write_line(f, arr[idx], word)
for word, idx in itr:
f.write(b'\n')
_write_line(f, arr[idx], word) | def save(f, arr, vocab) | 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... | 4.616709 | 4.642581 | 0.994427 |
emb = word_embedding.WordEmbedding.load(
inputfile, format=_input_choices[from_format][1],
binary=_input_choices[from_format][2])
emb.save(outputfile, format=_output_choices[to_format][1],
binary=_output_choices[to_format][2]) | def convert(outputfile, inputfile, to_format, from_format) | Convert pretrained word embedding file in one format to another. | 3.59666 | 3.31116 | 1.086223 |
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')
elif t == word_embedding._word2vec_text:
_echo_format_result('word2vec-text')
else:
... | def check_format(inputfile) | Check format of inputfile. | 3.850522 | 3.895284 | 0.988509 |
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) | def list() | List available format. | 4.923778 | 4.598813 | 1.070663 |
from twitter.cmdline import Action, OPTIONS
twitter = Twitter.from_oauth_file()
Action()(twitter, OPTIONS) | def main() | Do the default action of `twitter` command. | 31.034586 | 21.718559 | 1.428943 |
if filepath is None:
# Use default OAuth filepath from `twitter` command-line program.
home = os.environ.get('HOME', os.environ.get('USERPROFILE', ''))
filepath = os.path.join(home, '.twitter_oauth')
oauth_token, oauth_token_secret = read_token_file(filepath... | def from_oauth_file(cls, filepath=None) | 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... | 3.015493 | 2.701148 | 1.116375 |
if q is None:
raise ValueError('No search query provided for `q` keyword.')
return self.twitter.search.tweets(q=q, **kw) | def search(self, q=None, **kw) | Search twitter for ``q``, return `results`__ directly from twitter.
__ https://dev.twitter.com/rest/reference/get/search/tweets | 6.169933 | 5.488029 | 1.124253 |
return self.lookup(s['id_str'] for s in result['statuses'], **kw) | def lookup_search_result(self, result, **kw) | Perform :meth:`lookup` on return value of :meth:`search`. | 13.301462 | 11.154033 | 1.192525 |
result_id_pack = ','.join([str(_id) for _id in id_list])
if not result_id_pack:
return []
return self.twitter.statuses.lookup(_id=result_id_pack) | def lookup(self, id_list, **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 | 4.948424 | 5.067007 | 0.976597 |
with open(get_abspath(filepath)) as version_file:
return re.search(
r,
version_file.read()).group('version') | def get_version(filepath='src/birding/version.py') | Get version without import, which avoids dependency issues. | 5.63591 | 5.131152 | 1.098371 |
url = '{base_url}/search/{stream}'.format(**vars(self))
params = {
'q': q,
}
params.update(self.params)
params.update(kw)
response = self.session.get(url, params=params)
response.raise_for_status()
return response.json() | def search(self, q, **kw) | Search Gnip for given query, returning deserialized response. | 2.78158 | 2.5239 | 1.102096 |
if isinstance(result, dict):
# Result is a search result.
statuses = result['results']
else:
# Result is a lookup result.
statuses = result
status_str_list = []
for status in statuses:
status_str_list.append(textwrap.de... | def dump(result) | Dump result into a string, useful for debugging. | 4.741366 | 4.478897 | 1.058601 |
shelf_cls = import_name(config['shelf_class'], default_ns='birding.shelf')
init = {}
init.update(default_init)
init.update(config['shelf_init'])
shelf = shelf_cls(**init)
if hasattr(shelf, 'set_expiration') and 'shelf_expiration' in config:
shelf.set_expiration(config['shelf_expirat... | def shelf_from_config(config, **default_init) | Get a `Shelf` instance dynamically based on config.
`config` is a dictionary containing ``shelf_*`` keys as defined in
:mod:`birding.config`. | 3.350271 | 3.146267 | 1.06484 |
value, freshness = value
if not self.is_fresh(freshness):
raise KeyError('{} (stale)'.format(key))
return value | def unpack(self, key, value) | Unpack and return value only if it is fresh. | 7.96362 | 6.11206 | 1.302936 |
if self.expire_after is None:
return True
return self.freshness() - freshness <= self.expire_after | def is_fresh(self, freshness) | Return False if given freshness value has expired, else True. | 6.132793 | 5.677833 | 1.080129 |
return {
'non_field': form.non_field_errors(),
'field_specific': OrderedDict(
(field, form.errors[field.name])
for field in form
if field.name in form.errors
)
} | def get_form_errors(form) | Django form errors do not obey natural field order,
this template tag returns non-field and field-specific errors
:param form: the form instance | 3.560184 | 3.117862 | 1.141867 |
request = context.get('request')
return {
'alt_urls': make_alternate_language_urls(request),
'breadcrumbs': context.get('breadcrumbs'),
'breadcrumbs_back': context.get('breadcrumbs_back'),
} | def sub_nav(context) | 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 | 4.584277 | 3.039836 | 1.508067 |
try:
# get instance id and aws region
instance_details = requests.get('http://169.254.169.254/latest/dynamic/instance-identity/document',
timeout=5).json()
instance_id = instance_details['instanceId']
instance_region = instance_details['re... | def is_first_instance_aws() | Returns True if the current instance is the first instance in the ASG group,
sorted by instance_id. | 2.186452 | 2.168279 | 1.008381 |
current_pod_name = current_pod_name or os.environ.get('POD_NAME')
if not current_pod_name:
raise StackInterrogationException('Pod name not known')
namespace = 'money-to-prisoners-%s' % settings.ENVIRONMENT
try:
load_incluster_config()
except ConfigException as e:
raise ... | def is_first_instance_k8s(current_pod_name=None) | Returns True if the current pod is the first replica in Kubernetes cluster. | 2.732188 | 2.70373 | 1.010525 |
'''
This function will split arguments separated by spaces or commas
to be backwards compatible with the original ArcGet command line tool
'''
if not args:
return args
split = list()
for arg in args:
if ',' in arg:
split.extend([x for x in arg.split(',') if x])
... | def splitarg(args) | This function will split arguments separated by spaces or commas
to be backwards compatible with the original ArcGet command line tool | 5.557303 | 2.277102 | 2.440516 |
redirect_to = request.POST.get(
redirect_field_name,
request.GET.get(redirect_field_name, '')
)
def get_redirect_to():
# Ensure the user-originating redirection url is safe.
if not is_safe_url(url=redirect_to, host=request.get_host()):
return resolve_url(set... | 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. | 1.440671 | 1.464542 | 0.9837 |
auth_logout(request)
if next_page is not None:
next_page = resolve_url(next_page)
if (redirect_field_name in request.POST or
redirect_field_name in request.GET):
next_page = request.POST.get(redirect_field_name,
request.GET.get(redirect... | 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. | 1.554354 | 1.543926 | 1.006754 |
# Handle cache lookup explicitly in order to support keyword arguments.
cache_key = (filepath, default_loader, on_missing)
if CACHE.get(cache_key) is not None:
return CACHE.get(cache_key)
logger = logging.getLogger('birding')
if filepath is None:
filepath = BIRDING_CONF
if... | def get_config(filepath=None, default_loader=None, on_missing=None) | 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... | 4.050435 | 3.724216 | 1.087594 |
fd = StringIO()
fd.write(get_defaults_str(*a, **kw))
fd.seek(0)
return fd | 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`. | 3.69218 | 3.95931 | 0.932531 |
if raw is None:
raw = __doc__
return unicode(textwrap.dedent(raw.split(after)[-1]).strip()) | def get_defaults_str(raw=None, after='Defaults::') | Get the string YAML representation of configuration defaults. | 5.080249 | 4.687251 | 1.083844 |
result = {}
for key in upper:
if is_mapping(upper[key]):
lower_value = lower.get(key, {})
if not is_mapping(lower_value):
msg = 'Attempting to overlay a mapping on a non-mapping: {}'
raise ValueError(msg.format(key))
result[key] = ... | def overlay(upper, lower) | 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.
... | 2.095383 | 2.291396 | 0.914457 |
if '.' not in name:
if default_ns is None:
return importlib.import_module(name)
else:
name = default_ns + '.' + name
module_name, object_name = name.rsplit('.', 1)
module = importlib.import_module(module_name)
return getattr(module, object_name) | def import_name(name, default_ns=None) | 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... | 1.844564 | 2.534928 | 0.727659 |
config = get_config()['ResultTopicBolt']
kafka_class = import_name(config['kafka_class'])
return follow_topic(kafka_class, config['topic'], **config['kafka_init']) | def follow_topic_from_config() | Read kafka config, then dispatch to `follow_topic`. | 10.533475 | 9.034978 | 1.165855 |
while True:
try:
client = kafka_class(**kafka_init)
topic = client.topics[name]
consumer = topic.get_simple_consumer(reset_offset_on_start=True)
except Exception as e:
if not should_try_kafka_again(e):
raise
with flushi... | def follow_topic(kafka_class, name, retry_interval=1, **kafka_init) | Dump each message from kafka topic to stdio. | 3.491214 | 3.368863 | 1.036318 |
dump = Dump()
for line in fd:
if not line.strip():
continue
with flushing(sys.stdout, sys.stderr):
status = load(line)
if status:
dump(status) | def follow_fd(fd) | Dump each line of input to stdio. | 7.420163 | 6.160089 | 1.204555 |
msg = 'Unable to retrieve'
return isinstance(error, KafkaException) and str(error).startswith(msg) | def should_try_kafka_again(error) | Determine if the error means to retry or fail, True to retry. | 8.958789 | 7.388702 | 1.212498 |
data = line0.strip().split(b' ')
if len(data) <= 2:
return False
# check if data[2:] is float values
try:
map(float, data[2:])
except:
return False
return True | def check_valid(line0, line1) | Check if a file is valid Glove format.
Args:
line0 (bytes): First line of the file
line1 (bytes): Second line of the file
Returns:
boo: ``True`` if it is valid. ``False`` if it is invalid. | 4.430247 | 4.271106 | 1.03726 |
arr = None
for line in fin:
try:
token, v = _parse_line(line, dtype)
except (ValueError, IndexError):
raise ParseError(b'Parsing error in line: ' + line)
if token in vocab:
if arr is None:
arr = np.empty((len(vocab), len(v)), dtype... | def load_with_vocab(fin, vocab, dtype=np.float32) | Load word embedding file with predefined vocabulary
Args:
fin (File): File object to read. File should be open for reading ascii.
vocab (dict): Mapping from words (``bytes``) to vector indices
(``int``).
dtype (numpy.dtype): Element data type to use for the array.
Returns:
... | 2.893685 | 3.166676 | 0.913793 |
vocab = {}
arr = None
i = 0
for line in fin:
if max_vocab is not None and i >= max_vocab:
break
try:
token, v = _parse_line(line, dtype)
except (ValueError, IndexError):
raise ParseError(b'Parsing error in line: ' + line)
if token ... | def load(fin, dtype=np.float32, max_vocab=None) | Load word embedding file.
Args:
fin (File): File object to read. File should be open for reading ascii.
dtype (numpy.dtype): Element data type to use for the array.
max_vocab (int): Number of vocabulary to read.
Returns:
numpy.ndarray: Word embedding representation vectors
... | 2.761489 | 2.993118 | 0.922613 |
with mock.patch('setuptools.setup'):
from setup import install_requires, extras_require
requirements = install_requires.copy()
if extras:
requirements.extend(extras_require[extras])
return context.pip_command('install', *requirements) | def python_dependencies(context: Context, extras=None) | Updates python dependencies | 7.029847 | 6.142385 | 1.144482 |
if bump and version:
raise TaskError('You cannot bump and set a specific version')
if bump:
from mtp_common import VERSION
version = list(VERSION)
version[-1] += 1
else:
try:
version = list(map(int, version.split('.')))
assert len(version... | def set_version(context: Context, version=None, bump=False) | Updates the version of MTP-common | 2.616431 | 2.453088 | 1.066587 |
try:
from sphinx.application import Sphinx
except ImportError:
context.pip_command('install', 'Sphinx')
from sphinx.application import Sphinx
context.shell('cp', 'README.rst', 'docs/README.rst')
app = Sphinx('docs', 'docs', 'docs/build', 'docs/build/.doctrees', buildername=... | def docs(context: Context) | Generates static documentation | 4.772081 | 4.13504 | 1.154059 |
paths = ['docs/build', 'build', 'dist', '.eggs'] + glob.glob('*.egg-info')
context.shell('rm -rf %s' % paths_for_shell(paths))
context.shell('find %s -name "*.pyc" -or -name __pycache__ -delete' % context.app.django_app_name)
if delete_dependencies:
context.info('Cleaning local %s dependen... | def clean(context: Context, delete_dependencies: bool = False) | Deletes build outputs | 4.23226 | 3.948258 | 1.071931 |
data = api_client.authenticate(username, password)
if not data:
return
return User(
data.get('pk'), data.get('token'), data.get('user_data')
) | def authenticate(self, username=None, password=None) | Returns a valid `MojUser` if the authentication is successful
or None if the credentials were wrong. | 5.820187 | 5.606785 | 1.038061 |
if getattr(settings, 'NOMIS_API_CLIENT_TOKEN', ''):
return settings.NOMIS_API_CLIENT_TOKEN
global client_token
if not client_token or client_token['expires'] and client_token['expires'] - now() < datetime.timedelta(days=1):
session = None
try:
session = api_client.ge... | def get_client_token() | Requests and stores the NOMIS API client token from mtp-api | 3.338049 | 2.837691 | 1.176326 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.