text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def commit_update():
""" Switch the target boot partition. """
unused = _find_unused_partition()
new = _switch_partition()
if new != unused:
msg = f"Bad switch: switched to {new} when {unused} was unused"
LOG.error(msg)
raise RuntimeError(msg)
else:
LOG.info(f'commit_... | [
"def",
"commit_update",
"(",
")",
":",
"unused",
"=",
"_find_unused_partition",
"(",
")",
"new",
"=",
"_switch_partition",
"(",
")",
"if",
"new",
"!=",
"unused",
":",
"msg",
"=",
"f\"Bad switch: switched to {new} when {unused} was unused\"",
"LOG",
".",
"error",
"... | 34.7 | 16.4 |
def _recursive_repr(item):
"""Hack around python `repr` to deterministically represent dictionaries.
This is able to represent more things than json.dumps, since it does not require things to be JSON serializable
(e.g. datetimes).
"""
if isinstance(item, basestring):
result = str(item)
... | [
"def",
"_recursive_repr",
"(",
"item",
")",
":",
"if",
"isinstance",
"(",
"item",
",",
"basestring",
")",
":",
"result",
"=",
"str",
"(",
"item",
")",
"elif",
"isinstance",
"(",
"item",
",",
"list",
")",
":",
"result",
"=",
"'[{}]'",
".",
"format",
"... | 40.875 | 22.375 |
def format(self, version=0x10, wipe=None):
"""Format a FeliCa Lite Tag for NDEF.
"""
return super(FelicaLite, self).format(version, wipe) | [
"def",
"format",
"(",
"self",
",",
"version",
"=",
"0x10",
",",
"wipe",
"=",
"None",
")",
":",
"return",
"super",
"(",
"FelicaLite",
",",
"self",
")",
".",
"format",
"(",
"version",
",",
"wipe",
")"
] | 31.6 | 12.4 |
def fromtab(args):
"""
%prog fromtab tabfile fastafile
Convert 2-column sequence file to FASTA format. One usage for this is to
generatea `adapters.fasta` for TRIMMOMATIC.
"""
p = OptionParser(fromtab.__doc__)
p.set_sep(sep=None)
p.add_option("--noheader", default=False, action="store_t... | [
"def",
"fromtab",
"(",
"args",
")",
":",
"p",
"=",
"OptionParser",
"(",
"fromtab",
".",
"__doc__",
")",
"p",
".",
"set_sep",
"(",
"sep",
"=",
"None",
")",
"p",
".",
"add_option",
"(",
"\"--noheader\"",
",",
"default",
"=",
"False",
",",
"action",
"="... | 28.25 | 17.65 |
def replace_namespaced_replica_set_scale(self, name, namespace, body, **kwargs):
"""
replace scale of the specified ReplicaSet
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
>>> thread = api.replace_namesp... | [
"def",
"replace_namespaced_replica_set_scale",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"body",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
... | 68.64 | 40.88 |
def smart_reroot(treefile, outgroupfile, outfile, format=0):
"""
simple function to reroot Newick format tree using ete2
Tree reading format options see here:
http://packages.python.org/ete2/tutorial/tutorial_trees.html#reading-newick-trees
"""
tree = Tree(treefile, format=format)
leaves = ... | [
"def",
"smart_reroot",
"(",
"treefile",
",",
"outgroupfile",
",",
"outfile",
",",
"format",
"=",
"0",
")",
":",
"tree",
"=",
"Tree",
"(",
"treefile",
",",
"format",
"=",
"format",
")",
"leaves",
"=",
"[",
"t",
".",
"name",
"for",
"t",
"in",
"tree",
... | 32.125 | 19 |
def tokenize(self, path):
"""Tokenizes a text file."""
assert os.path.exists(path)
# Add words to the dictionary
with open(path, 'r') as f:
tokens = 0
for line in f:
words = line.split() + ['<eos>']
tokens += len(words)
... | [
"def",
"tokenize",
"(",
"self",
",",
"path",
")",
":",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
"# Add words to the dictionary",
"with",
"open",
"(",
"path",
",",
"'r'",
")",
"as",
"f",
":",
"tokens",
"=",
"0",
"for",
"line",
"in... | 31.73913 | 12.521739 |
def on_log(request, page_name):
"""Show the list of recent changes."""
page = Page.query.filter_by(name=page_name).first()
if page is None:
return page_missing(request, page_name, False)
return Response(generate_template("action_log.html", page=page)) | [
"def",
"on_log",
"(",
"request",
",",
"page_name",
")",
":",
"page",
"=",
"Page",
".",
"query",
".",
"filter_by",
"(",
"name",
"=",
"page_name",
")",
".",
"first",
"(",
")",
"if",
"page",
"is",
"None",
":",
"return",
"page_missing",
"(",
"request",
"... | 45 | 14.333333 |
def _predict_one(self, document, encoding=None, return_blocks=False):
"""
Predict class (content=1 or not-content=0) of each block in an HTML
document.
Args:
documents (str): HTML document
Returns:
``np.ndarray``: array of binary predictions for content ... | [
"def",
"_predict_one",
"(",
"self",
",",
"document",
",",
"encoding",
"=",
"None",
",",
"return_blocks",
"=",
"False",
")",
":",
"# blockify",
"blocks",
"=",
"self",
".",
"blockifier",
".",
"blockify",
"(",
"document",
",",
"encoding",
"=",
"encoding",
")"... | 34.757576 | 21.121212 |
def sim_jaro_winkler(
src,
tar,
qval=1,
mode='winkler',
long_strings=False,
boost_threshold=0.7,
scaling_factor=0.1,
):
"""Return the Jaro or Jaro-Winkler similarity of two strings.
This is a wrapper for :py:meth:`JaroWinkler.sim`.
Parameters
----------
src : str
... | [
"def",
"sim_jaro_winkler",
"(",
"src",
",",
"tar",
",",
"qval",
"=",
"1",
",",
"mode",
"=",
"'winkler'",
",",
"long_strings",
"=",
"False",
",",
"boost_threshold",
"=",
"0.7",
",",
"scaling_factor",
"=",
"0.1",
",",
")",
":",
"return",
"JaroWinkler",
"("... | 32.6 | 25 |
def get_query_includes(tokenized_terms, search_fields):
"""
Builds a query for included terms in a text search.
"""
query = None
for term in tokenized_terms:
or_query = None
for field_name in search_fields:
q = Q(**{"%s__icontains" % field_name: term})
if or_q... | [
"def",
"get_query_includes",
"(",
"tokenized_terms",
",",
"search_fields",
")",
":",
"query",
"=",
"None",
"for",
"term",
"in",
"tokenized_terms",
":",
"or_query",
"=",
"None",
"for",
"field_name",
"in",
"search_fields",
":",
"q",
"=",
"Q",
"(",
"*",
"*",
... | 29.222222 | 12.333333 |
def log1p(
data: Union[AnnData, np.ndarray, spmatrix],
copy: bool = False,
chunked: bool = False,
chunk_size: Optional[int] = None,
) -> Optional[AnnData]:
"""Logarithmize the data matrix.
Computes :math:`X = \\log(X + 1)`, where :math:`log` denotes the natural logarithm.
Parameters
--... | [
"def",
"log1p",
"(",
"data",
":",
"Union",
"[",
"AnnData",
",",
"np",
".",
"ndarray",
",",
"spmatrix",
"]",
",",
"copy",
":",
"bool",
"=",
"False",
",",
"chunked",
":",
"bool",
"=",
"False",
",",
"chunk_size",
":",
"Optional",
"[",
"int",
"]",
"=",... | 29.672727 | 21.690909 |
def curriculum2schedule(curriculum, first_day, compress=False, time_table=None):
"""
将课程表转换为上课时间表, 如果 compress=False 结果是未排序的, 否则为压缩并排序后的上课时间表
:param curriculum: 课表
:param first_day: 第一周周一, 如 datetime.datetime(2016, 8, 29)
:param compress: 压缩连续的课时为一个
:param time_table: 每天上课的时间表, 形如 ``((start tim... | [
"def",
"curriculum2schedule",
"(",
"curriculum",
",",
"first_day",
",",
"compress",
"=",
"False",
",",
"time_table",
"=",
"None",
")",
":",
"schedule",
"=",
"[",
"]",
"time_table",
"=",
"time_table",
"or",
"(",
"(",
"timedelta",
"(",
"hours",
"=",
"8",
"... | 42.980392 | 19.607843 |
def save_sbml(filename, model, y0=None, volume=1.0, is_valid=True):
"""
Save a model in the SBML format.
Parameters
----------
model : NetworkModel
y0 : dict
Initial condition.
volume : Real or Real3, optional
A size of the simulation volume.
is_valid : bool, optional
... | [
"def",
"save_sbml",
"(",
"filename",
",",
"model",
",",
"y0",
"=",
"None",
",",
"volume",
"=",
"1.0",
",",
"is_valid",
"=",
"True",
")",
":",
"y0",
"=",
"y0",
"or",
"{",
"}",
"import",
"libsbml",
"document",
"=",
"export_sbml",
"(",
"model",
",",
"... | 26.230769 | 17.923077 |
def check_for_connection(self):
""" Scan arguments for a `@name` one.
"""
for idx, arg in enumerate(self.args):
if arg.startswith('@'):
if arg[1:] not in config.connections:
self.parser.error("Undefined connection '{}'!".format(arg[1:]))
... | [
"def",
"check_for_connection",
"(",
"self",
")",
":",
"for",
"idx",
",",
"arg",
"in",
"enumerate",
"(",
"self",
".",
"args",
")",
":",
"if",
"arg",
".",
"startswith",
"(",
"'@'",
")",
":",
"if",
"arg",
"[",
"1",
":",
"]",
"not",
"in",
"config",
"... | 46.272727 | 15.545455 |
def get_code_version_numbers(cp):
"""Will extract the version information from the executables listed in
the executable section of the supplied ConfigParser object.
Returns
--------
dict
A dictionary keyed by the executable name with values giving the
version string for each executa... | [
"def",
"get_code_version_numbers",
"(",
"cp",
")",
":",
"code_version_dict",
"=",
"{",
"}",
"for",
"_",
",",
"value",
"in",
"cp",
".",
"items",
"(",
"'executables'",
")",
":",
"_",
",",
"exe_name",
"=",
"os",
".",
"path",
".",
"split",
"(",
"value",
... | 42.821429 | 19.928571 |
def _get_possible_query_bridging_contigs(self, nucmer_hits, log_fh=None, log_outprefix=None):
'''Input is dict qry_name -> list of nucmer hits to that qry. Returns dict qry_name -> tuple(start hit, end hit)'''
bridges = {}
writing_log_file = None not in [log_fh, log_outprefix]
for qry_n... | [
"def",
"_get_possible_query_bridging_contigs",
"(",
"self",
",",
"nucmer_hits",
",",
"log_fh",
"=",
"None",
",",
"log_outprefix",
"=",
"None",
")",
":",
"bridges",
"=",
"{",
"}",
"writing_log_file",
"=",
"None",
"not",
"in",
"[",
"log_fh",
",",
"log_outprefix"... | 52.36 | 37.6 |
def jtag_send(self, tms, tdi, num_bits):
"""Sends data via JTAG.
Sends data via JTAG on the rising clock edge, TCK. At on each rising
clock edge, on bit is transferred in from TDI and out to TDO. The
clock uses the TMS to step through the standard JTAG state machine.
Args:
... | [
"def",
"jtag_send",
"(",
"self",
",",
"tms",
",",
"tdi",
",",
"num_bits",
")",
":",
"if",
"not",
"util",
".",
"is_natural",
"(",
"num_bits",
")",
"or",
"num_bits",
"<=",
"0",
"or",
"num_bits",
">",
"32",
":",
"raise",
"ValueError",
"(",
"'Number of bit... | 41.933333 | 27.133333 |
def parse_source_file(source_file):
"""Parses a source file thing and returns the file name
Example:
>>> parse_file('hg:hg.mozilla.org/releases/mozilla-esr52:js/src/jit/MIR.h:755067c14b06')
'js/src/jit/MIR.h'
:arg str source_file: the source file ("file") from a stack frame
:returns: the fil... | [
"def",
"parse_source_file",
"(",
"source_file",
")",
":",
"if",
"not",
"source_file",
":",
"return",
"None",
"vcsinfo",
"=",
"source_file",
".",
"split",
"(",
"':'",
")",
"if",
"len",
"(",
"vcsinfo",
")",
"==",
"4",
":",
"# These are repositories or cloud file... | 30 | 22.588235 |
def encode_access_token(identity, secret, algorithm, expires_delta, fresh,
user_claims, csrf, identity_claim_key, user_claims_key,
json_encoder=None):
"""
Creates a new encoded (utf-8) access token.
:param identity: Identifier for who this token is for (ex, u... | [
"def",
"encode_access_token",
"(",
"identity",
",",
"secret",
",",
"algorithm",
",",
"expires_delta",
",",
"fresh",
",",
"user_claims",
",",
"csrf",
",",
"identity_claim_key",
",",
"user_claims_key",
",",
"json_encoder",
"=",
"None",
")",
":",
"if",
"isinstance"... | 42.674419 | 21.046512 |
def trigger_all_callbacks(self, callbacks=None):
"""Trigger callbacks for all keys on all or a subset of subscribers.
:param Iterable callbacks: list of callbacks or none for all subscribed
:rtype: Iterable[tornado.concurrent.Future]
"""
return [ret
for key in se... | [
"def",
"trigger_all_callbacks",
"(",
"self",
",",
"callbacks",
"=",
"None",
")",
":",
"return",
"[",
"ret",
"for",
"key",
"in",
"self",
"for",
"ret",
"in",
"self",
".",
"trigger_callbacks",
"(",
"key",
",",
"callbacks",
"=",
"None",
")",
"]"
] | 42.888889 | 17.666667 |
def _get_content(context, page, content_type, lang, fallback=True):
"""Helper function used by ``PlaceholderNode``."""
if not page:
return ''
if not lang and 'lang' in context:
lang = context.get('lang', pages_settings.PAGE_DEFAULT_LANGUAGE)
page = get_page_from_string_or_id(page, lang... | [
"def",
"_get_content",
"(",
"context",
",",
"page",
",",
"content_type",
",",
"lang",
",",
"fallback",
"=",
"True",
")",
":",
"if",
"not",
"page",
":",
"return",
"''",
"if",
"not",
"lang",
"and",
"'lang'",
"in",
"context",
":",
"lang",
"=",
"context",
... | 29.4 | 25.533333 |
def from_config(cls, config):
"""Instantiates an initializer from a configuration dictionary."""
return cls(**{
'initializers': [tf.compat.v2.initializers.deserialize(init)
for init in config.get('initializers', [])],
'sizes': config.get('sizes', []),
'validate_a... | [
"def",
"from_config",
"(",
"cls",
",",
"config",
")",
":",
"return",
"cls",
"(",
"*",
"*",
"{",
"'initializers'",
":",
"[",
"tf",
".",
"compat",
".",
"v2",
".",
"initializers",
".",
"deserialize",
"(",
"init",
")",
"for",
"init",
"in",
"config",
".",... | 45.125 | 18.125 |
def save_state(self, state):
"""Save a state doc to the LRS
:param state: State document to be saved
:type state: :class:`tincan.documents.state_document.StateDocument`
:return: LRS Response object with saved state as content
:rtype: :class:`tincan.lrs_response.LRSResponse`
... | [
"def",
"save_state",
"(",
"self",
",",
"state",
")",
":",
"request",
"=",
"HTTPRequest",
"(",
"method",
"=",
"\"PUT\"",
",",
"resource",
"=",
"\"activities/state\"",
",",
"content",
"=",
"state",
".",
"content",
",",
")",
"if",
"state",
".",
"content_type"... | 34.466667 | 16.7 |
def get(self, url, **kwargs):
"""Send a GET request to the specified URL.
Method directly wraps around `Session.get` and updates browser
attributes.
<http://docs.python-requests.org/en/master/api/#requests.get>
Args:
url: URL for the new `Request` object.
... | [
"def",
"get",
"(",
"self",
",",
"url",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
",",
"*",
"*",
"kwargs",
")",
"self",
".",
"_url",
"=",
"response",
".",
"url",
"self",
".",
"_response",
... | 32.333333 | 19.444444 |
def temperature(self) -> Optional[ErrorValue]:
"""Sample temperature"""
try:
return ErrorValue(self._data['Temperature'], self._data.setdefault('TemperatureError', 0.0))
except KeyError:
return None | [
"def",
"temperature",
"(",
"self",
")",
"->",
"Optional",
"[",
"ErrorValue",
"]",
":",
"try",
":",
"return",
"ErrorValue",
"(",
"self",
".",
"_data",
"[",
"'Temperature'",
"]",
",",
"self",
".",
"_data",
".",
"setdefault",
"(",
"'TemperatureError'",
",",
... | 40.166667 | 21.833333 |
def to_dict(self):
"""Return all the details of this MLPipeline in a dict.
The dict structure contains all the `__init__` arguments of the
MLPipeline, as well as the current hyperparameter values and the
specification of the tunable_hyperparameters::
{
"prim... | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"{",
"'primitives'",
":",
"self",
".",
"primitives",
",",
"'init_params'",
":",
"self",
".",
"init_params",
",",
"'input_names'",
":",
"self",
".",
"input_names",
",",
"'output_names'",
":",
"self",
".",
"... | 36.3125 | 14.5625 |
def init_from_file(cls,
catalog,
name=None,
path=None,
clean=False,
merge=True,
pop_schema=True,
ignore_keys=[],
compare_to_existing=Tru... | [
"def",
"init_from_file",
"(",
"cls",
",",
"catalog",
",",
"name",
"=",
"None",
",",
"path",
"=",
"None",
",",
"clean",
"=",
"False",
",",
"merge",
"=",
"True",
",",
"pop_schema",
"=",
"True",
",",
"ignore_keys",
"=",
"[",
"]",
",",
"compare_to_existing... | 35.690476 | 16.5 |
def save_model(self, model, meta_data=None, index_fields=None):
"""
model (instance): Model instance.
meta (dict): JSON serializable meta data for logging of save operation.
{'lorem': 'ipsum', 'dolar': 5}
index_fields (list): Tuple list for indexing keys in ri... | [
"def",
"save_model",
"(",
"self",
",",
"model",
",",
"meta_data",
"=",
"None",
",",
"index_fields",
"=",
"None",
")",
":",
"# if model:",
"# self._model = model",
"if",
"settings",
".",
"DEBUG",
":",
"t1",
"=",
"time",
".",
"time",
"(",
")",
"clean_val... | 35.881356 | 17.508475 |
def push_script(self, scriptable, script, callback=None):
"""Run the script and add it to the list of threads."""
if script in self.threads:
self.threads[script].finish()
thread = Thread(self.run_script(scriptable, script),
scriptable, callback)
... | [
"def",
"push_script",
"(",
"self",
",",
"scriptable",
",",
"script",
",",
"callback",
"=",
"None",
")",
":",
"if",
"script",
"in",
"self",
".",
"threads",
":",
"self",
".",
"threads",
"[",
"script",
"]",
".",
"finish",
"(",
")",
"thread",
"=",
"Threa... | 47 | 10.375 |
def _aws_get_instance_by_tag(region, name, tag, raw):
"""Get all instances matching a tag."""
client = boto3.session.Session().client('ec2', region)
matching_reservations = client.describe_instances(Filters=[{'Name': tag, 'Values': [name]}]).get('Reservations', [])
instances = []
[[instances.append(... | [
"def",
"_aws_get_instance_by_tag",
"(",
"region",
",",
"name",
",",
"tag",
",",
"raw",
")",
":",
"client",
"=",
"boto3",
".",
"session",
".",
"Session",
"(",
")",
".",
"client",
"(",
"'ec2'",
",",
"region",
")",
"matching_reservations",
"=",
"client",
".... | 66.625 | 36.75 |
def create(self, path, visibility):
"""
Create a new FunctionVersionInstance
:param unicode path: The path
:param FunctionVersionInstance.Visibility visibility: The visibility
:returns: Newly created FunctionVersionInstance
:rtype: twilio.rest.serverless.v1.service.func... | [
"def",
"create",
"(",
"self",
",",
"path",
",",
"visibility",
")",
":",
"data",
"=",
"values",
".",
"of",
"(",
"{",
"'Path'",
":",
"path",
",",
"'Visibility'",
":",
"visibility",
",",
"}",
")",
"payload",
"=",
"self",
".",
"_version",
".",
"create",
... | 31.291667 | 20.625 |
def build_finished(app, exception):
"""
When the build is finished, we copy the javascript files (if specified)
to the build directory (the static folder)
"""
# Skip for non-html or if javascript is not inlined
if not app.env.config.wavedrom_html_jsinline:
return
if app.config.offli... | [
"def",
"build_finished",
"(",
"app",
",",
"exception",
")",
":",
"# Skip for non-html or if javascript is not inlined",
"if",
"not",
"app",
".",
"env",
".",
"config",
".",
"wavedrom_html_jsinline",
":",
"return",
"if",
"app",
".",
"config",
".",
"offline_skin_js_pat... | 52.769231 | 28.769231 |
def symmetric_difference_update(self, other):
# type: (Iterable[Any]) -> _BaseSet
"""
Update the TerminalSet.
Keep elements from self and other, but discard elements that are in both.
:param other: Iterable object with elements to compare with.
:return: Current instance w... | [
"def",
"symmetric_difference_update",
"(",
"self",
",",
"other",
")",
":",
"# type: (Iterable[Any]) -> _BaseSet",
"intersect",
"=",
"self",
".",
"intersection",
"(",
"other",
")",
"self",
".",
"remove",
"(",
"*",
"intersect",
")",
"for",
"elem",
"in",
"set",
"... | 39.692308 | 12.307692 |
def is_protected_type(obj):
"""Determine if the object instance is of a protected type.
Objects of protected types are preserved as-is when passed to
force_unicode(strings_only=True).
"""
return isinstance(obj, (
types.NoneType,
int, long,
datetime.datetime, datetime.date, d... | [
"def",
"is_protected_type",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"(",
"types",
".",
"NoneType",
",",
"int",
",",
"long",
",",
"datetime",
".",
"datetime",
",",
"datetime",
".",
"date",
",",
"datetime",
".",
"time",
",",
"float... | 29.333333 | 16.666667 |
def p_finally(self, p):
"""finally : FINALLY block"""
p[0] = self.asttypes.Finally(elements=p[2])
p[0].setpos(p) | [
"def",
"p_finally",
"(",
"self",
",",
"p",
")",
":",
"p",
"[",
"0",
"]",
"=",
"self",
".",
"asttypes",
".",
"Finally",
"(",
"elements",
"=",
"p",
"[",
"2",
"]",
")",
"p",
"[",
"0",
"]",
".",
"setpos",
"(",
"p",
")"
] | 33.25 | 11.5 |
def clear(self):
"""
Command: 0x03
clear all leds
Data:
[Command]
"""
header = bytearray()
header.append(LightProtocolCommand.Clear)
return self.send(header) | [
"def",
"clear",
"(",
"self",
")",
":",
"header",
"=",
"bytearray",
"(",
")",
"header",
".",
"append",
"(",
"LightProtocolCommand",
".",
"Clear",
")",
"return",
"self",
".",
"send",
"(",
"header",
")"
] | 12.769231 | 22.307692 |
def start(self):
"""
Start the daemon
"""
# Check for a pidfile to see if the daemon already runs
logger.info('Starting daemon')
try:
with open(self.pidfile, 'r') as fd:
pid = int(fd.read().strip())
except IOError:
pid = Non... | [
"def",
"start",
"(",
"self",
")",
":",
"# Check for a pidfile to see if the daemon already runs",
"logger",
".",
"info",
"(",
"'Starting daemon'",
")",
"try",
":",
"with",
"open",
"(",
"self",
".",
"pidfile",
",",
"'r'",
")",
"as",
"fd",
":",
"pid",
"=",
"in... | 26.681818 | 18.045455 |
def load_module_from_path(i):
"""
Input: {
path - module path
module_code_name - module name
(cfg) - configuration of the module if exists ...
(skip_init) - if 'yes', skip init
(data_uoa) - module UOA (usefu... | [
"def",
"load_module_from_path",
"(",
"i",
")",
":",
"p",
"=",
"i",
"[",
"'path'",
"]",
"n",
"=",
"i",
"[",
"'module_code_name'",
"]",
"xcfg",
"=",
"i",
".",
"get",
"(",
"'cfg'",
",",
"None",
")",
"# Find module",
"try",
":",
"x",
"=",
"imp",
".",
... | 31.758621 | 24.195402 |
def set_system_date(newdate):
'''
Set the Windows system date. Use <mm-dd-yy> format for the date.
Args:
newdate (str):
The date to set. Can be any of the following formats
- YYYY-MM-DD
- MM-DD-YYYY
- MM-DD-YY
- MM/DD/YYYY
- M... | [
"def",
"set_system_date",
"(",
"newdate",
")",
":",
"fmts",
"=",
"[",
"'%Y-%m-%d'",
",",
"'%m-%d-%Y'",
",",
"'%m-%d-%y'",
",",
"'%m/%d/%Y'",
",",
"'%m/%d/%y'",
",",
"'%Y/%m/%d'",
"]",
"# Get date/time object from newdate",
"dt_obj",
"=",
"_try_parse_datetime",
"(",
... | 26.285714 | 21.314286 |
def _suitableVerbExpansion( foundSubcatChain ):
'''
V6tab etteantud jadast osa, mis sobib:
*) kui liikmeid on 3, keskmine on konjuktsioon ning esimene ja viimane
klapivad, tagastab selle kolmiku;
Nt. ei_0 saa_0 lihtsalt välja astuda_? ja_? uttu tõmmata_?
... | [
"def",
"_suitableVerbExpansion",
"(",
"foundSubcatChain",
")",
":",
"markings",
"=",
"[",
"]",
"tokens",
"=",
"[",
"]",
"nonConjTokens",
"=",
"[",
"]",
"for",
"(",
"marking",
",",
"token",
")",
"in",
"foundSubcatChain",
":",
"markings",
".",
"append",
"(",... | 46.034483 | 20.724138 |
def zoom_for_pixelsize(pixel_size, max_z=24, tilesize=256):
"""
Get mercator zoom level corresponding to a pixel resolution.
Freely adapted from
https://github.com/OSGeo/gdal/blob/b0dfc591929ebdbccd8a0557510c5efdb893b852/gdal/swig/python/scripts/gdal2tiles.py#L294
Parameters
----------
pix... | [
"def",
"zoom_for_pixelsize",
"(",
"pixel_size",
",",
"max_z",
"=",
"24",
",",
"tilesize",
"=",
"256",
")",
":",
"for",
"z",
"in",
"range",
"(",
"max_z",
")",
":",
"if",
"pixel_size",
">",
"_meters_per_pixel",
"(",
"z",
",",
"0",
",",
"tilesize",
"=",
... | 28.961538 | 23.653846 |
def get_currency_symbol(self):
"""Get the currency Symbol
"""
locale = locales.getLocale('en')
setup = api.get_setup()
currency = setup.getCurrency()
return locale.numbers.currencies[currency].symbol | [
"def",
"get_currency_symbol",
"(",
"self",
")",
":",
"locale",
"=",
"locales",
".",
"getLocale",
"(",
"'en'",
")",
"setup",
"=",
"api",
".",
"get_setup",
"(",
")",
"currency",
"=",
"setup",
".",
"getCurrency",
"(",
")",
"return",
"locale",
".",
"numbers"... | 34.428571 | 5.428571 |
def draw_grid(self):
"""Draws the grid and tiles."""
self.screen.fill((0xbb, 0xad, 0xa0), self.origin + (self.game_width, self.game_height))
for y, row in enumerate(self.grid):
for x, cell in enumerate(row):
self.screen.blit(self.tiles[cell], self.get_tile_location(x,... | [
"def",
"draw_grid",
"(",
"self",
")",
":",
"self",
".",
"screen",
".",
"fill",
"(",
"(",
"0xbb",
",",
"0xad",
",",
"0xa0",
")",
",",
"self",
".",
"origin",
"+",
"(",
"self",
".",
"game_width",
",",
"self",
".",
"game_height",
")",
")",
"for",
"y"... | 53.166667 | 20 |
def setup_installation():
"""Install necessary GUI resources
By default, RAFCON should be installed via `setup.py` (`pip install rafcon`). Thereby, all resources are being
installed. However, if this is not the case, one can set the `RAFCON_CHECK_INSTALLATION` env variable to `True`.
Then, the in... | [
"def",
"setup_installation",
"(",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"RAFCON_CHECK_INSTALLATION\"",
",",
"False",
")",
"==",
"\"True\"",
":",
"rafcon_root",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"rafcon",
".",
"__file__",
")",
... | 61.357143 | 31.142857 |
def _path_to_module(path):
"""Translates paths to *.py? files into module paths.
>>> _path_to_module("rapport/bar.py")
'rapport.bar'
>>> _path_to_module("/usr/lib/rapport/bar.py")
'rapport.bar'
"""
# Split of preceeding path elements:
path = "rapport" + path.split("rappo... | [
"def",
"_path_to_module",
"(",
"path",
")",
":",
"# Split of preceeding path elements:",
"path",
"=",
"\"rapport\"",
"+",
"path",
".",
"split",
"(",
"\"rapport\"",
")",
"[",
"1",
"]",
"# Split of ending and replace os.sep with dots:",
"path",
"=",
"path",
".",
"repl... | 33.692308 | 12.923077 |
def from_offset(tu, file, offset):
"""Retrieve a SourceLocation from a given character offset.
tu -- TranslationUnit file belongs to
file -- File instance to obtain offset from
offset -- Integer character offset within file
"""
return conf.lib.clang_getLocationForOffset(... | [
"def",
"from_offset",
"(",
"tu",
",",
"file",
",",
"offset",
")",
":",
"return",
"conf",
".",
"lib",
".",
"clang_getLocationForOffset",
"(",
"tu",
",",
"file",
",",
"offset",
")"
] | 41.25 | 13 |
def mime(self):
"""Produce the final MIME message."""
author = self.author
sender = self.sender
if not author:
raise ValueError("You must specify an author.")
if not self.subject:
raise ValueError("You must specify a subject.")
if len(self.recipients) == 0:
raise ValueError("You must specify a... | [
"def",
"mime",
"(",
"self",
")",
":",
"author",
"=",
"self",
".",
"author",
"sender",
"=",
"self",
".",
"sender",
"if",
"not",
"author",
":",
"raise",
"ValueError",
"(",
"\"You must specify an author.\"",
")",
"if",
"not",
"self",
".",
"subject",
":",
"r... | 26.636364 | 24.431818 |
def get_text(self):
"""Get the loaded, decompressed, and decoded text of this content."""
self._load_raw_content()
if self._text is None:
assert self._raw_content is not None
ret_cont = self._raw_content
if self.compressed:
ret_cont = zlib.deco... | [
"def",
"get_text",
"(",
"self",
")",
":",
"self",
".",
"_load_raw_content",
"(",
")",
"if",
"self",
".",
"_text",
"is",
"None",
":",
"assert",
"self",
".",
"_raw_content",
"is",
"not",
"None",
"ret_cont",
"=",
"self",
".",
"_raw_content",
"if",
"self",
... | 40.153846 | 10.384615 |
def handle_version(self, message_header, message):
"""
This method will handle the Version message and
will send a VerAck message when it receives the
Version message.
:param message_header: The Version message header
:param message: The Version message
"""
... | [
"def",
"handle_version",
"(",
"self",
",",
"message_header",
",",
"message",
")",
":",
"log",
".",
"debug",
"(",
"\"handle version\"",
")",
"verack",
"=",
"VerAck",
"(",
")",
"log",
".",
"debug",
"(",
"\"send VerAck\"",
")",
"self",
".",
"send_message",
"(... | 30.941176 | 14.235294 |
def get_mesh_name(mesh_id, offline=False):
"""Get the MESH label for the given MESH ID.
Uses the mappings table in `indra/resources`; if the MESH ID is not listed
there, falls back on the NLM REST API.
Parameters
----------
mesh_id : str
MESH Identifier, e.g. 'D003094'.
offline : b... | [
"def",
"get_mesh_name",
"(",
"mesh_id",
",",
"offline",
"=",
"False",
")",
":",
"indra_mesh_mapping",
"=",
"mesh_id_to_name",
".",
"get",
"(",
"mesh_id",
")",
"if",
"offline",
"or",
"indra_mesh_mapping",
"is",
"not",
"None",
":",
"return",
"indra_mesh_mapping",
... | 33.423077 | 21.076923 |
def update_file(dk_api, kitchen, recipe_name, message, files_to_update_param):
"""
reutrns a string.
:param dk_api: -- api object
:param kitchen: string
:param recipe_name: string -- kitchen name, string
:param message: string message -- commit message, string
:p... | [
"def",
"update_file",
"(",
"dk_api",
",",
"kitchen",
",",
"recipe_name",
",",
"message",
",",
"files_to_update_param",
")",
":",
"rc",
"=",
"DKReturnCode",
"(",
")",
"if",
"kitchen",
"is",
"None",
"or",
"recipe_name",
"is",
"None",
"or",
"message",
"is",
"... | 38.773585 | 18.132075 |
def download(url, dest):
"""Download the image to disk."""
path = os.path.join(dest, url.split('/')[-1])
r = requests.get(url, stream=True)
r.raise_for_status()
with open(path, 'wb') as f:
for chunk in r.iter_content(chunk_size=1024):
if chunk:
f.write(chunk)
... | [
"def",
"download",
"(",
"url",
",",
"dest",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dest",
",",
"url",
".",
"split",
"(",
"'/'",
")",
"[",
"-",
"1",
"]",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
... | 32.2 | 11.9 |
def get_hull_energy(self, comp):
"""
Args:
comp (Composition): Input composition
Returns:
Energy of lowest energy equilibrium at desired composition. Not
normalized by atoms, i.e. E(Li4O2) = 2 * E(Li2O)
"""
e = 0
for k, v in self.get_d... | [
"def",
"get_hull_energy",
"(",
"self",
",",
"comp",
")",
":",
"e",
"=",
"0",
"for",
"k",
",",
"v",
"in",
"self",
".",
"get_decomposition",
"(",
"comp",
")",
".",
"items",
"(",
")",
":",
"e",
"+=",
"k",
".",
"energy_per_atom",
"*",
"v",
"return",
... | 31.384615 | 16.615385 |
def _read_num( # noqa: C901 # pylint: disable=too-many-statements
ctx: ReaderContext
) -> MaybeNumber:
"""Return a numeric (complex, Decimal, float, int, Fraction) from the input stream."""
chars: List[str] = []
reader = ctx.reader
is_complex = False
is_decimal = False
is_float = False
... | [
"def",
"_read_num",
"(",
"# noqa: C901 # pylint: disable=too-many-statements",
"ctx",
":",
"ReaderContext",
")",
"->",
"MaybeNumber",
":",
"chars",
":",
"List",
"[",
"str",
"]",
"=",
"[",
"]",
"reader",
"=",
"ctx",
".",
"reader",
"is_complex",
"=",
"False",
"... | 32.465909 | 18.488636 |
def _get_resource_raw(
self, cls, id, extra=None, headers=None, stream=False, **filters
):
"""Get an individual REST resource"""
headers = headers or {}
headers.update(self.session.headers)
postfix = "/{}".format(extra) if extra else ""
if cls.api_root != "a":
... | [
"def",
"_get_resource_raw",
"(",
"self",
",",
"cls",
",",
"id",
",",
"extra",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"stream",
"=",
"False",
",",
"*",
"*",
"filters",
")",
":",
"headers",
"=",
"headers",
"or",
"{",
"}",
"headers",
".",
"upd... | 38.347826 | 21.782609 |
def atmost(cls, lits, bound=1, top_id=None, encoding=EncType.seqcounter):
"""
This method can be used for creating a CNF encoding of an AtMostK
constraint, i.e. of :math:`\sum_{i=1}^{n}{x_i}\leq k`. The method
shares the arguments and the return type with method
:... | [
"def",
"atmost",
"(",
"cls",
",",
"lits",
",",
"bound",
"=",
"1",
",",
"top_id",
"=",
"None",
",",
"encoding",
"=",
"EncType",
".",
"seqcounter",
")",
":",
"if",
"encoding",
"<",
"0",
"or",
"encoding",
">",
"9",
":",
"raise",
"(",
"NoSuchEncodingErro... | 33.617647 | 23.5 |
def lcsubstrings(seq1, seq2, positions=False):
"""Find the longest common substring(s) in the sequences `seq1` and `seq2`.
If positions evaluates to `True` only their positions will be returned,
together with their length, in a tuple:
(length, [(start pos in seq1, start pos in seq2)..])
Otherwise, the subst... | [
"def",
"lcsubstrings",
"(",
"seq1",
",",
"seq2",
",",
"positions",
"=",
"False",
")",
":",
"L1",
",",
"L2",
"=",
"len",
"(",
"seq1",
")",
",",
"len",
"(",
"seq2",
")",
"ms",
"=",
"[",
"]",
"mlen",
"=",
"last",
"=",
"0",
"if",
"L1",
"<",
"L2",... | 23.717391 | 22.630435 |
def quit(self):
"""Remove this user from all channels and reinitialize the user's list
of joined channels.
"""
for c in self.channels:
c.users.remove(self.nick)
self.channels = [] | [
"def",
"quit",
"(",
"self",
")",
":",
"for",
"c",
"in",
"self",
".",
"channels",
":",
"c",
".",
"users",
".",
"remove",
"(",
"self",
".",
"nick",
")",
"self",
".",
"channels",
"=",
"[",
"]"
] | 29.125 | 12 |
def _sanitize_data(runnable_jobs_data):
"""We receive data from runnable jobs api and return the sanitized data that meets our needs.
This is a loop to remove duplicates (including buildsystem -> * transformations if needed)
By doing this, it allows us to have a single database query
It returns saniti... | [
"def",
"_sanitize_data",
"(",
"runnable_jobs_data",
")",
":",
"job_build_system_type",
"=",
"{",
"}",
"sanitized_list",
"=",
"[",
"]",
"for",
"job",
"in",
"runnable_jobs_data",
":",
"if",
"not",
"valid_platform",
"(",
"job",
"[",
"'platform'",
"]",
")",
":",
... | 44.591837 | 23.693878 |
def _get_parser():
"""Parse input options."""
import argparse
parser = argparse.ArgumentParser(description=("Convert between mesh formats."))
parser.add_argument("infile", type=str, help="mesh file to be read from")
parser.add_argument(
"--input-format",
"-i",
type=str,
... | [
"def",
"_get_parser",
"(",
")",
":",
"import",
"argparse",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"(",
"\"Convert between mesh formats.\"",
")",
")",
"parser",
".",
"add_argument",
"(",
"\"infile\"",
",",
"type",
"=",
"str",
... | 23.039216 | 24.647059 |
def image(self):
"""
Returns a PngImageFile instance of the chart
You must have PIL installed for this to work
"""
try:
try:
import Image
except ImportError:
from PIL import Image
except ImportError:
rai... | [
"def",
"image",
"(",
"self",
")",
":",
"try",
":",
"try",
":",
"import",
"Image",
"except",
"ImportError",
":",
"from",
"PIL",
"import",
"Image",
"except",
"ImportError",
":",
"raise",
"ImportError",
"(",
"'You must install PIL to fetch image objects'",
")",
"tr... | 30.5 | 15.277778 |
def safe_makedirs(path):
"""A safe function for creating a directory tree."""
try:
os.makedirs(path)
except OSError as err:
if err.errno == errno.EEXIST:
if not os.path.isdir(path):
raise
else:
raise | [
"def",
"safe_makedirs",
"(",
"path",
")",
":",
"try",
":",
"os",
".",
"makedirs",
"(",
"path",
")",
"except",
"OSError",
"as",
"err",
":",
"if",
"err",
".",
"errno",
"==",
"errno",
".",
"EEXIST",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
... | 26.6 | 15 |
def model_average(X, penalization):
"""Run ModelAverage in default mode (QuicGraphicalLassoCV) to obtain proportion
matrix.
NOTE: This returns precision_ proportions, not cov, prec estimates, so we
return the raw proportions for "cov" and the threshold support
estimate for prec.
... | [
"def",
"model_average",
"(",
"X",
",",
"penalization",
")",
":",
"n_trials",
"=",
"100",
"print",
"(",
"\"ModelAverage with:\"",
")",
"print",
"(",
"\" estimator: QuicGraphicalLasso (default)\"",
")",
"print",
"(",
"\" n_trials: {}\"",
".",
"format",
"(",
"n_tri... | 37.129032 | 20.483871 |
def add_hosted_zone_id_for_alias_target_if_missing(self, rs):
"""Add proper hosted zone id to record set alias target if missing."""
alias_target = getattr(rs, "AliasTarget", None)
if alias_target:
hosted_zone_id = getattr(alias_target, "HostedZoneId", None)
if not hosted... | [
"def",
"add_hosted_zone_id_for_alias_target_if_missing",
"(",
"self",
",",
"rs",
")",
":",
"alias_target",
"=",
"getattr",
"(",
"rs",
",",
"\"AliasTarget\"",
",",
"None",
")",
"if",
"alias_target",
":",
"hosted_zone_id",
"=",
"getattr",
"(",
"alias_target",
",",
... | 52.411765 | 17.705882 |
def getaddresses (addr):
"""Return list of email addresses from given field value."""
parsed = [mail for name, mail in AddressList(addr).addresslist if mail]
if parsed:
addresses = parsed
elif addr:
# we could not parse any mail addresses, so try with the raw string
addresses = [... | [
"def",
"getaddresses",
"(",
"addr",
")",
":",
"parsed",
"=",
"[",
"mail",
"for",
"name",
",",
"mail",
"in",
"AddressList",
"(",
"addr",
")",
".",
"addresslist",
"if",
"mail",
"]",
"if",
"parsed",
":",
"addresses",
"=",
"parsed",
"elif",
"addr",
":",
... | 33.545455 | 21.363636 |
def get_assessment_parts_by_banks(self, bank_ids):
"""Gets the list of assessment part corresponding to a list of ``Banks``.
arg: bank_ids (osid.id.IdList): list of bank ``Ids``
return: (osid.assessment.authoring.AssessmentPartList) - list of
assessment parts
raise: ... | [
"def",
"get_assessment_parts_by_banks",
"(",
"self",
",",
"bank_ids",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceBinSession.get_resources_by_bins",
"assessment_part_list",
"=",
"[",
"]",
"for",
"bank_id",
"in",
"bank_ids",
":",
"assessment_part_list",... | 46.210526 | 16.526316 |
def edit_message_reply_markup(self, chat_id, message_id, reply_markup, **options):
"""
Edit a reply markup of message in a chat
:param int chat_id: ID of the chat the message to edit is in
:param int message_id: ID of the message to edit
:param str reply_markup: New inline keybo... | [
"def",
"edit_message_reply_markup",
"(",
"self",
",",
"chat_id",
",",
"message_id",
",",
"reply_markup",
",",
"*",
"*",
"options",
")",
":",
"return",
"self",
".",
"api_call",
"(",
"\"editMessageReplyMarkup\"",
",",
"chat_id",
"=",
"chat_id",
",",
"message_id",
... | 37.0625 | 16.1875 |
def get_manifest_and_response(self, alias):
"""
Request the manifest for an alias and return the manifest and the
response.
:param alias: Alias name.
:type alias: str
:rtype: tuple
:returns: Tuple containing the manifest as a string (JSON) and the `requests.Resp... | [
"def",
"get_manifest_and_response",
"(",
"self",
",",
"alias",
")",
":",
"r",
"=",
"self",
".",
"_request",
"(",
"'get'",
",",
"'manifests/'",
"+",
"alias",
",",
"headers",
"=",
"{",
"'Accept'",
":",
"_schema2_mimetype",
"+",
"', '",
"+",
"_schema1_mimetype"... | 40.75 | 23.5 |
def _rsadp(self, c):
"""
Internal method providing raw RSA decryption, i.e. simple modular
exponentiation of the given ciphertext representative 'c', a long
between 0 and n-1.
This is the decryption primitive RSADP described in PKCS#1 v2.1,
i.e. RFC 3447 Sect. 5.1.2.
... | [
"def",
"_rsadp",
"(",
"self",
",",
"c",
")",
":",
"n",
"=",
"self",
".",
"modulus",
"if",
"type",
"(",
"c",
")",
"is",
"int",
":",
"c",
"=",
"long",
"(",
"c",
")",
"if",
"type",
"(",
"c",
")",
"is",
"not",
"long",
"or",
"c",
">",
"n",
"-"... | 31 | 22.62963 |
def new_pos(self, html_div):
"""factory method pattern"""
pos = self.Position(self, html_div)
pos.bind_mov()
self.positions.append(pos)
return pos | [
"def",
"new_pos",
"(",
"self",
",",
"html_div",
")",
":",
"pos",
"=",
"self",
".",
"Position",
"(",
"self",
",",
"html_div",
")",
"pos",
".",
"bind_mov",
"(",
")",
"self",
".",
"positions",
".",
"append",
"(",
"pos",
")",
"return",
"pos"
] | 30.166667 | 10.166667 |
def _start_ssh_agent(cls):
"""Starts ssh-agent and returns the environment variables related to it"""
env = dict()
stdout = ClHelper.run_command('ssh-agent -s')
lines = stdout.split('\n')
for line in lines:
if not line or line.startswith('echo '):
cont... | [
"def",
"_start_ssh_agent",
"(",
"cls",
")",
":",
"env",
"=",
"dict",
"(",
")",
"stdout",
"=",
"ClHelper",
".",
"run_command",
"(",
"'ssh-agent -s'",
")",
"lines",
"=",
"stdout",
".",
"split",
"(",
"'\\n'",
")",
"for",
"line",
"in",
"lines",
":",
"if",
... | 36.769231 | 10.307692 |
def getAttributeValueType(self, index):
"""
Return the type of the attribute at the given index
:param index: index of the attribute
"""
offset = self._get_attribute_offset(index)
return self.m_attributes[offset + const.ATTRIBUTE_IX_VALUE_TYPE] | [
"def",
"getAttributeValueType",
"(",
"self",
",",
"index",
")",
":",
"offset",
"=",
"self",
".",
"_get_attribute_offset",
"(",
"index",
")",
"return",
"self",
".",
"m_attributes",
"[",
"offset",
"+",
"const",
".",
"ATTRIBUTE_IX_VALUE_TYPE",
"]"
] | 35.75 | 13.25 |
def preset_ls(remote):
"""List presets
\b
Usage:
$ be preset ls
- ad
- game
- film
"""
if self.isactive():
lib.echo("ERROR: Exit current project first")
sys.exit(lib.USER_ERROR)
if remote:
presets = _extern.github_presets()
else:
... | [
"def",
"preset_ls",
"(",
"remote",
")",
":",
"if",
"self",
".",
"isactive",
"(",
")",
":",
"lib",
".",
"echo",
"(",
"\"ERROR: Exit current project first\"",
")",
"sys",
".",
"exit",
"(",
"lib",
".",
"USER_ERROR",
")",
"if",
"remote",
":",
"presets",
"=",... | 19.037037 | 20.148148 |
def __setUpTrakers(self):
''' set symbols '''
for symbol in self.symbols:
self.__trakers[symbol]=OneTraker(symbol, self, self.buyingRatio) | [
"def",
"__setUpTrakers",
"(",
"self",
")",
":",
"for",
"symbol",
"in",
"self",
".",
"symbols",
":",
"self",
".",
"__trakers",
"[",
"symbol",
"]",
"=",
"OneTraker",
"(",
"symbol",
",",
"self",
",",
"self",
".",
"buyingRatio",
")"
] | 40.75 | 17.25 |
def _get_image_information(self):
"""
:returns: Dictionary information about the container image
"""
result = yield from self.manager.query("GET", "images/{}/json".format(self._image))
return result | [
"def",
"_get_image_information",
"(",
"self",
")",
":",
"result",
"=",
"yield",
"from",
"self",
".",
"manager",
".",
"query",
"(",
"\"GET\"",
",",
"\"images/{}/json\"",
".",
"format",
"(",
"self",
".",
"_image",
")",
")",
"return",
"result"
] | 38.833333 | 17.166667 |
def load_table(self, table):
"""
Load the file contents into the supplied Table using the
specified key and filetype. The input table should have the
filenames as values which will be replaced by the loaded
data. If data_key is specified, this key will be used to index
th... | [
"def",
"load_table",
"(",
"self",
",",
"table",
")",
":",
"items",
",",
"data_keys",
"=",
"[",
"]",
",",
"None",
"for",
"key",
",",
"filename",
"in",
"table",
".",
"items",
"(",
")",
":",
"data_dict",
"=",
"self",
".",
"filetype",
".",
"data",
"(",... | 44.85 | 14.15 |
def getiddfile(versionid):
"""find the IDD file of the E+ installation"""
vlist = versionid.split('.')
if len(vlist) == 1:
vlist = vlist + ['0', '0']
elif len(vlist) == 2:
vlist = vlist + ['0']
ver_str = '-'.join(vlist)
eplus_exe, _ = eppy.runner.run_functions.install_paths(ver... | [
"def",
"getiddfile",
"(",
"versionid",
")",
":",
"vlist",
"=",
"versionid",
".",
"split",
"(",
"'.'",
")",
"if",
"len",
"(",
"vlist",
")",
"==",
"1",
":",
"vlist",
"=",
"vlist",
"+",
"[",
"'0'",
",",
"'0'",
"]",
"elif",
"len",
"(",
"vlist",
")",
... | 35.916667 | 12.25 |
def get_weights_from_kmodel(kmodel):
"""
Convert kmodel's weights to bigdl format.
We are supposing the order is the same as the execution order.
:param kmodel: keras model
:return: list of ndarray
"""
layers_with_weights = [layer for layer in kmodel.layers if lay... | [
"def",
"get_weights_from_kmodel",
"(",
"kmodel",
")",
":",
"layers_with_weights",
"=",
"[",
"layer",
"for",
"layer",
"in",
"kmodel",
".",
"layers",
"if",
"layer",
".",
"weights",
"]",
"bweights",
"=",
"[",
"]",
"for",
"klayer",
"in",
"layers_with_weights",
"... | 39.733333 | 13.6 |
def spkw10(handle, body, center, inframe, first, last, segid, consts, n, elems,
epochs):
"""
Write an SPK type 10 segment to the DAF open and attached to
the input handle.
http://naif.jpl.nasa.gov/pub/naif/toolkit_docs/C/cspice/spkw10_c.html
:param handle: The handle of a DAF file open ... | [
"def",
"spkw10",
"(",
"handle",
",",
"body",
",",
"center",
",",
"inframe",
",",
"first",
",",
"last",
",",
"segid",
",",
"consts",
",",
"n",
",",
"elems",
",",
"epochs",
")",
":",
"handle",
"=",
"ctypes",
".",
"c_int",
"(",
"handle",
")",
"body",
... | 39.090909 | 16.545455 |
def _col_type_set(self, col, df):
"""
Determines the set of types present in a DataFrame column.
:param str col: A column name.
:param pandas.DataFrame df: The dataset. Usually ``self._data``.
:return: A set of Types.
"""
type_set = set()
if df[col].dtype... | [
"def",
"_col_type_set",
"(",
"self",
",",
"col",
",",
"df",
")",
":",
"type_set",
"=",
"set",
"(",
")",
"if",
"df",
"[",
"col",
"]",
".",
"dtype",
"==",
"np",
".",
"dtype",
"(",
"object",
")",
":",
"unindexed_col",
"=",
"list",
"(",
"df",
"[",
... | 33.7 | 12.4 |
def accepts_contributor_roles(func):
"""
Decorator that accepts only contributor roles
:param func:
:return:
"""
if inspect.isclass(func):
apply_function_to_members(func, accepts_contributor_roles)
return func
else:
@functools.wraps(func)
def decorator(*args, ... | [
"def",
"accepts_contributor_roles",
"(",
"func",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"func",
")",
":",
"apply_function_to_members",
"(",
"func",
",",
"accepts_contributor_roles",
")",
"return",
"func",
"else",
":",
"@",
"functools",
".",
"wraps",
"... | 27.866667 | 17.066667 |
def get(key, default=-1):
"""Backport support for original codes."""
if isinstance(key, int):
return Checksum(key)
if key not in Checksum._member_map_:
extend_enum(Checksum, key, default)
return Checksum[key] | [
"def",
"get",
"(",
"key",
",",
"default",
"=",
"-",
"1",
")",
":",
"if",
"isinstance",
"(",
"key",
",",
"int",
")",
":",
"return",
"Checksum",
"(",
"key",
")",
"if",
"key",
"not",
"in",
"Checksum",
".",
"_member_map_",
":",
"extend_enum",
"(",
"Che... | 36.857143 | 7.714286 |
def body_echo(cls, request,
foo: (Ptypes.body, String('A body parameter'))) -> [
(200, 'Ok', String)]:
'''Echo the body parameter.'''
log.info('Echoing body param, value is: {}'.format(foo))
for i in range(randint(0, MAX_LOOP_DURATION)):
yield
ms... | [
"def",
"body_echo",
"(",
"cls",
",",
"request",
",",
"foo",
":",
"(",
"Ptypes",
".",
"body",
",",
"String",
"(",
"'A body parameter'",
")",
")",
")",
"->",
"[",
"(",
"200",
",",
"'Ok'",
",",
"String",
")",
"]",
":",
"log",
".",
"info",
"(",
"'Ech... | 42 | 15.333333 |
def extract_archive(archive, verbosity=0, outdir=None, program=None, interactive=True):
"""Extract given archive."""
util.check_existing_filename(archive)
if verbosity >= 0:
util.log_info("Extracting %s ..." % archive)
return _extract_archive(archive, verbosity=verbosity, interactive=interactive... | [
"def",
"extract_archive",
"(",
"archive",
",",
"verbosity",
"=",
"0",
",",
"outdir",
"=",
"None",
",",
"program",
"=",
"None",
",",
"interactive",
"=",
"True",
")",
":",
"util",
".",
"check_existing_filename",
"(",
"archive",
")",
"if",
"verbosity",
">=",
... | 58 | 25.333333 |
def options(self, request, *args, **kwargs):
"""
Handles responding to requests for the OPTIONS HTTP verb.
"""
response = Response()
response.headers['Allow'] = ', '.join(self.allowed_methods)
response.headers['Content-Length'] = '0'
return response | [
"def",
"options",
"(",
"self",
",",
"request",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"Response",
"(",
")",
"response",
".",
"headers",
"[",
"'Allow'",
"]",
"=",
"', '",
".",
"join",
"(",
"self",
".",
"allowed_methods",... | 27.090909 | 19.272727 |
def get_slot_value(payload, slot_name):
""" Return the parsed value of a slot. An intent has the form:
{
"text": "brew me a cappuccino with 3 sugars tomorrow",
"slots": [
{"value": {"slotName": "coffee_type", "value": "cappuccino"}},
... | [
"def",
"get_slot_value",
"(",
"payload",
",",
"slot_name",
")",
":",
"if",
"not",
"'slots'",
"in",
"payload",
":",
"return",
"[",
"]",
"slots",
"=",
"[",
"]",
"for",
"candidate",
"in",
"payload",
"[",
"'slots'",
"]",
":",
"if",
"'slotName'",
"in",
"can... | 33.4 | 23.253333 |
def Toeplitz(x, d=None, D=None, kind='F'):
""" Creates multilevel Toeplitz TT-matrix with ``D`` levels.
Possible _matrix types:
* 'F' - full Toeplitz _matrix, size(x) = 2^{d+1}
* 'C' - circulant _matrix, size(x) = 2^d
* 'L' - lower triangular Toeplitz _m... | [
"def",
"Toeplitz",
"(",
"x",
",",
"d",
"=",
"None",
",",
"D",
"=",
"None",
",",
"kind",
"=",
"'F'",
")",
":",
"# checking for arguments consistency",
"def",
"check_kinds",
"(",
"D",
",",
"kind",
")",
":",
"if",
"D",
"%",
"len",
"(",
"kind",
")",
"=... | 37.348101 | 16.506329 |
def transform(grammar, text):
"""Transform text by replacing matches to grammar."""
results = []
intervals = []
for result, start, stop in all_matches(grammar, text):
if result is not ignore_transform:
internal_assert(isinstance(result, str), "got non-string transform result", result... | [
"def",
"transform",
"(",
"grammar",
",",
"text",
")",
":",
"results",
"=",
"[",
"]",
"intervals",
"=",
"[",
"]",
"for",
"result",
",",
"start",
",",
"stop",
"in",
"all_matches",
"(",
"grammar",
",",
"text",
")",
":",
"if",
"result",
"is",
"not",
"i... | 35.939394 | 19.242424 |
def format_vars(args):
"""Format the given vars in the form: 'flag=value'"""
variables = []
for key, value in args.items():
if value:
variables += ['{0}={1}'.format(key, value)]
return variables | [
"def",
"format_vars",
"(",
"args",
")",
":",
"variables",
"=",
"[",
"]",
"for",
"key",
",",
"value",
"in",
"args",
".",
"items",
"(",
")",
":",
"if",
"value",
":",
"variables",
"+=",
"[",
"'{0}={1}'",
".",
"format",
"(",
"key",
",",
"value",
")",
... | 32 | 14.714286 |
def from_message(cls, message):
"""Creates an instance from CSP report message.
If the message is not valid, the result will still have as much fields set as possible.
@param message: JSON encoded CSP report.
@type message: text
"""
self = cls(json=message)
try:... | [
"def",
"from_message",
"(",
"cls",
",",
"message",
")",
":",
"self",
"=",
"cls",
"(",
"json",
"=",
"message",
")",
"try",
":",
"decoded_data",
"=",
"json",
".",
"loads",
"(",
"message",
")",
"except",
"ValueError",
":",
"# Message is not a valid JSON. Return... | 39.145833 | 19.0625 |
def _init_data_map(self):
""" OVERRIDDEN: Initialize required ISO-19115 data map with XPATHS and specialized functions """
if self._data_map is not None:
return # Initiation happens once
# Parse and validate the ISO metadata root
if self._xml_tree is None:
iso... | [
"def",
"_init_data_map",
"(",
"self",
")",
":",
"if",
"self",
".",
"_data_map",
"is",
"not",
"None",
":",
"return",
"# Initiation happens once",
"# Parse and validate the ISO metadata root",
"if",
"self",
".",
"_xml_tree",
"is",
"None",
":",
"iso_root",
"=",
"ISO_... | 47.797468 | 28.886076 |
def binarize(obj, threshold=0):
"""
Return a copy of the object with binarized piano-roll(s).
Parameters
----------
threshold : int or float
Threshold to binarize the piano-roll(s). Default to zero.
"""
_check_supported(obj)
copied = deepcopy(obj)
copied.binarize(threshold)... | [
"def",
"binarize",
"(",
"obj",
",",
"threshold",
"=",
"0",
")",
":",
"_check_supported",
"(",
"obj",
")",
"copied",
"=",
"deepcopy",
"(",
"obj",
")",
"copied",
".",
"binarize",
"(",
"threshold",
")",
"return",
"copied"
] | 23.214286 | 18.642857 |
def webhooks(request):
"""
Handles all known webhooks from stripe, and calls signals.
Plug in as you need.
"""
if request.method != "POST":
return HttpResponse("Invalid Request.", status=400)
json = simplejson.loads(request.POST["json"])
if json["event"] == "recurring_payment_fail... | [
"def",
"webhooks",
"(",
"request",
")",
":",
"if",
"request",
".",
"method",
"!=",
"\"POST\"",
":",
"return",
"HttpResponse",
"(",
"\"Invalid Request.\"",
",",
"status",
"=",
"400",
")",
"json",
"=",
"simplejson",
".",
"loads",
"(",
"request",
".",
"POST",... | 44.030303 | 35.484848 |
async def find(self, **kwargs):
"""Find all entries with given search key.
Accepts named parameter key and arbitrary values.
Returns list of entry id`s.
find(**kwargs) => document (if exist)
find(**kwargs) => {"error":404,"reason":"Not found"} (if does not exist)
find() => {"error":400, "reason":"Missed re... | [
"async",
"def",
"find",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"kwargs",
",",
"dict",
")",
"and",
"len",
"(",
"kwargs",
")",
"!=",
"1",
":",
"return",
"{",
"\"error\"",
":",
"400",
",",
"\"reason\"",
":",
... | 33.823529 | 15.647059 |
def resolve_widget(self, field):
"""
Given a Field or BoundField, return widget instance.
Todo:
Raise an exception if given field object does not have a
widget.
Arguments:
field (Field or BoundField): A field instance.
Returns:
d... | [
"def",
"resolve_widget",
"(",
"self",
",",
"field",
")",
":",
"# When filter is used within template we have to reach the field",
"# instance through the BoundField.",
"if",
"hasattr",
"(",
"field",
",",
"'field'",
")",
":",
"widget",
"=",
"field",
".",
"field",
".",
... | 30.608696 | 21.043478 |
def cookietostr(self):
"Cookie values are bytes in Python3. This function Convert bytes to string with env.encoding(default to utf-8)."
self.cookies = dict((k, (v.decode(self.encoding) if not isinstance(v, str) else v)) for k,v in self.cookies.items())
return self.cookies | [
"def",
"cookietostr",
"(",
"self",
")",
":",
"self",
".",
"cookies",
"=",
"dict",
"(",
"(",
"k",
",",
"(",
"v",
".",
"decode",
"(",
"self",
".",
"encoding",
")",
"if",
"not",
"isinstance",
"(",
"v",
",",
"str",
")",
"else",
"v",
")",
")",
"for"... | 73.25 | 48.75 |
def clear_tab_stop(self, how=0):
"""Clear a horizontal tab stop.
:param int how: defines a way the tab stop should be cleared:
* ``0`` or nothing -- Clears a horizontal tab stop at cursor
position.
* ``3`` -- Clears all horizontal tab stops.
"""
if... | [
"def",
"clear_tab_stop",
"(",
"self",
",",
"how",
"=",
"0",
")",
":",
"if",
"how",
"==",
"0",
":",
"# Clears a horizontal tab stop at cursor position, if it's",
"# present, or silently fails if otherwise.",
"self",
".",
"tabstops",
".",
"discard",
"(",
"self",
".",
... | 36.533333 | 18.533333 |
def get_election(self, row, race):
"""
Gets the Election object for the given row of election results.
Depends on knowing the Race object.
If this is the presidential election, this will determine the
Division attached to the election based on the row's statename.
This ... | [
"def",
"get_election",
"(",
"self",
",",
"row",
",",
"race",
")",
":",
"election_day",
"=",
"election",
".",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"row",
"[",
"\"electiondate\"",
"]",
")",
"if",
"row",
"[",
"\"racetypeid\"",
"]",
... | 34.06 | 18.38 |
def visit_functiondef(self, node):
'''
Verifies no logger statements inside __virtual__
'''
if (not isinstance(node, astroid.FunctionDef) or
node.is_method()
or node.type != 'function'
or not node.body
):
# only process functions... | [
"def",
"visit_functiondef",
"(",
"self",
",",
"node",
")",
":",
"if",
"(",
"not",
"isinstance",
"(",
"node",
",",
"astroid",
".",
"FunctionDef",
")",
"or",
"node",
".",
"is_method",
"(",
")",
"or",
"node",
".",
"type",
"!=",
"'function'",
"or",
"not",
... | 41.4 | 17.7 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.