text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def make_body(self, resp, params, meta, content):
"""Construct response body in ``resp`` object using JSON serialization.
Args:
resp (falcon.Response): response object where to include
serialized body
params (dict): dictionary of parsed parameters
met... | [
"def",
"make_body",
"(",
"self",
",",
"resp",
",",
"params",
",",
"meta",
",",
"content",
")",
":",
"response",
"=",
"{",
"'meta'",
":",
"meta",
",",
"'content'",
":",
"content",
"}",
"resp",
".",
"content_type",
"=",
"'application/json'",
"resp",
".",
... | 34.44 | 21.56 |
def validate(document, spec):
"""Validate that a document meets a specification. Returns True if
validation was successful, but otherwise raises a ValueError."""
if not spec:
return True
missing = []
for key, field in spec.iteritems():
if field.required and key not in document:
... | [
"def",
"validate",
"(",
"document",
",",
"spec",
")",
":",
"if",
"not",
"spec",
":",
"return",
"True",
"missing",
"=",
"[",
"]",
"for",
"key",
",",
"field",
"in",
"spec",
".",
"iteritems",
"(",
")",
":",
"if",
"field",
".",
"required",
"and",
"key"... | 38.208333 | 17.5 |
def _create_api_uri(self, *parts):
"""Creates fully qualified endpoint URIs.
:param parts: the string parts that form the request URI
"""
return urljoin(self.API_URI, '/'.join(map(quote, parts))) | [
"def",
"_create_api_uri",
"(",
"self",
",",
"*",
"parts",
")",
":",
"return",
"urljoin",
"(",
"self",
".",
"API_URI",
",",
"'/'",
".",
"join",
"(",
"map",
"(",
"quote",
",",
"parts",
")",
")",
")"
] | 29.571429 | 18.142857 |
def _add_model(self, model_list_or_dict, core_element, model_class, model_key=None, load_meta_data=True):
"""Adds one model for a given core element.
The method will add a model for a given core object and checks if there is a corresponding model object in the
future expected model list. The me... | [
"def",
"_add_model",
"(",
"self",
",",
"model_list_or_dict",
",",
"core_element",
",",
"model_class",
",",
"model_key",
"=",
"None",
",",
"load_meta_data",
"=",
"True",
")",
":",
"found_model",
"=",
"self",
".",
"_get_future_expected_model",
"(",
"core_element",
... | 53.310345 | 36.62069 |
def iterate(self, max_iter=150, n_rewightings=1):
r"""Iterate
This method calls update until either convergence criteria is met or
the maximum number of iterations is reached
Parameters
----------
max_iter : int, optional
Maximum number of iterations (defaul... | [
"def",
"iterate",
"(",
"self",
",",
"max_iter",
"=",
"150",
",",
"n_rewightings",
"=",
"1",
")",
":",
"self",
".",
"_run_alg",
"(",
"max_iter",
")",
"if",
"not",
"isinstance",
"(",
"self",
".",
"_reweight",
",",
"type",
"(",
"None",
")",
")",
":",
... | 30.888889 | 17.481481 |
def _formatFilterQuery(self, request=None, featureSets=[]):
"""
Generate a formatted sparql query with appropriate filters
"""
query = self._baseQuery()
filters = []
if issubclass(request.__class__,
protocol.SearchGenotypePhenotypeRequest):
... | [
"def",
"_formatFilterQuery",
"(",
"self",
",",
"request",
"=",
"None",
",",
"featureSets",
"=",
"[",
"]",
")",
":",
"query",
"=",
"self",
".",
"_baseQuery",
"(",
")",
"filters",
"=",
"[",
"]",
"if",
"issubclass",
"(",
"request",
".",
"__class__",
",",
... | 37.6 | 18 |
def get_plain_text(self):
"""Returns a list"""
_msg = self.message if self.message is not None else [""]
msg = _msg if isinstance(_msg, list) else [_msg]
line = "" if not self.line else ", line {}".format(self.line)
ret = ["{} found in file '{}'{}::".format(self.type.capital... | [
"def",
"get_plain_text",
"(",
"self",
")",
":",
"_msg",
"=",
"self",
".",
"message",
"if",
"self",
".",
"message",
"is",
"not",
"None",
"else",
"[",
"\"\"",
"]",
"msg",
"=",
"_msg",
"if",
"isinstance",
"(",
"_msg",
",",
"list",
")",
"else",
"[",
"_... | 45.2 | 19.7 |
def tile_to_path(self, tile):
'''return full path to a tile'''
return os.path.join(self.cache_path, self.service, tile.path()) | [
"def",
"tile_to_path",
"(",
"self",
",",
"tile",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"cache_path",
",",
"self",
".",
"service",
",",
"tile",
".",
"path",
"(",
")",
")"
] | 42.666667 | 14 |
def adjust_for_triggers(self):
"""Remove trigger-related plugins when needed
If there are no triggers defined, it's assumed the
feature is disabled and all trigger-related plugins
are removed.
If there are triggers defined, and this is a custom
base image, some trigger-... | [
"def",
"adjust_for_triggers",
"(",
"self",
")",
":",
"triggers",
"=",
"self",
".",
"template",
"[",
"'spec'",
"]",
".",
"get",
"(",
"'triggers'",
",",
"[",
"]",
")",
"remove_plugins",
"=",
"[",
"(",
"\"prebuild_plugins\"",
",",
"\"check_and_set_rebuild\"",
"... | 38.368421 | 20.473684 |
def query_metric_stats(self, metric_type, metric_id=None, start=None, end=None, bucketDuration=None, **query_options):
"""
Query for metric aggregates from the server. This is called buckets in the Hawkular-Metrics documentation.
:param metric_type: MetricType to be matched (required)
:... | [
"def",
"query_metric_stats",
"(",
"self",
",",
"metric_type",
",",
"metric_id",
"=",
"None",
",",
"start",
"=",
"None",
",",
"end",
"=",
"None",
",",
"bucketDuration",
"=",
"None",
",",
"*",
"*",
"query_options",
")",
":",
"if",
"start",
"is",
"not",
"... | 48.324324 | 28 |
def _parse_metafiles(self, metafile_input):
"""
Parses class input and verifies metadata file names.
:param metafile_input: class input parameter `metafiles`
:type metafile_input: str or list(str) or None
:return: verified list of metadata files
:rtype: list(str)
... | [
"def",
"_parse_metafiles",
"(",
"self",
",",
"metafile_input",
")",
":",
"all_metafiles",
"=",
"AwsConstants",
".",
"S2_L1C_METAFILES",
"if",
"self",
".",
"data_source",
"is",
"DataSource",
".",
"SENTINEL2_L1C",
"else",
"AwsConstants",
".",
"S2_L2A_METAFILES",
"if",... | 48.62069 | 21.862069 |
def get_directory(request):
"""Get API directory as a nested list of lists."""
def get_url(url):
return reverse(url, request=request) if url else url
def is_active_url(path, url):
return path.startswith(url) if url and path else False
path = request.path
directory_list = []
d... | [
"def",
"get_directory",
"(",
"request",
")",
":",
"def",
"get_url",
"(",
"url",
")",
":",
"return",
"reverse",
"(",
"url",
",",
"request",
"=",
"request",
")",
"if",
"url",
"else",
"url",
"def",
"is_active_url",
"(",
"path",
",",
"url",
")",
":",
"re... | 29.146341 | 18.170732 |
def div_safe( numerator, denominator ):
"""
Ufunc-extension that returns 0 instead of nan when dividing numpy arrays
Parameters
----------
numerator: array-like
denominator: scalar or array-like that can be validly divided by the numerator
returns a numpy array
example: div_safe( [-1... | [
"def",
"div_safe",
"(",
"numerator",
",",
"denominator",
")",
":",
"#First handle scalars",
"if",
"np",
".",
"isscalar",
"(",
"numerator",
")",
":",
"raise",
"ValueError",
"(",
"\"div_safe should only be used with an array-like numerator\"",
")",
"#Then numpy arrays",
"... | 29.153846 | 23.615385 |
def get_commits(repo_dir, old_commit, new_commit, hide_merges=True):
"""Find all commits between two commit SHAs."""
repo = Repo(repo_dir)
commits = repo.iter_commits(rev="{0}..{1}".format(old_commit, new_commit))
if hide_merges:
return [x for x in commits if not x.summary.startswith("Merge ")]
... | [
"def",
"get_commits",
"(",
"repo_dir",
",",
"old_commit",
",",
"new_commit",
",",
"hide_merges",
"=",
"True",
")",
":",
"repo",
"=",
"Repo",
"(",
"repo_dir",
")",
"commits",
"=",
"repo",
".",
"iter_commits",
"(",
"rev",
"=",
"\"{0}..{1}\"",
".",
"format",
... | 43.875 | 22.25 |
def parse_reaction(reaction_def, default_compartment, context=None):
"""Parse a structured reaction definition as obtained from a YAML file
Returns a ReactionEntry.
"""
reaction_id = reaction_def.get('id')
_check_id(reaction_id, 'Reaction')
reaction_props = dict(reaction_def)
# Parse rea... | [
"def",
"parse_reaction",
"(",
"reaction_def",
",",
"default_compartment",
",",
"context",
"=",
"None",
")",
":",
"reaction_id",
"=",
"reaction_def",
".",
"get",
"(",
"'id'",
")",
"_check_id",
"(",
"reaction_id",
",",
"'Reaction'",
")",
"reaction_props",
"=",
"... | 31.222222 | 16.944444 |
def listen_for_dweets_from(thing_name, timeout=900, key=None, session=None):
"""Create a real-time subscription to dweets
"""
url = BASE_URL + '/listen/for/dweets/from/{0}'.format(thing_name)
session = session or requests.Session()
if key is not None:
params = {'key': key}
else:
... | [
"def",
"listen_for_dweets_from",
"(",
"thing_name",
",",
"timeout",
"=",
"900",
",",
"key",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"url",
"=",
"BASE_URL",
"+",
"'/listen/for/dweets/from/{0}'",
".",
"format",
"(",
"thing_name",
")",
"session",
"=... | 39.619048 | 21.190476 |
def draw_beam(ax, p1, p2, width=0, beta1=None, beta2=None,
format=None, **kwds):
r"""Draw a laser beam."""
if format is None: format = 'k-'
if width == 0:
x0 = [p1[0], p2[0]]
y0 = [p1[1], p2[1]]
ax.plot(x0, y0, format, **kwds)
else:
a = width/2
... | [
"def",
"draw_beam",
"(",
"ax",
",",
"p1",
",",
"p2",
",",
"width",
"=",
"0",
",",
"beta1",
"=",
"None",
",",
"beta2",
"=",
"None",
",",
"format",
"=",
"None",
",",
"*",
"*",
"kwds",
")",
":",
"if",
"format",
"is",
"None",
":",
"format",
"=",
... | 127.733333 | 118.333333 |
def QA_fetch_get_sz_margin(date):
"""return shenzhen margin data
Arguments:
date {str YYYY-MM-DD} -- date format
Returns:
pandas.DataFrame -- res for margin data
"""
if date in trade_date_sse:
return pd.read_excel(_sz_url.format(date)).assign(date=date).assign(sse='sz') | [
"def",
"QA_fetch_get_sz_margin",
"(",
"date",
")",
":",
"if",
"date",
"in",
"trade_date_sse",
":",
"return",
"pd",
".",
"read_excel",
"(",
"_sz_url",
".",
"format",
"(",
"date",
")",
")",
".",
"assign",
"(",
"date",
"=",
"date",
")",
".",
"assign",
"("... | 25.5 | 20.583333 |
def run_forever(self) -> None:
'''Execute the tasky/asyncio event loop until terminated.'''
Log.debug('running event loop until terminated')
asyncio.ensure_future(self.init())
self.loop.run_forever()
self.loop.close() | [
"def",
"run_forever",
"(",
"self",
")",
"->",
"None",
":",
"Log",
".",
"debug",
"(",
"'running event loop until terminated'",
")",
"asyncio",
".",
"ensure_future",
"(",
"self",
".",
"init",
"(",
")",
")",
"self",
".",
"loop",
".",
"run_forever",
"(",
")",
... | 36 | 17.142857 |
async def get_bearer_info(self):
"""Get the application bearer token from client_id and client_secret."""
if self.client_id is None:
raise SpotifyException(_GET_BEARER_ERR % 'client_id')
elif self.client_secret is None:
raise SpotifyException(_GET_BEARER_ERR % 'client_se... | [
"async",
"def",
"get_bearer_info",
"(",
"self",
")",
":",
"if",
"self",
".",
"client_id",
"is",
"None",
":",
"raise",
"SpotifyException",
"(",
"_GET_BEARER_ERR",
"%",
"'client_id'",
")",
"elif",
"self",
".",
"client_secret",
"is",
"None",
":",
"raise",
"Spot... | 40.722222 | 23.722222 |
def unique(self, *args):
"""
Returns all unique values as a DataFrame. This is executing:
SELECT
DISTINCT
<name_of_the_column_1>
, <name_of_the_column_2>
, <name_of_the_column_3>
...
F... | [
"def",
"unique",
"(",
"self",
",",
"*",
"args",
")",
":",
"q",
"=",
"self",
".",
"_query_templates",
"[",
"'table'",
"]",
"[",
"'unique'",
"]",
".",
"format",
"(",
"columns",
"=",
"self",
".",
"_format_columns",
"(",
"args",
")",
",",
"schema",
"=",
... | 25.259259 | 20.296296 |
def token(self, id, **kwargs):
"""
Retrieve a service request ID from a token.
>>> Three('api.city.gov').token('12345')
{'service_request_id': {'for': {'token': '12345'}}}
"""
data = self.get('tokens', id, **kwargs)
return data | [
"def",
"token",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"data",
"=",
"self",
".",
"get",
"(",
"'tokens'",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
"return",
"data"
] | 30.666667 | 12.888889 |
def dict_from_hdf5(dict_like, h5group):
"""
Load a dictionnary-like object from a h5 file group
"""
# Read attributes
for name, value in h5group.attrs.items():
dict_like[name] = value | [
"def",
"dict_from_hdf5",
"(",
"dict_like",
",",
"h5group",
")",
":",
"# Read attributes",
"for",
"name",
",",
"value",
"in",
"h5group",
".",
"attrs",
".",
"items",
"(",
")",
":",
"dict_like",
"[",
"name",
"]",
"=",
"value"
] | 29.285714 | 7 |
def remove_binding(site, hostheader='', ipaddress='*', port=80):
'''
Remove an IIS binding.
Args:
site (str): The IIS site name.
hostheader (str): The host header of the binding.
ipaddress (str): The IP address of the binding.
port (int): The TCP port of the binding.
Re... | [
"def",
"remove_binding",
"(",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
")",
":",
"name",
"=",
"_get_binding_info",
"(",
"hostheader",
",",
"ipaddress",
",",
"port",
")",
"current_bindings",
"=",
"list_bind... | 30.209302 | 21.744186 |
def getVariantAnnotationSets(self, datasetId):
"""
Returns the list of ReferenceSets for this server.
"""
# TODO this should be displayed per-variant set, not per dataset.
variantAnnotationSets = []
dataset = app.backend.getDataRepository().getDataset(datasetId)
f... | [
"def",
"getVariantAnnotationSets",
"(",
"self",
",",
"datasetId",
")",
":",
"# TODO this should be displayed per-variant set, not per dataset.",
"variantAnnotationSets",
"=",
"[",
"]",
"dataset",
"=",
"app",
".",
"backend",
".",
"getDataRepository",
"(",
")",
".",
"getD... | 44.181818 | 11.272727 |
def all_project_administrators(self):
"""
Get the list of project administrators
:return:
"""
for project in self.project_list():
log.info('Processing project: {0} - {1}'.format(project.get('key'), project.get('name')))
yield {
'project_key... | [
"def",
"all_project_administrators",
"(",
"self",
")",
":",
"for",
"project",
"in",
"self",
".",
"project_list",
"(",
")",
":",
"log",
".",
"info",
"(",
"'Processing project: {0} - {1}'",
".",
"format",
"(",
"project",
".",
"get",
"(",
"'key'",
")",
",",
"... | 50.166667 | 23 |
def feed_interval_get(feed_id, parameters):
'Get adaptive interval between checks for a feed.'
val = cache.get(getkey( T_INTERVAL,
key=feed_interval_key(feed_id, parameters) ))
return val if isinstance(val, tuple) else (val, None) | [
"def",
"feed_interval_get",
"(",
"feed_id",
",",
"parameters",
")",
":",
"val",
"=",
"cache",
".",
"get",
"(",
"getkey",
"(",
"T_INTERVAL",
",",
"key",
"=",
"feed_interval_key",
"(",
"feed_id",
",",
"parameters",
")",
")",
")",
"return",
"val",
"if",
"is... | 46.2 | 7.8 |
def get_comments_of_credit_note_per_page(self, credit_note_id, per_page=1000, page=1):
"""
Get comments of credit note per page
:param credit_note_id: the credit note id
:param per_page: How many objects per page. Default: 1000
:param page: Which page. Default: 1
:return... | [
"def",
"get_comments_of_credit_note_per_page",
"(",
"self",
",",
"credit_note_id",
",",
"per_page",
"=",
"1000",
",",
"page",
"=",
"1",
")",
":",
"return",
"self",
".",
"_get_resource_per_page",
"(",
"resource",
"=",
"CREDIT_NOTE_COMMENTS",
",",
"per_page",
"=",
... | 35.333333 | 14.933333 |
def _x2c(self, x):
""" Convert windowdow coordinates to cheb coordinates [-1,1] """
return ((2 * x - self.window[1] - self.window[0]) /
(self.window[1] - self.window[0])) | [
"def",
"_x2c",
"(",
"self",
",",
"x",
")",
":",
"return",
"(",
"(",
"2",
"*",
"x",
"-",
"self",
".",
"window",
"[",
"1",
"]",
"-",
"self",
".",
"window",
"[",
"0",
"]",
")",
"/",
"(",
"self",
".",
"window",
"[",
"1",
"]",
"-",
"self",
"."... | 49.75 | 12.75 |
def defect_concentration(self, chemical_potentials, temperature=300, fermi_level=0.0):
"""
Get the defect concentration for a temperature and Fermi level.
Args:
temperature:
the temperature in K
fermi_level:
the fermi level in eV (with resp... | [
"def",
"defect_concentration",
"(",
"self",
",",
"chemical_potentials",
",",
"temperature",
"=",
"300",
",",
"fermi_level",
"=",
"0.0",
")",
":",
"n",
"=",
"self",
".",
"multiplicity",
"*",
"1e24",
"/",
"self",
".",
"defect",
".",
"bulk_structure",
".",
"v... | 39.6875 | 21.8125 |
def get_new_header(configuration, pofile):
"""
Insert info about edX into the po file headers
"""
team = pofile.metadata.get('Language-Team', None)
if not team:
return TRANSIFEX_HEADER.format(configuration.TRANSIFEX_URL)
return TRANSIFEX_HEADER.format(team) | [
"def",
"get_new_header",
"(",
"configuration",
",",
"pofile",
")",
":",
"team",
"=",
"pofile",
".",
"metadata",
".",
"get",
"(",
"'Language-Team'",
",",
"None",
")",
"if",
"not",
"team",
":",
"return",
"TRANSIFEX_HEADER",
".",
"format",
"(",
"configuration",... | 35.25 | 9.5 |
def fetch(self, plan_id, data={}, **kwargs):
""""
Fetch Plan for given Id
Args:
plan_id : Id for which Plan object has to be retrieved
Returns:
Plan dict for given subscription Id
"""
return super(Plan, self).fetch(plan_id, data, **kwargs) | [
"def",
"fetch",
"(",
"self",
",",
"plan_id",
",",
"data",
"=",
"{",
"}",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Plan",
",",
"self",
")",
".",
"fetch",
"(",
"plan_id",
",",
"data",
",",
"*",
"*",
"kwargs",
")"
] | 27.545455 | 18.181818 |
def topoSort(roots, getParents):
"""Return a topological sorting of nodes in a graph.
roots - list of root nodes to search from
getParents - function which returns the parents of a given node
"""
results = []
visited = set()
# Use iterative version to avoid stack limits for large datasets... | [
"def",
"topoSort",
"(",
"roots",
",",
"getParents",
")",
":",
"results",
"=",
"[",
"]",
"visited",
"=",
"set",
"(",
")",
"# Use iterative version to avoid stack limits for large datasets",
"stack",
"=",
"[",
"(",
"node",
",",
"0",
")",
"for",
"node",
"in",
"... | 31.16 | 16 |
def reject(self):
"""Handle ESC key"""
if self.controller.is_running:
self.info(self.tr("Stopping.."))
self.controller.is_running = False | [
"def",
"reject",
"(",
"self",
")",
":",
"if",
"self",
".",
"controller",
".",
"is_running",
":",
"self",
".",
"info",
"(",
"self",
".",
"tr",
"(",
"\"Stopping..\"",
")",
")",
"self",
".",
"controller",
".",
"is_running",
"=",
"False"
] | 28.833333 | 12.5 |
def get_window(self, window, bands=None,
xsize=None, ysize=None,
resampling=Resampling.cubic, masked=None, affine=None
):
"""Get window from raster.
:param window: requested window
:param bands: list of indices of requested bads, default ... | [
"def",
"get_window",
"(",
"self",
",",
"window",
",",
"bands",
"=",
"None",
",",
"xsize",
"=",
"None",
",",
"ysize",
"=",
"None",
",",
"resampling",
"=",
"Resampling",
".",
"cubic",
",",
"masked",
"=",
"None",
",",
"affine",
"=",
"None",
")",
":",
... | 49.275 | 26.35 |
def trigger(self, attr, old, new, hint=None, setter=None):
''' Trigger callbacks for ``attr`` on this object.
Args:
attr (str) :
old (object) :
new (object) :
Returns:
None
'''
def invoke():
callbacks = self._callback... | [
"def",
"trigger",
"(",
"self",
",",
"attr",
",",
"old",
",",
"new",
",",
"hint",
"=",
"None",
",",
"setter",
"=",
"None",
")",
":",
"def",
"invoke",
"(",
")",
":",
"callbacks",
"=",
"self",
".",
"_callbacks",
".",
"get",
"(",
"attr",
")",
"if",
... | 29.333333 | 22.571429 |
def as_page(self):
"""
Wrap this Tag as a self-contained webpage. Create a page with
the following structure:
.. code-block:: html
<!DOCTYPE html>
<html>
<head>
<meta http-equiv="Content-type"
content="text/htm... | [
"def",
"as_page",
"(",
"self",
")",
":",
"H",
"=",
"HTML",
"(",
")",
"utf8",
"=",
"H",
".",
"meta",
"(",
"{",
"'http-equiv'",
":",
"'Content-type'",
"}",
",",
"content",
"=",
"\"text/html\"",
",",
"charset",
"=",
"\"UTF-8\"",
")",
"return",
"H",
".",... | 29.740741 | 14.555556 |
def extend(self, values):
"""Extend the array, appending the given values."""
self.database.run_script(
'array_extend',
keys=[self.key],
args=values) | [
"def",
"extend",
"(",
"self",
",",
"values",
")",
":",
"self",
".",
"database",
".",
"run_script",
"(",
"'array_extend'",
",",
"keys",
"=",
"[",
"self",
".",
"key",
"]",
",",
"args",
"=",
"values",
")"
] | 32.666667 | 10.5 |
def _parse_qualimap_globals(table):
"""Retrieve metrics of interest from globals table.
"""
out = {}
want = {"Mapped reads": _parse_num_pct,
"Duplication rate": lambda k, v: {k: v}}
for row in table.find_all("tr"):
col, val = [x.text for x in row.find_all("td")]
if col in... | [
"def",
"_parse_qualimap_globals",
"(",
"table",
")",
":",
"out",
"=",
"{",
"}",
"want",
"=",
"{",
"\"Mapped reads\"",
":",
"_parse_num_pct",
",",
"\"Duplication rate\"",
":",
"lambda",
"k",
",",
"v",
":",
"{",
"k",
":",
"v",
"}",
"}",
"for",
"row",
"in... | 34.090909 | 10.272727 |
def load_raw_arrays(self, columns, start_date, end_date, assets):
"""
Parameters
----------
fields : list of str
'open', 'high', 'low', 'close', or 'volume'
start_dt: Timestamp
Beginning of the window range.
end_dt: Timestamp
End of the wi... | [
"def",
"load_raw_arrays",
"(",
"self",
",",
"columns",
",",
"start_date",
",",
"end_date",
",",
"assets",
")",
":",
"rolls_by_asset",
"=",
"{",
"}",
"tc",
"=",
"self",
".",
"trading_calendar",
"start_session",
"=",
"tc",
".",
"minute_to_session_label",
"(",
... | 36.835443 | 16.278481 |
def tange_pth(v, temp, v0, gamma0, a, b, theta0, n, z,
t_ref=300., three_r=3. * constants.R):
"""
calculate thermal pressure for the Tange equation
:param v: unit-cell volume in A^3
:param temp: temperature in K
:param v0: unit-cell volume in A^3 at 1 bar
:param gamma0: Gruneisen ... | [
"def",
"tange_pth",
"(",
"v",
",",
"temp",
",",
"v0",
",",
"gamma0",
",",
"a",
",",
"b",
",",
"theta0",
",",
"n",
",",
"z",
",",
"t_ref",
"=",
"300.",
",",
"three_r",
"=",
"3.",
"*",
"constants",
".",
"R",
")",
":",
"v_mol",
"=",
"vol_uc2mol",
... | 34.818182 | 11.787879 |
def eps_from_series(self):
"""
Workhorse function that handles grabbing series data from csvs and
requesting episodal information from RSS feeds
"""
csvs = []
for _, _, filenames in os.walk('./{}'.format(self.directory)):
csvs.extend(filenames)
series_set = set()
for c in csvs:
... | [
"def",
"eps_from_series",
"(",
"self",
")",
":",
"csvs",
"=",
"[",
"]",
"for",
"_",
",",
"_",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"'./{}'",
".",
"format",
"(",
"self",
".",
"directory",
")",
")",
":",
"csvs",
".",
"extend",
"(",
"file... | 27.222222 | 18.037037 |
def setShowTerritory(self, state):
"""
Sets the display mode for this widget to the inputed mode.
:param state | <bool>
"""
if state == self._showTerritory:
return
self._showTerritory = state
self.setDirty() | [
"def",
"setShowTerritory",
"(",
"self",
",",
"state",
")",
":",
"if",
"state",
"==",
"self",
".",
"_showTerritory",
":",
"return",
"self",
".",
"_showTerritory",
"=",
"state",
"self",
".",
"setDirty",
"(",
")"
] | 27.090909 | 12.909091 |
def mean(self, axis=0, *args, **kwargs):
"""
Mean of non-NA/null values
Returns
-------
mean : float
"""
nv.validate_mean(args, kwargs)
valid_vals = self._valid_sp_values
sp_sum = valid_vals.sum()
ct = len(valid_vals)
if self._nul... | [
"def",
"mean",
"(",
"self",
",",
"axis",
"=",
"0",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"nv",
".",
"validate_mean",
"(",
"args",
",",
"kwargs",
")",
"valid_vals",
"=",
"self",
".",
"_valid_sp_values",
"sp_sum",
"=",
"valid_vals",
".",... | 26.444444 | 14.222222 |
def create_document(self,
parent,
document,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates a new document.
... | [
"def",
"create_document",
"(",
"self",
",",
"parent",
",",
"document",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEF... | 44.814815 | 23.802469 |
def diskdata():
"""Get total disk size in GB."""
p = os.popen("/bin/df -l -P")
ddata = {}
tsize = 0
for line in p.readlines():
d = line.split()
if ("/dev/sd" in d[0] or "/dev/hd" in d[0] or "/dev/mapper" in d[0]):
tsize = tsize + int(d[1])
ddata["Disk_GB"] = int(tsize... | [
"def",
"diskdata",
"(",
")",
":",
"p",
"=",
"os",
".",
"popen",
"(",
"\"/bin/df -l -P\"",
")",
"ddata",
"=",
"{",
"}",
"tsize",
"=",
"0",
"for",
"line",
"in",
"p",
".",
"readlines",
"(",
")",
":",
"d",
"=",
"line",
".",
"split",
"(",
")",
"if",... | 29.083333 | 16.916667 |
def fire_event(self, event, *args, **kwargs):
"""Fires a event."""
self.event_queue.append((event, args))
self.process_events() | [
"def",
"fire_event",
"(",
"self",
",",
"event",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"event_queue",
".",
"append",
"(",
"(",
"event",
",",
"args",
")",
")",
"self",
".",
"process_events",
"(",
")"
] | 37 | 5.5 |
def get_eidos_bayesian_scorer(prior_counts=None):
"""Return a BayesianScorer based on Eidos curation counts."""
table = load_eidos_curation_table()
subtype_counts = {'eidos': {r: [c, i] for r, c, i in
zip(table['RULE'], table['Num correct'],
ta... | [
"def",
"get_eidos_bayesian_scorer",
"(",
"prior_counts",
"=",
"None",
")",
":",
"table",
"=",
"load_eidos_curation_table",
"(",
")",
"subtype_counts",
"=",
"{",
"'eidos'",
":",
"{",
"r",
":",
"[",
"c",
",",
"i",
"]",
"for",
"r",
",",
"c",
",",
"i",
"in... | 46.416667 | 17.833333 |
def seek(self, pos=0):
"""Set the stream's file pointer to pos. Negative seeking
is forbidden.
"""
if pos - self.pos >= 0:
blocks, remainder = divmod(pos - self.pos, self.bufsize)
for i in range(blocks):
self.read(self.bufsize)
self.... | [
"def",
"seek",
"(",
"self",
",",
"pos",
"=",
"0",
")",
":",
"if",
"pos",
"-",
"self",
".",
"pos",
">=",
"0",
":",
"blocks",
",",
"remainder",
"=",
"divmod",
"(",
"pos",
"-",
"self",
".",
"pos",
",",
"self",
".",
"bufsize",
")",
"for",
"i",
"i... | 35.666667 | 12.833333 |
def url_dirname(url):
""" Return the folder containing the '.json' file
"""
p = six.moves.urllib.parse.urlparse(url)
for e in [private.FILE_EXT_JSON, private.FILE_EXT_YAML]:
if p.path.endswith(e):
return six.moves.urllib.parse.urlunparse(
p[:2]+
(os.pa... | [
"def",
"url_dirname",
"(",
"url",
")",
":",
"p",
"=",
"six",
".",
"moves",
".",
"urllib",
".",
"parse",
".",
"urlparse",
"(",
"url",
")",
"for",
"e",
"in",
"[",
"private",
".",
"FILE_EXT_JSON",
",",
"private",
".",
"FILE_EXT_YAML",
"]",
":",
"if",
... | 31.75 | 13.25 |
def update(table_name, **fields):
""" Build a update query.
>>> update('foo_table', a=5, b=2)
"UPDATE `foo_table` SET `a`=%(_QB_a)s, `b`=%(_QB_b)s", { '_QB_a': 5, '_QB_b': 2 }
"""
prefix = "UPDATE `%s` SET " % table_name
sets, params = simple_expression(', ', **fields)
return prefix + sets,... | [
"def",
"update",
"(",
"table_name",
",",
"*",
"*",
"fields",
")",
":",
"prefix",
"=",
"\"UPDATE `%s` SET \"",
"%",
"table_name",
"sets",
",",
"params",
"=",
"simple_expression",
"(",
"', '",
",",
"*",
"*",
"fields",
")",
"return",
"prefix",
"+",
"sets",
... | 35.444444 | 13.222222 |
def _count_righthand_zero_bits(number, bits):
"""Count the number of zero bits on the right hand side.
Args:
number: an integer.
bits: maximum number of bits to count.
Returns:
The number of zero bits on the right hand side of the number.
"""
if number == 0:
return... | [
"def",
"_count_righthand_zero_bits",
"(",
"number",
",",
"bits",
")",
":",
"if",
"number",
"==",
"0",
":",
"return",
"bits",
"return",
"min",
"(",
"bits",
",",
"_compat_bit_length",
"(",
"~",
"number",
"&",
"(",
"number",
"-",
"1",
")",
")",
")"
] | 26.928571 | 21.285714 |
def _get_demand_array_construct(self):
""" Returns a construct for an array of power demand data.
"""
bus_no = integer.setResultsName("bus_no")
s_rating = real.setResultsName("s_rating") # MVA
p_direction = real.setResultsName("p_direction") # p.u.
q_direction = real.setR... | [
"def",
"_get_demand_array_construct",
"(",
"self",
")",
":",
"bus_no",
"=",
"integer",
".",
"setResultsName",
"(",
"\"bus_no\"",
")",
"s_rating",
"=",
"real",
".",
"setResultsName",
"(",
"\"s_rating\"",
")",
"# MVA",
"p_direction",
"=",
"real",
".",
"setResultsN... | 51.941176 | 22.323529 |
def _invokeWrite(self, fileIO, session, directory, filename, replaceParamFile):
"""
Invoke File Write Method on Other Files
"""
# Default value for instance
instance = None
try:
# Handle case where fileIO interfaces with single file
# Retrieve Fil... | [
"def",
"_invokeWrite",
"(",
"self",
",",
"fileIO",
",",
"session",
",",
"directory",
",",
"filename",
",",
"replaceParamFile",
")",
":",
"# Default value for instance",
"instance",
"=",
"None",
"try",
":",
"# Handle case where fileIO interfaces with single file",
"# Ret... | 40.585366 | 21.804878 |
def show_updates(self):
"""
Check installed packages for available updates on PyPI
@param project_name: optional package name to check; checks every
installed pacakge if none specified
@type project_name: string
@returns: None
"""
di... | [
"def",
"show_updates",
"(",
"self",
")",
":",
"dists",
"=",
"Distributions",
"(",
")",
"if",
"self",
".",
"project_name",
":",
"#Check for a single package",
"pkg_list",
"=",
"[",
"self",
".",
"project_name",
"]",
"else",
":",
"#Check for every installed package",... | 39.386364 | 19.704545 |
def _raise_server_index(self):
"""Round robin magic: Raises the current redis server index and returns it"""
self._current_server_index = (self._current_server_index + 1) % len(self._servers)
return self._current_server_index | [
"def",
"_raise_server_index",
"(",
"self",
")",
":",
"self",
".",
"_current_server_index",
"=",
"(",
"self",
".",
"_current_server_index",
"+",
"1",
")",
"%",
"len",
"(",
"self",
".",
"_servers",
")",
"return",
"self",
".",
"_current_server_index"
] | 41 | 23.5 |
def reset_downloads_folder():
''' Clears the downloads folder.
If settings.ARCHIVE_EXISTING_DOWNLOADS is set to True, archives it. '''
if os.path.exists(downloads_path) and not os.listdir(downloads_path) == []:
archived_downloads_folder = os.path.join(downloads_path, '..',
... | [
"def",
"reset_downloads_folder",
"(",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"downloads_path",
")",
"and",
"not",
"os",
".",
"listdir",
"(",
"downloads_path",
")",
"==",
"[",
"]",
":",
"archived_downloads_folder",
"=",
"os",
".",
"path",
... | 60.636364 | 23.363636 |
def set_generator_validation_nb(self, number):
"""
sets self.nb_val_samples which is used in model.fit if input is a generator
:param number:
:return:
"""
self.nb_val_samples = number
diff_to_batch = number % self.get_batch_size()
if diff_to_batch > 0:
... | [
"def",
"set_generator_validation_nb",
"(",
"self",
",",
"number",
")",
":",
"self",
".",
"nb_val_samples",
"=",
"number",
"diff_to_batch",
"=",
"number",
"%",
"self",
".",
"get_batch_size",
"(",
")",
"if",
"diff_to_batch",
">",
"0",
":",
"self",
".",
"nb_val... | 34.466667 | 19.4 |
def fit(self, Xs=None, ys=None, Xt=None, yt=None):
"""Builds an optimal coupling and estimates the associated mapping
from source and target sets of samples (Xs, ys) and (Xt, yt)
Parameters
----------
Xs : array-like, shape (n_source_samples, n_features)
The training... | [
"def",
"fit",
"(",
"self",
",",
"Xs",
"=",
"None",
",",
"ys",
"=",
"None",
",",
"Xt",
"=",
"None",
",",
"yt",
"=",
"None",
")",
":",
"# check the necessary inputs parameters are here",
"if",
"check_params",
"(",
"Xs",
"=",
"Xs",
",",
"Xt",
"=",
"Xt",
... | 37.625 | 20.107143 |
def make_timestamp(ts: OptTs = None) -> int:
"""Create zipkin timestamp in microseconds, or convert available one
from second. Useful when user supplies ts from time.time() call.
"""
ts = ts if ts is not None else time.time()
return int(ts * 1000 * 1000) | [
"def",
"make_timestamp",
"(",
"ts",
":",
"OptTs",
"=",
"None",
")",
"->",
"int",
":",
"ts",
"=",
"ts",
"if",
"ts",
"is",
"not",
"None",
"else",
"time",
".",
"time",
"(",
")",
"return",
"int",
"(",
"ts",
"*",
"1000",
"*",
"1000",
")"
] | 44.833333 | 7.666667 |
def unlock_keychain(username):
""" If the user is running via SSH, their Keychain must be unlocked first. """
if 'SSH_TTY' not in os.environ:
return
# Don't unlock if we've already seen this user.
if username in _unlocked:
return
_unlocked.add(username)
if sys.platform == 'da... | [
"def",
"unlock_keychain",
"(",
"username",
")",
":",
"if",
"'SSH_TTY'",
"not",
"in",
"os",
".",
"environ",
":",
"return",
"# Don't unlock if we've already seen this user.",
"if",
"username",
"in",
"_unlocked",
":",
"return",
"_unlocked",
".",
"add",
"(",
"username... | 34.266667 | 26 |
def _fieldnames_to_colnames(model_cls, fieldnames):
"""Get the names of columns referenced by the given model fields."""
get_field = model_cls._meta.get_field
fields = map(get_field, fieldnames)
return {f.column for f in fields} | [
"def",
"_fieldnames_to_colnames",
"(",
"model_cls",
",",
"fieldnames",
")",
":",
"get_field",
"=",
"model_cls",
".",
"_meta",
".",
"get_field",
"fields",
"=",
"map",
"(",
"get_field",
",",
"fieldnames",
")",
"return",
"{",
"f",
".",
"column",
"for",
"f",
"... | 51.2 | 4 |
def hook_get_results(self, changelist):
"""Triggered by `ChangeList.get_results()`."""
# Poor NestedSet guys they've punished themselves once chosen that approach,
# and now we punish them again with all those DB hits.
result_list = list(changelist.result_list)
# Get children ... | [
"def",
"hook_get_results",
"(",
"self",
",",
"changelist",
")",
":",
"# Poor NestedSet guys they've punished themselves once chosen that approach,",
"# and now we punish them again with all those DB hits.",
"result_list",
"=",
"list",
"(",
"changelist",
".",
"result_list",
")",
"... | 38.348837 | 27.372093 |
def unpack_rgb(data, dtype=None, bitspersample=None, rescale=True):
"""Return array from byte string containing packed samples.
Use to unpack RGB565 or RGB555 to RGB888 format.
Parameters
----------
data : byte str
The data to be decoded. Samples in each pixel are stored consecutively.
... | [
"def",
"unpack_rgb",
"(",
"data",
",",
"dtype",
"=",
"None",
",",
"bitspersample",
"=",
"None",
",",
"rescale",
"=",
"True",
")",
":",
"if",
"bitspersample",
"is",
"None",
":",
"bitspersample",
"=",
"(",
"5",
",",
"6",
",",
"5",
")",
"if",
"dtype",
... | 35.927273 | 19.090909 |
def get_account_funds(self, wallet=None, session=None, lightweight=None):
"""
Get available to bet amount.
:param str wallet: Name of the wallet in question
:param requests.session session: Requests session object
:param bool lightweight: If True will return dict not a resource
... | [
"def",
"get_account_funds",
"(",
"self",
",",
"wallet",
"=",
"None",
",",
"session",
"=",
"None",
",",
"lightweight",
"=",
"None",
")",
":",
"params",
"=",
"clean_locals",
"(",
"locals",
"(",
")",
")",
"method",
"=",
"'%s%s'",
"%",
"(",
"self",
".",
... | 44.642857 | 21.214286 |
def get_parent_vault_nodes(self):
"""Gets the parents of this vault.
return: (osid.authorization.VaultNodeList) - the parents of this
vault
*compliance: mandatory -- This method must be implemented.*
"""
parent_vault_nodes = []
for node in self._my_map['... | [
"def",
"get_parent_vault_nodes",
"(",
"self",
")",
":",
"parent_vault_nodes",
"=",
"[",
"]",
"for",
"node",
"in",
"self",
".",
"_my_map",
"[",
"'parentNodes'",
"]",
":",
"parent_vault_nodes",
".",
"append",
"(",
"VaultNode",
"(",
"node",
".",
"_my_map",
",",... | 35.9375 | 14.375 |
def _compute_scaled_schoenfeld(self, X, T, E, weights, index=None):
r"""
Let s_k be the kth schoenfeld residuals. Then E[s_k] = 0.
For tests of proportionality, we want to test if \beta_i(t) is \beta_i (constant) or not.
Let V_k be the contribution to the information matrix at time t_k.... | [
"def",
"_compute_scaled_schoenfeld",
"(",
"self",
",",
"X",
",",
"T",
",",
"E",
",",
"weights",
",",
"index",
"=",
"None",
")",
":",
"n_deaths",
"=",
"self",
".",
"event_observed",
".",
"sum",
"(",
")",
"scaled_schoenfeld_resids",
"=",
"n_deaths",
"*",
"... | 38.666667 | 34.185185 |
def annotate_image(self, request, retry=None, timeout=None):
"""Run image detection and annotation for an image.
Example:
>>> from google.cloud.vision_v1 import ImageAnnotatorClient
>>> client = ImageAnnotatorClient()
>>> request = {
... 'image': {
... | [
"def",
"annotate_image",
"(",
"self",
",",
"request",
",",
"retry",
"=",
"None",
",",
"timeout",
"=",
"None",
")",
":",
"# If the image is a file handler, set the content.",
"image",
"=",
"protobuf",
".",
"get",
"(",
"request",
",",
"\"image\"",
")",
"if",
"ha... | 44.577778 | 23.244444 |
def get_log_events(awsclient, log_group_name, log_stream_name, start_ts=None):
"""Get log events for the specified log group and stream.
this is used in tenkai output instance diagnostics
:param log_group_name: log group name
:param log_stream_name: log stream name
:param start_ts: timestamp
:r... | [
"def",
"get_log_events",
"(",
"awsclient",
",",
"log_group_name",
",",
"log_stream_name",
",",
"start_ts",
"=",
"None",
")",
":",
"client_logs",
"=",
"awsclient",
".",
"get_client",
"(",
"'logs'",
")",
"request",
"=",
"{",
"'logGroupName'",
":",
"log_group_name"... | 31.96 | 17.08 |
def choose(self, versions, conflict='silent'):
"""
Choose the highest version in the range.
:param versions: Iterable of available versions.
"""
assert conflict in ('silent', 'warning', 'error')
if not versions:
raise VersionRangeMismatch('No versions to choose from')
version_map = {}
for version in... | [
"def",
"choose",
"(",
"self",
",",
"versions",
",",
"conflict",
"=",
"'silent'",
")",
":",
"assert",
"conflict",
"in",
"(",
"'silent'",
",",
"'warning'",
",",
"'error'",
")",
"if",
"not",
"versions",
":",
"raise",
"VersionRangeMismatch",
"(",
"'No versions t... | 36.605263 | 14.868421 |
def get_scratch_path(self, local_file):
"""Construct and return a path in the scratch area from a local file.
"""
(local_dirname, local_basename) = self.split_local_path(local_file)
return self.construct_scratch_path(local_dirname, local_basename) | [
"def",
"get_scratch_path",
"(",
"self",
",",
"local_file",
")",
":",
"(",
"local_dirname",
",",
"local_basename",
")",
"=",
"self",
".",
"split_local_path",
"(",
"local_file",
")",
"return",
"self",
".",
"construct_scratch_path",
"(",
"local_dirname",
",",
"loca... | 55 | 13.8 |
def skyline_empirical(self, gen=1.0, n_points = 20):
'''
returns the skyline, i.e., an estimate of the inverse rate of coalesence.
Here, the skyline is estimated from a sliding window average of the observed
mergers, i.e., without reference to the coalescence likelihood.
paramete... | [
"def",
"skyline_empirical",
"(",
"self",
",",
"gen",
"=",
"1.0",
",",
"n_points",
"=",
"20",
")",
":",
"mergers",
"=",
"self",
".",
"tree_events",
"[",
":",
",",
"1",
"]",
">",
"0",
"merger_tvals",
"=",
"self",
".",
"tree_events",
"[",
"mergers",
","... | 46.029412 | 25.147059 |
def get_queryset(self, request):
"""
Annote the queryset with an 'is_active' property that's true iff that row is the most
recently added row for that particular set of KEY_FIELDS values.
Filter the queryset to show only is_active rows by default.
"""
if request.GET.get(S... | [
"def",
"get_queryset",
"(",
"self",
",",
"request",
")",
":",
"if",
"request",
".",
"GET",
".",
"get",
"(",
"ShowHistoryFilter",
".",
"parameter_name",
")",
"==",
"'1'",
":",
"queryset",
"=",
"self",
".",
"model",
".",
"objects",
".",
"with_active_flag",
... | 44.933333 | 18.4 |
def installed(name, enabled=True):
'''
Make sure that we have the given bundle ID or path to command
installed in the assistive access panel.
name
The bundle ID or path to command
enable
Should assistive access be enabled on this application?
'''
ret = {'name': name,
... | [
"def",
"installed",
"(",
"name",
",",
"enabled",
"=",
"True",
")",
":",
"ret",
"=",
"{",
"'name'",
":",
"name",
",",
"'result'",
":",
"True",
",",
"'comment'",
":",
"''",
",",
"'changes'",
":",
"{",
"}",
"}",
"is_installed",
"=",
"__salt__",
"[",
"... | 27.212121 | 25.090909 |
def load_texture(self, file_path, cell_size=(256, 256)):
"""
Load a spritesheet texture.
cell_size is the uniform size of each cell in the spritesheet.
"""
super(SpriteSheet, self).load_texture(file_path)
self.__cell_bounds = cell_size
self.__generate_cells() | [
"def",
"load_texture",
"(",
"self",
",",
"file_path",
",",
"cell_size",
"=",
"(",
"256",
",",
"256",
")",
")",
":",
"super",
"(",
"SpriteSheet",
",",
"self",
")",
".",
"load_texture",
"(",
"file_path",
")",
"self",
".",
"__cell_bounds",
"=",
"cell_size",... | 38.5 | 9.75 |
def generate_set_partition_strings(n):
"""Generate the restricted growth strings for all of the partitions of an `n`-member set.
Uses Algorithm H from page 416 of volume 4A of Knuth's `The Art of Computer
Programming`. Returns the partitions in lexicographical order.
Parameters
----------
... | [
"def",
"generate_set_partition_strings",
"(",
"n",
")",
":",
"# Handle edge cases:",
"if",
"n",
"==",
"0",
":",
"return",
"[",
"]",
"elif",
"n",
"==",
"1",
":",
"return",
"[",
"scipy",
".",
"array",
"(",
"[",
"0",
"]",
")",
"]",
"partitions",
"=",
"[... | 32.490566 | 20.490566 |
def get_progenies(p1, p2, x_linked=False, tolerance=0):
"""
Returns possible progenies in a trio.
"""
_p1 = expand_alleles(p1, tolerance=tolerance)
_p2 = expand_alleles(p2, tolerance=tolerance)
possible_progenies = set(tuple(sorted(x)) for x in product(_p1, _p2))
if x_linked: # Add all hemi... | [
"def",
"get_progenies",
"(",
"p1",
",",
"p2",
",",
"x_linked",
"=",
"False",
",",
"tolerance",
"=",
"0",
")",
":",
"_p1",
"=",
"expand_alleles",
"(",
"p1",
",",
"tolerance",
"=",
"tolerance",
")",
"_p2",
"=",
"expand_alleles",
"(",
"p2",
",",
"toleranc... | 42.1 | 11.1 |
def _calc_bkg_bkgrms(self):
"""
Calculate the background and background RMS estimate in each of
the meshes.
Both meshes are computed at the same time here method because
the filtering of both depends on the background mesh.
The ``background_mesh`` and ``background_rms_m... | [
"def",
"_calc_bkg_bkgrms",
"(",
"self",
")",
":",
"if",
"self",
".",
"sigma_clip",
"is",
"not",
"None",
":",
"data_sigclip",
"=",
"self",
".",
"sigma_clip",
"(",
"self",
".",
"_mesh_data",
",",
"axis",
"=",
"1",
")",
"else",
":",
"data_sigclip",
"=",
"... | 40.185185 | 22.740741 |
def keysym_to_keycodes(self, keysym):
"""Look up all the keycodes that is bound to keysym. A list of
tuples (keycode, index) is returned, sorted primarily on the
lowest index and secondarily on the lowest keycode."""
try:
# Copy the map list, reversing the arguments
... | [
"def",
"keysym_to_keycodes",
"(",
"self",
",",
"keysym",
")",
":",
"try",
":",
"# Copy the map list, reversing the arguments",
"return",
"map",
"(",
"lambda",
"x",
":",
"(",
"x",
"[",
"1",
"]",
",",
"x",
"[",
"0",
"]",
")",
",",
"self",
".",
"_keymap_sym... | 47 | 15.888889 |
def v1_subfolder_list(request, response, kvlclient, fid):
'''Retrieves a list of subfolders in a folder for the current user.
The route for this endpoint is:
``GET /dossier/v1/folder/<fid>/subfolder``.
(Temporarily, the "current user" can be set via the
``annotator_id`` query parameter.)
The ... | [
"def",
"v1_subfolder_list",
"(",
"request",
",",
"response",
",",
"kvlclient",
",",
"fid",
")",
":",
"fid",
"=",
"urllib",
".",
"unquote",
"(",
"fid",
")",
"try",
":",
"return",
"sorted",
"(",
"imap",
"(",
"attrgetter",
"(",
"'name'",
")",
",",
"ifilte... | 34.684211 | 21.736842 |
def words(fpth):
"""
ww = words(os.path.join(app_root, 'ig/helper.py'))
for k, v in (ww.most_common(3)):
print(k, v)
:param fpth:
:type fpth:
:return:
:rtype:
"""
from collections import Counter
words__ = Counter()
with open(fpth) as fp:
for line in fp:
... | [
"def",
"words",
"(",
"fpth",
")",
":",
"from",
"collections",
"import",
"Counter",
"words__",
"=",
"Counter",
"(",
")",
"with",
"open",
"(",
"fpth",
")",
"as",
"fp",
":",
"for",
"line",
"in",
"fp",
":",
"words__",
".",
"update",
"(",
"line",
".",
"... | 21.705882 | 17.352941 |
def create_meta_data(cls, options, args, parser):
"""
Override in subclass if required.
"""
meta_data = []
meta_data.append(('spiff_version', cls.get_version()))
if options.target_engine:
meta_data.append(('target_engine', options.target_engine))
if op... | [
"def",
"create_meta_data",
"(",
"cls",
",",
"options",
",",
"args",
",",
"parser",
")",
":",
"meta_data",
"=",
"[",
"]",
"meta_data",
".",
"append",
"(",
"(",
"'spiff_version'",
",",
"cls",
".",
"get_version",
"(",
")",
")",
")",
"if",
"options",
".",
... | 38.166667 | 12.833333 |
async def select(**data):
"""
RPC method for selecting data from the database
:return selected data
"""
try:
select_data = clickhouse_queries.select_from_table(table=data['table'], query=data['query'], fields=data['fields'])
return str(select_data)
except ServerException as e:
... | [
"async",
"def",
"select",
"(",
"*",
"*",
"data",
")",
":",
"try",
":",
"select_data",
"=",
"clickhouse_queries",
".",
"select_from_table",
"(",
"table",
"=",
"data",
"[",
"'table'",
"]",
",",
"query",
"=",
"data",
"[",
"'query'",
"]",
",",
"fields",
"=... | 29.470588 | 19 |
def flush_devices(self):
"""
overwrite the complete memory with zeros
"""
self.rom.program([0 for i in range(self.rom.size)])
self.flash.program([0 for i in range(self.flash.size)])
for i in range(self.ram.size):
self.ram.write(i, 0) | [
"def",
"flush_devices",
"(",
"self",
")",
":",
"self",
".",
"rom",
".",
"program",
"(",
"[",
"0",
"for",
"i",
"in",
"range",
"(",
"self",
".",
"rom",
".",
"size",
")",
"]",
")",
"self",
".",
"flash",
".",
"program",
"(",
"[",
"0",
"for",
"i",
... | 30.375 | 9.375 |
def _edits1(word: str) -> Set[str]:
"""
Return a set of words with edit distance of 1 from the input word
"""
splits = [(word[:i], word[i:]) for i in range(len(word) + 1)]
deletes = [L + R[1:] for L, R in splits if R]
transposes = [L + R[1] + R[0] + R[2:] for L, R in splits if len(R) > 1]
re... | [
"def",
"_edits1",
"(",
"word",
":",
"str",
")",
"->",
"Set",
"[",
"str",
"]",
":",
"splits",
"=",
"[",
"(",
"word",
"[",
":",
"i",
"]",
",",
"word",
"[",
"i",
":",
"]",
")",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"word",
")",
"+",
"1... | 46 | 20.181818 |
def transition_matrix_non_reversible(C):
"""implementation of transition_matrix"""
if not scipy.sparse.issparse(C):
C = scipy.sparse.csr_matrix(C)
rowsum = C.tocsr().sum(axis=1)
# catch div by zero
if np.min(rowsum) == 0.0:
raise ValueError("matrix C contains rows with sum zero.")
... | [
"def",
"transition_matrix_non_reversible",
"(",
"C",
")",
":",
"if",
"not",
"scipy",
".",
"sparse",
".",
"issparse",
"(",
"C",
")",
":",
"C",
"=",
"scipy",
".",
"sparse",
".",
"csr_matrix",
"(",
"C",
")",
"rowsum",
"=",
"C",
".",
"tocsr",
"(",
")",
... | 37.545455 | 8.181818 |
def smooth_rectangle(x, y, rec_w, rec_h, gaussian_width_x, gaussian_width_y):
"""
Rectangle with a solid central region, then Gaussian fall-off at the edges.
"""
gaussian_x_coord = abs(x)-rec_w/2.0
gaussian_y_coord = abs(y)-rec_h/2.0
box_x=np.less(gaussian_x_coord,0.0)
box_y=np.less(gaussi... | [
"def",
"smooth_rectangle",
"(",
"x",
",",
"y",
",",
"rec_w",
",",
"rec_h",
",",
"gaussian_width_x",
",",
"gaussian_width_y",
")",
":",
"gaussian_x_coord",
"=",
"abs",
"(",
"x",
")",
"-",
"rec_w",
"/",
"2.0",
"gaussian_y_coord",
"=",
"abs",
"(",
"y",
")",... | 38.95 | 19.65 |
def write(self, fb):
"""Write a single function benchmark.
Args:
fb (FunctionBenchmark): FunctionBenchmark class instance.
Before passing to this, you should call ``fb.benchmark()``.
"""
print('[{}.{}]'.format(fb.module, fb.func.__name__), file=self.file)
... | [
"def",
"write",
"(",
"self",
",",
"fb",
")",
":",
"print",
"(",
"'[{}.{}]'",
".",
"format",
"(",
"fb",
".",
"module",
",",
"fb",
".",
"func",
".",
"__name__",
")",
",",
"file",
"=",
"self",
".",
"file",
")",
"print",
"(",
"'class = {}'",
".",
"fo... | 47.571429 | 21.095238 |
def _assemble_agent_str(agent):
"""Assemble an Agent object to text."""
agent_str = agent.name
# Only do the more detailed assembly for molecular agents
if not isinstance(agent, ist.Agent):
return agent_str
# Handle mutation conditions
if agent.mutations:
is_generic = False
... | [
"def",
"_assemble_agent_str",
"(",
"agent",
")",
":",
"agent_str",
"=",
"agent",
".",
"name",
"# Only do the more detailed assembly for molecular agents",
"if",
"not",
"isinstance",
"(",
"agent",
",",
"ist",
".",
"Agent",
")",
":",
"return",
"agent_str",
"# Handle m... | 38.010309 | 16.742268 |
def check_mods_docs_readme():
""" Check that all modules are listed in the YAML index
at the top of docs/README.md """
docs_mods = []
readme_fn = os.path.join( os.path.dirname(config.MULTIQC_DIR), 'docs', 'README.md')
if not os.path.isfile(readme_fn):
if os.environ.get('TRAVIS_BUILD_DIR') ... | [
"def",
"check_mods_docs_readme",
"(",
")",
":",
"docs_mods",
"=",
"[",
"]",
"readme_fn",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"config",
".",
"MULTIQC_DIR",
")",
",",
"'docs'",
",",
"'README.md'",
")",
"if",
... | 44.058824 | 22.911765 |
def closest_common_ancestor(self, other):
"""
Find the common ancestor between this history node and 'other'.
:param other: the PathHistory to find a common ancestor with.
:return: the common ancestor SimStateHistory, or None if there isn't one
"""
our_history_... | [
"def",
"closest_common_ancestor",
"(",
"self",
",",
"other",
")",
":",
"our_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"self",
")",
")",
"their_history_iter",
"=",
"reversed",
"(",
"HistoryIter",
"(",
"other",
")",
")",
"sofar",
"=",
"set",
"("... | 34.131579 | 15.973684 |
async def get_devices(self) -> List[Device]:
"""Get information about the users avaliable devices.
Returns
-------
devices : List[Device]
The devices the user has available.
"""
data = await self.http.available_devices()
return [Device(item) for item ... | [
"async",
"def",
"get_devices",
"(",
"self",
")",
"->",
"List",
"[",
"Device",
"]",
":",
"data",
"=",
"await",
"self",
".",
"http",
".",
"available_devices",
"(",
")",
"return",
"[",
"Device",
"(",
"item",
")",
"for",
"item",
"in",
"data",
"[",
"'devi... | 33 | 13.8 |
def ch_stop_time(self, *channels: List[Channel]) -> int:
"""Return maximum time of timeslots over all channels.
Args:
*channels: Channels over which to obtain stop time.
"""
intervals = list(itertools.chain(*(self._table[chan] for chan in channels
... | [
"def",
"ch_stop_time",
"(",
"self",
",",
"*",
"channels",
":",
"List",
"[",
"Channel",
"]",
")",
"->",
"int",
":",
"intervals",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"(",
"self",
".",
"_table",
"[",
"chan",
"]",
"for",
"chan",
"in"... | 41.363636 | 22 |
def get_variants(self, arch=None, types=None, recursive=False):
"""
Return all variants of given arch and types.
Supported variant types:
self - include the top-level ("self") variant as well
addon
variant
optional
"""
types = ... | [
"def",
"get_variants",
"(",
"self",
",",
"arch",
"=",
"None",
",",
"types",
"=",
"None",
",",
"recursive",
"=",
"False",
")",
":",
"types",
"=",
"types",
"or",
"[",
"]",
"result",
"=",
"[",
"]",
"if",
"\"self\"",
"in",
"types",
":",
"result",
".",
... | 31.259259 | 20.074074 |
def simulate(self, timepoints):
"""
Simulate initialised solver for the specified timepoints
:param timepoints: timepoints that will be returned from simulation
:return: a list of trajectories for each of the equations in the problem.
"""
solver = self._solver
la... | [
"def",
"simulate",
"(",
"self",
",",
"timepoints",
")",
":",
"solver",
"=",
"self",
".",
"_solver",
"last_timepoint",
"=",
"timepoints",
"[",
"-",
"1",
"]",
"try",
":",
"simulated_timepoints",
",",
"simulated_values",
"=",
"solver",
".",
"simulate",
"(",
"... | 42.703704 | 27.740741 |
def table_mask(self):
"""ndarray, True where table margin <= min_base_size, same shape as slice."""
margin = compress_pruned(
self._slice.margin(
axis=None,
weighted=False,
include_transforms_for_dims=self._hs_dims,
prune=self._... | [
"def",
"table_mask",
"(",
"self",
")",
":",
"margin",
"=",
"compress_pruned",
"(",
"self",
".",
"_slice",
".",
"margin",
"(",
"axis",
"=",
"None",
",",
"weighted",
"=",
"False",
",",
"include_transforms_for_dims",
"=",
"self",
".",
"_hs_dims",
",",
"prune"... | 36 | 20.35 |
def deep_merge(*args):
"""
>>> dbt.utils.deep_merge({'a': 1, 'b': 2, 'c': 3}, {'a': 2}, {'a': 3, 'b': 1}) # noqa
{'a': 3, 'b': 1, 'c': 3}
"""
if len(args) == 0:
return None
if len(args) == 1:
return copy.deepcopy(args[0])
lst = list(args)
last = copy.deepcopy(lst.pop(l... | [
"def",
"deep_merge",
"(",
"*",
"args",
")",
":",
"if",
"len",
"(",
"args",
")",
"==",
"0",
":",
"return",
"None",
"if",
"len",
"(",
"args",
")",
"==",
"1",
":",
"return",
"copy",
".",
"deepcopy",
"(",
"args",
"[",
"0",
"]",
")",
"lst",
"=",
"... | 24.466667 | 19.533333 |
def _render_attributes(self, resource):
"""Render the resources's attributes."""
attributes = {}
attrs_to_ignore = set()
for key, relationship in resource.__mapper__.relationships.items():
attrs_to_ignore.update(set(
[column.name for column in relationship.lo... | [
"def",
"_render_attributes",
"(",
"self",
",",
"resource",
")",
":",
"attributes",
"=",
"{",
"}",
"attrs_to_ignore",
"=",
"set",
"(",
")",
"for",
"key",
",",
"relationship",
"in",
"resource",
".",
"__mapper__",
".",
"relationships",
".",
"items",
"(",
")",... | 37.15625 | 18.65625 |
def _map_sextuple_to_phenotype(
self, superterm1_id, subterm1_id, quality_id, superterm2_id,
subterm2_id, modifier):
"""
This will take the 6-part EQ-style annotation
used by ZFIN and return the ZP id.
Currently relies on an external mapping file,
but the ... | [
"def",
"_map_sextuple_to_phenotype",
"(",
"self",
",",
"superterm1_id",
",",
"subterm1_id",
",",
"quality_id",
",",
"superterm2_id",
",",
"subterm2_id",
",",
"modifier",
")",
":",
"zp_id",
"=",
"None",
"# zfin uses free-text modifiers,",
"# but we need to convert them to ... | 33.727273 | 17.181818 |
def update_project(self, resource_name, resource):
"""
Updates an entity in the data model using the given resource.
Args:
resource_name (string): Current name of the resource (in case the
resource is getting its name changed).
resource (intern.resource.b... | [
"def",
"update_project",
"(",
"self",
",",
"resource_name",
",",
"resource",
")",
":",
"self",
".",
"project_service",
".",
"set_auth",
"(",
"self",
".",
"_token_project",
")",
"return",
"self",
".",
"project_service",
".",
"update",
"(",
"resource_name",
",",... | 36.947368 | 22 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.