text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def round(self, ndigits=0):
"""
Rounds the amount using the current ``Decimal`` rounding algorithm.
"""
if ndigits is None:
ndigits = 0
return self.__class__(
amount=self.amount.quantize(Decimal('1e' + str(-ndigits))),
currency=self.currency) | [
"def",
"round",
"(",
"self",
",",
"ndigits",
"=",
"0",
")",
":",
"if",
"ndigits",
"is",
"None",
":",
"ndigits",
"=",
"0",
"return",
"self",
".",
"__class__",
"(",
"amount",
"=",
"self",
".",
"amount",
".",
"quantize",
"(",
"Decimal",
"(",
"'1e'",
"... | 34.444444 | 13.777778 |
def _make_input(self, action, old_quat):
"""
Helper function that returns a dictionary with keys dpos, rotation from a raw input
array. The first three elements are taken to be displacement in position, and a
quaternion indicating the change in rotation with respect to @old_quat.
... | [
"def",
"_make_input",
"(",
"self",
",",
"action",
",",
"old_quat",
")",
":",
"return",
"{",
"\"dpos\"",
":",
"action",
"[",
":",
"3",
"]",
",",
"# IK controller takes an absolute orientation in robot base frame",
"\"rotation\"",
":",
"T",
".",
"quat2mat",
"(",
"... | 47.909091 | 24.818182 |
def bump(args: argparse.Namespace) -> None:
"""
:args: An argparse.Namespace object.
This function is bound to the 'bump' sub-command. It increments the version
integer of the user's choice ('major', 'minor', or 'patch').
"""
try:
last_tag = last_git_release_tag(git_tags())
except N... | [
"def",
"bump",
"(",
"args",
":",
"argparse",
".",
"Namespace",
")",
"->",
"None",
":",
"try",
":",
"last_tag",
"=",
"last_git_release_tag",
"(",
"git_tags",
"(",
")",
")",
"except",
"NoGitTagsException",
":",
"print",
"(",
"SemVer",
"(",
"0",
",",
"1",
... | 29.142857 | 15.238095 |
def stitch_block_rows(block_list):
'''
Stitches blocks together into a single block rowwise. These blocks are 2D tables usually
generated from tableproc. The final block will be of dimensions (sum(num_rows), max(num_cols)).
'''
stitched = list(itertools.chain(*block_list))
max_length = max... | [
"def",
"stitch_block_rows",
"(",
"block_list",
")",
":",
"stitched",
"=",
"list",
"(",
"itertools",
".",
"chain",
"(",
"*",
"block_list",
")",
")",
"max_length",
"=",
"max",
"(",
"len",
"(",
"row",
")",
"for",
"row",
"in",
"stitched",
")",
"for",
"row"... | 43.181818 | 23.363636 |
def load_stock_links(self):
""" Read stock links into the model """
links = self.__get_session().query(dal.AssetClassStock).all()
for entity in links:
# log(DEBUG, f"adding {entity.symbol} to {entity.assetclassid}")
# mapping
stock: Stock = Stock(entity.symbol... | [
"def",
"load_stock_links",
"(",
"self",
")",
":",
"links",
"=",
"self",
".",
"__get_session",
"(",
")",
".",
"query",
"(",
"dal",
".",
"AssetClassStock",
")",
".",
"all",
"(",
")",
"for",
"entity",
"in",
"links",
":",
"# log(DEBUG, f\"adding {entity.symbol} ... | 46.428571 | 15.5 |
def freeze(wait, force_kill):
'''Freeze manager.'''
if wait and force_kill:
print('You cannot use both --wait and --force-kill options '
'at the same time.', file=sys.stderr)
return
with Session() as session:
if wait:
while True:
resp = sess... | [
"def",
"freeze",
"(",
"wait",
",",
"force_kill",
")",
":",
"if",
"wait",
"and",
"force_kill",
":",
"print",
"(",
"'You cannot use both --wait and --force-kill options '",
"'at the same time.'",
",",
"file",
"=",
"sys",
".",
"stderr",
")",
"return",
"with",
"Sessio... | 32.892857 | 19.892857 |
def read_tx_body(ptr, tx):
"""
Returns {'ins': [...], 'outs': [...]}
"""
_obj = {"ins": [], "outs": [], 'locktime': None}
# number of inputs
ins = read_var_int(ptr, tx)
# all inputs
for i in range(ins):
_obj["ins"].append({
"outpoint": {
"hash": read... | [
"def",
"read_tx_body",
"(",
"ptr",
",",
"tx",
")",
":",
"_obj",
"=",
"{",
"\"ins\"",
":",
"[",
"]",
",",
"\"outs\"",
":",
"[",
"]",
",",
"'locktime'",
":",
"None",
"}",
"# number of inputs",
"ins",
"=",
"read_var_int",
"(",
"ptr",
",",
"tx",
")",
"... | 23.903226 | 17.83871 |
def _try_b32_decode(v):
"""
Attempt to decode a b32-encoded username which is sometimes generated by
internal Globus components.
The expectation is that the string is a valid ID, username, or b32-encoded
name. Therefore, we can do some simple checking on it.
If it does not appear to be formatt... | [
"def",
"_try_b32_decode",
"(",
"v",
")",
":",
"# should start with \"u_\"",
"if",
"not",
"v",
".",
"startswith",
"(",
"\"u_\"",
")",
":",
"return",
"None",
"# usernames have @ , we want to allow `u_foo@example.com`",
"# b32 names never have @",
"if",
"\"@\"",
"in",
"v",... | 28.40625 | 21.96875 |
def get_config_tuple_from_egrc(egrc_path):
"""
Create a Config named tuple from the values specified in the .egrc. Expands
any paths as necessary.
egrc_path must exist and point a file.
If not present in the .egrc, properties of the Config are returned as None.
"""
with open(egrc_path, 'r'... | [
"def",
"get_config_tuple_from_egrc",
"(",
"egrc_path",
")",
":",
"with",
"open",
"(",
"egrc_path",
",",
"'r'",
")",
"as",
"egrc",
":",
"try",
":",
"config",
"=",
"ConfigParser",
".",
"RawConfigParser",
"(",
")",
"except",
"AttributeError",
":",
"config",
"="... | 35.171875 | 20.921875 |
def tag_autocomplete_js(format_string=None):
"""format_string should be ``app_label model counts``
renders 'tagging_ext/tag_autocomplete_js.html"""
if format_string:
context_list = format_string.split(' ')
context = {
'app_label':context_list[0],'model':context_list[1], 'cou... | [
"def",
"tag_autocomplete_js",
"(",
"format_string",
"=",
"None",
")",
":",
"if",
"format_string",
":",
"context_list",
"=",
"format_string",
".",
"split",
"(",
"' '",
")",
"context",
"=",
"{",
"'app_label'",
":",
"context_list",
"[",
"0",
"]",
",",
"'model'"... | 37.583333 | 21.5 |
def compute_integrated_acquisition_withGradients(acquisition,x):
'''
Used to compute the acquisition function with gradients when samples of the hyper-parameters have been generated (used in GP_MCMC model).
:param acquisition: acquisition function with GpyOpt model type GP_MCMC.
:param x: location wher... | [
"def",
"compute_integrated_acquisition_withGradients",
"(",
"acquisition",
",",
"x",
")",
":",
"acqu_x",
"=",
"0",
"d_acqu_x",
"=",
"0",
"for",
"i",
"in",
"range",
"(",
"acquisition",
".",
"model",
".",
"num_hmc_samples",
")",
":",
"acquisition",
".",
"model",... | 38.380952 | 31.047619 |
def _render_item(self, depth, key, value = None, **settings):
"""
Format single list item.
"""
strptrn = self.INDENT * depth
lchar = self.lchar(settings[self.SETTING_LIST_STYLE])
s = self._es_text(settings, settings[self.SETTING_LIST_FORMATING])
lchar = self.fmt... | [
"def",
"_render_item",
"(",
"self",
",",
"depth",
",",
"key",
",",
"value",
"=",
"None",
",",
"*",
"*",
"settings",
")",
":",
"strptrn",
"=",
"self",
".",
"INDENT",
"*",
"depth",
"lchar",
"=",
"self",
".",
"lchar",
"(",
"settings",
"[",
"self",
"."... | 36.235294 | 19.647059 |
def _expand_formula_(formula_string):
"""
Accounts for the many ways a user may write a formula string, and returns an expanded chemical formula string.
Assumptions:
-The Chemical Formula string it is supplied is well-written, and has no hanging parethneses
-The number of repeats occurs after the el... | [
"def",
"_expand_formula_",
"(",
"formula_string",
")",
":",
"formula_string",
"=",
"re",
".",
"sub",
"(",
"r'[^A-Za-z0-9\\(\\)\\[\\]\\·\\.]+',",
" ",
"',",
" ",
"ormula_string)",
"",
"hydrate_pos",
"=",
"formula_string",
".",
"find",
"(",
"'·')",
"",
"if",
"hydr... | 44.94 | 15.78 |
def run_location(self, value):
"""The run_location property.
Args:
value (string). the property value.
"""
if value == self._defaults['runLocation'] and 'runLocation' in self._values:
del self._values['runLocation']
else:
self._values[... | [
"def",
"run_location",
"(",
"self",
",",
"value",
")",
":",
"if",
"value",
"==",
"self",
".",
"_defaults",
"[",
"'runLocation'",
"]",
"and",
"'runLocation'",
"in",
"self",
".",
"_values",
":",
"del",
"self",
".",
"_values",
"[",
"'runLocation'",
"]",
"el... | 33.3 | 15.7 |
def compute_file_hashes(file_path, hashes=frozenset(['md5'])):
"""
Digests data read from file denoted by file_path.
"""
if not os.path.exists(file_path):
logging.warning("%s does not exist" % file_path)
return
else:
logging.debug("Computing [%s] hashes for file [%s]" % ('... | [
"def",
"compute_file_hashes",
"(",
"file_path",
",",
"hashes",
"=",
"frozenset",
"(",
"[",
"'md5'",
"]",
")",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"logging",
".",
"warning",
"(",
"\"%s does not exist\"",
"%... | 36.25 | 20.875 |
def refresh_products(self, **kwargs):
"""
Refresh a product's cached info. Basically calls product_get
with the passed arguments, and tries to intelligently update
our product cache.
For example, if we already have cached info for product=foo,
and you pass in names=["bar... | [
"def",
"refresh_products",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"for",
"product",
"in",
"self",
".",
"product_get",
"(",
"*",
"*",
"kwargs",
")",
":",
"updated",
"=",
"False",
"for",
"current",
"in",
"self",
".",
"_cache",
".",
"products",
... | 40.217391 | 18.652174 |
def set_result(self, job_id, result):
"""Set the result for a job.
This will overwrite any existing results for the job.
Args:
job_id: The ID of the WorkItem to set the result for.
result: A WorkResult indicating the result of the job.
Raises:
KeyError: ... | [
"def",
"set_result",
"(",
"self",
",",
"job_id",
",",
"result",
")",
":",
"with",
"self",
".",
"_conn",
":",
"try",
":",
"self",
".",
"_conn",
".",
"execute",
"(",
"'''\n REPLACE INTO results\n VALUES (?, ?, ?, ?, ?)\n ... | 35 | 18.318182 |
def ethnicities_clean():
""" Get dictionary of unformatted ethnicity types mapped to clean corresponding ethnicity strings """
eths_clean = {}
fname = pkg_resources.resource_filename(__name__, 'resources/Ethnicity_Groups.csv')
with open(fname, 'rU') as csvfile:
reader = csv.reader(csvfile, delimiter = ',')... | [
"def",
"ethnicities_clean",
"(",
")",
":",
"eths_clean",
"=",
"{",
"}",
"fname",
"=",
"pkg_resources",
".",
"resource_filename",
"(",
"__name__",
",",
"'resources/Ethnicity_Groups.csv'",
")",
"with",
"open",
"(",
"fname",
",",
"'rU'",
")",
"as",
"csvfile",
":"... | 32.411765 | 17.764706 |
def generate_table_from(data):
"Output a nicely formatted ascii table"
table = Texttable(max_width=120)
table.add_row(["view", "method", "status", "count", "minimum", "maximum", "mean", "stdev", "queries", "querytime"])
table.set_cols_align(["l", "l", "l", "r", "r", "r", "r", "r", "r", "r"])
for i... | [
"def",
"generate_table_from",
"(",
"data",
")",
":",
"table",
"=",
"Texttable",
"(",
"max_width",
"=",
"120",
")",
"table",
".",
"add_row",
"(",
"[",
"\"view\"",
",",
"\"method\"",
",",
"\"status\"",
",",
"\"count\"",
",",
"\"minimum\"",
",",
"\"maximum\"",
... | 46.565217 | 31.173913 |
def appliance_time_and_locale_configuration(self):
"""
Gets the ApplianceTimeAndLocaleConfiguration API client.
Returns:
ApplianceTimeAndLocaleConfiguration:
"""
if not self.__appliance_time_and_locale_configuration:
self.__appliance_time_and_locale_confi... | [
"def",
"appliance_time_and_locale_configuration",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"__appliance_time_and_locale_configuration",
":",
"self",
".",
"__appliance_time_and_locale_configuration",
"=",
"ApplianceTimeAndLocaleConfiguration",
"(",
"self",
".",
"__conn... | 43.8 | 22.4 |
def tagReportCallback(llrpMsg):
"""Function to run each time the reader reports seeing tags."""
global tagReport
tags = llrpMsg.msgdict['RO_ACCESS_REPORT']['TagReportData']
if len(tags):
logger.info('saw tag(s): %s', pprint.pformat(tags))
else:
logger.info('no tags seen')
ret... | [
"def",
"tagReportCallback",
"(",
"llrpMsg",
")",
":",
"global",
"tagReport",
"tags",
"=",
"llrpMsg",
".",
"msgdict",
"[",
"'RO_ACCESS_REPORT'",
"]",
"[",
"'TagReportData'",
"]",
"if",
"len",
"(",
"tags",
")",
":",
"logger",
".",
"info",
"(",
"'saw tag(s): %s... | 40.15 | 16.8 |
def _get_deltas(self, rake):
"""
Return the value of deltas (delta_R, delta_S, delta_V, delta_I),
as defined in "Table 5: Model 1" pag 198
"""
# delta_R = 1 for reverse focal mechanism (45<rake<135)
# and for interface events, 0 for all other events
# delta_S = 1 ... | [
"def",
"_get_deltas",
"(",
"self",
",",
"rake",
")",
":",
"# delta_R = 1 for reverse focal mechanism (45<rake<135)",
"# and for interface events, 0 for all other events",
"# delta_S = 1 for Strike-slip focal mechanisms (0<=rake<=45) or",
"# (135<=rake<=180) or (-45<=rake<=0), 0 for all other e... | 36.925926 | 18.62963 |
def minimize_matrix(self):
"""
This method finds and returns the permutations that produce the lowest
ewald sum calls recursive function to iterate through permutations
"""
if self._algo == EwaldMinimizer.ALGO_FAST or \
self._algo == EwaldMinimizer.ALGO_BE... | [
"def",
"minimize_matrix",
"(",
"self",
")",
":",
"if",
"self",
".",
"_algo",
"==",
"EwaldMinimizer",
".",
"ALGO_FAST",
"or",
"self",
".",
"_algo",
"==",
"EwaldMinimizer",
".",
"ALGO_BEST_FIRST",
":",
"return",
"self",
".",
"_recurse",
"(",
"self",
".",
"_m... | 49.555556 | 19.111111 |
def save_as_plt(self, fname, pixel_array=None, vmin=None, vmax=None,
cmap=None, format=None, origin=None):
""" This method saves the image from a numpy array using matplotlib
:param fname: Location and name of the image file to be saved.
:param pixel_array: Numpy pixel array, i.e. ``num... | [
"def",
"save_as_plt",
"(",
"self",
",",
"fname",
",",
"pixel_array",
"=",
"None",
",",
"vmin",
"=",
"None",
",",
"vmax",
"=",
"None",
",",
"cmap",
"=",
"None",
",",
"format",
"=",
"None",
",",
"origin",
"=",
"None",
")",
":",
"from",
"matplotlib",
... | 37.9 | 14.566667 |
def process_full_position(data, header, var_only=False):
"""
Return genetic data when all alleles called on same line.
Returns an array containing one item, a tuple of five items:
(string) chromosome
(string) start position (1-based)
(array of strings) matching dbSNP entries
... | [
"def",
"process_full_position",
"(",
"data",
",",
"header",
",",
"var_only",
"=",
"False",
")",
":",
"feature_type",
"=",
"data",
"[",
"header",
"[",
"'varType'",
"]",
"]",
"# Skip unmatchable, uncovered, or pseudoautosomal-in-X",
"if",
"(",
"feature_type",
"==",
... | 37.056604 | 12.264151 |
def diff_aff(self):
"""Symmetric diffusion affinity matrix
Return or calculate the symmetric diffusion affinity matrix
.. math:: A(x,y) = K(x,y) (d(x) d(y))^{-1/2}
where :math:`d` is the degrees (row sums of the kernel.)
Returns
-------
diff_aff : array-like,... | [
"def",
"diff_aff",
"(",
"self",
")",
":",
"row_degrees",
"=",
"np",
".",
"array",
"(",
"self",
".",
"kernel",
".",
"sum",
"(",
"axis",
"=",
"1",
")",
")",
".",
"reshape",
"(",
"-",
"1",
",",
"1",
")",
"col_degrees",
"=",
"np",
".",
"array",
"("... | 36.956522 | 23.869565 |
def seed_url(self):
"""A URL that can be used to open the page.
The URL is formatted from :py:attr:`URL_TEMPLATE`, which is then
appended to :py:attr:`base_url` unless the template results in an
absolute URL.
:return: URL that can be used to open the page.
:rtype: str
... | [
"def",
"seed_url",
"(",
"self",
")",
":",
"url",
"=",
"self",
".",
"base_url",
"if",
"self",
".",
"URL_TEMPLATE",
"is",
"not",
"None",
":",
"url",
"=",
"urlparse",
".",
"urljoin",
"(",
"self",
".",
"base_url",
",",
"self",
".",
"URL_TEMPLATE",
".",
"... | 30.21875 | 19.46875 |
def main(*argv):
""" main driver of program """
try:
adminUsername = argv[0]
adminPassword = argv[1]
siteURL = argv[2]
username = argv[3]
groupName = argv[4]
# Logic
#
# Connect to AGOL
#
sh = arcrest.AGOLTokenSecurityHandler(ad... | [
"def",
"main",
"(",
"*",
"argv",
")",
":",
"try",
":",
"adminUsername",
"=",
"argv",
"[",
"0",
"]",
"adminPassword",
"=",
"argv",
"[",
"1",
"]",
"siteURL",
"=",
"argv",
"[",
"2",
"]",
"username",
"=",
"argv",
"[",
"3",
"]",
"groupName",
"=",
"arg... | 40.272727 | 18.181818 |
def rows(self):
"""
Return/yield tuples or lists corresponding to each row to be inserted.
"""
with self.input().open('r') as fobj:
for line in fobj:
yield line.strip('\n').split('\t') | [
"def",
"rows",
"(",
"self",
")",
":",
"with",
"self",
".",
"input",
"(",
")",
".",
"open",
"(",
"'r'",
")",
"as",
"fobj",
":",
"for",
"line",
"in",
"fobj",
":",
"yield",
"line",
".",
"strip",
"(",
"'\\n'",
")",
".",
"split",
"(",
"'\\t'",
")"
] | 34 | 12.571429 |
def move_up(self):
"""Move up one level in the hierarchy, unless already on top."""
if self.current_item.parent is not None:
self.current_item = self.current_item.parent
for f in self._hooks["up"]:
f(self)
if self.current_item is self.root:
for f in s... | [
"def",
"move_up",
"(",
"self",
")",
":",
"if",
"self",
".",
"current_item",
".",
"parent",
"is",
"not",
"None",
":",
"self",
".",
"current_item",
"=",
"self",
".",
"current_item",
".",
"parent",
"for",
"f",
"in",
"self",
".",
"_hooks",
"[",
"\"up\"",
... | 33.818182 | 13.818182 |
def get_time_index_range(self,
date_search_start=None,
date_search_end=None,
time_index_start=None,
time_index_end=None,
time_index=None):
"""
Generates a time... | [
"def",
"get_time_index_range",
"(",
"self",
",",
"date_search_start",
"=",
"None",
",",
"date_search_end",
"=",
"None",
",",
"time_index_start",
"=",
"None",
",",
"time_index_end",
"=",
"None",
",",
"time_index",
"=",
"None",
")",
":",
"# get the range of time bas... | 40.94958 | 20.563025 |
def deploy_app(self, site_folder, runtime_type=''):
''' a method to deploy a static html page to heroku using php '''
title = '%s.deploy_php' % self.__class__.__name__
# validate inputs
input_fields = {
'site_folder': site_folder,
'runtime_type': runtime_t... | [
"def",
"deploy_app",
"(",
"self",
",",
"site_folder",
",",
"runtime_type",
"=",
"''",
")",
":",
"title",
"=",
"'%s.deploy_php'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"# validate inputs\r",
"input_fields",
"=",
"{",
"'site_folder'",
":",
"site_folder",... | 41.958333 | 20.275 |
def resample(self, indexer: Optional[Mapping[Hashable, str]] = None,
skipna=None, closed: Optional[str] = None,
label: Optional[str] = None,
base: int = 0, keep_attrs: Optional[bool] = None,
loffset=None,
**indexer_kwargs: str):
... | [
"def",
"resample",
"(",
"self",
",",
"indexer",
":",
"Optional",
"[",
"Mapping",
"[",
"Hashable",
",",
"str",
"]",
"]",
"=",
"None",
",",
"skipna",
"=",
"None",
",",
"closed",
":",
"Optional",
"[",
"str",
"]",
"=",
"None",
",",
"label",
":",
"Optio... | 43.129032 | 22.072581 |
def stop_button_click_handler(self):
"""Method to handle what to do when the stop button is pressed"""
self.stop_button.setDisabled(True)
# Interrupt computations or stop debugging
if not self.shellwidget._reading:
self.interrupt_kernel()
else:
self... | [
"def",
"stop_button_click_handler",
"(",
"self",
")",
":",
"self",
".",
"stop_button",
".",
"setDisabled",
"(",
"True",
")",
"# Interrupt computations or stop debugging\r",
"if",
"not",
"self",
".",
"shellwidget",
".",
"_reading",
":",
"self",
".",
"interrupt_kernel... | 43.5 | 7.5 |
def follow(self, login):
"""Make the authenticated user follow login.
:param str login: (required), user to follow
:returns: bool
"""
resp = False
if login:
url = self._build_url('user', 'following', login)
resp = self._boolean(self._put(url), 204... | [
"def",
"follow",
"(",
"self",
",",
"login",
")",
":",
"resp",
"=",
"False",
"if",
"login",
":",
"url",
"=",
"self",
".",
"_build_url",
"(",
"'user'",
",",
"'following'",
",",
"login",
")",
"resp",
"=",
"self",
".",
"_boolean",
"(",
"self",
".",
"_p... | 30.545455 | 17.181818 |
def create_metric_definition(self, metric_type, metric_id, **tags):
"""
Create metric definition with custom definition. **tags should be a set of tags, such as
units, env ..
:param metric_type: MetricType of the new definition
:param metric_id: metric_id is the string index of ... | [
"def",
"create_metric_definition",
"(",
"self",
",",
"metric_type",
",",
"metric_id",
",",
"*",
"*",
"tags",
")",
":",
"item",
"=",
"{",
"'id'",
":",
"metric_id",
"}",
"if",
"len",
"(",
"tags",
")",
">",
"0",
":",
"# We have some arguments to pass..",
"dat... | 34.821429 | 19.392857 |
def set(self, key: Any, value: Any) -> None:
""" Sets the value of a key to a supplied value """
if key is not None:
self[key] = value | [
"def",
"set",
"(",
"self",
",",
"key",
":",
"Any",
",",
"value",
":",
"Any",
")",
"->",
"None",
":",
"if",
"key",
"is",
"not",
"None",
":",
"self",
"[",
"key",
"]",
"=",
"value"
] | 39.75 | 7 |
async def send_heartbeat(self, name):
"""Send a heartbeat for a service.
Args:
name (string): The name of the service to send a heartbeat for
"""
await self.send_command(OPERATIONS.CMD_HEARTBEAT, {'name': name},
MESSAGES.HeartbeatResponse, ti... | [
"async",
"def",
"send_heartbeat",
"(",
"self",
",",
"name",
")",
":",
"await",
"self",
".",
"send_command",
"(",
"OPERATIONS",
".",
"CMD_HEARTBEAT",
",",
"{",
"'name'",
":",
"name",
"}",
",",
"MESSAGES",
".",
"HeartbeatResponse",
",",
"timeout",
"=",
"5.0"... | 35.777778 | 23.222222 |
def _brahmic(data, scheme_map, **kw):
"""Transliterate `data` with the given `scheme_map`. This function is used
when the source scheme is a Brahmic scheme.
:param data: the data to transliterate
:param scheme_map: a dict that maps between characters in the old scheme
and characters in the... | [
"def",
"_brahmic",
"(",
"data",
",",
"scheme_map",
",",
"*",
"*",
"kw",
")",
":",
"if",
"scheme_map",
".",
"from_scheme",
".",
"name",
"==",
"northern",
".",
"GURMUKHI",
":",
"data",
"=",
"northern",
".",
"GurmukhiScheme",
".",
"replace_tippi",
"(",
"tex... | 34.064103 | 20.871795 |
def p_CommentOrEmptyLineList(p):
'''
CommentOrEmptyLineList :
| CommentOrEmptyLine
| CommentOrEmptyLineList CommentOrEmptyLine
'''
if len(p) <= 1:
p[0] = CommentOrEmptyLineList(None, None)
elif len(p) <= 2:
p[0] = CommentOrEmptyL... | [
"def",
"p_CommentOrEmptyLineList",
"(",
"p",
")",
":",
"if",
"len",
"(",
"p",
")",
"<=",
"1",
":",
"p",
"[",
"0",
"]",
"=",
"CommentOrEmptyLineList",
"(",
"None",
",",
"None",
")",
"elif",
"len",
"(",
"p",
")",
"<=",
"2",
":",
"p",
"[",
"0",
"]... | 32.333333 | 18.5 |
def _compute_projection(self, X, W):
"""Compute the LPP projection matrix
Parameters
----------
X : array_like, (n_samples, n_features)
The input data
W : array_like or sparse matrix, (n_samples, n_samples)
The precomputed adjacency matrix
Return... | [
"def",
"_compute_projection",
"(",
"self",
",",
"X",
",",
"W",
")",
":",
"# TODO: check W input; handle sparse case",
"X",
"=",
"check_array",
"(",
"X",
")",
"D",
"=",
"np",
".",
"diag",
"(",
"W",
".",
"sum",
"(",
"1",
")",
")",
"L",
"=",
"D",
"-",
... | 32.833333 | 18.875 |
def start_event_loop_qt4(app=None):
"""Start the qt4 event loop in a consistent manner."""
if app is None:
app = get_app_qt4([''])
if not is_event_loop_running_qt4(app):
app._in_event_loop = True
app.exec_()
app._in_event_loop = False
else:
app._in_event_loop = Tr... | [
"def",
"start_event_loop_qt4",
"(",
"app",
"=",
"None",
")",
":",
"if",
"app",
"is",
"None",
":",
"app",
"=",
"get_app_qt4",
"(",
"[",
"''",
"]",
")",
"if",
"not",
"is_event_loop_running_qt4",
"(",
"app",
")",
":",
"app",
".",
"_in_event_loop",
"=",
"T... | 31.3 | 10.9 |
def focusOutEvent( self, event ):
"""
Overloads the focus out event to cancel editing when the widget loses
focus.
:param event | <QFocusEvent>
"""
super(XNavigationEdit, self).focusOutEvent(event)
self.cancelEdit() | [
"def",
"focusOutEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"XNavigationEdit",
",",
"self",
")",
".",
"focusOutEvent",
"(",
"event",
")",
"self",
".",
"cancelEdit",
"(",
")"
] | 28.5 | 16.7 |
def updateCurrentValue(self, value):
"""
Disables snapping during the current value update to ensure a smooth
transition for node animations. Since this can only be called via
code, we don't need to worry about snapping to the grid for a user.
"""
xsnap = None
ys... | [
"def",
"updateCurrentValue",
"(",
"self",
",",
"value",
")",
":",
"xsnap",
"=",
"None",
"ysnap",
"=",
"None",
"if",
"value",
"!=",
"self",
".",
"endValue",
"(",
")",
":",
"xsnap",
"=",
"self",
".",
"targetObject",
"(",
")",
".",
"isXSnappedToGrid",
"("... | 39.047619 | 18.571429 |
def get_votes_comment(self, *args, **kwargs):
""" :allowed_param: 'commentId'
"""
return bind_api(
api=self,
path='/comments/{commentId}/votes',
payload_type='vote',
payload_list=True,
allowed_param=['commentId']
)(*args, **kwar... | [
"def",
"get_votes_comment",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"bind_api",
"(",
"api",
"=",
"self",
",",
"path",
"=",
"'/comments/{commentId}/votes'",
",",
"payload_type",
"=",
"'vote'",
",",
"payload_list",
"=",
"T... | 31.4 | 8 |
def pec(self, value):
"""True if Packet Error Codes (PEC) are enabled"""
pec = bool(value)
if pec != self._pec:
if ioctl(self._fd, SMBUS.I2C_PEC, pec):
raise IOError(ffi.errno)
self._pec = pec | [
"def",
"pec",
"(",
"self",
",",
"value",
")",
":",
"pec",
"=",
"bool",
"(",
"value",
")",
"if",
"pec",
"!=",
"self",
".",
"_pec",
":",
"if",
"ioctl",
"(",
"self",
".",
"_fd",
",",
"SMBUS",
".",
"I2C_PEC",
",",
"pec",
")",
":",
"raise",
"IOError... | 35.714286 | 10 |
def other_set_producer(socket, which_set, image_archive, patch_archive,
groundtruth):
"""Push image files read from the valid/test set TAR to a socket.
Parameters
----------
socket : :class:`zmq.Socket`
PUSH socket on which to send images.
which_set : str
Whic... | [
"def",
"other_set_producer",
"(",
"socket",
",",
"which_set",
",",
"image_archive",
",",
"patch_archive",
",",
"groundtruth",
")",
":",
"patch_images",
"=",
"extract_patch_images",
"(",
"patch_archive",
",",
"which_set",
")",
"num_patched",
"=",
"0",
"with",
"tar_... | 44.111111 | 19.333333 |
def fill_key_info(self, key_info, signature_method):
"""
Fills the KeyInfo node
:param key_info: KeyInfo node
:type key_info: lxml.etree.Element
:param signature_method: Signature node to use
:type signature_method: str
:return: None
"""
x509_data... | [
"def",
"fill_key_info",
"(",
"self",
",",
"key_info",
",",
"signature_method",
")",
":",
"x509_data",
"=",
"key_info",
".",
"find",
"(",
"'ds:X509Data'",
",",
"namespaces",
"=",
"constants",
".",
"NS_MAP",
")",
"if",
"x509_data",
"is",
"not",
"None",
":",
... | 42.62069 | 14 |
def kill(self, unique_id, configs=None):
""" Issues a kill -9 to the specified process
calls the deployers get_pid function for the process. If no pid_file/pid_keyword is specified
a generic grep of ps aux command is executed on remote machine based on process parameters
which may not be reliable if mor... | [
"def",
"kill",
"(",
"self",
",",
"unique_id",
",",
"configs",
"=",
"None",
")",
":",
"self",
".",
"_send_signal",
"(",
"unique_id",
",",
"signal",
".",
"SIGKILL",
",",
"configs",
")"
] | 52 | 23.555556 |
def fit(self, values, bins):
"""
Fit the transform using the given values (in our case ic50s).
Parameters
----------
values : ic50 values
bins : bins for the cumulative distribution function
Anything that can be passed to numpy.histogram's "bins" argument
... | [
"def",
"fit",
"(",
"self",
",",
"values",
",",
"bins",
")",
":",
"assert",
"self",
".",
"cdf",
"is",
"None",
"assert",
"self",
".",
"bin_edges",
"is",
"None",
"assert",
"len",
"(",
"values",
")",
">",
"0",
"(",
"hist",
",",
"self",
".",
"bin_edges"... | 36.428571 | 16.619048 |
def to_glyphs_background_image(self, ufo_glyph, layer):
"""Copy the background image from the UFO Glyph to the GSLayer."""
ufo_image = ufo_glyph.image
if ufo_image.fileName is None:
return
image = self.glyphs_module.GSBackgroundImage()
image.path = ufo_image.fileName
image.transform = Tr... | [
"def",
"to_glyphs_background_image",
"(",
"self",
",",
"ufo_glyph",
",",
"layer",
")",
":",
"ufo_image",
"=",
"ufo_glyph",
".",
"image",
"if",
"ufo_image",
".",
"fileName",
"is",
"None",
":",
"return",
"image",
"=",
"self",
".",
"glyphs_module",
".",
"GSBack... | 41.875 | 8.875 |
def items(self, folder_id, subfolder_id, ann_id=None):
'''Yields an unodered generator of items in a subfolder.
The generator yields items, which are represented by a tuple
of ``content_id`` and ``subtopic_id``. The format of these
identifiers is unspecified.
By default (with `... | [
"def",
"items",
"(",
"self",
",",
"folder_id",
",",
"subfolder_id",
",",
"ann_id",
"=",
"None",
")",
":",
"self",
".",
"assert_valid_folder_id",
"(",
"folder_id",
")",
"self",
".",
"assert_valid_folder_id",
"(",
"subfolder_id",
")",
"ann_id",
"=",
"self",
".... | 43.413793 | 18.172414 |
def from_json(json):
"""Creates a Track from a JSON file.
No preprocessing is done.
Arguments:
json: map with the keys: name (optional) and segments.
Return:
A track instance
"""
segments = [Segment.from_json(s) for s in json['segments']]
... | [
"def",
"from_json",
"(",
"json",
")",
":",
"segments",
"=",
"[",
"Segment",
".",
"from_json",
"(",
"s",
")",
"for",
"s",
"in",
"json",
"[",
"'segments'",
"]",
"]",
"return",
"Track",
"(",
"json",
"[",
"'name'",
"]",
",",
"segments",
")",
".",
"comp... | 30.333333 | 20.083333 |
def phrase_replace(self, replace_dict):
"""
Replace phrases with single token, mapping defined in replace_dict
"""
def r(tokens):
text = ' ' + ' '.join(tokens)
for k, v in replace_dict.items():
text = text.replace(... | [
"def",
"phrase_replace",
"(",
"self",
",",
"replace_dict",
")",
":",
"def",
"r",
"(",
"tokens",
")",
":",
"text",
"=",
"' '",
"+",
"' '",
".",
"join",
"(",
"tokens",
")",
"for",
"k",
",",
"v",
"in",
"replace_dict",
".",
"items",
"(",
")",
":",
"t... | 35 | 17.166667 |
def unexpanduser(path):
r"""
Replaces home directory with '~'
"""
homedir = expanduser('~')
if path.startswith(homedir):
path = '~' + path[len(homedir):]
return path | [
"def",
"unexpanduser",
"(",
"path",
")",
":",
"homedir",
"=",
"expanduser",
"(",
"'~'",
")",
"if",
"path",
".",
"startswith",
"(",
"homedir",
")",
":",
"path",
"=",
"'~'",
"+",
"path",
"[",
"len",
"(",
"homedir",
")",
":",
"]",
"return",
"path"
] | 23.75 | 8.125 |
def load_segment(self, f, is_irom_segment=False):
""" Load the next segment from the image file """
file_offs = f.tell()
(offset, size) = struct.unpack('<II', f.read(8))
self.warn_if_unusual_segment(offset, size, is_irom_segment)
segment_data = f.read(size)
if len(segment... | [
"def",
"load_segment",
"(",
"self",
",",
"f",
",",
"is_irom_segment",
"=",
"False",
")",
":",
"file_offs",
"=",
"f",
".",
"tell",
"(",
")",
"(",
"offset",
",",
"size",
")",
"=",
"struct",
".",
"unpack",
"(",
"'<II'",
",",
"f",
".",
"read",
"(",
"... | 52.727273 | 18.818182 |
def load_values(self):
"""
Go through the env var map, transferring the values to this object
as attributes.
:raises: RuntimeError if a required env var isn't defined.
"""
for config_name, evar in self.evar_defs.items():
if evar.is_required and evar.name not... | [
"def",
"load_values",
"(",
"self",
")",
":",
"for",
"config_name",
",",
"evar",
"in",
"self",
".",
"evar_defs",
".",
"items",
"(",
")",
":",
"if",
"evar",
".",
"is_required",
"and",
"evar",
".",
"name",
"not",
"in",
"os",
".",
"environ",
":",
"raise"... | 43.703704 | 18.222222 |
def _dispense_during_transfer(self, vol, loc, **kwargs):
"""
Performs a :any:`dispense` when running a :any:`transfer`, and
optionally a :any:`mix`, :any:`touch_tip`, and/or
:any:`blow_out` afterwards.
"""
mix_after = kwargs.get('mix_after', (0, 0))
rate = kwargs.... | [
"def",
"_dispense_during_transfer",
"(",
"self",
",",
"vol",
",",
"loc",
",",
"*",
"*",
"kwargs",
")",
":",
"mix_after",
"=",
"kwargs",
".",
"get",
"(",
"'mix_after'",
",",
"(",
"0",
",",
"0",
")",
")",
"rate",
"=",
"kwargs",
".",
"get",
"(",
"'rat... | 36.625 | 14.25 |
def cred_def_id(self, issuer_did: str, schema_seq_no: int) -> str:
"""
Return credential definition identifier for input issuer DID and schema sequence number.
:param issuer_did: DID of credential definition issuer
:param schema_seq_no: schema sequence number
:return: credential... | [
"def",
"cred_def_id",
"(",
"self",
",",
"issuer_did",
":",
"str",
",",
"schema_seq_no",
":",
"int",
")",
"->",
"str",
":",
"return",
"'{}:3:CL:{}{}'",
".",
"format",
"(",
"# 3 marks indy cred def id, CL is sig type",
"issuer_did",
",",
"schema_seq_no",
",",
"self"... | 39.230769 | 21.846154 |
def apply_attribute(node: Node, attr: XmlAttr):
"""Maps xml attribute to instance node property and setups bindings"""
setter = get_setter(attr)
stripped_value = attr.value.strip() if attr.value else ''
if is_expression(stripped_value):
(binding_type, expr_body) = parse_expression(stripped_value... | [
"def",
"apply_attribute",
"(",
"node",
":",
"Node",
",",
"attr",
":",
"XmlAttr",
")",
":",
"setter",
"=",
"get_setter",
"(",
"attr",
")",
"stripped_value",
"=",
"attr",
".",
"value",
".",
"strip",
"(",
")",
"if",
"attr",
".",
"value",
"else",
"''",
"... | 51.555556 | 17.777778 |
def check_auth(user):
'''
Check if the user should or shouldn't be inside the system:
- If the user is staff or superuser: LOGIN GRANTED
- If the user has a Person and it is not "disabled": LOGIN GRANTED
- Elsewhere: LOGIN DENIED
'''
# Initialize authentication
auth = None
person = ... | [
"def",
"check_auth",
"(",
"user",
")",
":",
"# Initialize authentication",
"auth",
"=",
"None",
"person",
"=",
"None",
"# Check if there is an user",
"if",
"user",
":",
"# It means that Django accepted the user and it is active",
"if",
"user",
".",
"is_staff",
"or",
"us... | 34.472222 | 22.138889 |
def _create_array(self, arr: np.ndarray) -> int:
"""Returns the handle of a RawArray created from the given numpy array.
Args:
arr: A numpy ndarray.
Returns:
The handle (int) of the array.
Raises:
ValueError: if arr is not a ndarray or of an unsupported d... | [
"def",
"_create_array",
"(",
"self",
",",
"arr",
":",
"np",
".",
"ndarray",
")",
"->",
"int",
":",
"if",
"not",
"isinstance",
"(",
"arr",
",",
"np",
".",
"ndarray",
")",
":",
"raise",
"ValueError",
"(",
"'Array is not a numpy ndarray.'",
")",
"try",
":",... | 34.358974 | 21.333333 |
def collapse_focussed(self):
"""
Collapse currently focussed position; works only if the underlying
tree allows it.
"""
if implementsCollapseAPI(self._tree):
w, focuspos = self.get_focus()
self._tree.collapse(focuspos)
self._walker.clear_cache(... | [
"def",
"collapse_focussed",
"(",
"self",
")",
":",
"if",
"implementsCollapseAPI",
"(",
"self",
".",
"_tree",
")",
":",
"w",
",",
"focuspos",
"=",
"self",
".",
"get_focus",
"(",
")",
"self",
".",
"_tree",
".",
"collapse",
"(",
"focuspos",
")",
"self",
"... | 33.9 | 8.7 |
def _send_bootstrap_request(self, request):
"""Make a request using an ephemeral broker connection
This routine is used to make broker-unaware requests to get the initial
cluster metadata. It cycles through the configured hosts, trying to
connect and send the request to each in turn. Th... | [
"def",
"_send_bootstrap_request",
"(",
"self",
",",
"request",
")",
":",
"hostports",
"=",
"list",
"(",
"self",
".",
"_bootstrap_hosts",
")",
"random",
".",
"shuffle",
"(",
"hostports",
")",
"for",
"host",
",",
"port",
"in",
"hostports",
":",
"ep",
"=",
... | 43.479167 | 26.25 |
def filter(self, dict_name, priority_min='-inf', priority_max='+inf',
start=0, limit=None):
'''Get a subset of a dictionary.
This retrieves only keys with priority scores greater than or
equal to `priority_min` and less than or equal to `priority_max`.
Of those keys, it s... | [
"def",
"filter",
"(",
"self",
",",
"dict_name",
",",
"priority_min",
"=",
"'-inf'",
",",
"priority_max",
"=",
"'+inf'",
",",
"start",
"=",
"0",
",",
"limit",
"=",
"None",
")",
":",
"conn",
"=",
"redis",
".",
"Redis",
"(",
"connection_pool",
"=",
"self"... | 41.5 | 21.558824 |
def clip(dataset, normal='x', origin=None, invert=True):
"""
Clip a dataset by a plane by specifying the origin and normal. If no
parameters are given the clip will occur in the center of that dataset
Parameters
----------
normal : tuple(float) or str
Length ... | [
"def",
"clip",
"(",
"dataset",
",",
"normal",
"=",
"'x'",
",",
"origin",
"=",
"None",
",",
"invert",
"=",
"True",
")",
":",
"if",
"isinstance",
"(",
"normal",
",",
"str",
")",
":",
"normal",
"=",
"NORMALS",
"[",
"normal",
".",
"lower",
"(",
")",
... | 39.029412 | 19.558824 |
def has_space(self, length=1, offset=0):
"""Returns boolean if self.pos + length < working string length."""
return self.pos + (length + offset) - 1 < self.length | [
"def",
"has_space",
"(",
"self",
",",
"length",
"=",
"1",
",",
"offset",
"=",
"0",
")",
":",
"return",
"self",
".",
"pos",
"+",
"(",
"length",
"+",
"offset",
")",
"-",
"1",
"<",
"self",
".",
"length"
] | 58.666667 | 7 |
def script_post_save(model, os_path, contents_manager, **kwargs):
"""convert notebooks to Python script after save with nbconvert
replaces `ipython notebook --script`
"""
from nbconvert.exporters.script import ScriptExporter
if model['type'] != 'notebook':
return
global _script_export... | [
"def",
"script_post_save",
"(",
"model",
",",
"os_path",
",",
"contents_manager",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"nbconvert",
".",
"exporters",
".",
"script",
"import",
"ScriptExporter",
"if",
"model",
"[",
"'type'",
"]",
"!=",
"'notebook'",
":",... | 32.36 | 22.2 |
def decorate(func, caller, extras=()):
"""
decorate(func, caller) decorates a function using a caller.
"""
evaldict = dict(_call_=caller, _func_=func)
es = ''
for i, extra in enumerate(extras):
ex = '_e%d_' % i
evaldict[ex] = extra
es += ex + ', '
fun = FunctionMaker.... | [
"def",
"decorate",
"(",
"func",
",",
"caller",
",",
"extras",
"=",
"(",
")",
")",
":",
"evaldict",
"=",
"dict",
"(",
"_call_",
"=",
"caller",
",",
"_func_",
"=",
"func",
")",
"es",
"=",
"''",
"for",
"i",
",",
"extra",
"in",
"enumerate",
"(",
"ext... | 32.0625 | 11.3125 |
def update_access_key(self, access_key_id, status, user_name=None):
"""
Changes the status of the specified access key from Active to Inactive
or vice versa. This action can be used to disable a user's key as
part of a key rotation workflow.
If the user_name is not specified, t... | [
"def",
"update_access_key",
"(",
"self",
",",
"access_key_id",
",",
"status",
",",
"user_name",
"=",
"None",
")",
":",
"params",
"=",
"{",
"'AccessKeyId'",
":",
"access_key_id",
",",
"'Status'",
":",
"status",
"}",
"if",
"user_name",
":",
"params",
"[",
"'... | 37 | 20.166667 |
def _fix_call_activities_signavio(self, bpmn, filename):
"""
Signavio produces slightly invalid BPMN for call activity nodes... It
is supposed to put a reference to the id of the called process in to
the calledElement attribute. Instead it stores a string (which is the
name of th... | [
"def",
"_fix_call_activities_signavio",
"(",
"self",
",",
"bpmn",
",",
"filename",
")",
":",
"for",
"node",
"in",
"xpath_eval",
"(",
"bpmn",
")",
"(",
"\".//bpmn:callActivity\"",
")",
":",
"calledElement",
"=",
"node",
".",
"get",
"(",
"'calledElement'",
",",
... | 51.4 | 20.3 |
def _calc_hash_da(self, rs):
"""Compute hash of D and A timestamps for single-step D+A case.
"""
self.hash_d = hash_(rs.get_state())[:6]
self.hash_a = self.hash_d | [
"def",
"_calc_hash_da",
"(",
"self",
",",
"rs",
")",
":",
"self",
".",
"hash_d",
"=",
"hash_",
"(",
"rs",
".",
"get_state",
"(",
")",
")",
"[",
":",
"6",
"]",
"self",
".",
"hash_a",
"=",
"self",
".",
"hash_d"
] | 38 | 5.2 |
def host_domains(self, ip=None, limit=None, **kwargs):
"""Pass in an IP address."""
return self._results('reverse-ip', '/v1/{0}/host-domains'.format(ip), limit=limit, **kwargs) | [
"def",
"host_domains",
"(",
"self",
",",
"ip",
"=",
"None",
",",
"limit",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"_results",
"(",
"'reverse-ip'",
",",
"'/v1/{0}/host-domains'",
".",
"format",
"(",
"ip",
")",
",",
"limit"... | 63.333333 | 24.666667 |
def print_cm(cm, labels, hide_zeroes=False, hide_diagonal=False, hide_threshold=None):
"""pretty print for confusion matrixes"""
columnwidth = max([len(x) for x in labels] + [5]) # 5 is value length
empty_cell = " " * columnwidth
# Print header
print(" " + empty_cell, end=" ")
for label in l... | [
"def",
"print_cm",
"(",
"cm",
",",
"labels",
",",
"hide_zeroes",
"=",
"False",
",",
"hide_diagonal",
"=",
"False",
",",
"hide_threshold",
"=",
"None",
")",
":",
"columnwidth",
"=",
"max",
"(",
"[",
"len",
"(",
"x",
")",
"for",
"x",
"in",
"labels",
"]... | 42.227273 | 17.454545 |
def segmentlistdict(self):
"""
A segmentlistdict object describing the instruments and
time spanned by this CacheEntry. A new object is
constructed each time this attribute is accessed (segments
are immutable so there is no reason to try to share a
reference to the CacheEntry's internal segment;
modifica... | [
"def",
"segmentlistdict",
"(",
"self",
")",
":",
"# the import has to be done here to break the cyclic",
"# dependancy",
"from",
"pycbc_glue",
".",
"ligolw",
".",
"lsctables",
"import",
"instrument_set_from_ifos",
"instruments",
"=",
"instrument_set_from_ifos",
"(",
"self",
... | 43.90625 | 28.84375 |
def file_url(self, entity_id, filename, channel=None):
'''Generate a URL for a file in an archive without requesting it.
@param entity_id The ID of the entity to look up.
@param filename The name of the file in the archive.
@param channel Optional channel name.
'''
url =... | [
"def",
"file_url",
"(",
"self",
",",
"entity_id",
",",
"filename",
",",
"channel",
"=",
"None",
")",
":",
"url",
"=",
"'{}/{}/archive/{}'",
".",
"format",
"(",
"self",
".",
"url",
",",
"_get_path",
"(",
"entity_id",
")",
",",
"filename",
")",
"return",
... | 46.1 | 19.9 |
def transform_value(self, value):
"""Convert the value to be stored.
This does nothing by default but subclasses can change this.
Then the index will be able to filter on the transformed value.
For example if the transform capitalizes some text, the filter
would be ``myfield__ca... | [
"def",
"transform_value",
"(",
"self",
",",
"value",
")",
":",
"if",
"not",
"self",
".",
"transform",
":",
"return",
"value",
"try",
":",
"# we store a staticmethod but we accept a method taking `self` and `value`",
"return",
"self",
".",
"transform",
"(",
"self",
"... | 38.555556 | 21.277778 |
async def get_match(self, m_id, force_update=False) -> Match:
""" get a single match by id
|methcoro|
Args:
m_id: match id
force_update (default=False): True to force an update to the Challonge API
Returns:
Match
Raises:
APIExce... | [
"async",
"def",
"get_match",
"(",
"self",
",",
"m_id",
",",
"force_update",
"=",
"False",
")",
"->",
"Match",
":",
"found_m",
"=",
"self",
".",
"_find_match",
"(",
"m_id",
")",
"if",
"force_update",
"or",
"found_m",
"is",
"None",
":",
"await",
"self",
... | 24.190476 | 21.285714 |
def smeft_evolve_leadinglog(C_in, scale_in, scale_out, newphys=True):
"""Solve the SMEFT RGEs in the leading log approximation.
Input C_in and output C_out are dictionaries of arrays."""
C_out = deepcopy(C_in)
b = beta.beta(C_out, newphys=newphys)
for k, C in C_out.items():
C_out[k] = C + b... | [
"def",
"smeft_evolve_leadinglog",
"(",
"C_in",
",",
"scale_in",
",",
"scale_out",
",",
"newphys",
"=",
"True",
")",
":",
"C_out",
"=",
"deepcopy",
"(",
"C_in",
")",
"b",
"=",
"beta",
".",
"beta",
"(",
"C_out",
",",
"newphys",
"=",
"newphys",
")",
"for"... | 41.666667 | 16.444444 |
def _findrange(parlist,roots=['JUMP','DMXR1_','DMXR2_','DMX_','efac','log10_efac']):
"""Rewrite a list of parameters name by detecting ranges (e.g., JUMP1, JUMP2, ...)
and compressing them."""
rootdict = {root: [] for root in roots}
res = []
for par in parlist:
found = False
for ro... | [
"def",
"_findrange",
"(",
"parlist",
",",
"roots",
"=",
"[",
"'JUMP'",
",",
"'DMXR1_'",
",",
"'DMXR2_'",
",",
"'DMX_'",
",",
"'efac'",
",",
"'log10_efac'",
"]",
")",
":",
"rootdict",
"=",
"{",
"root",
":",
"[",
"]",
"for",
"root",
"in",
"roots",
"}",... | 38.44 | 23 |
def com_google_fonts_check_metadata_valid_filename_values(font,
family_metadata):
"""METADATA.pb font.filename field contains font name in right format?"""
expected = os.path.basename(font)
failed = True
for font_metadata in family_metadata.fonts:
if... | [
"def",
"com_google_fonts_check_metadata_valid_filename_values",
"(",
"font",
",",
"family_metadata",
")",
":",
"expected",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"font",
")",
"failed",
"=",
"True",
"for",
"font_metadata",
"in",
"family_metadata",
".",
"font... | 44.642857 | 17.428571 |
def _init_map(self):
"""stub"""
super(edXAssetContentFormRecord, self)._init_map()
AssetContentTextFormRecord._init_map(self)
FilesFormRecord._init_map(self)
ProvenanceFormRecord._init_map(self) | [
"def",
"_init_map",
"(",
"self",
")",
":",
"super",
"(",
"edXAssetContentFormRecord",
",",
"self",
")",
".",
"_init_map",
"(",
")",
"AssetContentTextFormRecord",
".",
"_init_map",
"(",
"self",
")",
"FilesFormRecord",
".",
"_init_map",
"(",
"self",
")",
"Proven... | 38.166667 | 8.833333 |
def single_request_timeout(self, value):
"""The timeout (seconds) for a single HTTP REST API request."""
check_type(value, int)
assert value is None or value > 0
self._single_request_timeout = value | [
"def",
"single_request_timeout",
"(",
"self",
",",
"value",
")",
":",
"check_type",
"(",
"value",
",",
"int",
")",
"assert",
"value",
"is",
"None",
"or",
"value",
">",
"0",
"self",
".",
"_single_request_timeout",
"=",
"value"
] | 45.2 | 3 |
def logical_name(self):
"""The logical name of the seat.
This is an identifier to group sets of devices within the compositor.
Returns:
str: The logical name of this seat.
"""
pchar = self._libinput.libinput_seat_get_logical_name(self._handle)
return string_at(pchar).decode() | [
"def",
"logical_name",
"(",
"self",
")",
":",
"pchar",
"=",
"self",
".",
"_libinput",
".",
"libinput_seat_get_logical_name",
"(",
"self",
".",
"_handle",
")",
"return",
"string_at",
"(",
"pchar",
")",
".",
"decode",
"(",
")"
] | 25.818182 | 21.363636 |
def _data(self, asa=None):
"""
Returns the contents of the node: a dataframe or a file path, or passes
the node and its contents to a callable.
"""
if asa is not None:
if self._store is None or self._hashes is None:
msg = (
"Can onl... | [
"def",
"_data",
"(",
"self",
",",
"asa",
"=",
"None",
")",
":",
"if",
"asa",
"is",
"not",
"None",
":",
"if",
"self",
".",
"_store",
"is",
"None",
"or",
"self",
".",
"_hashes",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Can only use asa functions with built... | 45.695652 | 18.565217 |
def _compute_grover_oracle_matrix(bitstring_map: Dict[str, int]) -> np.ndarray:
"""
Computes the unitary matrix that encodes the oracle function for Grover's algorithm
:param bitstring_map: dict with string keys corresponding to bitstrings,
and integer values corresponding to the desir... | [
"def",
"_compute_grover_oracle_matrix",
"(",
"bitstring_map",
":",
"Dict",
"[",
"str",
",",
"int",
"]",
")",
"->",
"np",
".",
"ndarray",
":",
"n_bits",
"=",
"len",
"(",
"list",
"(",
"bitstring_map",
".",
"keys",
"(",
")",
")",
"[",
"0",
"]",
")",
"or... | 49.4375 | 22.3125 |
def _build_body_schema(serializer, body_parameters):
""" body is built differently, since it's a single argument no matter what. """
description = ""
if isinstance(body_parameters, Param):
schema = serializer.to_json_schema(body_parameters.arginfo.type)
description = body_parameters.descript... | [
"def",
"_build_body_schema",
"(",
"serializer",
",",
"body_parameters",
")",
":",
"description",
"=",
"\"\"",
"if",
"isinstance",
"(",
"body_parameters",
",",
"Param",
")",
":",
"schema",
"=",
"serializer",
".",
"to_json_schema",
"(",
"body_parameters",
".",
"ar... | 34.9375 | 14.84375 |
def phase_diff(self, phase):
'''Compute the phase differential along a given axis
Parameters
----------
phase : np.ndarray
Input phase (in radians)
Returns
-------
dphase : np.ndarray like `phase`
The phase differential.
'''
... | [
"def",
"phase_diff",
"(",
"self",
",",
"phase",
")",
":",
"if",
"self",
".",
"conv",
"is",
"None",
":",
"axis",
"=",
"0",
"elif",
"self",
".",
"conv",
"in",
"(",
"'channels_last'",
",",
"'tf'",
")",
":",
"axis",
"=",
"0",
"elif",
"self",
".",
"co... | 29.875 | 16.625 |
def insort_event_right(self, event, lo=0, hi=None):
"""Insert event in queue, and keep it sorted assuming queue is sorted.
If event is already in queue, insert it to the right of the rightmost
event (to keep FIFO order).
Optional args lo (default 0) and hi (default len(a)) bound the
slice of a to ... | [
"def",
"insort_event_right",
"(",
"self",
",",
"event",
",",
"lo",
"=",
"0",
",",
"hi",
"=",
"None",
")",
":",
"if",
"lo",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"'lo must be non-negative'",
")",
"if",
"hi",
"is",
"None",
":",
"hi",
"=",
"len",
... | 28.5 | 20.958333 |
def wait(self, *args, **kwargs):
"""Wait for the completion event to be set."""
if _debug: IOCB._debug("wait(%d) %r %r", self.ioID, args, kwargs)
# waiting from a non-daemon thread could be trouble
return self.ioComplete.wait(*args, **kwargs) | [
"def",
"wait",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_debug",
":",
"IOCB",
".",
"_debug",
"(",
"\"wait(%d) %r %r\"",
",",
"self",
".",
"ioID",
",",
"args",
",",
"kwargs",
")",
"# waiting from a non-daemon thread could be ... | 45 | 18.666667 |
def top_path(sources, sinks, net_flux):
"""
Use the Dijkstra algorithm for finding the shortest path
connecting a set of source states from a set of sink states.
Parameters
----------
sources : array_like, int
One-dimensional list of nodes to define the source states.
sinks : array_... | [
"def",
"top_path",
"(",
"sources",
",",
"sinks",
",",
"net_flux",
")",
":",
"sources",
"=",
"np",
".",
"array",
"(",
"sources",
",",
"dtype",
"=",
"np",
".",
"int",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
")",
")",
"sinks",
"=",
"np",
"."... | 37.269565 | 23.33913 |
def peak_interval(data, alpha=_alpha, npoints=_npoints):
"""
Identify interval using Gaussian kernel density estimator.
"""
peak = kde_peak(data,npoints)
x = np.sort(data.flat); n = len(x)
# The number of entries in the interval
window = int(np.rint((1.0-alpha)*n))
# The start, stop, and... | [
"def",
"peak_interval",
"(",
"data",
",",
"alpha",
"=",
"_alpha",
",",
"npoints",
"=",
"_npoints",
")",
":",
"peak",
"=",
"kde_peak",
"(",
"data",
",",
"npoints",
")",
"x",
"=",
"np",
".",
"sort",
"(",
"data",
".",
"flat",
")",
"n",
"=",
"len",
"... | 36.55 | 10.35 |
def deflections_from_grid(self, grid, **kwargs):
"""
Calculate the deflection angles at a given set of arc-second gridded coordinates.
Parameters
----------
grid : grids.RegularGrid
The grid of (y,x) arc-second coordinates the deflection angles are computed on.
... | [
"def",
"deflections_from_grid",
"(",
"self",
",",
"grid",
",",
"*",
"*",
"kwargs",
")",
":",
"eta",
"=",
"np",
".",
"multiply",
"(",
"1.",
"/",
"self",
".",
"scale_radius",
",",
"self",
".",
"grid_to_grid_radii",
"(",
"grid",
")",
")",
"deflection_grid",... | 38.533333 | 30.666667 |
def _replaces(self):
"""tge"""
return {concat(a, c, b[1:])
for a, b in self.slices[:-1]
for c in ALPHABET} | [
"def",
"_replaces",
"(",
"self",
")",
":",
"return",
"{",
"concat",
"(",
"a",
",",
"c",
",",
"b",
"[",
"1",
":",
"]",
")",
"for",
"a",
",",
"b",
"in",
"self",
".",
"slices",
"[",
":",
"-",
"1",
"]",
"for",
"c",
"in",
"ALPHABET",
"}"
] | 30 | 7 |
def is_encodable(self, typ: TypeStr, arg: Any) -> bool:
"""
Determines if the python value ``arg`` is encodable as a value of the
ABI type ``typ``.
:param typ: A string representation for the ABI type against which the
python value ``arg`` will be checked e.g. ``'uint256'``,... | [
"def",
"is_encodable",
"(",
"self",
",",
"typ",
":",
"TypeStr",
",",
"arg",
":",
"Any",
")",
"->",
"bool",
":",
"encoder",
"=",
"self",
".",
"_registry",
".",
"get_encoder",
"(",
"typ",
")",
"try",
":",
"encoder",
".",
"validate_value",
"(",
"arg",
"... | 33.615385 | 20.230769 |
def map_psmnrcol_to_quantcol(quantcols, psmcols, tablefn_map):
"""This function yields tuples of table filename, isobaric quant column
and if necessary number-of-PSM column"""
if not psmcols:
for fn in quantcols:
for qcol in quantcols[fn]:
yield (tablefn_map[fn], qcol)
... | [
"def",
"map_psmnrcol_to_quantcol",
"(",
"quantcols",
",",
"psmcols",
",",
"tablefn_map",
")",
":",
"if",
"not",
"psmcols",
":",
"for",
"fn",
"in",
"quantcols",
":",
"for",
"qcol",
"in",
"quantcols",
"[",
"fn",
"]",
":",
"yield",
"(",
"tablefn_map",
"[",
... | 42.272727 | 12.909091 |
def serialize_to_bundle(self, transformer, path, model_name, serialize_node=True):
"""
:type transformer: sklearn.tree.tree.BaseDecisionTree
:type path: str
:type model_name: str
:type serialize_node: bool
:param transformer:
:param path:
:param model_name... | [
"def",
"serialize_to_bundle",
"(",
"self",
",",
"transformer",
",",
"path",
",",
"model_name",
",",
"serialize_node",
"=",
"True",
")",
":",
"# Define attributes",
"attributes",
"=",
"list",
"(",
")",
"attributes",
".",
"append",
"(",
"(",
"'num_features'",
",... | 35.375 | 20.625 |
def center_plot(self, ax):
"""
Centers and keep the aspect ratio in a 3D representation.
Created to help higher classes to manage cascade representation
of multiple lower objects.
:param ax: Axes to apply the method.
:type ax: mplot3d.Axes3D
... | [
"def",
"center_plot",
"(",
"self",
",",
"ax",
")",
":",
"# Domain\r",
"domain",
"=",
"self",
".",
"get_domain",
"(",
")",
"bound",
"=",
"np",
".",
"max",
"(",
"domain",
"[",
"1",
"]",
"-",
"domain",
"[",
"0",
"]",
")",
"centroid",
"=",
"self",
".... | 33.181818 | 15.818182 |
def sys_mmap_pgoff(self, address, size, prot, flags, fd, offset):
"""Wrapper for mmap2"""
return self.sys_mmap2(address, size, prot, flags, fd, offset) | [
"def",
"sys_mmap_pgoff",
"(",
"self",
",",
"address",
",",
"size",
",",
"prot",
",",
"flags",
",",
"fd",
",",
"offset",
")",
":",
"return",
"self",
".",
"sys_mmap2",
"(",
"address",
",",
"size",
",",
"prot",
",",
"flags",
",",
"fd",
",",
"offset",
... | 55 | 18 |
def setParamValue(self, row, **kwargs):
"""Sets the arguments as field=val for parameter
indexed by *row*
:param row: the ith parameter number
:type row: int
"""
param = self._parameters[row]
for key, val in kwargs.items():
param[key] = val | [
"def",
"setParamValue",
"(",
"self",
",",
"row",
",",
"*",
"*",
"kwargs",
")",
":",
"param",
"=",
"self",
".",
"_parameters",
"[",
"row",
"]",
"for",
"key",
",",
"val",
"in",
"kwargs",
".",
"items",
"(",
")",
":",
"param",
"[",
"key",
"]",
"=",
... | 30 | 9.5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.