text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def sh(cmd, ignore_error=False, cwd=None, shell=False, **kwargs):
"""
Execute a command with subprocess.Popen and block until output
Args:
cmd (tuple or str): same as subprocess.Popen args
Keyword Arguments:
ignore_error (bool): if False, raise an Exception if p.returncode is
... | [
"def",
"sh",
"(",
"cmd",
",",
"ignore_error",
"=",
"False",
",",
"cwd",
"=",
"None",
",",
"shell",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
".",
"update",
"(",
"{",
"'shell'",
":",
"shell",
",",
"'cwd'",
":",
"cwd",
",",
"'stder... | 32.794118 | 23.088235 |
def OnApprove(self, event):
"""File approve event handler"""
if not self.main_window.safe_mode:
return
msg = _(u"You are going to approve and trust a file that\n"
u"you have not created yourself.\n"
u"After proceeding, the file is executed.\n \n"
... | [
"def",
"OnApprove",
"(",
"self",
",",
"event",
")",
":",
"if",
"not",
"self",
".",
"main_window",
".",
"safe_mode",
":",
"return",
"msg",
"=",
"_",
"(",
"u\"You are going to approve and trust a file that\\n\"",
"u\"you have not created yourself.\\n\"",
"u\"After proceed... | 39.041667 | 22.875 |
def _check_by_re(self, url_data, content):
""" Finds urls by re.
:param url_data: object for url storing
:param content: file content
"""
for link_re in self._link_res:
for u in link_re.finditer(content):
self._save_url(url_data, content, u.group(1), ... | [
"def",
"_check_by_re",
"(",
"self",
",",
"url_data",
",",
"content",
")",
":",
"for",
"link_re",
"in",
"self",
".",
"_link_res",
":",
"for",
"u",
"in",
"link_re",
".",
"finditer",
"(",
"content",
")",
":",
"self",
".",
"_save_url",
"(",
"url_data",
","... | 35.888889 | 10.555556 |
def paste_template(self, template_name, template=None, deploy_dir=None):
" Paste template. "
LOGGER.debug("Paste template: %s" % template_name)
deploy_dir = deploy_dir or self.deploy_dir
template = template or self._get_template_path(template_name)
self.read([op.join(template, s... | [
"def",
"paste_template",
"(",
"self",
",",
"template_name",
",",
"template",
"=",
"None",
",",
"deploy_dir",
"=",
"None",
")",
":",
"LOGGER",
".",
"debug",
"(",
"\"Paste template: %s\"",
"%",
"template_name",
")",
"deploy_dir",
"=",
"deploy_dir",
"or",
"self",... | 40 | 18.833333 |
def run_nohup(self, cmd, working_dir=None):
"""
:param cmd:
:param working_dir: 当前的工作目录,如果没有 home 目录,会因为一些原因导致运行失败,比如没有无法创建 nohup.out
:return:
"""
cmd = 'nohup %s &\n\n' % cmd
if working_dir is not None:
cmd = 'cd {}; {}'.format(working_dir, cmd)
... | [
"def",
"run_nohup",
"(",
"self",
",",
"cmd",
",",
"working_dir",
"=",
"None",
")",
":",
"cmd",
"=",
"'nohup %s &\\n\\n'",
"%",
"cmd",
"if",
"working_dir",
"is",
"not",
"None",
":",
"cmd",
"=",
"'cd {}; {}'",
".",
"format",
"(",
"working_dir",
",",
"cmd",... | 31.090909 | 14.181818 |
def get_bootstrap(cls, name, ctx):
'''Returns an instance of a bootstrap with the given name.
This is the only way you should access a bootstrap class, as
it sets the bootstrap directory correctly.
'''
if name is None:
return None
if not hasattr(cls, 'bootstr... | [
"def",
"get_bootstrap",
"(",
"cls",
",",
"name",
",",
"ctx",
")",
":",
"if",
"name",
"is",
"None",
":",
"return",
"None",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'bootstraps'",
")",
":",
"cls",
".",
"bootstraps",
"=",
"{",
"}",
"if",
"name",
"in"... | 39.4 | 15.8 |
def load_class(self, classname):
"""
Loads a class looking for it in each module registered.
:param classname: Class name you want to load.
:type classname: str
:return: Class object
:rtype: type
"""
module_list = self._get_module_list()
for mod... | [
"def",
"load_class",
"(",
"self",
",",
"classname",
")",
":",
"module_list",
"=",
"self",
".",
"_get_module_list",
"(",
")",
"for",
"module",
"in",
"module_list",
":",
"try",
":",
"return",
"import_class",
"(",
"classname",
",",
"module",
".",
"__name__",
... | 29.157895 | 19.684211 |
def rm_docs(self):
"""Remove converted docs."""
for filename in self.created:
if os.path.exists(filename):
os.unlink(filename) | [
"def",
"rm_docs",
"(",
"self",
")",
":",
"for",
"filename",
"in",
"self",
".",
"created",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"os",
".",
"unlink",
"(",
"filename",
")"
] | 33.2 | 6 |
def get(self, content_id, feature_names=None):
'''Retrieve a feature collection.
If a feature collection with the given id does not
exist, then ``None`` is returned.
:param str content_id: Content identifier.
:param [str] feature_names:
A list of feature names to retr... | [
"def",
"get",
"(",
"self",
",",
"content_id",
",",
"feature_names",
"=",
"None",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"conn",
".",
"get",
"(",
"index",
"=",
"self",
".",
"index",
",",
"doc_type",
"=",
"self",
".",
"type",
",",
"id",
"=... | 38.761905 | 19.52381 |
def build(id=None, name=None, revision=None,
temporary_build=False, timestamp_alignment=False,
no_build_dependencies=False,
keep_pod_on_failure=False,
force_rebuild=False,
rebuild_mode=common.REBUILD_MODES_DEFAULT):
"""
Trigger a BuildConfiguration by name or ID... | [
"def",
"build",
"(",
"id",
"=",
"None",
",",
"name",
"=",
"None",
",",
"revision",
"=",
"None",
",",
"temporary_build",
"=",
"False",
",",
"timestamp_alignment",
"=",
"False",
",",
"no_build_dependencies",
"=",
"False",
",",
"keep_pod_on_failure",
"=",
"Fals... | 41.076923 | 13.230769 |
def node_predictions(self):
""" Determines which rows fall into which node """
pred = np.zeros(self.data_size)
for node in self:
if node.is_terminal:
pred[node.indices] = node.node_id
return pred | [
"def",
"node_predictions",
"(",
"self",
")",
":",
"pred",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"data_size",
")",
"for",
"node",
"in",
"self",
":",
"if",
"node",
".",
"is_terminal",
":",
"pred",
"[",
"node",
".",
"indices",
"]",
"=",
"node",
"... | 35.571429 | 9.571429 |
def set_defaults(self, config_file):
"""Set defaults.
"""
self.defaults = Defaults(config_file)
self.python = Python()
self.setuptools = Setuptools()
self.docutils = Docutils()
self.styles = self.defaults.styles
self.browser = self.defaults.browser
... | [
"def",
"set_defaults",
"(",
"self",
",",
"config_file",
")",
":",
"self",
".",
"defaults",
"=",
"Defaults",
"(",
"config_file",
")",
"self",
".",
"python",
"=",
"Python",
"(",
")",
"self",
".",
"setuptools",
"=",
"Setuptools",
"(",
")",
"self",
".",
"d... | 32.9 | 4.8 |
def print_info(self, capture):
"""Prints information about the unprocessed image.
Reads one frame from the source to determine image colors, dimensions
and data types.
Args:
capture: the source to read from.
"""
self.frame_offset += 1
ret, frame = ca... | [
"def",
"print_info",
"(",
"self",
",",
"capture",
")",
":",
"self",
".",
"frame_offset",
"+=",
"1",
"ret",
",",
"frame",
"=",
"capture",
".",
"read",
"(",
")",
"if",
"ret",
":",
"print",
"(",
"'Capture Information'",
")",
"print",
"(",
"'\\tDimensions (H... | 40.142857 | 20.095238 |
def get_url(pif, dataset, version=1, site="https://citrination.com"):
"""
Construct the URL of a PIF on a site
:param pif: to construct URL for
:param dataset: the pif will belong to
:param version: of the PIF (default: 1)
:param site: for the dataset (default: https://citrination.com)
:retu... | [
"def",
"get_url",
"(",
"pif",
",",
"dataset",
",",
"version",
"=",
"1",
",",
"site",
"=",
"\"https://citrination.com\"",
")",
":",
"return",
"\"{site}/datasets/{dataset}/version/{version}/pif/{uid}\"",
".",
"format",
"(",
"uid",
"=",
"pif",
".",
"uid",
",",
"ver... | 40.5 | 13.833333 |
def _set_metric(self, metric_name, metric_type, value, tags=None):
"""
Set a metric
"""
if metric_type == self.GAUGE:
self.gauge(metric_name, value, tags=tags)
else:
self.log.error('Metric type "{}" unknown'.format(metric_type)) | [
"def",
"_set_metric",
"(",
"self",
",",
"metric_name",
",",
"metric_type",
",",
"value",
",",
"tags",
"=",
"None",
")",
":",
"if",
"metric_type",
"==",
"self",
".",
"GAUGE",
":",
"self",
".",
"gauge",
"(",
"metric_name",
",",
"value",
",",
"tags",
"=",... | 35.625 | 15.375 |
def ll(self, folder="", begin_from_file="", num=-1, all_grant_data=False):
"""
Get the list of files and permissions from S3.
This is similar to LL (ls -lah) in Linux: List of files with permissions.
Parameters
----------
folder : string
Path to file on S3
... | [
"def",
"ll",
"(",
"self",
",",
"folder",
"=",
"\"\"",
",",
"begin_from_file",
"=",
"\"\"",
",",
"num",
"=",
"-",
"1",
",",
"all_grant_data",
"=",
"False",
")",
":",
"return",
"self",
".",
"ls",
"(",
"folder",
"=",
"folder",
",",
"begin_from_file",
"=... | 32.4375 | 19.208333 |
def _get_representative(self, obj):
"""Finds and returns the root of the set containing `obj`."""
if obj not in self._parents:
self._parents[obj] = obj
self._weights[obj] = 1
self._prev_next[obj] = [obj, obj]
self._min_values[obj] = obj
return... | [
"def",
"_get_representative",
"(",
"self",
",",
"obj",
")",
":",
"if",
"obj",
"not",
"in",
"self",
".",
"_parents",
":",
"self",
".",
"_parents",
"[",
"obj",
"]",
"=",
"obj",
"self",
".",
"_weights",
"[",
"obj",
"]",
"=",
"1",
"self",
".",
"_prev_n... | 29.75 | 12.4 |
def _setns(self, value):
"""
Set the default repository namespace to be used.
This method exists for compatibility. Use the :attr:`default_namespace`
property instead.
"""
if self.conn is not None:
self.conn.default_namespace = value
else:
... | [
"def",
"_setns",
"(",
"self",
",",
"value",
")",
":",
"if",
"self",
".",
"conn",
"is",
"not",
"None",
":",
"self",
".",
"conn",
".",
"default_namespace",
"=",
"value",
"else",
":",
"self",
".",
"__default_namespace",
"=",
"value"
] | 31.181818 | 15.545455 |
def is_deposit_confirmed(
channel_state: NettingChannelState,
block_number: BlockNumber,
) -> bool:
"""True if the block which mined the deposit transaction has been
confirmed.
"""
if not channel_state.deposit_transaction_queue:
return False
return is_transaction_confirmed(
... | [
"def",
"is_deposit_confirmed",
"(",
"channel_state",
":",
"NettingChannelState",
",",
"block_number",
":",
"BlockNumber",
",",
")",
"->",
"bool",
":",
"if",
"not",
"channel_state",
".",
"deposit_transaction_queue",
":",
"return",
"False",
"return",
"is_transaction_con... | 28.5 | 16.642857 |
def isRectangular(self):
"""Check if quad is rectangular.
"""
# if any two of the 4 corners are equal return false
upper = (self.ur - self.ul).unit
if not bool(upper):
return False
right = (self.lr - self.ur).unit
if not bool(right):
return False
... | [
"def",
"isRectangular",
"(",
"self",
")",
":",
"# if any two of the 4 corners are equal return false",
"upper",
"=",
"(",
"self",
".",
"ur",
"-",
"self",
".",
"ul",
")",
".",
"unit",
"if",
"not",
"bool",
"(",
"upper",
")",
":",
"return",
"False",
"right",
... | 38.318182 | 13.727273 |
def get_captcha(self, id=None):
""" http://api.yandex.ru/cleanweb/doc/dg/concepts/get-captcha.xml"""
payload = {'id': id}
r = self.request('get', 'http://cleanweb-api.yandex.ru/1.0/get-captcha', params=payload)
return dict((item.tag, item.text) for item in ET.fromstring(r.content)) | [
"def",
"get_captcha",
"(",
"self",
",",
"id",
"=",
"None",
")",
":",
"payload",
"=",
"{",
"'id'",
":",
"id",
"}",
"r",
"=",
"self",
".",
"request",
"(",
"'get'",
",",
"'http://cleanweb-api.yandex.ru/1.0/get-captcha'",
",",
"params",
"=",
"payload",
")",
... | 62 | 23.2 |
def print_status(self, repo_name, repo_path):
"""Print repository status."""
color = Color()
self.logger.info(color.colored(
"=> [%s] %s" % (repo_name, repo_path), "green"))
try:
repo = Repository(repo_path)
repo.status()
except RepositoryError... | [
"def",
"print_status",
"(",
"self",
",",
"repo_name",
",",
"repo_path",
")",
":",
"color",
"=",
"Color",
"(",
")",
"self",
".",
"logger",
".",
"info",
"(",
"color",
".",
"colored",
"(",
"\"=> [%s] %s\"",
"%",
"(",
"repo_name",
",",
"repo_path",
")",
",... | 32.083333 | 11.916667 |
def get_json_payload_magic_envelope(self, payload):
"""Encrypted JSON payload"""
private_key = self._get_user_key()
return EncryptedPayload.decrypt(payload=payload, private_key=private_key) | [
"def",
"get_json_payload_magic_envelope",
"(",
"self",
",",
"payload",
")",
":",
"private_key",
"=",
"self",
".",
"_get_user_key",
"(",
")",
"return",
"EncryptedPayload",
".",
"decrypt",
"(",
"payload",
"=",
"payload",
",",
"private_key",
"=",
"private_key",
")"... | 52.5 | 13.5 |
def get_node_label(self, model):
"""
Defines how labels are constructed from models.
Default - uses verbose name, lines breaks where sensible
"""
if model.is_proxy:
label = "(P) %s" % (model.name.title())
else:
label = "%s" % (model.name.title())
... | [
"def",
"get_node_label",
"(",
"self",
",",
"model",
")",
":",
"if",
"model",
".",
"is_proxy",
":",
"label",
"=",
"\"(P) %s\"",
"%",
"(",
"model",
".",
"name",
".",
"title",
"(",
")",
")",
"else",
":",
"label",
"=",
"\"%s\"",
"%",
"(",
"model",
".",... | 27.863636 | 14.681818 |
def _get_known_noncoding_het_snp(data_dict):
'''If ref is coding, return None. If the data dict has a known snp, and
samtools made a call, then return the string ref_name_change and the
% of reads supporting the variant type. If noncoding, but no
samtools call, then return None'... | [
"def",
"_get_known_noncoding_het_snp",
"(",
"data_dict",
")",
":",
"if",
"data_dict",
"[",
"'gene'",
"]",
"==",
"'1'",
":",
"return",
"None",
"if",
"data_dict",
"[",
"'known_var'",
"]",
"==",
"'1'",
"and",
"data_dict",
"[",
"'ref_ctg_effect'",
"]",
"==",
"'S... | 47.482759 | 27 |
def loadb(chars, no_bytes=False, object_hook=None, object_pairs_hook=None, intern_object_keys=False):
"""Decodes and returns UBJSON from the given bytes or bytesarray object. See
load() for available arguments."""
with BytesIO(chars) as fp:
return load(fp, no_bytes=no_bytes, object_hook=object_ho... | [
"def",
"loadb",
"(",
"chars",
",",
"no_bytes",
"=",
"False",
",",
"object_hook",
"=",
"None",
",",
"object_pairs_hook",
"=",
"None",
",",
"intern_object_keys",
"=",
"False",
")",
":",
"with",
"BytesIO",
"(",
"chars",
")",
"as",
"fp",
":",
"return",
"load... | 69 | 25.5 |
def main():
"""
Update the ossuary Postgres db with images observed for OSSOS.
iq: Go through and check all ossuary's images for new existence of IQs/zeropoints.
comment: Go through all ossuary and
Then updates ossuary with new images that are at any stage of processing.
Constructs full image en... | [
"def",
"main",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"-iq\"",
",",
"\"--iq\"",
",",
"action",
"=",
"\"store_true\"",
",",
"help",
"=",
"\"Check existing images in ossuary that do not yet ha... | 52.589041 | 27.30137 |
def residual_plots(df, rep_stats=None, els=['Mg', 'Sr', 'Al', 'Mn', 'Fe', 'Cu', 'Zn', 'B']):
"""
Function for plotting Test User and LAtools data comparison.
Parameters
----------
df : pandas.DataFrame
A dataframe containing reference ('X/Ca_r'), test user
('X/Ca_t') and LAtools ('... | [
"def",
"residual_plots",
"(",
"df",
",",
"rep_stats",
"=",
"None",
",",
"els",
"=",
"[",
"'Mg'",
",",
"'Sr'",
",",
"'Al'",
",",
"'Mn'",
",",
"'Fe'",
",",
"'Cu'",
",",
"'Zn'",
",",
"'B'",
"]",
")",
":",
"# get corresponding analyte and ratio names",
"As",... | 31.729412 | 18.976471 |
def has_near_match_generic_ngrams(subsequence, sequence, search_params):
"""search for near-matches of subsequence in sequence
This searches for near-matches, where the nearly-matching parts of the
sequence must meet the following limitations (relative to the subsequence):
* the maximum allowed number... | [
"def",
"has_near_match_generic_ngrams",
"(",
"subsequence",
",",
"sequence",
",",
"search_params",
")",
":",
"if",
"not",
"subsequence",
":",
"raise",
"ValueError",
"(",
"'Given subsequence is empty!'",
")",
"for",
"match",
"in",
"_find_near_matches_generic_ngrams",
"("... | 43.117647 | 25.470588 |
def _repeat(self, index, stage, stop):
""" Repeat a stage.
:param index: Stage index.
:param stage: Stage object to repeat.
:param iterations: Number of iterations (default infinite).
:param stages: Stages back to repeat (default 1).
"""
times = None
if '... | [
"def",
"_repeat",
"(",
"self",
",",
"index",
",",
"stage",
",",
"stop",
")",
":",
"times",
"=",
"None",
"if",
"'iterations'",
"in",
"stage",
".",
"kwargs",
":",
"times",
"=",
"stage",
".",
"kwargs",
"[",
"'iterations'",
"]",
"-",
"1",
"stages_back",
... | 35.166667 | 14 |
def is_builtin_type(tp):
"""Checks if the given type is a builtin one.
"""
return hasattr(__builtins__, tp.__name__) and tp is getattr(__builtins__, tp.__name__) | [
"def",
"is_builtin_type",
"(",
"tp",
")",
":",
"return",
"hasattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")",
"and",
"tp",
"is",
"getattr",
"(",
"__builtins__",
",",
"tp",
".",
"__name__",
")"
] | 42.5 | 16.5 |
def inspect(self, w):
"""Get the latest value of the wire given, if possible."""
if isinstance(w, WireVector):
w = w.name
try:
vals = self.tracer.trace[w]
except KeyError:
pass
else:
if not vals:
raise PyrtlError('No... | [
"def",
"inspect",
"(",
"self",
",",
"w",
")",
":",
"if",
"isinstance",
"(",
"w",
",",
"WireVector",
")",
":",
"w",
"=",
"w",
".",
"name",
"try",
":",
"vals",
"=",
"self",
".",
"tracer",
".",
"trace",
"[",
"w",
"]",
"except",
"KeyError",
":",
"p... | 37.076923 | 20.461538 |
def get_tops(self):
'''
Gather the top files
'''
tops = collections.defaultdict(list)
include = collections.defaultdict(list)
done = collections.defaultdict(list)
errors = []
# Gather initial top files
try:
saltenvs = set()
... | [
"def",
"get_tops",
"(",
"self",
")",
":",
"tops",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"include",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"done",
"=",
"collections",
".",
"defaultdict",
"(",
"list",
")",
"errors",
"... | 42.215909 | 15.556818 |
def format_invoke_command(self, string):
"""
Formats correctly the string output from the invoke() method,
replacing line breaks and tabs when necessary.
"""
string = string.replace('\\n', '\n')
formated_response = ''
for line in string.splitlines():
... | [
"def",
"format_invoke_command",
"(",
"self",
",",
"string",
")",
":",
"string",
"=",
"string",
".",
"replace",
"(",
"'\\\\n'",
",",
"'\\n'",
")",
"formated_response",
"=",
"''",
"for",
"line",
"in",
"string",
".",
"splitlines",
"(",
")",
":",
"if",
"line... | 34.333333 | 12.888889 |
def update_saved_search(self, id, **kwargs): # noqa: E501
"""Update a specific saved search # noqa: E501
# noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.update_saved_searc... | [
"def",
"update_saved_search",
"(",
"self",
",",
"id",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
"self",
".",
"update_s... | 49.590909 | 25.863636 |
def ParseLines(self, input_lines):
"""Parses list of lines.
Args:
input_lines: A list of strings of input to parse (no newlines on the
strings).
Raises:
PDDMError if there are any issues.
"""
current_macro = None
for line in input_lines:
if line.startswith(... | [
"def",
"ParseLines",
"(",
"self",
",",
"input_lines",
")",
":",
"current_macro",
"=",
"None",
"for",
"line",
"in",
"input_lines",
":",
"if",
"line",
".",
"startswith",
"(",
"'PDDM-'",
")",
":",
"directive",
"=",
"line",
".",
"split",
"(",
"' '",
",",
"... | 33.051282 | 17.794872 |
def init_session(db_url=None, echo=False, engine=None, settings=None):
"""
A SQLAlchemy Session requires that an engine be initialized if one isn't
provided.
"""
if engine is None:
engine = init_engine(db_url=db_url, echo=echo, settings=settings)
return sessionmaker(bind=engine) | [
"def",
"init_session",
"(",
"db_url",
"=",
"None",
",",
"echo",
"=",
"False",
",",
"engine",
"=",
"None",
",",
"settings",
"=",
"None",
")",
":",
"if",
"engine",
"is",
"None",
":",
"engine",
"=",
"init_engine",
"(",
"db_url",
"=",
"db_url",
",",
"ech... | 38 | 18.5 |
def _srvc_make_overview_tables(self, tables_to_make, traj=None):
"""Creates the overview tables in overview group"""
for table_name in tables_to_make:
# Prepare the tables desciptions, depending on which overview table we create
# we need different columns
paramdescri... | [
"def",
"_srvc_make_overview_tables",
"(",
"self",
",",
"tables_to_make",
",",
"traj",
"=",
"None",
")",
":",
"for",
"table_name",
"in",
"tables_to_make",
":",
"# Prepare the tables desciptions, depending on which overview table we create",
"# we need different columns",
"paramd... | 45.402985 | 24.671642 |
def network_expansion_diff (networkA, networkB, filename=None, boundaries=[]):
"""Plot relative network expansion derivation of AC- and DC-lines.
Parameters
----------
networkA: PyPSA network container
Holds topology of grid including results from powerflow analysis
networkB: PyPSA netw... | [
"def",
"network_expansion_diff",
"(",
"networkA",
",",
"networkB",
",",
"filename",
"=",
"None",
",",
"boundaries",
"=",
"[",
"]",
")",
":",
"cmap",
"=",
"plt",
".",
"cm",
".",
"jet",
"array_line",
"=",
"[",
"[",
"'Line'",
"]",
"*",
"len",
"(",
"netw... | 33.411765 | 21.955882 |
def p_iteration_statement_4(self, p):
"""
iteration_statement \
: FOR LPAREN left_hand_side_expr IN expr RPAREN statement
"""
p[0] = ast.ForIn(item=p[3], iterable=p[5], statement=p[7]) | [
"def",
"p_iteration_statement_4",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"ast",
".",
"ForIn",
"(",
"item",
"=",
"p",
"[",
"3",
"]",
",",
"iterable",
"=",
"p",
"[",
"5",
"]",
",",
"statement",
"=",
"p",
"[",
"7",
"]",
")"
] | 37.166667 | 11.5 |
def set_input_by_xpath(self, xpath, value):
"""
Set the value of form element by xpath
:param xpath: xpath path
:param value: value which should be set to element
"""
elem = self.select(xpath).node()
if self._lxml_form is None:
# Explicitly set the ... | [
"def",
"set_input_by_xpath",
"(",
"self",
",",
"xpath",
",",
"value",
")",
":",
"elem",
"=",
"self",
".",
"select",
"(",
"xpath",
")",
".",
"node",
"(",
")",
"if",
"self",
".",
"_lxml_form",
"is",
"None",
":",
"# Explicitly set the default form",
"# which ... | 30.909091 | 14 |
def into_view(self):
"""Converts the index into a view"""
try:
return View._from_ptr(rustcall(
_lib.lsm_index_into_view,
self._get_ptr()))
finally:
self._ptr = None | [
"def",
"into_view",
"(",
"self",
")",
":",
"try",
":",
"return",
"View",
".",
"_from_ptr",
"(",
"rustcall",
"(",
"_lib",
".",
"lsm_index_into_view",
",",
"self",
".",
"_get_ptr",
"(",
")",
")",
")",
"finally",
":",
"self",
".",
"_ptr",
"=",
"None"
] | 29.625 | 11.875 |
def write_hdf5(self, filename, dataset_name=None, info=None, group_name=None):
r"""Writes a unyt_array to hdf5 file.
Parameters
----------
filename: string
The filename to create and write a dataset to
dataset_name: string
The name of the dataset to crea... | [
"def",
"write_hdf5",
"(",
"self",
",",
"filename",
",",
"dataset_name",
"=",
"None",
",",
"info",
"=",
"None",
",",
"group_name",
"=",
"None",
")",
":",
"from",
"unyt",
".",
"_on_demand_imports",
"import",
"_h5py",
"as",
"h5py",
"import",
"pickle",
"if",
... | 31.746032 | 20.15873 |
def polygonVertices(x, y, radius, sides, rotationDegrees=0, stretchHorizontal=1.0, stretchVertical=1.0):
"""
Returns a generator that produces the (x, y) points of the vertices of a regular polygon.
`x` and `y` mark the center of the polygon, `radius` indicates the size,
`sides` specifies what kind of p... | [
"def",
"polygonVertices",
"(",
"x",
",",
"y",
",",
"radius",
",",
"sides",
",",
"rotationDegrees",
"=",
"0",
",",
"stretchHorizontal",
"=",
"1.0",
",",
"stretchVertical",
"=",
"1.0",
")",
":",
"# TODO - validate x, y, radius, sides",
"# Setting the start point like ... | 32.823529 | 26.676471 |
def paintEvent(self, event):
"""Qt Override.
Include a validation icon to the left of the line edit.
"""
super(IconLineEdit, self).paintEvent(event)
painter = QPainter(self)
rect = self.geometry()
space = int((rect.height())/6)
h = rect.height() - space
... | [
"def",
"paintEvent",
"(",
"self",
",",
"event",
")",
":",
"super",
"(",
"IconLineEdit",
",",
"self",
")",
".",
"paintEvent",
"(",
"event",
")",
"painter",
"=",
"QPainter",
"(",
"self",
")",
"rect",
"=",
"self",
".",
"geometry",
"(",
")",
"space",
"="... | 32.1875 | 16.9375 |
def ramp_array(rampdata, ti, gain=1.0, ron=1.0,
badpixels=None, dtype='float64',
saturation=65631, blank=0, nsig=None, normalize=False):
"""Loop over the first axis applying ramp processing.
*rampdata* is assumed to be a 3D numpy.ndarray containing the
result of a nIR observat... | [
"def",
"ramp_array",
"(",
"rampdata",
",",
"ti",
",",
"gain",
"=",
"1.0",
",",
"ron",
"=",
"1.0",
",",
"badpixels",
"=",
"None",
",",
"dtype",
"=",
"'float64'",
",",
"saturation",
"=",
"65631",
",",
"blank",
"=",
"0",
",",
"nsig",
"=",
"None",
",",... | 35.25 | 18.808824 |
def acquisition_function_withGradients(self, x):
"""
Returns the acquisition function and its its gradient at x.
"""
aqu_x = self.acquisition_function(x)
aqu_x_grad = self.d_acquisition_function(x)
return aqu_x, aqu_x_grad | [
"def",
"acquisition_function_withGradients",
"(",
"self",
",",
"x",
")",
":",
"aqu_x",
"=",
"self",
".",
"acquisition_function",
"(",
"x",
")",
"aqu_x_grad",
"=",
"self",
".",
"d_acquisition_function",
"(",
"x",
")",
"return",
"aqu_x",
",",
"aqu_x_grad"
] | 38.428571 | 9 |
def mark_dirty(self):
"""Invalidates memoized fingerprints for this payload.
Exposed for testing.
:API: public
"""
self._fingerprint_memo_map = {}
for field in self._fields.values():
field.mark_dirty() | [
"def",
"mark_dirty",
"(",
"self",
")",
":",
"self",
".",
"_fingerprint_memo_map",
"=",
"{",
"}",
"for",
"field",
"in",
"self",
".",
"_fields",
".",
"values",
"(",
")",
":",
"field",
".",
"mark_dirty",
"(",
")"
] | 22.4 | 16.1 |
def compute_similarities(hdf5_file, data, N_processes):
"""Compute a matrix of pairwise L2 Euclidean distances among samples from 'data'.
This computation is to be done in parallel by 'N_processes' distinct processes.
Those processes (which are instances of the class 'Similarities_worker')
... | [
"def",
"compute_similarities",
"(",
"hdf5_file",
",",
"data",
",",
"N_processes",
")",
":",
"slice_queue",
"=",
"multiprocessing",
".",
"JoinableQueue",
"(",
")",
"pid_list",
"=",
"[",
"]",
"for",
"i",
"in",
"range",
"(",
"N_processes",
")",
":",
"worker",
... | 38.615385 | 22.230769 |
def sub_channel(self):
"""Get the SUB socket channel object."""
if self._sub_channel is None:
self._sub_channel = self.sub_channel_class(self.context,
self.session,
(self.ip, self.io... | [
"def",
"sub_channel",
"(",
"self",
")",
":",
"if",
"self",
".",
"_sub_channel",
"is",
"None",
":",
"self",
".",
"_sub_channel",
"=",
"self",
".",
"sub_channel_class",
"(",
"self",
".",
"context",
",",
"self",
".",
"session",
",",
"(",
"self",
".",
"ip"... | 51 | 18.142857 |
def simplify_other(major, minor, dist):
"""
Simplify the point featurecollection of poi with another point features accoording by distance.
Attention: point featurecollection only
Keyword arguments:
major -- major geojson
minor -- minor geojson
dist -- distance
return a geoj... | [
"def",
"simplify_other",
"(",
"major",
",",
"minor",
",",
"dist",
")",
":",
"result",
"=",
"deepcopy",
"(",
"major",
")",
"if",
"major",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
"and",
"minor",
"[",
"'type'",
"]",
"==",
"'FeatureCollection'",
":",
... | 38.676471 | 17.088235 |
def build_y(self):
"""Build transmission line admittance matrix into self.Y"""
if not self.n:
return
self.y1 = mul(self.u, self.g1 + self.b1 * 1j)
self.y2 = mul(self.u, self.g2 + self.b2 * 1j)
self.y12 = div(self.u, self.r + self.x * 1j)
self.m = polar(self.ta... | [
"def",
"build_y",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"n",
":",
"return",
"self",
".",
"y1",
"=",
"mul",
"(",
"self",
".",
"u",
",",
"self",
".",
"g1",
"+",
"self",
".",
"b1",
"*",
"1j",
")",
"self",
".",
"y2",
"=",
"mul",
"(",... | 41.5 | 17.090909 |
def batchnorm_2d(nf:int, norm_type:NormType=NormType.Batch):
"A batchnorm2d layer with `nf` features initialized depending on `norm_type`."
bn = nn.BatchNorm2d(nf)
with torch.no_grad():
bn.bias.fill_(1e-3)
bn.weight.fill_(0. if norm_type==NormType.BatchZero else 1.)
return bn | [
"def",
"batchnorm_2d",
"(",
"nf",
":",
"int",
",",
"norm_type",
":",
"NormType",
"=",
"NormType",
".",
"Batch",
")",
":",
"bn",
"=",
"nn",
".",
"BatchNorm2d",
"(",
"nf",
")",
"with",
"torch",
".",
"no_grad",
"(",
")",
":",
"bn",
".",
"bias",
".",
... | 43.142857 | 22.571429 |
def formatTime (self, record, datefmt=None):
"""Returns the creation time of the given LogRecord as formatted text.
NOTE: The datefmt parameter and self.converter (the time
conversion method) are ignored. BSD Syslog Protocol messages
always use local time, and by our convention, Syslog... | [
"def",
"formatTime",
"(",
"self",
",",
"record",
",",
"datefmt",
"=",
"None",
")",
":",
"if",
"self",
".",
"bsd",
":",
"lt_ts",
"=",
"datetime",
".",
"datetime",
".",
"fromtimestamp",
"(",
"record",
".",
"created",
")",
"ts",
"=",
"lt_ts",
".",
"strf... | 42.470588 | 18.058824 |
def _convertEntities(self, match):
"""Used in a call to re.sub to replace HTML, XML, and numeric
entities with the appropriate Unicode characters. If HTML
entities are being converted, any unrecognized entities are
escaped."""
x = match.group(1)
if self.convertHTMLEntitie... | [
"def",
"_convertEntities",
"(",
"self",
",",
"match",
")",
":",
"x",
"=",
"match",
".",
"group",
"(",
"1",
")",
"if",
"self",
".",
"convertHTMLEntities",
"and",
"x",
"in",
"name2codepoint",
":",
"return",
"unichr",
"(",
"name2codepoint",
"[",
"x",
"]",
... | 38.791667 | 11.708333 |
def ready(self):
"""Perform application initialization."""
# Initialize the type extension composer.
from . composer import composer
composer.discover_extensions()
is_migrating = sys.argv[1:2] == ['migrate']
if is_migrating:
# Do not register signals and ES i... | [
"def",
"ready",
"(",
"self",
")",
":",
"# Initialize the type extension composer.",
"from",
".",
"composer",
"import",
"composer",
"composer",
".",
"discover_extensions",
"(",
")",
"is_migrating",
"=",
"sys",
".",
"argv",
"[",
"1",
":",
"2",
"]",
"==",
"[",
... | 39.571429 | 18.857143 |
def _setup_file_hierarchy_limit(
self, files_count_limit, files_size_limit, temp_dir, cgroups, pid_to_kill):
"""Start thread that enforces any file-hiearchy limits."""
if files_count_limit is not None or files_size_limit is not None:
file_hierarchy_limit_thread = FileHierarchyLim... | [
"def",
"_setup_file_hierarchy_limit",
"(",
"self",
",",
"files_count_limit",
",",
"files_size_limit",
",",
"temp_dir",
",",
"cgroups",
",",
"pid_to_kill",
")",
":",
"if",
"files_count_limit",
"is",
"not",
"None",
"or",
"files_size_limit",
"is",
"not",
"None",
":",... | 51.466667 | 14.666667 |
def format_raw_script(raw_script):
"""Creates single script from a list of script parts.
:type raw_script: [basestring]
:rtype: basestring
"""
if six.PY2:
script = ' '.join(arg.decode('utf-8') for arg in raw_script)
else:
script = ' '.join(raw_script)
return script.strip() | [
"def",
"format_raw_script",
"(",
"raw_script",
")",
":",
"if",
"six",
".",
"PY2",
":",
"script",
"=",
"' '",
".",
"join",
"(",
"arg",
".",
"decode",
"(",
"'utf-8'",
")",
"for",
"arg",
"in",
"raw_script",
")",
"else",
":",
"script",
"=",
"' '",
".",
... | 23.692308 | 19.384615 |
def _set_bridge_domain(self, v, load=False):
"""
Setter method for bridge_domain, mapped from YANG variable /bridge_domain (list)
If this variable is read-only (config: false) in the
source YANG file, then _set_bridge_domain is considered as a private
method. Backends looking to populate this variab... | [
"def",
"_set_bridge_domain",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"... | 152 | 73.181818 |
def init_app(self, app):
"""
This callback can be used to initialize an application for the
use with this prometheus reporter setup.
This is usually used with a flask "app factory" configuration. Please
see: http://flask.pocoo.org/docs/1.0/patterns/appfactories/
Note, t... | [
"def",
"init_app",
"(",
"self",
",",
"app",
")",
":",
"if",
"self",
".",
"path",
":",
"self",
".",
"register_endpoint",
"(",
"self",
".",
"path",
",",
"app",
")",
"if",
"self",
".",
"_export_defaults",
":",
"self",
".",
"export_defaults",
"(",
"self",
... | 32.454545 | 20.181818 |
def parse_forensic_report(feedback_report, sample, msg_date,
nameservers=None, dns_timeout=2.0,
strip_attachment_payloads=False,
parallel=False):
"""
Converts a DMARC forensic report and sample to a ``OrderedDict``
Args:
... | [
"def",
"parse_forensic_report",
"(",
"feedback_report",
",",
"sample",
",",
"msg_date",
",",
"nameservers",
"=",
"None",
",",
"dns_timeout",
"=",
"2.0",
",",
"strip_attachment_payloads",
"=",
"False",
",",
"parallel",
"=",
"False",
")",
":",
"delivery_results",
... | 42.321739 | 19.973913 |
def update_case(case_obj, existing_case):
"""Update an existing case
This will add paths to VCF files, individuals etc
Args:
case_obj(models.Case)
existing_case(models.Case)
Returns:
updated_case(models.Case): Updated existing case
"""
variant_nrs = ['nr_va... | [
"def",
"update_case",
"(",
"case_obj",
",",
"existing_case",
")",
":",
"variant_nrs",
"=",
"[",
"'nr_variants'",
",",
"'nr_sv_variants'",
"]",
"individuals",
"=",
"[",
"(",
"'individuals'",
",",
"'_inds'",
")",
",",
"(",
"'sv_individuals'",
",",
"'_sv_inds'",
... | 36.65625 | 20.75 |
def get_qrcode_url(self, ticket, data=None):
"""
通过 ticket 换取二维码地址
详情请参考
https://iot.weixin.qq.com/wiki/new/index.html?page=3-4-4
:param ticket: 二维码 ticket
:param data: 额外数据
:return: 二维码地址
"""
url = 'https://we.qq.com/d/{ticket}'.format(ticket=tic... | [
"def",
"get_qrcode_url",
"(",
"self",
",",
"ticket",
",",
"data",
"=",
"None",
")",
":",
"url",
"=",
"'https://we.qq.com/d/{ticket}'",
".",
"format",
"(",
"ticket",
"=",
"ticket",
")",
"if",
"data",
":",
"if",
"isinstance",
"(",
"data",
",",
"(",
"dict",... | 33.411765 | 16.588235 |
def write_virtual_memory(self, cpu_id, address, size, bytes_p):
"""Writes guest virtual memory, access handles (MMIO++) are ignored.
This feature is not implemented in the 4.0.0 release but may show up
in a dot release.
in cpu_id of type int
The identifier of the Vi... | [
"def",
"write_virtual_memory",
"(",
"self",
",",
"cpu_id",
",",
"address",
",",
"size",
",",
"bytes_p",
")",
":",
"if",
"not",
"isinstance",
"(",
"cpu_id",
",",
"baseinteger",
")",
":",
"raise",
"TypeError",
"(",
"\"cpu_id can only be an instance of type baseinteg... | 39.69697 | 18.878788 |
def sync_model(self, comment='', compact_central=False,
release_borrowed=True, release_workset=True,
save_local=False):
"""Append a sync model entry to the journal.
This instructs Revit to sync the currently open workshared model.
Args:
comment... | [
"def",
"sync_model",
"(",
"self",
",",
"comment",
"=",
"''",
",",
"compact_central",
"=",
"False",
",",
"release_borrowed",
"=",
"True",
",",
"release_workset",
"=",
"True",
",",
"save_local",
"=",
"False",
")",
":",
"self",
".",
"_add_entry",
"(",
"templa... | 43.814815 | 22.666667 |
def alter_field(self, model, old_field, new_field, strict=False):
"""Ran when the configuration on a field changed."""
is_old_field_hstore = isinstance(old_field, HStoreField)
is_new_field_hstore = isinstance(new_field, HStoreField)
if not is_old_field_hstore and not is_new_field_hstor... | [
"def",
"alter_field",
"(",
"self",
",",
"model",
",",
"old_field",
",",
"new_field",
",",
"strict",
"=",
"False",
")",
":",
"is_old_field_hstore",
"=",
"isinstance",
"(",
"old_field",
",",
"HStoreField",
")",
"is_new_field_hstore",
"=",
"isinstance",
"(",
"new... | 36.3 | 17.05 |
def wrap(self, LayoutClass, *args, **kwargs):
"""
Wraps every layout object pointed in `self.slice` under a `LayoutClass` instance with
`args` and `kwargs` passed.
"""
def wrap_object(layout_object, j):
layout_object.fields[j] = self.wrapped_object(
La... | [
"def",
"wrap",
"(",
"self",
",",
"LayoutClass",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"def",
"wrap_object",
"(",
"layout_object",
",",
"j",
")",
":",
"layout_object",
".",
"fields",
"[",
"j",
"]",
"=",
"self",
".",
"wrapped_object",
"(... | 37.272727 | 16.909091 |
def vxvyvz_to_vrpmllpmbb(vx,vy,vz,l,b,d,XYZ=False,degree=False):
"""
NAME:
vxvyvz_to_vrpmllpmbb
PURPOSE:
Transform velocities in the rectangular Galactic coordinate frame to the spherical Galactic coordinate frame (can take vector inputs)
INPUT:
vx - velocity towards the Galact... | [
"def",
"vxvyvz_to_vrpmllpmbb",
"(",
"vx",
",",
"vy",
",",
"vz",
",",
"l",
",",
"b",
",",
"d",
",",
"XYZ",
"=",
"False",
",",
"degree",
"=",
"False",
")",
":",
"#Whether to use degrees and scalar input is handled by decorators",
"if",
"XYZ",
":",
"#undo the inc... | 25.606061 | 25.606061 |
def scan_dir_for_template_files(search_dir):
"""
Return a map of "likely service/template name" to "template file".
This includes all the template files in fixtures and in services.
"""
template_files = {}
cf_dir = os.path.join(search_dir, 'cloudformation')
for type in os.listdir(cf_dir):
... | [
"def",
"scan_dir_for_template_files",
"(",
"search_dir",
")",
":",
"template_files",
"=",
"{",
"}",
"cf_dir",
"=",
"os",
".",
"path",
".",
"join",
"(",
"search_dir",
",",
"'cloudformation'",
")",
"for",
"type",
"in",
"os",
".",
"listdir",
"(",
"cf_dir",
")... | 41.846154 | 12.615385 |
def save(self, filename):
"""Save metadata to XML file"""
with io.open(filename,'w',encoding='utf-8') as f:
f.write(self.xml()) | [
"def",
"save",
"(",
"self",
",",
"filename",
")",
":",
"with",
"io",
".",
"open",
"(",
"filename",
",",
"'w'",
",",
"encoding",
"=",
"'utf-8'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"xml",
"(",
")",
")"
] | 38 | 10.25 |
def filename_for_track(track):
"""
:return: A safe filename for the given track
"""
artist = track.user['permalink']
title = track.title
return '{}-{}.mp3'.format(artist, title).lower().replace(' ', '_').replace('/', '_') | [
"def",
"filename_for_track",
"(",
"track",
")",
":",
"artist",
"=",
"track",
".",
"user",
"[",
"'permalink'",
"]",
"title",
"=",
"track",
".",
"title",
"return",
"'{}-{}.mp3'",
".",
"format",
"(",
"artist",
",",
"title",
")",
".",
"lower",
"(",
")",
".... | 29.875 | 15.875 |
def execute_cmdline_scenarios(scenario_name, args, command_args):
"""
Execute scenario sequences based on parsed command-line arguments.
This is useful for subcommands that run scenario sequences, which
excludes subcommands such as ``list``, ``login``, and ``matrix``.
``args`` and ``command_args``... | [
"def",
"execute_cmdline_scenarios",
"(",
"scenario_name",
",",
"args",
",",
"command_args",
")",
":",
"scenarios",
"=",
"molecule",
".",
"scenarios",
".",
"Scenarios",
"(",
"get_configs",
"(",
"args",
",",
"command_args",
")",
",",
"scenario_name",
")",
"scenari... | 42.657895 | 21.184211 |
def _windows_wwns():
'''
Return Fibre Channel port WWNs from a Windows host.
'''
ps_cmd = r'Get-WmiObject -ErrorAction Stop ' \
r'-class MSFC_FibrePortHBAAttributes ' \
r'-namespace "root\WMI" | ' \
r'Select -Expandproperty Attributes | ' \
r'%{($_.Por... | [
"def",
"_windows_wwns",
"(",
")",
":",
"ps_cmd",
"=",
"r'Get-WmiObject -ErrorAction Stop '",
"r'-class MSFC_FibrePortHBAAttributes '",
"r'-namespace \"root\\WMI\" | '",
"r'Select -Expandproperty Attributes | '",
"r'%{($_.PortWWN | % {\"{0:x2}\" -f $_}) -join \"\"}'",
"ret",
"=",
"[",
"... | 34.571429 | 17.857143 |
def delete_dataset(self, project_id, dataset_id):
"""
Delete a dataset of Big query in your project.
:param project_id: The name of the project where we have the dataset .
:type project_id: str
:param dataset_id: The dataset to be delete.
:type dataset_id: str
:re... | [
"def",
"delete_dataset",
"(",
"self",
",",
"project_id",
",",
"dataset_id",
")",
":",
"project_id",
"=",
"project_id",
"if",
"project_id",
"is",
"not",
"None",
"else",
"self",
".",
"project_id",
"self",
".",
"log",
".",
"info",
"(",
"'Deleting from project: %s... | 40.333333 | 19.166667 |
def data_csv(request, measurement_list):
"""This view generates a csv output of all data for a strain.
For this function to work, you have to provide the filtered set of measurements."""
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename=data.c... | [
"def",
"data_csv",
"(",
"request",
",",
"measurement_list",
")",
":",
"response",
"=",
"HttpResponse",
"(",
"content_type",
"=",
"'text/csv'",
")",
"response",
"[",
"'Content-Disposition'",
"]",
"=",
"'attachment; filename=data.csv'",
"writer",
"=",
"csv",
".",
"w... | 42.041667 | 14.208333 |
def merge_tasks(core_collections, sandbox_collections, id_prefix, new_tasks, batch_size=100, wipe=False):
"""Merge core and sandbox collections into a temporary collection in the sandbox.
:param core_collections: Core collection info
:type core_collections: Collections
:param sandbox_collections: Sandb... | [
"def",
"merge_tasks",
"(",
"core_collections",
",",
"sandbox_collections",
",",
"id_prefix",
",",
"new_tasks",
",",
"batch_size",
"=",
"100",
",",
"wipe",
"=",
"False",
")",
":",
"merged",
"=",
"copy",
".",
"copy",
"(",
"sandbox_collections",
")",
"# create/cl... | 34.764706 | 13.705882 |
def validate_float(cls, value):
"""
Note that int values are accepted.
"""
if not isinstance(value, (int, float)):
raise TypeError(
"value must be a number, got %s" % type(value)
) | [
"def",
"validate_float",
"(",
"cls",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"int",
",",
"float",
")",
")",
":",
"raise",
"TypeError",
"(",
"\"value must be a number, got %s\"",
"%",
"type",
"(",
"value",
")",
")"
] | 30.625 | 9.875 |
def maximum_vline_bundle(self, x0, y0, y1):
"""Compute a maximum set of vertical lines in the unit cells ``(x0,y)``
for :math:`y0 \leq y \leq y1`.
INPUTS:
y0,x0,x1: int
OUTPUT:
list of lists of qubits
"""
y_range = range(y1, y0 - 1, -1) if y0 < ... | [
"def",
"maximum_vline_bundle",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"y1",
")",
":",
"y_range",
"=",
"range",
"(",
"y1",
",",
"y0",
"-",
"1",
",",
"-",
"1",
")",
"if",
"y0",
"<",
"y1",
"else",
"range",
"(",
"y1",
",",
"y0",
"+",
"1",
")",
... | 33.142857 | 19.857143 |
def p_expr_LT_expr(p):
""" expr : expr LT expr
"""
p[0] = make_binary(p.lineno(2), 'LT', p[1], p[3], lambda x, y: x < y) | [
"def",
"p_expr_LT_expr",
"(",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"make_binary",
"(",
"p",
".",
"lineno",
"(",
"2",
")",
",",
"'LT'",
",",
"p",
"[",
"1",
"]",
",",
"p",
"[",
"3",
"]",
",",
"lambda",
"x",
",",
"y",
":",
"x",
"<",
"y",
... | 32.25 | 12.75 |
def write_tokens_to_file(self):
''' Write api tokens to a file '''
config = dict()
config['API_KEY'] = self.api_key
config['ACCESS_TOKEN'] = self.access_token
config['REFRESH_TOKEN'] = self.refresh_token
config['AUTHORIZATION_CODE'] = self.authorization_code
if se... | [
"def",
"write_tokens_to_file",
"(",
"self",
")",
":",
"config",
"=",
"dict",
"(",
")",
"config",
"[",
"'API_KEY'",
"]",
"=",
"self",
".",
"api_key",
"config",
"[",
"'ACCESS_TOKEN'",
"]",
"=",
"self",
".",
"access_token",
"config",
"[",
"'REFRESH_TOKEN'",
"... | 39.727273 | 11.909091 |
def clear_adb_log(self):
"""Clears cached adb content."""
try:
self._ad.adb.logcat('-c')
except adb.AdbError as e:
# On Android O, the clear command fails due to a known bug.
# Catching this so we don't crash from this Android issue.
if b'failed to... | [
"def",
"clear_adb_log",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"_ad",
".",
"adb",
".",
"logcat",
"(",
"'-c'",
")",
"except",
"adb",
".",
"AdbError",
"as",
"e",
":",
"# On Android O, the clear command fails due to a known bug.",
"# Catching this so we don'... | 39.916667 | 16.416667 |
def remove(path):
"""Wrapper that switches between os.remove and shutil.rmtree depending on
whether the provided path is a file or directory.
"""
if not os.path.exists(path):
return
if os.path.isdir(path):
return shutil.rmtree(path)
if os.path.isfile(path):
return os.r... | [
"def",
"remove",
"(",
"path",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"return",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"path",
")",
":",
"return",
"shutil",
".",
"rmtree",
"(",
"path",
")",
"if",
"os... | 24.538462 | 17.769231 |
def get_Mapping_key_value(mp):
"""Retrieves the key and value types from a PEP 484 mapping or subclass of such.
mp must be a (subclass of) typing.Mapping.
"""
try:
res = _select_Generic_superclass_parameters(mp, typing.Mapping)
except TypeError:
res = None
if res is None:
... | [
"def",
"get_Mapping_key_value",
"(",
"mp",
")",
":",
"try",
":",
"res",
"=",
"_select_Generic_superclass_parameters",
"(",
"mp",
",",
"typing",
".",
"Mapping",
")",
"except",
"TypeError",
":",
"res",
"=",
"None",
"if",
"res",
"is",
"None",
":",
"raise",
"T... | 33.5 | 17.583333 |
def _build_filter(*patterns):
"""
Given a list of patterns, return a callable that will be true only if
the input matches at least one of the patterns.
"""
return lambda name: any(fnmatchcase(name, pat=pat) for pat in patterns) | [
"def",
"_build_filter",
"(",
"*",
"patterns",
")",
":",
"return",
"lambda",
"name",
":",
"any",
"(",
"fnmatchcase",
"(",
"name",
",",
"pat",
"=",
"pat",
")",
"for",
"pat",
"in",
"patterns",
")"
] | 43.666667 | 17 |
def from_python_file(
cls, python_file, lambdas_path, json_filename: str, stem: str
):
"""Builds GrFN object from Python file."""
with open(python_file, "r") as f:
pySrc = f.read()
return cls.from_python_src(pySrc, lambdas_path, json_filename, stem) | [
"def",
"from_python_file",
"(",
"cls",
",",
"python_file",
",",
"lambdas_path",
",",
"json_filename",
":",
"str",
",",
"stem",
":",
"str",
")",
":",
"with",
"open",
"(",
"python_file",
",",
"\"r\"",
")",
"as",
"f",
":",
"pySrc",
"=",
"f",
".",
"read",
... | 41.571429 | 18.714286 |
def get_version(cls, settings: Dict[str, Any], path: str) -> Optional[str]:
"""Generate the version string to be used in static URLs.
``settings`` is the `Application.settings` dictionary and ``path``
is the relative location of the requested asset on the filesystem.
The returned value ... | [
"def",
"get_version",
"(",
"cls",
",",
"settings",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"path",
":",
"str",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"abs_path",
"=",
"cls",
".",
"get_absolute_path",
"(",
"settings",
"[",
"\"static_path\""... | 49.733333 | 23.466667 |
def is_playing_shared_game(self, steamID, appid_playing, format=None):
"""Returns valid lender SteamID if game currently played is borrowed.
steamID: The users ID
appid_playing: The game player is currently playing
format: Return format. None defaults to json. (json, xml, vdf)
... | [
"def",
"is_playing_shared_game",
"(",
"self",
",",
"steamID",
",",
"appid_playing",
",",
"format",
"=",
"None",
")",
":",
"parameters",
"=",
"{",
"'steamid'",
":",
"steamID",
",",
"'appid_playing'",
":",
"appid_playing",
"}",
"if",
"format",
"is",
"not",
"No... | 43.8 | 19 |
def AddRow(self, *args):
''' Parms are a variable number of Elements '''
NumRows = len(self.Rows) # number of existing rows is our row number
CurrentRowNumber = NumRows # this row's number
CurrentRow = [] # start with a blank row and build up
# ------------------------- Add t... | [
"def",
"AddRow",
"(",
"self",
",",
"*",
"args",
")",
":",
"NumRows",
"=",
"len",
"(",
"self",
".",
"Rows",
")",
"# number of existing rows is our row number",
"CurrentRowNumber",
"=",
"NumRows",
"# this row's number",
"CurrentRow",
"=",
"[",
"]",
"# start with a b... | 60.583333 | 24.25 |
def DoesNotContain(self, value):
"""Sets the type of the WHERE clause as "does not contain".
Args:
value: The value to be used in the WHERE condition.
Returns:
The query builder that this WHERE builder links to.
"""
self._awql = self._CreateSingleValueCondition(value, 'DOES_NOT_CONTAIN... | [
"def",
"DoesNotContain",
"(",
"self",
",",
"value",
")",
":",
"self",
".",
"_awql",
"=",
"self",
".",
"_CreateSingleValueCondition",
"(",
"value",
",",
"'DOES_NOT_CONTAIN'",
")",
"return",
"self",
".",
"_query_builder"
] | 31.181818 | 20.636364 |
def is_list_of_list(item):
"""
check whether the item is list (tuple)
and consist of list (tuple) elements
"""
if (
type(item) in (list, tuple)
and len(item)
and isinstance(item[0], (list, tuple))
):
return True
return False | [
"def",
"is_list_of_list",
"(",
"item",
")",
":",
"if",
"(",
"type",
"(",
"item",
")",
"in",
"(",
"list",
",",
"tuple",
")",
"and",
"len",
"(",
"item",
")",
"and",
"isinstance",
"(",
"item",
"[",
"0",
"]",
",",
"(",
"list",
",",
"tuple",
")",
")... | 22.75 | 13.083333 |
def expand_user(path):
"""Expand '~'-style usernames in strings.
This is similar to :func:`os.path.expanduser`, but it computes and returns
extra information that will be useful if the input was being used in
computing completions, and you wish to return the completions with the
original '~' instea... | [
"def",
"expand_user",
"(",
"path",
")",
":",
"# Default values",
"tilde_expand",
"=",
"False",
"tilde_val",
"=",
"''",
"newpath",
"=",
"path",
"if",
"path",
".",
"startswith",
"(",
"'~'",
")",
":",
"tilde_expand",
"=",
"True",
"rest",
"=",
"len",
"(",
"p... | 27.368421 | 20.894737 |
def chunked_qs(qs, chunk_size=10000, fields=None):
"""
Generator to iterate over the given QuerySet, chunk_size rows at a time
Usage:
>>> qs = FailureLine.objects.filter(action='test_result')
>>> for qs in chunked_qs(qs, chunk_size=10000, fields=['id', 'message']):
... for line... | [
"def",
"chunked_qs",
"(",
"qs",
",",
"chunk_size",
"=",
"10000",
",",
"fields",
"=",
"None",
")",
":",
"min_id",
"=",
"0",
"while",
"True",
":",
"chunk",
"=",
"qs",
".",
"filter",
"(",
"id__gt",
"=",
"min_id",
")",
".",
"order_by",
"(",
"'id'",
")"... | 29.282051 | 25.128205 |
def p_params(self, p):
'params : params_begin param_end'
p[0] = p[1] + (p[2],)
p.set_lineno(0, p.lineno(1)) | [
"def",
"p_params",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"p",
"[",
"1",
"]",
"+",
"(",
"p",
"[",
"2",
"]",
",",
")",
"p",
".",
"set_lineno",
"(",
"0",
",",
"p",
".",
"lineno",
"(",
"1",
")",
")"
] | 32 | 8.5 |
def _GetEventData(
self, parser_mediator, record_index, evt_record, recovered=False):
"""Retrieves event data from the Windows EventLog (EVT) record.
Args:
parser_mediator (ParserMediator): mediates interactions between parsers
and other components, such as storage and dfvfs.
record... | [
"def",
"_GetEventData",
"(",
"self",
",",
"parser_mediator",
",",
"record_index",
",",
"evt_record",
",",
"recovered",
"=",
"False",
")",
":",
"event_data",
"=",
"WinEvtRecordEventData",
"(",
")",
"try",
":",
"event_data",
".",
"record_number",
"=",
"evt_record"... | 37.290909 | 20.927273 |
def run(self, model, tol=0.001, max_iters=999, verbose=True):
"""
Runs EM iterations
:param model: Normalization model (1: Gene->Allele->Isoform, 2: Gene->Isoform->Allele, 3: Gene->Isoform*Allele, 4: Gene*Isoform*Allele)
:param tol: Tolerance for termination
:param max_iters: Ma... | [
"def",
"run",
"(",
"self",
",",
"model",
",",
"tol",
"=",
"0.001",
",",
"max_iters",
"=",
"999",
",",
"verbose",
"=",
"True",
")",
":",
"orig_err_states",
"=",
"np",
".",
"seterr",
"(",
"all",
"=",
"'raise'",
")",
"np",
".",
"seterr",
"(",
"under",... | 49.529412 | 22.941176 |
def lookup(self, vtype, vname, target_id=None):
"""Return value of vname from the variable store vtype.
Valid vtypes are `strings` 'counters', and `pending`. If the value
is not found in the current steps store, earlier steps will be
checked. If not found, '', 0, or (None, None) is retu... | [
"def",
"lookup",
"(",
"self",
",",
"vtype",
",",
"vname",
",",
"target_id",
"=",
"None",
")",
":",
"nullvals",
"=",
"{",
"'strings'",
":",
"''",
",",
"'counters'",
":",
"0",
",",
"'pending'",
":",
"(",
"None",
",",
"None",
")",
"}",
"nullval",
"=",... | 34.731707 | 17.121951 |
def convertVariable(self, key, varName, varValue):
"""Puts the function in the globals() of the main module."""
if isinstance(varValue, encapsulation.FunctionEncapsulation):
result = varValue.getFunction()
# Update the global scope of the function to match the current module
... | [
"def",
"convertVariable",
"(",
"self",
",",
"key",
",",
"varName",
",",
"varValue",
")",
":",
"if",
"isinstance",
"(",
"varValue",
",",
"encapsulation",
".",
"FunctionEncapsulation",
")",
":",
"result",
"=",
"varValue",
".",
"getFunction",
"(",
")",
"# Updat... | 45.307692 | 15 |
def _is_better_match(x, y, matched_a, matched_b, attributes_dict_a, attributes_dict_b):
"""
:param x: The first element of a possible match.
:param y: The second element of a possible match.
:param matched_a: The current matches for the first set.
:param... | [
"def",
"_is_better_match",
"(",
"x",
",",
"y",
",",
"matched_a",
",",
"matched_b",
",",
"attributes_dict_a",
",",
"attributes_dict_b",
")",
":",
"attributes_x",
"=",
"attributes_dict_a",
"[",
"x",
"]",
"attributes_y",
"=",
"attributes_dict_b",
"[",
"y",
"]",
"... | 52.428571 | 24.619048 |
def parse_mailto(mailto_str):
"""
Interpret mailto-string
:param mailto_str: the string to interpret. Must conform to :rfc:2368.
:type mailto_str: str
:return: the header fields and the body found in the mailto link as a tuple
of length two
:rtype: tuple(dict(str->list(str)), str)
"... | [
"def",
"parse_mailto",
"(",
"mailto_str",
")",
":",
"if",
"mailto_str",
".",
"startswith",
"(",
"'mailto:'",
")",
":",
"import",
"urllib",
".",
"parse",
"to_str",
",",
"parms_str",
"=",
"mailto_str",
"[",
"7",
":",
"]",
".",
"partition",
"(",
"'?'",
")",... | 30.433333 | 16.433333 |
def _check_quotas(self, time_ms):
"""
Check if we have violated our quota for any metric that
has a configured quota
"""
for metric in self._metrics:
if metric.config and metric.config.quota:
value = metric.value(time_ms)
if not metric.... | [
"def",
"_check_quotas",
"(",
"self",
",",
"time_ms",
")",
":",
"for",
"metric",
"in",
"self",
".",
"_metrics",
":",
"if",
"metric",
".",
"config",
"and",
"metric",
".",
"config",
".",
"quota",
":",
"value",
"=",
"metric",
".",
"value",
"(",
"time_ms",
... | 48.785714 | 15.928571 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.