code string | signature string | docstring string | loss_without_docstring float64 | loss_with_docstring float64 | factor float64 |
|---|---|---|---|---|---|
logger = logging.getLogger(name)
if name is None:
name = "root"
if handlers is None:
handlers = []
logger.setLevel(level)
if len(handlers) != 0:
logger.handlers = []
if "console" in handlers:
if not isinstance(handlers['console'], collections.Iterable):
handlers['console'] = {}
if "handler" in... | def get_logger(name=None, level=logging.NOTSET, handlers=None) | Create a Python logging Logger for the given name. A special case is
when the name is None, as this will represent the root Logger object.
When handlers are specified, the currently configured handlers for this name
are removed, and the specified handlers are set.
Parameters
----------
name: string
Name of th... | 1.638778 | 1.62416 | 1.009 |
for name, value in inspect.getmembers(self):
if inspect.isclass(value) and issubclass(value, self._Endpoint) and (value is not self._Endpoint):
endpoint_instance = value(self.requester)
setattr(self, endpoint_instance.endpoint_base, endpoint_instance)
... | def _attach_endpoints(self) | Dynamically attaches endpoint callables to this client | 2.60398 | 2.521221 | 1.032825 |
genes = {}
with open(path, "r") as handle:
header = handle.readline().strip().split("\t")
for line in handle:
line = line.rstrip().split("\t")
gene = line[0]
position = int(line[2]) - 1
consequence = line[3]
var_t... | def load_de_novos(path, exclude_indels=True) | load mutations into dict indexed by HGNC ID.
Args:
path: path to file containing de novo data. This should have five tab-
separated columns e.g.
hgnc chr pos consequence var_type
CTC1 17 8139190 missense_variant snv
CTC1 17 813919... | 3.238412 | 2.974659 | 1.088667 |
if not isinstance(thread, threading.Thread):
self.logger.error("Thread {0} is not actually a Thread!".format(name))
raise Exception("Thread {0} is not actually a Thread!".format(name))
if name in self.thread_list:
self.logger.error("Thread {0} already registered!".format(name))
raise Exception("Thre... | def registerThread(self, name, thread) | Register a new Thread , under the given descriptive name.
Trying to register multiple threads under the same name will raise an Exception.
Parameters
----------
name: string
Name to register the given thread under.
thread: threading.Thread, or a subclass
Thread object to register. | 1.820195 | 1.963993 | 0.926783 |
if not name in self.thread_list:
self.logger.error("Thread {0} is not registered!".format(name))
raise Exception("Thread {0} is not registered!".format(name))
return self.thread_list[name] | def getThread(self, name) | Retrieve the Thread registered under the given name.
If the given name does not exists in the Thread list, an Exception is raised.
Parameters
----------
name: string
Name of the Thread to retrieve | 2.24176 | 2.505756 | 0.894644 |
if not name in self.thread_list:
self.logger.error("Thread {0} is not registered!".format(name))
raise Exception("Thread {0} is not registered!".format(name))
del self.thread_list[name]
self.logger.debug("Unregistered thread {0}".format(name)) | def unregisterThread(self, name) | Unregister the Thread registered under the given name.
Make sure that the given Thread is properly stopped, or that a reference is
kept in another place. Once unregistered, this class will not keep any
other references to the Thread.
Parameters
----------
name: string
Name of the Thread to unregister | 1.974318 | 2.395821 | 0.824068 |
self.logger.info("Starting all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Starting {0}".format(thr.name))
thr.start()
self.logger.info("Started all threads") | def startAll(self) | Start all registered Threads. | 2.80163 | 2.613999 | 1.071779 |
self.logger.info("Stopping all threads...")
for thread in self.getThreads():
thr = self.getThread(thread)
self.logger.debug("Stopping {0}".format(thr.name))
thr.stop = True
thr.join()
self.unregisterThread(thread)
self.logger.info("Stopped all threads")
if stop:
self.logger.fatal("Comitt... | def stopAll(self, stop=False) | Stop all registered Threads. This is method assumes that the Thread is using
and internal variable called stop to control its main loop. Stopping a Thread
is achieved as follows:
1. The Thread is retrieved.
2. $thread.stop is set to False.
3. The Thread is joined, and will wait until the Thread exits.
4. T... | 3.259887 | 3.122602 | 1.043965 |
if hasattr(request, 'usersettings'):
usersettings = request.usersettings
else:
from .shortcuts import get_current_usersettings
usersettings = get_current_usersettings()
return {
'usersettings': usersettings
} | def usersettings(request) | Returns the current ``UserSettings`` based on
the SITE_ID in the project's settings as context variables
If there is no 'usersettings' attribute in the request, fetches the
current UserSettings (from usersettings.shortcuts.get_current_usersettings). | 2.955221 | 2.272909 | 1.300193 |
self.attempt = 0
headers = {"content-type": "application/json"}
ext = "/info/rest"
r = self.ensembl_request(ext, headers)
response = json.loads(r)
self.cache.set_ensembl_api_version(response["release"]) | def check_ensembl_api_version(self) | check the ensembl api version matches a currently working version
This function is included so when the api version changes, we notice the
change, and we can manually check the responses for the new version. | 6.40971 | 5.697567 | 1.124991 |
data = self.cache.get_cached_data(url)
if data is not None:
return data, 200, headers
self.rate_limit_ensembl_requests()
req = request.Request(url, headers=headers)
try:
handler = request.urlopen(req)
except HTTP... | def open_url(self, url, headers) | open url with python libraries | 4.161695 | 4.186486 | 0.994078 |
self.attempt += 1
if self.attempt > 5:
raise ValueError("too many attempts, figure out why its failing")
response, status, requested_headers = self.open_url(self.server + ext, headers=headers)
# we might end up passing too many simultaneous... | def ensembl_request(self, ext, headers) | obtain sequence via the ensembl REST API | 3.729962 | 3.714073 | 1.004278 |
headers = {"content-type": "application/json"}
# http://grch37.rest.ensembl.org/xrefs/symbol/homo_sapiens/KMT2A?content-type=application/json
self.attempt = 0
ext = "/xrefs/symbol/homo_sapiens/{}".format(hgnc_symbol)
r = self.ensembl_request(ex... | def get_genes_for_hgnc_id(self, hgnc_symbol) | obtain the ensembl gene IDs that correspond to a HGNC symbol | 3.254666 | 3.141284 | 1.036094 |
ensembl_server = self.server
gene_names_server = "http://rest.genenames.org"
self.server = gene_names_server
headers = {"accept": "application/json", "content-type": "application/json"}
ext = "/fetch/symbol/{}".format(hgnc_symbol)
try:
... | def get_previous_symbol(self, hgnc_symbol) | sometimes we get HGNC symbols that do not match the ensembl rest version
that we are currently using. We can look for earlier HGNC symbols for
the gene using the service at rest.genenames.org
Args:
hgnc_symbol: HGNC symbol for the gene (eg "MLL2")
Returns:
... | 3.858514 | 3.616528 | 1.066911 |
chroms = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", \
"12", "13", "14", "15", "16", "17", "18", "19", "20", "21", "22", \
"X", "Y"}
headers = {"content-type": "application/json"}
transcript_ids = []
for gene_id... | def get_transcript_ids_for_ensembl_gene_ids(self, gene_ids, hgnc_symbols) | fetch the ensembl transcript IDs for a given ensembl gene ID.
Args:
gene_ids: list of Ensembl gene IDs for the gene
hgnc_symbols: list of possible HGNC symbols for gene | 3.416821 | 3.444195 | 0.992052 |
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/sequence/id/{0}?type=genomic;expand_3prime={1};expand_5prime={1}".format(transcript_id, expand)
r = self.ensembl_request(ext, headers)
gene = json.loads(r)
... | def get_genomic_seq_for_transcript(self, transcript_id, expand) | obtain the sequence for a transcript from ensembl | 3.848571 | 3.564613 | 1.07966 |
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=cds".format(transcript_id)
return self.ensembl_request(ext, headers) | def get_cds_seq_for_transcript(self, transcript_id) | obtain the sequence for a transcript from ensembl | 9.103439 | 7.506807 | 1.212691 |
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/id/{}?type=protein".format(transcript_id)
return self.ensembl_request(ext, headers) | def get_protein_seq_for_transcript(self, transcript_id) | obtain the sequence for a transcript from ensembl | 8.577107 | 6.999487 | 1.225391 |
headers = {"content-type": "text/plain"}
self.attempt = 0
ext = "/sequence/region/human/{}:{}..{}:1".format(chrom, start_pos, end_pos)
return self.ensembl_request(ext, headers) | def get_genomic_seq_for_region(self, chrom, start_pos, end_pos) | obtain the sequence for a genomic region | 7.63042 | 7.555872 | 1.009866 |
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=gene".format(transcript_id)
r = self.ensembl_request(ext, headers)
for gene in json.loads(r):
if gene["external_name"] == hgnc_id:
... | def get_chrom_for_transcript(self, transcript_id, hgnc_id) | obtain the sequence for a transcript from ensembl | 5.420102 | 4.789021 | 1.131777 |
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=exon".format(transcript_id)
r = self.ensembl_request(ext, headers)
exon_ranges = []
for exon in json.loads(r):
if exon["Parent"] !... | def get_exon_ranges_for_transcript(self, transcript_id) | obtain the sequence for a transcript from ensembl | 3.58287 | 3.309523 | 1.082594 |
headers = {"content-type": "application/json"}
self.attempt = 0
ext = "/overlap/id/{}?feature=cds".format(transcript_id)
r = self.ensembl_request(ext, headers)
cds_ranges = []
for cds_range in json.loads(r):
if cds_range["Pa... | def get_cds_ranges_for_transcript(self, transcript_id) | obtain the sequence for a transcript from ensembl | 3.773268 | 3.475905 | 1.08555 |
current_time = time.time()
diff_time = current_time - self.prior_time
# sleep until the current rate limit period is finished
if diff_time < self.rate_limit:
time.sleep(self.rate_limit - diff_time)
# set the access time to now, for ... | def rate_limit_ensembl_requests(self) | limit ensembl requests to one per 0.067 s | 3.904452 | 3.729769 | 1.046835 |
global _py_funcs
_lazy_init()
# Save references to the tool's load() and render() functions
load_key = nbtool.origin + '|' + nbtool.id + '|load'
render_key = nbtool.origin + '|' + nbtool.id + '|render'
_py_funcs[load_key] = nbtool.load
_py_funcs[render_key] = nbtool.render
# Clean... | def register(nbtool) | Register the provided NBTool object | 3.074771 | 3.061574 | 1.004311 |
return SimpleCliTool()._call_cli(command, cwd, universal_newlines, redirect_stderr) | def call_simple_cli(command, cwd=None, universal_newlines=False, redirect_stderr=False) | Simple wrapper around SimpleCliTool. Simple. | 5.719099 | 3.654746 | 1.564842 |
command = str(command.encode("utf-8").decode("ascii", "ignore"))
env = os.environ.copy()
env.update(self.envvars)
stderr = STDOUT if redirect_stderr else PIPE
proc = Popen(shlex.split(command), stdout=PIPE, stderr=stderr, cwd=cwd, universal_newlines=universal_newlines, env=env)
stdout, stderr = proc.comm... | def _call_cli(self, command, cwd=None, universal_newlines=False, redirect_stderr=False) | Executes the given command, internally using Popen. The output of
stdout and stderr are returned as a tuple. The returned tuple looks
like: (stdout, stderr, returncode)
Parameters
----------
command: string
The command to execute.
cwd: string
Change the working directory of the program to the specifi... | 2.308086 | 2.56936 | 0.898312 |
payload = [{'statement': s, 'parameters': p, 'resultDataContents':['rest']} for (s, p) in statements]
http_response = self._http_req("POST", self._tx, {'statements': payload})
if self._tx == TX_ENDPOINT:
self._tx = http_response.getheader('Location')
response = sel... | def _execute(self, cursor, statements) | Executes a list of statements, returning an iterator of results sets. Each
statement should be a tuple of (statement, params). | 7.381152 | 6.847244 | 1.077974 |
data = msg['content']['data']
# If the message is a call invoke, run the function and send
# the results.
if 'callback' in data:
guid = data['callback']
callback = callback_registry[guid]
args = data['arguments']
args = [self.dese... | def _on_msg(self, msg) | Handle messages from the front-end | 4.371652 | 4.346592 | 1.005765 |
if hasattr(obj, '_jsid'):
return {'immutable': False, 'value': obj._jsid}
else:
obj_json = {'immutable': True}
try:
json.dumps(obj)
obj_json['value'] = obj
except:
pass
if callable(obj):
... | def serialize(self, obj) | Serialize an object for sending to the front-end. | 3.708193 | 3.68487 | 1.006329 |
if obj['immutable']:
return obj['value']
else:
guid = obj['value']
if not guid in object_registry:
instance = JSObject(self, guid)
object_registry[guid] = instance
return object_registry[guid] | def deserialize(self, obj) | Deserialize an object from the front-end. | 4.80866 | 4.8489 | 0.991701 |
msg = {
'index': self._calls,
'method': method,
}
msg.update(parameters)
promise = SimplePromise()
self._callbacks[self._calls] = promise
self._calls += 1
self._comm.send(msg)
return promise | def _send(self, method, **parameters) | Sends a message to the front-end and returns a promise. | 4.344996 | 3.545142 | 1.22562 |
if not properties:
properties = {}
properties['correlation_id'] = original_headers.correlation_id
publish_message(channel, '', original_headers.reply_to, message, properties) | def rpc_reply(channel, original_headers, message, properties=None) | Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
channel: object
Properly initialized AMQP channel to use.
original_headers: dict
The headers of the originating message that caused this reply.
message: string
Message to reply ... | 3.233413 | 3.712463 | 0.870962 |
if not hasattr(self, "queue_name") and consumer_callback:
raise ValueError("Trying to set a callback, while no general purpose queue was declared.")
self.rpc_consumer_tag = self.channel.basic_consume(consumer_callback=self._rpc_response_callback, queue=self.rpc_queue_name, exclusive=False)
if consumer_cal... | def consume(self, consumer_callback=None, exclusive=False) | Initialize consuming of messages from an AMQP RPC queue. Messages will be consumed after start_consuming() is called.
An internal callback will be used to handle incoming RPC responses. Only responses that have been registered with register_response()
will be kept internally, all other responses will be dropped si... | 5.588056 | 4.00625 | 1.394834 |
self.logger.debug("Received RPC response with correlation_id: {0}".format(header_frame.correlation_id))
if header_frame.correlation_id in self.responses:
self.responses[header_frame.correlation_id] = {
"method_frame": method_frame,
"header_frame": header_frame,
"body": body
}
channel.basic_ac... | def _rpc_response_callback(self, channel, method_frame, header_frame, body) | Internal callback used by consume()
Parameters
----------
channel: object
Channel from which the callback originated
method_frame: dict
Information about the message
header_frame: dict
Headers of the message
body: string
Body of the message | 1.954571 | 2.130934 | 0.917236 |
if not correlation_id:
correlation_id = str(uuid.uuid1())
if correlation_id in self.responses:
raise KeyError("Correlation_id {0} was already registered, and therefor not unique.".format(correlation_id))
self.responses[correlation_id] = None
return correlation_id | def register_response(self, correlation_id=None) | Register the receiving of a RPC response. Will return the given correlation_id after registering, or if correlation_id is None, will
generate a correlation_id and return it after registering. If the given correlation_id has already been used, an KeyError will be
raised.
UUID version 1 will be used when generatin... | 2.879709 | 2.962435 | 0.972075 |
if correlation_id not in self.responses:
raise KeyError("Given RPC response correlation_id was not registered.")
if not self.responses[correlation_id]:
return None
response = self.responses[correlation_id]
del(self.responses[correlation_id])
return response | def retrieve_response(self, correlation_id) | Retrieve a registered RPC response. If the correlation_id was not registered, an KeyError will the raised. If not value has been
received yet, None will be returned. After retrieving the response, the value will be unset internally.
The returned value will include the entire RabbitMQ message, consisting of a dict ... | 3.127988 | 2.539212 | 1.231874 |
if not properties:
properties = {}
properties['correlation_id'] = self.register_response(correlation_id)
properties['reply_to'] = self.rpc_queue_name
if not self.publish(exchange, routing_key, message, properties, mandatory=True):
self.retrieve_response(properties['correlation_id'])
raise MessageNo... | def request_response(self, exchange, routing_key, message, properties=None, correlation_id=None, timeout=6) | This function wraps publish, and sets the properties necessary to allow end-to-end communication using the Rpc paradigm.
This function assumes that the named exchange and routing_key combination will result in a AMQP queue to pickup the request, and
reply using another AMQP message. To achieve this, the following ... | 3.349914 | 3.076238 | 1.088964 |
return publish_message(self.channel, exchange, routing_key, message, properties, mandatory) | def publish(self, exchange, routing_key, message, properties=None, mandatory=False) | Publish a message to an AMQP exchange.
Parameters
----------
exchange: string
Exchange to publish to.
routing_key: string
Routing key to use for this message.
message: string
Message to publish.
properties: dict
Properties to set on message. This parameter is optional, but if set, at least the ... | 3.44516 | 5.573131 | 0.618173 |
rpc_reply(self.channel, original_headers, message, properties) | def reply(self, original_headers, message, properties=None) | Reply to a RPC request. This function will use the default exchange, to directly contact the reply_to queue.
Parameters
----------
original_headers: dict
The headers of the originating message that caused this reply.
message: string
Message to reply with
properties: dict
Properties to set on message... | 6.864495 | 11.468534 | 0.59855 |
instance = kwargs['instance']
try:
del USERSETTINGS_CACHE[instance.site.pk]
except KeyError:
pass | def clear_usersettings_cache(sender, **kwargs) | Clears the cache (if primed) each time a ``UserSettings`` is saved or deleted | 4.524736 | 4.415671 | 1.0247 |
from django.conf import settings
try:
site_id = settings.SITE_ID
except AttributeError:
raise ImproperlyConfigured(
'You\'re using the Django "sites framework" without having '
'set the SITE_ID setting. Create a site in your databa... | def get_current(self) | Returns the current ``UserSettings`` based on the SITE_ID in the
project's settings. The ``UserSettings`` object is cached the first
time it's retrieved from the database. | 3.120749 | 2.510704 | 1.242978 |
if base_url[-1] != "/":
base_url += "/"
if path[0] == "/":
path = path[1:]
return urljoin(base_url, path) | def append_url(base_url, path) | Append path to base_url in a sensible way. | 1.976295 | 1.821047 | 1.085252 |
with open(path) as handle:
lines = [ x.strip().split('\t') for x in handle ]
nonsense = sum([ 10**(float(x[4])) for x in lines[1:] if x[4] != 'NA' ])
length = sum([ int(x[2]) for x in lines[1:] if x[2] != 'NA' ])
# add the frameshift rates to each line in turn, while writing ... | def include_frameshift_rates(path) | add per-gene frameshift mutation rates to the output file
We make a crude estimate of the frameshift mutation rate by assessing the
total frameshift burden (across all genes in a dataset) as 1.25 times the
nonsense burden. Then apportion the frameshift burden proportional to each
genes CDS length.
... | 2.968302 | 2.79643 | 1.061461 |
return ''.join(
random.choice(string.ascii_uppercase + string.digits)
for x in range(10)) | def _randomString() | Random string for message signing | 3.843303 | 3.280577 | 1.171532 |
txid = _randomString()
sock = session.socket
sock.send(bytearray('d1:q6:cookie4:txid10:%se' % txid, 'utf-8'))
msg = _getMessage(session, txid)
cookie = msg['cookie']
txid = _randomString()
tohash = (password + cookie).encode('utf-8')
req = {
'q': funcName,
'hash': h... | def _callFunc(session, funcName, password, args) | Call custom cjdns admin function | 4.150166 | 4.091854 | 1.014251 |
timeOfLastSend = time.time()
timeOfLastRecv = time.time()
try:
while True:
if timeOfLastSend + KEEPALIVE_INTERVAL_SECONDS < time.time():
if timeOfLastRecv + 10 < time.time():
raise exceptions.PingTimeout()
session.socket.send(
... | def _receiverThread(session) | Receiving messages from cjdns admin server | 4.886305 | 4.860126 | 1.005386 |
while True:
if txid in session.messages:
msg = session.messages[txid]
del session.messages[txid]
return msg
else:
try:
# apparently any timeout at all allows the thread to be
# stopped but none make it unstoppable ... | def _getMessage(session, txid) | Getting message associated with txid | 4.31647 | 4.247537 | 1.016229 |
def functionHandler(self, *args, **kwargs):
call_args = {}
for (key, value) in oargList.items():
call_args[key] = value
for i, arg in enumerate(argList):
if i < len(args):
call_args[arg] = args[i]
for (key, value) in kwargs.items():
... | def _functionFabric(func_name, argList, oargList, password) | Function fabric for Session class | 2.614581 | 2.625379 | 0.995887 |
sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
sock.connect((ipAddr, port))
sock.settimeout(2)
# Make sure it pongs.
sock.send(b'd1:q4:pinge')
data = sock.recv(BUFFER_SIZE)
if not data.endswith(b'1:q4:ponge'):
raise exceptions.NotACjdnsAdminSocket("Looks like %s:%d is... | def connect(ipAddr, port, password) | Connect to cjdns admin with this attributes | 4.896825 | 4.781854 | 1.024043 |
if path is None:
path = os.path.expanduser('~/.cjdnsadmin')
try:
with open(path, 'r') as adminInfo:
data = json.load(adminInfo)
except IOError:
logger.info('~/.cjdnsadmin not found; using default credentials', file=sys.stderr)
data = {
'password'... | def connectWithAdminInfo(path=None) | Connect to cjdns admin with data from user file | 3.158512 | 2.894184 | 1.091331 |
if properties is None:
properties = {}
if properties and "routing_key" in properties:
routing_key = properties["routing_key"]
del(properties["routing_key"])
if properties and "exchange" in properties:
exchange = properties["exchange"]
del(properties["exchange"])
if not routing_key:
raise ValueError("... | def publish_message(channel, exchange, routing_key, message, properties=None, mandatory=False) | Publish a message to an AMQP exchange.
Parameters
----------
channel: object
Properly initialized AMQP channel to use.
exchange: string
Exchange to publish to.
routing_key: string
Routing key to use for this message.
message: string
Message to publish.
properties: dict
Properties to set on message. Th... | 2.135435 | 2.300687 | 0.928173 |
return publish_message(self.channel, self.exchange_name, self.default_routing_key, message, properties, mandatory) | def publish(self, message, properties=None, mandatory=False) | Publish a message to an AMQP exchange.
Parameters
----------
message: string
Message to publish.
properties: dict
Properties to set on message. This parameter is optional, but if set, at least the following options must be set:
content_type: string - what content_type to specify, default is 'text/pla... | 4.209833 | 5.550329 | 0.758483 |
with open(path, 'rt') as f:
lines = [ x.split('\t')[:2] for x in f if not x.startswith('hgnc') ]
transcripts = {}
for symbol, tx in lines:
if symbol not in transcripts:
transcripts[symbol] = []
transcripts[symbol].append(tx)
return transcripts | def load_genes(path) | load a file listing gene and transcript IDs
Args:
path: path to file containing gene IDs and transcript IDs e.g.
gene_1 transcript_1.1 length_1 denovo_count
gene_2 transcript_2.1 length_3 denovo_count
Returns:
dict of transcripts eg {'CTC1': ["... | 2.842956 | 2.715968 | 1.046756 |
rates = {'missense': 0, 'nonsense': 0, 'splice_lof': 0,
'splice_region': 0, 'synonymous': 0}
combined = None
for tx_id in transcripts:
try:
tx = construct_gene_object(ensembl, tx_id)
except ValueError:
continue
if len(tx.get_cds... | def get_mutation_rates(transcripts, mut_dict, ensembl) | determines mutation rates per functional category for transcripts
Args:
transcripts: list of transcript IDs for a gene
mut_dict: dictionary of local sequence context mutation rates
ensembl: EnsemblRequest object, to retrieve information from Ensembl.
Returns:
tuple of (... | 4.643095 | 4.656102 | 0.997206 |
parser = argparse.ArgumentParser(description='denovonear cli interface')
############################################################################
# CLI options in common
parent = argparse.ArgumentParser(add_help=False)
parent.add_argument("--out", help="output filename")
paren... | def get_options() | get the command line switches | 3.587973 | 3.587977 | 0.999999 |
if key[-2:] != '.k':
raise ValueError('Key does not end with .k')
key_bytes = base32.decode(key[:-2])
hash_one = sha512(key_bytes).digest()
hash_two = sha512(hash_one).hexdigest()
return ':'.join([hash_two[i:i+4] for i in range(0, 32, 4)]) | def to_ipv6(key) | Get IPv6 address from a public key. | 3.03869 | 2.791552 | 1.088531 |
matches = []
for root, dirnames, filenames in os.walk(self.path):
if not self.recursive:
while len(dirnames) > 0:
dirnames.pop()
for include in self.include:
for filename in fnmatch.filter(filenames, include):
matches.append(os.path.join(root, filename))
return matches | def glob(self) | Traverse directory, and return all absolute filenames of files that
match the globbing patterns. | 2.096864 | 2.13136 | 0.983815 |
if not self.has_add_permission(request):
raise PermissionDenied
extra_qs = ''
if request.META['QUERY_STRING']:
extra_qs = '&' + request.META['QUERY_STRING']
site_choices = self.get_site_choices()
if len(site_choices) == 1:
return Ht... | def select_site_view(self, request, form_url='') | Display a choice form to select which site to add settings. | 2.141474 | 2.106565 | 1.016572 |
app_label = self.opts.app_label
context.update({
'has_change_permission': self.has_change_permission(request),
'form_url': mark_safe(form_url),
'opts': self.opts,
'add': True,
'save_on_top': self.save_on_top,
})
return... | def render_select_site_form(self, request, context, form_url='') | Render the site choice form. | 2.139447 | 2.133513 | 1.002782 |
consumer_key = xargs.get('consumer_key') or required_from_env('READABILITY_CONSUMER_KEY')
consumer_secret = xargs.get('consumer_secret') or required_from_env('READABILITY_CONSUMER_SECRET')
username = xargs.get('username') or required_from_env('READABILITY_USERNAME')
password = xargs.get('password')... | def xauth(base_url_template=DEFAULT_READER_URL_TEMPLATE, **xargs) | Returns an OAuth token tuple that can be used with clients.ReaderClient.
:param base_url_template: Template for generating Readability API urls.
:param consumer_key: Readability consumer key, otherwise read from READABILITY_CONSUMER_KEY.
:param consumer_secret: Readability consumer secret, otherwise read ... | 2.725583 | 2.778486 | 0.98096 |
transformed = []
for key in ['missense', 'nonsense', 'splice_lof', 'splice_region',
'synonymous']:
try:
value = math.log10(rates[key])
except ValueError:
value = "NA"
except KeyError:
continue
transformed... | def log_transform(rates) | log transform a numeric value, unless it is zero, or negative | 4.485559 | 4.934174 | 0.90908 |
try:
from django.apps import apps
get_model = apps.get_model
except ImportError:
from django.db.models.loading import get_model
try:
app_label, model_name = settings.USERSETTINGS_MODEL.split('.')
except ValueError:
raise ImproperlyConfigured('USERSETTINGS_MO... | def get_usersettings_model() | Returns the ``UserSettings`` model that is active in this project. | 1.617863 | 1.650771 | 0.980065 |
USERSETTINGS_MODEL = get_usersettings_model()
try:
current_usersettings = USERSETTINGS_MODEL.objects.get_current()
except USERSETTINGS_MODEL.DoesNotExist:
current_usersettings = USERSETTINGS_MODEL.get_default()
return current_usersettings | def get_current_usersettings() | Returns the current ``UserSettings`` based on
the SITE_ID in the project's settings | 2.344309 | 2.311743 | 1.014087 |
if len(de_novos) < 2:
return (float('nan'), float('nan'))
rename = {"lof": "loss_of_function"}
if consequence in rename:
consequence = rename[consequence]
weights = rates[consequence]
cds_positions = [ transcript.get_coding_distance(x)['pos'] for x in de_novo... | def get_p_value(transcript, rates, iterations, consequence, de_novos) | find the probability of getting de novos with a mean conservation
The probability is the number of simulations where the mean conservation
between simulated de novos is less than the observed conservation.
Args:
transcript: Transcript object for the current gene.
rates: SiteRates o... | 5.765565 | 4.96668 | 1.160849 |
parser = argparse.ArgumentParser(description="Script to batch process de"
"novo clustering.")
parser.add_argument("--in", dest="input", required=True, help="Path to"
"file listing known mutations in genes. See example file in data folder"
"for format.")
parser.add_argument(... | def get_options() | get the command line options | 5.514137 | 5.354874 | 1.029742 |
counts = {}
for x in lines:
x = x.split("\t")
gene = x[0]
consequence = x[3]
if gene not in counts:
counts[gene] = 0
if consequence != "missense_variant":
continue
counts[gene] += 1
return count... | def count_missense_per_gene(lines) | count the number of missense variants in each gene. | 2.31607 | 2.345882 | 0.987292 |
# open the de novos, drop the header line, then sort them (which will be by
# HGNC symbol, as the first element of each line)
with open(denovo_path, "r") as handle:
lines = handle.readlines()
header = lines.pop(0)
basename = os.path.basename(denovo_path)
# only in... | def split_denovos(denovo_path, temp_dir) | split de novos from an input file into files, one for each gene | 4.012193 | 3.887572 | 1.032056 |
# set up a random string to associate with the run
hash_string = "%8x" % random.getrandbits(32)
hash_string = hash_string.strip()
# done't allow the random strings to be equivalent to a number, since
# the LSF cluster interprets those differently from letter-containing
# strings
... | def get_random_string() | make a random string, which we can use for bsub job IDs, so that
different jobs do not have the same job IDs. | 6.633485 | 6.017078 | 1.102443 |
if job_id is None:
job_id = get_random_string()
job = "-J \"{0}\"".format(job_id)
mem = ""
if memory is not None:
mem = "-R 'select[mem>{0}] rusage[mem={0}]' -M {0}".format(memory)
requeue = ""
if requeue_code is not None:
requeue = "-Q 'EXCLUDE({... | def submit_bsub_job(command, job_id=None, dependent_id=None, memory=None, requeue_code=None, logfile=None) | construct a bsub job submission command
Args:
command: list of strings that forma unix command
job_id: string for job ID for submission
dependent_id: job ID, or list of job IDs which the current command needs
to have finished before the current command will start. Note that
... | 2.863449 | 2.830795 | 1.011535 |
temp_dir = tempfile.mkdtemp(dir=temp_dir)
count = split_denovos(de_novo_path, temp_dir)
# set up run parameters
job_name = "denovonear"
job_id = "{0}[1-{1}]%20".format(job_name, count)
basename = os.path.basename(de_novo_path)
infile = os.path.join(temp_dir, "tmp.\$LSB_JO... | def batch_process(de_novo_path, temp_dir, output_path) | sets up a lsf job array | 3.915932 | 3.866364 | 1.01282 |
if path is None:
path = resource_filename(__name__, "data/rates.txt")
rates = []
with open(path) as handle:
for line in handle:
if line.startswith("from"): # ignore the header line
continue
line = [ x.encode('utf8') for x in... | def load_mutation_rates(path=None) | load sequence context-based mutation rates
Args:
path: path to table of sequence context-based mutation rates. If None,
this defaults to per-trinucleotide rates provided by Kaitlin Samocha
(Broad Institute).
Returns:
list of [initial, changed, rate] lists e.g. [... | 3.425332 | 3.457847 | 0.990597 |
response = self.get("/user", auth=auth)
return GogsUser.from_json(response.json()) | def authenticated_user(self, auth) | Returns the user authenticated by ``auth``
:param auth.Authentication auth: authentication for user to retrieve
:return: user authenticated by the provided authentication
:rtype: GogsUser
:raises NetworkFailure: if there is an error communicating with the server
:raises ApiFail... | 7.122806 | 4.241537 | 1.679298 |
if username is None:
username = self.authenticated_user(auth).username
response = self.get("/users/{u}/tokens".format(u=username), auth=auth)
return [Token.from_json(o) for o in response.json()] | def get_tokens(self, auth, username=None) | Returns the tokens owned by the specified user. If no user is specified,
uses the user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
Must be a username-password authentication,
... | 3.223676 | 3.533835 | 0.912232 |
if username is None:
username = self.authenticated_user(auth).username
data = {"name": name}
response = self.post("/users/{u}/tokens".format(u=username), auth=auth, data=data)
return Token.from_json(response.json()) | def create_token(self, auth, name, username=None) | Creates a new token with the specified name for the specified user.
If no user is specified, uses user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
Must be a username-password authentication,
... | 3.067261 | 3.290305 | 0.932212 |
if username is None:
username = self.authenticated_user(auth).username
tokens = [token for token in self.get_tokens(auth, username) if token.name == name]
if len(tokens) > 0:
return tokens[0]
return self.create_token(auth, name, username) | def ensure_token(self, auth, name, username=None) | Ensures the existence of a token with the specified name for the
specified user. Creates a new token if none exists. If no user is
specified, uses user authenticated by ``auth``.
:param auth.Authentication auth: authentication for user to retrieve.
Must ... | 2.399461 | 2.543602 | 0.943332 |
gitignores = None if gitignore_templates is None \
else ",".join(gitignore_templates)
data = {
"name": name,
"description": description,
"private": private,
"auto_init": auto_init,
"gitignores": gitignores,
"lic... | def create_repo(self, auth, name, description=None, private=False, auto_init=False,
gitignore_templates=None, license_template=None, readme_template=None,
organization=None) | Creates a new repository, and returns the created repository.
:param auth.Authentication auth: authentication object
:param str name: name of the repository to create
:param str description: description of the repository to create
:param bool private: whether the create repository shoul... | 1.913881 | 1.957171 | 0.977881 |
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
return self._get(path, auth=auth).ok | def repo_exists(self, auth, username, repo_name) | Returns whether a repository with name ``repo_name`` owned by the user with username ``username`` exists.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:param str repo_name: name of repository
:return: whether the repository ... | 3.581136 | 4.733185 | 0.756602 |
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
response = self.get(path, auth=auth)
return GogsRepo.from_json(response.json()) | def get_repo(self, auth, username, repo_name) | Returns a the 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 representation of the re... | 2.940189 | 3.03372 | 0.969169 |
path = "/users/{u}/repos".format(u=username)
response = self.get(path, auth=auth)
return [GogsRepo.from_json(repo_json) for repo_json in response.json()] | def get_user_repos(self, auth, username) | Returns the repositories owned by
the user with username ``username``.
:param auth.Authentication auth: authentication object
:param str username: username of owner of repository
:return: a list of repositories
:rtype: List[GogsRepo]
:raises NetworkFailure: if there is ... | 3.131602 | 2.959284 | 1.058229 |
path = "/repos/{u}/{r}/branches/{b}".format(u=username, r=repo_name, b=branch_name)
response = self.get(path, auth=auth)
return GogsBranch.from_json(response.json()) | def get_branch(self, auth, username, repo_name, branch_name) | Returns the branch with name ``branch_name`` in the 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 containing the branch
:param str repo_name: n... | 2.619551 | 2.406691 | 1.088445 |
path = "/repos/{u}/{r}/branches".format(u=username, r=repo_name)
response = self.get(path, auth=auth)
return [GogsBranch.from_json(branch_json) for branch_json in response.json()] | def get_branches(self, auth, username, repo_name) | Returns the branches in the 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 containing the branch
:param str repo_name: name of the repository wi... | 2.90589 | 2.674187 | 1.086644 |
path = "/repos/{u}/{r}".format(u=username, r=repo_name)
self.delete(path, auth=auth) | def delete_repo(self, auth, username, repo_name) | Deletes the 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 to delete
:param str repo_name: name of repository to delete
:raises NetworkFailure: i... | 3.261651 | 4.723888 | 0.690459 |
# "auth_username": auth_username,
# "auth_password": auth_password,
data = {
"clone_addr": clone_addr,
"uid": uid,
"repo_name": repo_name,
"mirror": mirror,
"private": private,
"description": description,
}... | def migrate_repo(self, auth, clone_addr,
uid, repo_name, auth_username=None, auth_password=None,
mirror=False, private=False, description=None) | Migrate a repository from another Git hosting source for the authenticated user.
:param auth.Authentication auth: authentication object
:param str clone_addr: Remote Git address (HTTP/HTTPS URL or local path)
:param int uid: user ID of repository owner
:param str repo_name: Repository n... | 2.118302 | 2.067809 | 1.024418 |
# Since the source_id parameter was not well-documented at the time this method was
# written, force the default value
data = {
"login_name": login_name,
"username": username,
"email": email,
"password": password,
"send_notify"... | def create_user(self, auth, login_name, username, email, password, send_notify=False) | Creates a new user, and returns the created user.
:param auth.Authentication auth: authentication object, must be admin-level
:param str login_name: login name for created user
:param str username: username for created user
:param str email: email address for created user
:param... | 3.923717 | 3.826427 | 1.025426 |
path = "/users/{}".format(username)
return self._get(path).ok | def user_exists(self, username) | Returns whether a user with username ``username`` exists.
:param str username: username of user
:return: whether a user with the specified username exists
:rtype: bool
:raises NetworkFailure: if there is an error communicating with the server
:return: | 7.816015 | 10.48909 | 0.745157 |
params = {"q": username_keyword, "limit": limit}
response = self.get("/users/search", params=params)
return [GogsUser.from_json(user_json) for user_json in response.json()["data"]] | def search_users(self, username_keyword, limit=10) | Searches for users whose username matches ``username_keyword``, and returns
a list of matched users.
:param str username_keyword: keyword to search with
:param int limit: maximum number of returned users
:return: a list of matched users
:rtype: List[GogsUser]
:raises Net... | 3.235893 | 2.903851 | 1.114345 |
path = "/users/{}".format(username)
response = self.get(path, auth=auth)
return GogsUser.from_json(response.json()) | def get_user(self, auth, username) | Returns a representing the user with username ``username``.
:param auth.Authentication auth: authentication object, can be ``None``
:param str username: username of user to get
:return: the retrieved user
:rtype: GogsUser
:raises NetworkFailure: if there is an error communicatin... | 3.957209 | 3.462529 | 1.142867 |
path = "/admin/users/{}".format(username)
response = self.patch(path, auth=auth, data=update.as_dict())
return GogsUser.from_json(response.json()) | def update_user(self, auth, username, update) | Updates the user with username ``username`` according to ``update``.
:param auth.Authentication auth: authentication object, must be admin-level
:param str username: username of user to update
:param GogsUserUpdate update: a ``GogsUserUpdate`` object describing the requested update
:ret... | 4.346934 | 3.521657 | 1.234343 |
path = "/admin/users/{}".format(username)
self.delete(path, auth=auth) | def delete_user(self, auth, username) | Deletes the user with username ``username``. Should only be called if the
to-be-deleted user has no repositories.
:param auth.Authentication auth: authentication object, must be admin-level
:param str username: username of user to delete | 5.408185 | 7.342257 | 0.736583 |
path = "/repos/{u}/{r}/hooks".format(u=username, r=repo_name)
response = self.get(path, auth=auth)
return [GogsRepo.Hook.from_json(hook) for hook in response.json()] | def get_repo_hooks(self, auth, username, repo_name) | 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... | 3.226781 | 2.806903 | 1.149588 |
if events is None:
events = ["push"] # default value is mutable, so assign inside body
data = {
"type": hook_type,
"config": config,
"events": events,
"active": active
}
url = "/repos/{o}/{r}/hooks".format(o=organiza... | def create_hook(self, auth, repo_name, hook_type, config, events=None, organization=None, active=False) | 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... | 2.879808 | 2.704657 | 1.064759 |
if organization is not None:
path = "/repos/{o}/{r}/hooks/{i}".format(o=organization, r=repo_name, i=hook_id)
else:
path = "/repos/{r}/hooks/{i}".format(r=repo_name, i=hook_id)
response = self._patch(path, auth=auth, data=update.as_dict())
return GogsRepo... | def update_hook(self, auth, repo_name, hook_id, update, organization=None) | 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... | 2.415743 | 2.176985 | 1.109674 |
path = "/repos/{u}/{r}/hooks/{i}".format(u=username, r=repo_name, i=hook_id)
self.delete(path, auth=auth) | def delete_hook(self, auth, username, repo_name, hook_id) | 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
... | 2.607466 | 3.588176 | 0.726683 |
data = {
"username": org_name,
"full_name": full_name,
"description": description,
"website": website,
"location": location
}
url = "/admin/users/{u}/orgs".format(u=owner_name)
response = self.post(url, auth=auth, data... | def create_organization(self, auth, owner_name, org_name, full_name=None, description=None,
website=None, location=None) | 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
... | 2.614577 | 2.46709 | 1.059782 |
data = {
"name": name,
"description": description,
"permission": permission
}
url = "/admin/orgs/{o}/teams".format(o=org_name)
response = self.post(url, auth=auth, data=data)
return GogsTeam.from_json(response.json()) | def create_organization_team(self, auth, org_name, name, description=None, permission="read") | 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... | 2.586864 | 2.588881 | 0.999221 |
url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username)
self.put(url, auth=auth) | def add_team_membership(self, auth, team_id, username) | 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... | 3.327885 | 4.400913 | 0.756181 |
url = "/admin/teams/{t}/members/{u}".format(t=team_id, u=username)
self.delete(url, auth=auth) | def remove_team_membership(self, auth, team_id, username) | 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... | 3.217852 | 4.335177 | 0.742265 |
url = "/admin/teams/{t}/repos/{r}".format(t=team_id, r=repo_name)
self.put(url, auth=auth) | def add_repo_to_team(self, auth, team_id, repo_name) | 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... | 3.169697 | 3.954343 | 0.801573 |
url = "/admin/teams/{t}/repos/{r}".format(t=team_id, r=repo_name)
self.delete(url, auth=auth) | def remove_repo_from_team(self, auth, team_id, repo_name) | 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 ... | 3.066641 | 3.854544 | 0.795591 |
response = self.get("/repos/{u}/{r}/keys".format(u=username, r=repo_name), auth=auth)
return [GogsRepo.DeployKey.from_json(key_json) for key_json in response.json()] | def list_deploy_keys(self, auth, username, repo_name) | 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... | 3.212566 | 2.580508 | 1.244936 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.