text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def parse(raw_email):
# type: (six.string_types) -> Tuple[six.string_types, six.string_types]
"""Extract email from a full address. Example:
'John Doe <jdoe+github@foo.com>' -> jdoe@foo.com
>>> parse("John Doe <me+github.com@someorg.com")
('me', 'someorg.com')
>>> parse(42) # doctest: +IGNOR... | [
"def",
"parse",
"(",
"raw_email",
")",
":",
"# type: (six.string_types) -> Tuple[six.string_types, six.string_types]",
"if",
"not",
"isinstance",
"(",
"raw_email",
",",
"six",
".",
"string_types",
")",
":",
"raise",
"InvalidEmail",
"(",
"\"Invalid email: %s\"",
"%",
"ra... | 40.533333 | 0.000803 |
def create_todo_item(self, list_id, content, party_id=None, notify=False):
"""
This call lets you add an item to an existing list. The item is added
to the bottom of the list. If a person is responsible for the item,
give their id as the party_id value. If a company is responsible,
... | [
"def",
"create_todo_item",
"(",
"self",
",",
"list_id",
",",
"content",
",",
"party_id",
"=",
"None",
",",
"notify",
"=",
"False",
")",
":",
"path",
"=",
"'/todos/create_item/%u'",
"%",
"list_id",
"req",
"=",
"ET",
".",
"Element",
"(",
"'request'",
")",
... | 55.764706 | 0.002075 |
def _build_showstr(self, seed):
"""
Returns show() display string for data attribute
"""
output = ["%s (%s) data" % (seed, self.params['lang'])]
output.append('{')
maxwidth = WPToolsQuery.MAXWIDTH
for item in sorted(self.data):
if self.data[item] i... | [
"def",
"_build_showstr",
"(",
"self",
",",
"seed",
")",
":",
"output",
"=",
"[",
"\"%s (%s) data\"",
"%",
"(",
"seed",
",",
"self",
".",
"params",
"[",
"'lang'",
"]",
")",
"]",
"output",
".",
"append",
"(",
"'{'",
")",
"maxwidth",
"=",
"WPToolsQuery",
... | 33.627907 | 0.001344 |
def bam_to_fastq_pair(in_file, target_region, pair):
"""Generator to convert BAM files into name, seq, qual in a region.
"""
space, start, end = target_region
bam_file = pysam.Samfile(in_file, "rb")
for read in bam_file:
if (not read.is_unmapped and not read.mate_is_unmapped
... | [
"def",
"bam_to_fastq_pair",
"(",
"in_file",
",",
"target_region",
",",
"pair",
")",
":",
"space",
",",
"start",
",",
"end",
"=",
"target_region",
"bam_file",
"=",
"pysam",
".",
"Samfile",
"(",
"in_file",
",",
"\"rb\"",
")",
"for",
"read",
"in",
"bam_file",... | 45.789474 | 0.001126 |
def make_app(global_conf, **app_conf):
"""Create a WSGI application and return it
``global_conf``
The inherited configuration for this application. Normally from
the [DEFAULT] section of the Paste ini file.
``app_conf``
The application's local configuration. Normally specified in
... | [
"def",
"make_app",
"(",
"global_conf",
",",
"*",
"*",
"app_conf",
")",
":",
"# Configure the environment and fill conf dictionary.",
"environment",
".",
"load_environment",
"(",
"global_conf",
",",
"app_conf",
")",
"# Dispatch request to controllers.",
"app",
"=",
"contro... | 34.369565 | 0.001845 |
def get_object_stats(self, obj_name):
"""
:param obj_name: requested object name
:returns: all statistics values for the requested object.
"""
return dict(zip(self.captions, self.statistics[obj_name])) | [
"def",
"get_object_stats",
"(",
"self",
",",
"obj_name",
")",
":",
"return",
"dict",
"(",
"zip",
"(",
"self",
".",
"captions",
",",
"self",
".",
"statistics",
"[",
"obj_name",
"]",
")",
")"
] | 33.714286 | 0.008264 |
def fix_double_nodes(coor, ngroups, conns, eps):
"""
Detect and attempt fixing double nodes in a mesh.
The double nodes are nodes having the same coordinates
w.r.t. precision given by `eps`.
"""
n_nod, dim = coor.shape
cmap = find_map( coor, nm.zeros( (0,dim) ), eps = eps, allow_double = Tr... | [
"def",
"fix_double_nodes",
"(",
"coor",
",",
"ngroups",
",",
"conns",
",",
"eps",
")",
":",
"n_nod",
",",
"dim",
"=",
"coor",
".",
"shape",
"cmap",
"=",
"find_map",
"(",
"coor",
",",
"nm",
".",
"zeros",
"(",
"(",
"0",
",",
"dim",
")",
")",
",",
... | 31.789474 | 0.026506 |
def generate_dirlist_html(FS, filepath):
"""
Generate directory listing HTML
Arguments:
FS (FS): filesystem object to read files from
filepath (str): path to generate directory listings for
Keyword Arguments:
list_dir (callable: list[str]): list file names in a directory
... | [
"def",
"generate_dirlist_html",
"(",
"FS",
",",
"filepath",
")",
":",
"yield",
"'<table class=\"dirlist\">'",
"if",
"filepath",
"==",
"'/'",
":",
"filepath",
"=",
"''",
"for",
"name",
"in",
"FS",
".",
"listdir",
"(",
"filepath",
")",
":",
"full_path",
"=",
... | 30.48 | 0.001272 |
def log_exception(cls, msg):
"""Try to log an error message to this process's error log and the shared error log.
NB: Doesn't raise (logs an error instead).
"""
pid = os.getpid()
fatal_error_log_entry = cls._format_exception_message(msg, pid)
# We care more about this log than the shared log, ... | [
"def",
"log_exception",
"(",
"cls",
",",
"msg",
")",
":",
"pid",
"=",
"os",
".",
"getpid",
"(",
")",
"fatal_error_log_entry",
"=",
"cls",
".",
"_format_exception_message",
"(",
"msg",
",",
"pid",
")",
"# We care more about this log than the shared log, so write to i... | 40.96 | 0.012405 |
def set_storage_container_acl(kwargs=None, storage_conn=None, call=None):
'''
.. versionadded:: 2015.8.0
Set a storage container's acl
CLI Example:
.. code-block:: bash
salt-cloud -f set_storage_container my-azure name=mycontainer
name:
Name of existing container.
signed... | [
"def",
"set_storage_container_acl",
"(",
"kwargs",
"=",
"None",
",",
"storage_conn",
"=",
"None",
",",
"call",
"=",
"None",
")",
":",
"if",
"call",
"!=",
"'function'",
":",
"raise",
"SaltCloudSystemExit",
"(",
"'The create_storage_container function must be called wit... | 32.275 | 0.001504 |
def _render_table(data, fields=None):
""" Helper to render a list of dictionaries as an HTML display object. """
return IPython.core.display.HTML(datalab.utils.commands.HtmlBuilder.render_table(data, fields)) | [
"def",
"_render_table",
"(",
"data",
",",
"fields",
"=",
"None",
")",
":",
"return",
"IPython",
".",
"core",
".",
"display",
".",
"HTML",
"(",
"datalab",
".",
"utils",
".",
"commands",
".",
"HtmlBuilder",
".",
"render_table",
"(",
"data",
",",
"fields",
... | 70 | 0.018868 |
def clear(self):
"""
直接把现在的清空
"""
if not self.timer:
return
# 不阻塞
try:
self.timer.kill(block=False)
except:
pass
self.timer = None | [
"def",
"clear",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"timer",
":",
"return",
"# 不阻塞",
"try",
":",
"self",
".",
"timer",
".",
"kill",
"(",
"block",
"=",
"False",
")",
"except",
":",
"pass",
"self",
".",
"timer",
"=",
"None"
] | 16.846154 | 0.012987 |
def startswith(self, value):
"""
Sets the operator type to Query.Op.Startswith and sets \
the value to the inputted value. This method will only work on text \
based fields.
:param value <str>
:return <Query>
:usage ... | [
"def",
"startswith",
"(",
"self",
",",
"value",
")",
":",
"newq",
"=",
"self",
".",
"copy",
"(",
")",
"newq",
".",
"setOp",
"(",
"Query",
".",
"Op",
".",
"Startswith",
")",
"newq",
".",
"setValue",
"(",
"value",
")",
"return",
"newq"
] | 31.684211 | 0.008065 |
def update_one(self, filter, update, upsert=False,
bypass_document_validation=False,
collation=None, array_filters=None, session=None):
"""Update a single document matching the filter.
>>> for doc in db.test.find():
... print(doc)
...
... | [
"def",
"update_one",
"(",
"self",
",",
"filter",
",",
"update",
",",
"upsert",
"=",
"False",
",",
"bypass_document_validation",
"=",
"False",
",",
"collation",
"=",
"None",
",",
"array_filters",
"=",
"None",
",",
"session",
"=",
"None",
")",
":",
"common",... | 37.507246 | 0.001883 |
def createNetwork(dataSource):
"""Create the Network instance.
The network has a sensor region reading data from `dataSource` and passing
the encoded representation to an Identity Region.
:param dataSource: a RecordStream instance to get data from
:returns: a Network instance ready to run
"""
network = ... | [
"def",
"createNetwork",
"(",
"dataSource",
")",
":",
"network",
"=",
"Network",
"(",
")",
"# Our input is sensor data from the gym file. The RecordSensor region",
"# allows us to specify a file record stream as the input source via the",
"# dataSource attribute.",
"network",
".",
"ad... | 35.978723 | 0.016695 |
def readFILTERLIST(self):
""" Read a length-prefixed list of FILTERs """
number = self.readUI8()
return [self.readFILTER() for _ in range(number)] | [
"def",
"readFILTERLIST",
"(",
"self",
")",
":",
"number",
"=",
"self",
".",
"readUI8",
"(",
")",
"return",
"[",
"self",
".",
"readFILTER",
"(",
")",
"for",
"_",
"in",
"range",
"(",
"number",
")",
"]"
] | 41.75 | 0.011765 |
def fileUpd(self, buffer=None, filename=None, ufilename=None, desc=None):
"""Update annotation attached file."""
CheckParent(self)
return _fitz.Annot_fileUpd(self, buffer, filename, ufilename, desc) | [
"def",
"fileUpd",
"(",
"self",
",",
"buffer",
"=",
"None",
",",
"filename",
"=",
"None",
",",
"ufilename",
"=",
"None",
",",
"desc",
"=",
"None",
")",
":",
"CheckParent",
"(",
"self",
")",
"return",
"_fitz",
".",
"Annot_fileUpd",
"(",
"self",
",",
"b... | 31.285714 | 0.013333 |
def keyevent_to_keyseq(self, event):
"""Return a QKeySequence representation of the provided QKeyEvent."""
self.keyPressEvent(event)
event.accept()
return self.keySequence() | [
"def",
"keyevent_to_keyseq",
"(",
"self",
",",
"event",
")",
":",
"self",
".",
"keyPressEvent",
"(",
"event",
")",
"event",
".",
"accept",
"(",
")",
"return",
"self",
".",
"keySequence",
"(",
")"
] | 41 | 0.009569 |
def get_branch_info(self):
"""
Retrieve branch_info from Satellite Server
"""
branch_info = None
if os.path.exists(constants.cached_branch_info):
# use cached branch info file if less than 10 minutes old
# (failsafe, should be deleted at end of client run... | [
"def",
"get_branch_info",
"(",
"self",
")",
":",
"branch_info",
"=",
"None",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"constants",
".",
"cached_branch_info",
")",
":",
"# use cached branch info file if less than 10 minutes old",
"# (failsafe, should be deleted at end... | 47.688889 | 0.002283 |
def as_list(func):
""" A decorator used to return a JSON response of a list of model
objects. It expects the decorated function to return a list
of model instances. It then converts the instances to dicts
and serializes them into a json response
Examples:
>>> @app.route... | [
"def",
"as_list",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"response",
"=",
"func",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"isinstance",
"(",
"r... | 31.434783 | 0.001342 |
def make_spo(sub, prd, obj):
'''
Decorates the three given strings as a line of ntriples
'''
# To establish string as a curie and expand,
# we use a global curie_map(.yaml)
# sub are allways uri (unless a bnode)
# prd are allways uri (unless prd is 'a')
# should fail loudly if curie do... | [
"def",
"make_spo",
"(",
"sub",
",",
"prd",
",",
"obj",
")",
":",
"# To establish string as a curie and expand,",
"# we use a global curie_map(.yaml)",
"# sub are allways uri (unless a bnode)",
"# prd are allways uri (unless prd is 'a')",
"# should fail loudly if curie does not exist",
... | 32.806452 | 0.000955 |
def xmlrpc_run(self, port=24444, bind='127.0.0.1', logRequests=False):
'''Run xmlrpc server'''
import umsgpack
from pyspider.libs.wsgi_xmlrpc import WSGIXMLRPCApplication
try:
from xmlrpc.client import Binary
except ImportError:
from xmlrpclib import Binar... | [
"def",
"xmlrpc_run",
"(",
"self",
",",
"port",
"=",
"24444",
",",
"bind",
"=",
"'127.0.0.1'",
",",
"logRequests",
"=",
"False",
")",
":",
"import",
"umsgpack",
"from",
"pyspider",
".",
"libs",
".",
"wsgi_xmlrpc",
"import",
"WSGIXMLRPCApplication",
"try",
":"... | 37.558824 | 0.00229 |
def _ml_t_joint(self):
"""
Compute the joint maximum likelihood assignment of the internal nodes positions by
propagating from the tree leaves towards the root. Given the assignment of parent nodes,
reconstruct the maximum-likelihood positions of the child nodes by propagating
fr... | [
"def",
"_ml_t_joint",
"(",
"self",
")",
":",
"def",
"_cleanup",
"(",
")",
":",
"for",
"node",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
")",
":",
"del",
"node",
".",
"joint_pos_Lx",
"del",
"node",
".",
"joint_pos_Cx",
"self",
".",
"logger",
... | 56.191304 | 0.010189 |
def rules(self, x, y):
# type: (int, int) -> List[Type[Rule]]
"""
Get rules at specific position in the structure.
:param x: X coordinate
:param y: Y coordinate
:return: List of rules
"""
return [r for r in self._field[y][x]] | [
"def",
"rules",
"(",
"self",
",",
"x",
",",
"y",
")",
":",
"# type: (int, int) -> List[Type[Rule]]",
"return",
"[",
"r",
"for",
"r",
"in",
"self",
".",
"_field",
"[",
"y",
"]",
"[",
"x",
"]",
"]"
] | 31.222222 | 0.010381 |
def _reset(self):
"""
Reset the Screen.
"""
self._last_start_line = 0
self._colour = None
self._attr = None
self._bg = None
self._cur_x = None
self._cur_y = None | [
"def",
"_reset",
"(",
"self",
")",
":",
"self",
".",
"_last_start_line",
"=",
"0",
"self",
".",
"_colour",
"=",
"None",
"self",
".",
"_attr",
"=",
"None",
"self",
".",
"_bg",
"=",
"None",
"self",
".",
"_cur_x",
"=",
"None",
"self",
".",
"_cur_y",
"... | 22.4 | 0.008584 |
def plot_elements_to_ax(self, cid, ax=None, **kwargs):
"""Plot element data (parameter sets).
If the parameter *ax* is not set, then a new figure will be created
with a corresponding axes.
Parameters
----------
cid : int or :py:class:`numpy.ndarray`
if *cid... | [
"def",
"plot_elements_to_ax",
"(",
"self",
",",
"cid",
",",
"ax",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"rasterize",
"=",
"kwargs",
".",
"get",
"(",
"'rasterize'",
",",
"False",
")",
"xmin",
"=",
"kwargs",
".",
"get",
"(",
"'xmin'",
",",
... | 34.210526 | 0.000272 |
def _render(self, value, format):
""" Writes javascript to call momentjs function """
template = '<script>\ndocument.write(moment(\"{t}\").{f});\n</script>'
return Markup(template.format(t=value, f=format)) | [
"def",
"_render",
"(",
"self",
",",
"value",
",",
"format",
")",
":",
"template",
"=",
"'<script>\\ndocument.write(moment(\\\"{t}\\\").{f});\\n</script>'",
"return",
"Markup",
"(",
"template",
".",
"format",
"(",
"t",
"=",
"value",
",",
"f",
"=",
"format",
")",
... | 56.75 | 0.008696 |
def _get_ipmitool_path(self, cmd='ipmitool'):
"""Get full path to the ipmitool command using the unix
`which` command
"""
p = subprocess.Popen(["which", cmd],
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
out, err = p.communicate()
return o... | [
"def",
"_get_ipmitool_path",
"(",
"self",
",",
"cmd",
"=",
"'ipmitool'",
")",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"\"which\"",
",",
"cmd",
"]",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE... | 40.375 | 0.018182 |
def render(jinja_template_text=None, jinja_template_function='highstate_doc.markdown_default_jinja_template', **kwargs):
'''
Render highstate to a text format (default Markdown)
if `jinja_template_text` is not set, `jinja_template_function` is used.
jinja_template_text: jinja text that the render uses... | [
"def",
"render",
"(",
"jinja_template_text",
"=",
"None",
",",
"jinja_template_function",
"=",
"'highstate_doc.markdown_default_jinja_template'",
",",
"*",
"*",
"kwargs",
")",
":",
"config",
"=",
"_get_config",
"(",
"*",
"*",
"kwargs",
")",
"lowstates",
"=",
"proc... | 37.342105 | 0.00206 |
def ctype_for_encoding(self, encoding):
"""Return ctypes type for an encoded Objective-C type."""
if encoding in self.typecodes:
return self.typecodes[encoding]
elif encoding[0:1] == b'^' and encoding[1:] in self.typecodes:
return POINTER(self.typecodes[encoding[1:]])
... | [
"def",
"ctype_for_encoding",
"(",
"self",
",",
"encoding",
")",
":",
"if",
"encoding",
"in",
"self",
".",
"typecodes",
":",
"return",
"self",
".",
"typecodes",
"[",
"encoding",
"]",
"elif",
"encoding",
"[",
"0",
":",
"1",
"]",
"==",
"b'^'",
"and",
"enc... | 53 | 0.002317 |
def matrix_to_points(matrix, pitch, origin):
"""
Convert an (n,m,p) matrix into a set of points for each voxel center.
Parameters
-----------
matrix: (n,m,p) bool, voxel matrix
pitch: float, what pitch was the voxel matrix computed with
origin: (3,) float, what is the origin of the voxel ma... | [
"def",
"matrix_to_points",
"(",
"matrix",
",",
"pitch",
",",
"origin",
")",
":",
"indices",
"=",
"np",
".",
"column_stack",
"(",
"np",
".",
"nonzero",
"(",
"matrix",
")",
")",
"points",
"=",
"indices_to_points",
"(",
"indices",
"=",
"indices",
",",
"pitc... | 30.631579 | 0.001667 |
def parse_fqscreen(self, f):
""" Parse the FastQ Screen output into a 3D dict """
parsed_data = OrderedDict()
reads_processed = None
nohits_pct = None
for l in f['f']:
if l.startswith('%Hit_no_genomes:') or l.startswith('%Hit_no_libraries:'):
nohits_pc... | [
"def",
"parse_fqscreen",
"(",
"self",
",",
"f",
")",
":",
"parsed_data",
"=",
"OrderedDict",
"(",
")",
"reads_processed",
"=",
"None",
"nohits_pct",
"=",
"None",
"for",
"l",
"in",
"f",
"[",
"'f'",
"]",
":",
"if",
"l",
".",
"startswith",
"(",
"'%Hit_no_... | 61.625 | 0.009185 |
def _get_variants(data):
"""Retrieve variants from CWL and standard inputs for organizing variants.
"""
active_vs = []
if "variants" in data:
variants = data["variants"]
# CWL based list of variants
if isinstance(variants, dict) and "samples" in variants:
variants = v... | [
"def",
"_get_variants",
"(",
"data",
")",
":",
"active_vs",
"=",
"[",
"]",
"if",
"\"variants\"",
"in",
"data",
":",
"variants",
"=",
"data",
"[",
"\"variants\"",
"]",
"# CWL based list of variants",
"if",
"isinstance",
"(",
"variants",
",",
"dict",
")",
"and... | 45.115385 | 0.000835 |
def equivalent_to(self, token):
"""
Gets all tokens which match the character and scopes of a reference token
:param token: :class:`esi.models.Token`
:return: :class:`esi.managers.TokenQueryset`
"""
return self.filter(character_id=token.character_id).require_scopes_exact(... | [
"def",
"equivalent_to",
"(",
"self",
",",
"token",
")",
":",
"return",
"self",
".",
"filter",
"(",
"character_id",
"=",
"token",
".",
"character_id",
")",
".",
"require_scopes_exact",
"(",
"token",
".",
"scopes",
".",
"all",
"(",
")",
")",
".",
"filter",... | 53.75 | 0.011442 |
def main():
"""
Command-line processor. See ``--help`` for details.
"""
main_only_quicksetup_rootlogger(level=logging.DEBUG)
parser = argparse.ArgumentParser()
parser.add_argument(
"--mysql", default="mysql",
help="MySQL program (default=mysql)")
parser.add_argument(
... | [
"def",
"main",
"(",
")",
":",
"main_only_quicksetup_rootlogger",
"(",
"level",
"=",
"logging",
".",
"DEBUG",
")",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
")",
"parser",
".",
"add_argument",
"(",
"\"--mysql\"",
",",
"default",
"=",
"\"mysql\"",
... | 38.532468 | 0.000329 |
def srp1(*args,**kargs):
"""Send and receive packets at layer 2 and return only the first answer
nofilter: put 1 to avoid use of bpf filters
retry: if positive, how many times to resend unanswered packets
if negative, how many times to retry when no more packets are answered
timeout: how much time to ... | [
"def",
"srp1",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
":",
"if",
"not",
"\"timeout\"",
"in",
"kargs",
":",
"kargs",
"[",
"\"timeout\"",
"]",
"=",
"-",
"1",
"a",
",",
"b",
"=",
"srp",
"(",
"*",
"args",
",",
"*",
"*",
"kargs",
")",
"if"... | 39.882353 | 0.010086 |
def prep_bam_inputs(out_dir, sample, call_file, bam_file):
"""Prepare expected input BAM files from pre-aligned.
"""
base = utils.splitext_plus(os.path.basename(bam_file))[0]
with open(call_file) as in_handle:
for cur_hla in (x.strip() for x in in_handle):
out_file = os.path.join(uti... | [
"def",
"prep_bam_inputs",
"(",
"out_dir",
",",
"sample",
",",
"call_file",
",",
"bam_file",
")",
":",
"base",
"=",
"utils",
".",
"splitext_plus",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"bam_file",
")",
")",
"[",
"0",
"]",
"with",
"open",
"(",
... | 55.181818 | 0.008104 |
def comparator(objective):
"""
Higher order function creating a compare function for objectives.
Args:
objective (cipy.algorithms.core.Objective): The objective to create a
compare for.
Returns:
callable: Function accepting two objectives to compare.
Examples:
... | [
"def",
"comparator",
"(",
"objective",
")",
":",
"if",
"isinstance",
"(",
"objective",
",",
"Minimum",
")",
":",
"return",
"lambda",
"l",
",",
"r",
":",
"l",
"<",
"r",
"else",
":",
"return",
"lambda",
"l",
",",
"r",
":",
"l",
">",
"r"
] | 25.318182 | 0.00173 |
def detect_anomaly(self):
"""
Detect anomalies in the timeseries data for the submetrics specified in the config file. Identified anomalies are
stored in self.anomalies as well as written to .anomalies.csv file to be used by the client charting page. Anomaly
detection uses the luminol library (http://py... | [
"def",
"detect_anomaly",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"anomaly_detection_metrics",
"or",
"len",
"(",
"self",
".",
"anomaly_detection_metrics",
")",
"<=",
"0",
":",
"return",
"for",
"submetric",
"in",
"self",
".",
"anomaly_detection_metrics",
... | 54.857143 | 0.009386 |
def listen_many(*rooms):
"""Listen for changes in all registered listeners in all specified rooms"""
rooms = set(r.conn for r in rooms)
for room in rooms:
room.validate_listeners()
with ARBITRATOR.condition:
while any(r.connected for r in rooms):
ARBITRATOR.condition.wait()
... | [
"def",
"listen_many",
"(",
"*",
"rooms",
")",
":",
"rooms",
"=",
"set",
"(",
"r",
".",
"conn",
"for",
"r",
"in",
"rooms",
")",
"for",
"room",
"in",
"rooms",
":",
"room",
".",
"validate_listeners",
"(",
")",
"with",
"ARBITRATOR",
".",
"condition",
":"... | 34.5 | 0.002353 |
def _make_chunk_size(self, req_size):
"""
Takes an allocation size as requested by the user and modifies it to be a suitable chunk size.
"""
size = req_size
size += 2 * self._chunk_size_t_size # Two size fields
size = self._chunk_min_size if size < self._chunk_min_size e... | [
"def",
"_make_chunk_size",
"(",
"self",
",",
"req_size",
")",
":",
"size",
"=",
"req_size",
"size",
"+=",
"2",
"*",
"self",
".",
"_chunk_size_t_size",
"# Two size fields",
"size",
"=",
"self",
".",
"_chunk_min_size",
"if",
"size",
"<",
"self",
".",
"_chunk_m... | 54.8 | 0.008977 |
def build_response(
self, request, response, from_cache=False, cacheable_methods=None
):
"""
Build a response by making a request or using the cache.
This will end up calling send and returning a potentially
cached response
"""
cacheable = cacheable_methods o... | [
"def",
"build_response",
"(",
"self",
",",
"request",
",",
"response",
",",
"from_cache",
"=",
"False",
",",
"cacheable_methods",
"=",
"None",
")",
":",
"cacheable",
"=",
"cacheable_methods",
"or",
"self",
".",
"cacheable_methods",
"if",
"not",
"from_cache",
"... | 40.09589 | 0.001334 |
def decode_example(self, tfexample_data):
"""See base class for details."""
# TODO(epot): Support dynamic shape
if self.shape.count(None) < 2:
# Restore the shape if possible. TF Example flattened it.
shape = [-1 if i is None else i for i in self.shape]
tfexample_data = tf.reshape(tfexampl... | [
"def",
"decode_example",
"(",
"self",
",",
"tfexample_data",
")",
":",
"# TODO(epot): Support dynamic shape",
"if",
"self",
".",
"shape",
".",
"count",
"(",
"None",
")",
"<",
"2",
":",
"# Restore the shape if possible. TF Example flattened it.",
"shape",
"=",
"[",
"... | 46 | 0.010661 |
def detect_language(index_page):
"""
Detect `languages` using `langdetect` library.
Args:
index_page (str): HTML content of the page you wish to analyze.
Returns:
obj: One :class:`.SourceString` object.
"""
dom = dhtmlparser.parseString(index_page)
clean_content = dhtmlpar... | [
"def",
"detect_language",
"(",
"index_page",
")",
":",
"dom",
"=",
"dhtmlparser",
".",
"parseString",
"(",
"index_page",
")",
"clean_content",
"=",
"dhtmlparser",
".",
"removeTags",
"(",
"dom",
")",
"lang",
"=",
"None",
"try",
":",
"lang",
"=",
"langdetect",... | 23.291667 | 0.001718 |
def at_index(iterable, index):
# type: (Iterable[T], int) -> T
"""" Return the item at the index of this iterable or raises IndexError.
WARNING: this will consume generators.
Negative indices are allowed but be aware they will cause n items to
be held in memory, where n = abs(index)
... | [
"def",
"at_index",
"(",
"iterable",
",",
"index",
")",
":",
"# type: (Iterable[T], int) -> T",
"try",
":",
"if",
"index",
"<",
"0",
":",
"return",
"deque",
"(",
"iterable",
",",
"maxlen",
"=",
"abs",
"(",
"index",
")",
")",
".",
"popleft",
"(",
")",
"r... | 36.625 | 0.001664 |
def _init_add_goid_alt(self):
'''
Add alternate GO IDs to term counts.
'''
# Fill aspect_counts. Find alternate GO IDs that may not be on gocnts
goid_alts = set()
go2cnt_add = {}
aspect_counts = self.aspect_counts
gocnts = self.gocnts
go2obj = ... | [
"def",
"_init_add_goid_alt",
"(",
"self",
")",
":",
"# Fill aspect_counts. Find alternate GO IDs that may not be on gocnts",
"goid_alts",
"=",
"set",
"(",
")",
"go2cnt_add",
"=",
"{",
"}",
"aspect_counts",
"=",
"self",
".",
"aspect_counts",
"gocnts",
"=",
"self",
".",... | 41.793103 | 0.002419 |
def is_worktree(cwd,
user=None,
password=None,
output_encoding=None):
'''
.. versionadded:: 2015.8.0
This function will attempt to determine if ``cwd`` is part of a
worktree by checking its ``.git`` to see if it is a file containing a
reference to ano... | [
"def",
"is_worktree",
"(",
"cwd",
",",
"user",
"=",
"None",
",",
"password",
"=",
"None",
",",
"output_encoding",
"=",
"None",
")",
":",
"cwd",
"=",
"_expand_path",
"(",
"cwd",
",",
"user",
")",
"try",
":",
"toplevel",
"=",
"_get_toplevel",
"(",
"cwd",... | 33.771429 | 0.000411 |
def crop_frequencies(self, low=None, high=None, copy=False):
"""Crop this `Spectrogram` to the specified frequencies
Parameters
----------
low : `float`
lower frequency bound for cropped `Spectrogram`
high : `float`
upper frequency bound for cropped `Spec... | [
"def",
"crop_frequencies",
"(",
"self",
",",
"low",
"=",
"None",
",",
"high",
"=",
"None",
",",
"copy",
"=",
"False",
")",
":",
"if",
"low",
"is",
"not",
"None",
":",
"low",
"=",
"units",
".",
"Quantity",
"(",
"low",
",",
"self",
".",
"_default_yun... | 38.254902 | 0.001 |
def account(self, id):
"""Get :py:class:`ofxclient.Account` by section id"""
if self.parser.has_section(id):
return self._section_to_account(id)
return None | [
"def",
"account",
"(",
"self",
",",
"id",
")",
":",
"if",
"self",
".",
"parser",
".",
"has_section",
"(",
"id",
")",
":",
"return",
"self",
".",
"_section_to_account",
"(",
"id",
")",
"return",
"None"
] | 37.6 | 0.010417 |
def clean(input_string,
tag_dictionary=constants.SUPPORTED_TAGS):
"""
Sanitizes HTML. Tags not contained as keys in the tag_dictionary input are
removed, and child nodes are recursively moved to parent of removed node.
Attributes not contained as arguments in tag_dictionary are removed.
Do... | [
"def",
"clean",
"(",
"input_string",
",",
"tag_dictionary",
"=",
"constants",
".",
"SUPPORTED_TAGS",
")",
":",
"try",
":",
"assert",
"isinstance",
"(",
"input_string",
",",
"basestring",
")",
"except",
"AssertionError",
":",
"raise",
"TypeError",
"root",
"=",
... | 45.590164 | 0.002464 |
def save(self, filehandle, destination=None, metadata=None,
validate=True, catch_all_errors=False, *args, **kwargs):
"""Saves the filehandle to the provided destination or the attached
default destination. Allows passing arbitrary positional and keyword
arguments to the saving mecha... | [
"def",
"save",
"(",
"self",
",",
"filehandle",
",",
"destination",
"=",
"None",
",",
"metadata",
"=",
"None",
",",
"validate",
"=",
"True",
",",
"catch_all_errors",
"=",
"False",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"destination",
"=",
... | 45.617647 | 0.001894 |
def _serialize(self, value, ct):
"""Auto-serialization of the value based upon the content-type value.
:param any value: The value to serialize
:param ietfparse.: The content type to serialize
:rtype: str
:raises: ValueError
"""
key = '{}/{}'.format(ct.content_t... | [
"def",
"_serialize",
"(",
"self",
",",
"value",
",",
"ct",
")",
":",
"key",
"=",
"'{}/{}'",
".",
"format",
"(",
"ct",
".",
"content_type",
",",
"ct",
".",
"content_subtype",
")",
"if",
"key",
"not",
"in",
"self",
".",
"_SERIALIZATION_MAP",
":",
"raise"... | 44.578947 | 0.002312 |
def do_photometry(self, image, init_guesses=None):
"""
Perform PSF photometry in ``image``.
This method assumes that ``psf_model`` has centroids and flux
parameters which will be fitted to the data provided in
``image``. A compound model, in fact a sum of ``psf_model``,
... | [
"def",
"do_photometry",
"(",
"self",
",",
"image",
",",
"init_guesses",
"=",
"None",
")",
":",
"if",
"self",
".",
"bkg_estimator",
"is",
"not",
"None",
":",
"image",
"=",
"image",
"-",
"self",
".",
"bkg_estimator",
"(",
"image",
")",
"if",
"self",
".",... | 48.233645 | 0.00057 |
def set_mode(self, mode):
"""
Set *Vim* mode to ``mode``.
Supported modes:
* ``normal``
* ``insert``
* ``command``
* ``visual``
* ``visual-block``
This method behave as setter-only property.
Example:
>>> import headlessvim
... | [
"def",
"set_mode",
"(",
"self",
",",
"mode",
")",
":",
"keys",
"=",
"'\\033\\033'",
"if",
"mode",
"==",
"'normal'",
":",
"pass",
"elif",
"mode",
"==",
"'insert'",
":",
"keys",
"+=",
"'i'",
"elif",
"mode",
"==",
"'command'",
":",
"keys",
"+=",
"':'",
... | 24.794872 | 0.00199 |
def _decay():
"""L2 weight decay loss."""
costs = []
for var in tf.trainable_variables():
if var.op.name.find('DW') > 0:
costs.append(tf.nn.l2_loss(var))
return tf.add_n(costs) | [
"def",
"_decay",
"(",
")",
":",
"costs",
"=",
"[",
"]",
"for",
"var",
"in",
"tf",
".",
"trainable_variables",
"(",
")",
":",
"if",
"var",
".",
"op",
".",
"name",
".",
"find",
"(",
"'DW'",
")",
">",
"0",
":",
"costs",
".",
"append",
"(",
"tf",
... | 26.857143 | 0.030928 |
def stop_server(self):
"""
Stop serving
"""
if self.api_server is not None:
try:
self.api_server.socket.shutdown(socket.SHUT_RDWR)
except:
log.warning("Failed to shut down API server socket")
self.api_server.shutdown() | [
"def",
"stop_server",
"(",
"self",
")",
":",
"if",
"self",
".",
"api_server",
"is",
"not",
"None",
":",
"try",
":",
"self",
".",
"api_server",
".",
"socket",
".",
"shutdown",
"(",
"socket",
".",
"SHUT_RDWR",
")",
"except",
":",
"log",
".",
"warning",
... | 28.090909 | 0.009404 |
def separate_resources(self):
# type: () -> None
"""Move contents of resources key in internal dictionary into self.resources
Returns:
None
"""
self._separate_hdxobjects(self.resources, 'resources', 'name', hdx.data.resource.Resource) | [
"def",
"separate_resources",
"(",
"self",
")",
":",
"# type: () -> None",
"self",
".",
"_separate_hdxobjects",
"(",
"self",
".",
"resources",
",",
"'resources'",
",",
"'name'",
",",
"hdx",
".",
"data",
".",
"resource",
".",
"Resource",
")"
] | 35 | 0.017422 |
def add_classification_events(obj, events, labels, signal_label=None,
weights=None, test=False):
"""Add classification events to a TMVA::Factory or TMVA::DataLoader from NumPy arrays.
Parameters
----------
obj : TMVA::Factory or TMVA::DataLoader
A TMVA::Factory or ... | [
"def",
"add_classification_events",
"(",
"obj",
",",
"events",
",",
"labels",
",",
"signal_label",
"=",
"None",
",",
"weights",
"=",
"None",
",",
"test",
"=",
"False",
")",
":",
"if",
"NEW_TMVA_API",
":",
"# pragma: no cover",
"if",
"not",
"isinstance",
"(",... | 45.058824 | 0.000766 |
def rank(matrix, atol=1e-13, rtol=0):
"""
Estimate the rank, i.e., the dimension of the column space, of a matrix.
The algorithm used by this function is based on the singular value
decomposition of `stoichiometry_matrix`.
Parameters
----------
matrix : ndarray
The matrix should be... | [
"def",
"rank",
"(",
"matrix",
",",
"atol",
"=",
"1e-13",
",",
"rtol",
"=",
"0",
")",
":",
"matrix",
"=",
"np",
".",
"atleast_2d",
"(",
"matrix",
")",
"sigma",
"=",
"svd",
"(",
"matrix",
",",
"compute_uv",
"=",
"False",
")",
"tol",
"=",
"max",
"("... | 30.533333 | 0.000705 |
def progress(self):
"""
Deal with next token
Used to create, fillout and end groups and singles
As well as just append everything else
"""
tokenum, value, scol = self.current.values()
# Default to not appending anything
just_append = False
... | [
"def",
"progress",
"(",
"self",
")",
":",
"tokenum",
",",
"value",
",",
"scol",
"=",
"self",
".",
"current",
".",
"values",
"(",
")",
"# Default to not appending anything",
"just_append",
"=",
"False",
"# Prevent from group having automatic pass given to it",
"# If it... | 37.10101 | 0.001856 |
def get_tan_media(self, media_type = TANMediaType2.ALL, media_class = TANMediaClass4.ALL):
"""Get information about TAN lists/generators.
Returns tuple of fints.formals.TANUsageOption and a list of fints.formals.TANMedia4 or fints.formals.TANMedia5 objects."""
with self._get_dialog() as dialog... | [
"def",
"get_tan_media",
"(",
"self",
",",
"media_type",
"=",
"TANMediaType2",
".",
"ALL",
",",
"media_class",
"=",
"TANMediaClass4",
".",
"ALL",
")",
":",
"with",
"self",
".",
"_get_dialog",
"(",
")",
"as",
"dialog",
":",
"hktab",
"=",
"self",
".",
"_fin... | 40.882353 | 0.016878 |
def quick_doc(request_data):
"""
Worker that returns the documentation of the symbol under cursor.
"""
code = request_data['code']
line = request_data['line'] + 1
column = request_data['column']
path = request_data['path']
# encoding = 'utf-8'
encoding = 'utf-8'
script = jedi.Scr... | [
"def",
"quick_doc",
"(",
"request_data",
")",
":",
"code",
"=",
"request_data",
"[",
"'code'",
"]",
"line",
"=",
"request_data",
"[",
"'line'",
"]",
"+",
"1",
"column",
"=",
"request_data",
"[",
"'column'",
"]",
"path",
"=",
"request_data",
"[",
"'path'",
... | 29.777778 | 0.001808 |
def jenkins_request_with_headers(jenkins_server, req):
"""
We need to get the headers in addition to the body answer
to get the location from them
This function uses jenkins_request method from python-jenkins library
with just the return call changed
:param jenkins_server: The server to query
... | [
"def",
"jenkins_request_with_headers",
"(",
"jenkins_server",
",",
"req",
")",
":",
"try",
":",
"response",
"=",
"jenkins_server",
".",
"jenkins_request",
"(",
"req",
")",
"response_body",
"=",
"response",
".",
"content",
"response_headers",
"=",
"response",
".",
... | 43.934783 | 0.001452 |
def align_circulation_with_z(self, circulation=None):
"""
If the input orbit is a tube orbit, this function aligns the circulation
axis with the z axis and returns a copy.
Parameters
----------
circulation : array_like (optional)
Array of bits that specify th... | [
"def",
"align_circulation_with_z",
"(",
"self",
",",
"circulation",
"=",
"None",
")",
":",
"if",
"circulation",
"is",
"None",
":",
"circulation",
"=",
"self",
".",
"circulation",
"(",
")",
"circulation",
"=",
"atleast_2d",
"(",
"circulation",
",",
"insert_axis... | 36.338235 | 0.011032 |
def correct_rytov_output(radius, sphere_index, medium_index, radius_sampling):
r"""Error-correction of refractive index and radius for Rytov
This method corrects the fitting results for `radius`
:math:`r_\text{Ryt}` and `sphere_index` :math:`n_\text{Ryt}`
obtained using :func:`qpsphere.models.rytov` us... | [
"def",
"correct_rytov_output",
"(",
"radius",
",",
"sphere_index",
",",
"medium_index",
",",
"radius_sampling",
")",
":",
"params",
"=",
"get_params",
"(",
"radius_sampling",
")",
"x",
"=",
"sphere_index",
"/",
"medium_index",
"-",
"1",
"radius_sc",
"=",
"radius... | 33.034483 | 0.000507 |
def _build_string_type(var, property_path=None):
""" Builds schema definitions for string type values.
:param var: The string type value
:param List[str] property_path: The property path of the current type,
defaults to None, optional
:param property_path: [type], optional
:return: The buil... | [
"def",
"_build_string_type",
"(",
"var",
",",
"property_path",
"=",
"None",
")",
":",
"if",
"not",
"property_path",
":",
"property_path",
"=",
"[",
"]",
"schema",
"=",
"{",
"\"type\"",
":",
"\"string\"",
"}",
"if",
"is_builtin_type",
"(",
"var",
")",
":",
... | 28.4 | 0.00227 |
def get_ddlib_feats(span, context, idxs):
"""
Minimalist port of generic mention features from ddlib
"""
if span.stable_id not in unary_ddlib_feats:
unary_ddlib_feats[span.stable_id] = set()
for seq_feat in _get_seq_features(context, idxs):
unary_ddlib_feats[span.stable_id]... | [
"def",
"get_ddlib_feats",
"(",
"span",
",",
"context",
",",
"idxs",
")",
":",
"if",
"span",
".",
"stable_id",
"not",
"in",
"unary_ddlib_feats",
":",
"unary_ddlib_feats",
"[",
"span",
".",
"stable_id",
"]",
"=",
"set",
"(",
")",
"for",
"seq_feat",
"in",
"... | 32 | 0.001898 |
def set_secure_boot_mode(self, secure_boot_enable):
"""Enable/Disable secure boot on the server.
Resetting the server post updating this settings is needed
from the caller side to make this into effect.
:param secure_boot_enable: True, if secure boot needs to be
enabled f... | [
"def",
"set_secure_boot_mode",
"(",
"self",
",",
"secure_boot_enable",
")",
":",
"if",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
":",
"sushy_system",
"=",
"self",
".",
"_get_sushy_system",
"(",
"PROLIANT_SYSTEM_ID",
")",
"try",
":",
"sushy_system",
".",
"secu... | 49.433333 | 0.001323 |
def py_to_go_cookie(py_cookie):
'''Convert a python cookie to the JSON-marshalable Go-style cookie form.'''
# TODO (perhaps):
# HttpOnly
# Creation
# LastAccess
# Updated
# not done properly: CanonicalHost.
go_cookie = {
'Name': py_cookie.name,
'Value': py_cookie.... | [
"def",
"py_to_go_cookie",
"(",
"py_cookie",
")",
":",
"# TODO (perhaps):",
"# HttpOnly",
"# Creation",
"# LastAccess",
"# Updated",
"# not done properly: CanonicalHost.",
"go_cookie",
"=",
"{",
"'Name'",
":",
"py_cookie",
".",
"name",
",",
"'Value'",
":",
"py_co... | 37 | 0.001054 |
def start_with(self, request):
"""Start the crawler using the given request.
Args:
request (:class:`nyawc.http.Request`): The startpoint for the crawler.
"""
HTTPRequestHelper.patch_with_options(request, self.__options)
self.queue.add_request(request)
self... | [
"def",
"start_with",
"(",
"self",
",",
"request",
")",
":",
"HTTPRequestHelper",
".",
"patch_with_options",
"(",
"request",
",",
"self",
".",
"__options",
")",
"self",
".",
"queue",
".",
"add_request",
"(",
"request",
")",
"self",
".",
"__crawler_start",
"("... | 27.25 | 0.008876 |
def accept(self, arg1: JavaObject, arg2: JavaObject) -> None:
"""
>>> c = BiConsumer(lambda x,y : print(x + y))
>>> c.accept("foo", "bar")
foobar
"""
self.lambda_function(arg1, arg2) | [
"def",
"accept",
"(",
"self",
",",
"arg1",
":",
"JavaObject",
",",
"arg2",
":",
"JavaObject",
")",
"->",
"None",
":",
"self",
".",
"lambda_function",
"(",
"arg1",
",",
"arg2",
")"
] | 32 | 0.008696 |
def resume_service(name):
"""
Resume the service given by name.
@warn: This method requires UAC elevation in Windows Vista and above.
@note: Not all services support this.
@see: L{get_services}, L{get_active_services},
L{start_service}, L{stop_service}, L{pause_ser... | [
"def",
"resume_service",
"(",
"name",
")",
":",
"with",
"win32",
".",
"OpenSCManager",
"(",
"dwDesiredAccess",
"=",
"win32",
".",
"SC_MANAGER_CONNECT",
")",
"as",
"hSCManager",
":",
"with",
"win32",
".",
"OpenService",
"(",
"hSCManager",
",",
"name",
",",
"d... | 37.333333 | 0.011611 |
def HStruct_selectFields(structT, fieldsToUse):
"""
Select fields from structure (rest will become spacing)
:param structT: HStruct type instance
:param fieldsToUse: dict {name:{...}} or set of names to select,
dictionary is used to select nested fields
in HStruct or HUnion fields
... | [
"def",
"HStruct_selectFields",
"(",
"structT",
",",
"fieldsToUse",
")",
":",
"template",
"=",
"[",
"]",
"fieldsToUse",
"=",
"fieldsToUse",
"foundNames",
"=",
"set",
"(",
")",
"for",
"f",
"in",
"structT",
".",
"fields",
":",
"name",
"=",
"None",
"subfields"... | 30.222222 | 0.000712 |
def lincr(l,cap): # to increment a list up to a max-list of 'cap'
"""
Simulate a counting system from an n-dimensional list.
Usage: lincr(l,cap) l=list to increment, cap=max values for each list pos'n
Returns: next set of values for list l, OR -1 (if overflow)
"""
l[0] = l[0] + 1 # e.g., [0,0,0]... | [
"def",
"lincr",
"(",
"l",
",",
"cap",
")",
":",
"# to increment a list up to a max-list of 'cap'",
"l",
"[",
"0",
"]",
"=",
"l",
"[",
"0",
"]",
"+",
"1",
"# e.g., [0,0,0] --> [2,4,3] (=cap)",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"l",
")",
")",
":"... | 40.066667 | 0.011382 |
def available(self, context):
"""
Resource availability.
:param resort.engine.execution.Context context:
Current execution context.
"""
try:
if self.__available is None:
encoded_name = urllib.parse.quote_plus(self.__name)
status_code, msg = self.__endpoint.get(
"/resources/custom-... | [
"def",
"available",
"(",
"self",
",",
"context",
")",
":",
"try",
":",
"if",
"self",
".",
"__available",
"is",
"None",
":",
"encoded_name",
"=",
"urllib",
".",
"parse",
".",
"quote_plus",
"(",
"self",
".",
"__name",
")",
"status_code",
",",
"msg",
"=",... | 22.5 | 0.057569 |
def spatialDomainNoGrid(self):
"""
Superposition of analytical solutions without a gridded domain
"""
self.w = np.zeros(self.xw.shape)
if self.Debug:
print("w = ")
print(self.w.shape)
for i in range(len(self.q)):
# More efficient if we have created some 0-load ... | [
"def",
"spatialDomainNoGrid",
"(",
"self",
")",
":",
"self",
".",
"w",
"=",
"np",
".",
"zeros",
"(",
"self",
".",
"xw",
".",
"shape",
")",
"if",
"self",
".",
"Debug",
":",
"print",
"(",
"\"w = \"",
")",
"print",
"(",
"self",
".",
"w",
".",
"shape... | 32.941176 | 0.017361 |
def reset (self):
"""
Reset all variables to default values.
"""
# self.url is constructed by self.build_url() out of base_url
# and (base_ref or parent) as absolute and normed url.
# This the real url we use when checking so it also referred to
# as 'real url'
... | [
"def",
"reset",
"(",
"self",
")",
":",
"# self.url is constructed by self.build_url() out of base_url",
"# and (base_ref or parent) as absolute and normed url.",
"# This the real url we use when checking so it also referred to",
"# as 'real url'",
"self",
".",
"url",
"=",
"None",
"# a ... | 36.395833 | 0.00223 |
def __get_WIOD_SEA_extension(root_path, year, data_sheet='DATA'):
""" Utility function to get the extension data from the SEA file in WIOD
This function is based on the structure in the WIOD_SEA_July14 file.
Missing values are set to zero.
The function works if the SEA file is either in path or in a s... | [
"def",
"__get_WIOD_SEA_extension",
"(",
"root_path",
",",
"year",
",",
"data_sheet",
"=",
"'DATA'",
")",
":",
"sea_ext",
"=",
"'.xlsx'",
"sea_start",
"=",
"'WIOD_SEA'",
"_SEA_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"root_path",
",",
"'SEA'",
")",
... | 36.459184 | 0.000272 |
def get_log_attrs():
"""Get logging attributes from the opencensus context.
:rtype: :class:`LogAttrs`
:return: The current span's trace ID, span ID, and sampling decision.
"""
try:
tracer = execution_context.get_opencensus_tracer()
if tracer is None:
raise RuntimeError
... | [
"def",
"get_log_attrs",
"(",
")",
":",
"try",
":",
"tracer",
"=",
"execution_context",
".",
"get_opencensus_tracer",
"(",
")",
"if",
"tracer",
"is",
"None",
":",
"raise",
"RuntimeError",
"except",
"Exception",
":",
"# noqa",
"_meta_logger",
".",
"error",
"(",
... | 34.731707 | 0.000683 |
def is_publication_permissible(cursor, publication_id, uuid_):
"""Check the given publisher of this publication given
by ``publication_id`` is allowed to publish the content given
by ``uuid``.
"""
# Check the publishing user has permission to publish
cursor.execute("""\
SELECT 't'::boolean
FROM
... | [
"def",
"is_publication_permissible",
"(",
"cursor",
",",
"publication_id",
",",
"uuid_",
")",
":",
"# Check the publishing user has permission to publish",
"cursor",
".",
"execute",
"(",
"\"\"\"\\\nSELECT 't'::boolean\nFROM\n pending_documents AS pd\n NATURAL JOIN document_acl AS acl... | 26.84 | 0.001439 |
def create_html_mailto(
email,
subject=None,
body=None,
cc=None,
bcc=None,
link_label="%(email)s",
linkattrd=None,
escape_urlargd=True,
escape_linkattrd=True,
email_obfuscation_mode=None):
"""Creates a W3C compliant 'mailto' link.
... | [
"def",
"create_html_mailto",
"(",
"email",
",",
"subject",
"=",
"None",
",",
"body",
"=",
"None",
",",
"cc",
"=",
"None",
",",
"bcc",
"=",
"None",
",",
"link_label",
"=",
"\"%(email)s\"",
",",
"linkattrd",
"=",
"None",
",",
"escape_urlargd",
"=",
"True",... | 38.253731 | 0.00057 |
def chown(self, path, uid, gid, dir_fd=None, follow_symlinks=None):
"""Set ownership of a faked file.
Args:
path: (str) Path to the file or directory.
uid: (int) Numeric uid to set the file or directory to.
gid: (int) Numeric gid to set the file or directory to.
... | [
"def",
"chown",
"(",
"self",
",",
"path",
",",
"uid",
",",
"gid",
",",
"dir_fd",
"=",
"None",
",",
"follow_symlinks",
"=",
"None",
")",
":",
"if",
"follow_symlinks",
"is",
"None",
":",
"follow_symlinks",
"=",
"True",
"elif",
"sys",
".",
"version_info",
... | 42.219512 | 0.001129 |
def modify_attribute(self, attribute, value):
"""
Changes an attribute of this instance
:type attribute: string
:param attribute: The attribute you wish to change.
AttributeName - Expected value (default)
instanceType - A valid instanc... | [
"def",
"modify_attribute",
"(",
"self",
",",
"attribute",
",",
"value",
")",
":",
"return",
"self",
".",
"connection",
".",
"modify_instance_attribute",
"(",
"self",
".",
"id",
",",
"attribute",
",",
"value",
")"
] | 43.695652 | 0.001947 |
def check_directory(self):
"""Check if migrations directory exists."""
exists = os.path.exists(self.directory)
if not exists:
logger.error("No migrations directory found. Check your path or create a migration first.")
logger.error("Directory: %s" % self.directory)
... | [
"def",
"check_directory",
"(",
"self",
")",
":",
"exists",
"=",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"directory",
")",
"if",
"not",
"exists",
":",
"logger",
".",
"error",
"(",
"\"No migrations directory found. Check your path or create a migration f... | 46.857143 | 0.008982 |
def update(self, friendly_name=None, description=None):
""" Selectively updates Dataset information.
Args:
friendly_name: if not None, the new friendly name.
description: if not None, the new description.
Returns:
"""
self._get_info()
if self._info:
if friendly_name:
... | [
"def",
"update",
"(",
"self",
",",
"friendly_name",
"=",
"None",
",",
"description",
"=",
"None",
")",
":",
"self",
".",
"_get_info",
"(",
")",
"if",
"self",
".",
"_info",
":",
"if",
"friendly_name",
":",
"self",
".",
"_info",
"[",
"'friendlyName'",
"]... | 26.045455 | 0.010101 |
def sr(self, multi=0):
"""sr([multi=1]) -> (SndRcvList, PacketList)
Matches packets in the list and return ( (matched couples), (unmatched packets) )""" # noqa: E501
remain = self.res[:]
sr = []
i = 0
while i < len(remain):
s = remain[i]
j = i
... | [
"def",
"sr",
"(",
"self",
",",
"multi",
"=",
"0",
")",
":",
"# noqa: E501",
"remain",
"=",
"self",
".",
"res",
"[",
":",
"]",
"sr",
"=",
"[",
"]",
"i",
"=",
"0",
"while",
"i",
"<",
"len",
"(",
"remain",
")",
":",
"s",
"=",
"remain",
"[",
"i... | 34.423077 | 0.002174 |
def compare(self,
reference_classes: List,
query_classes: List,
method: Optional[SimAlgorithm] = SimAlgorithm.PHENODIGM) -> SimResult:
"""
Owlsim2 compare, calls compare_attribute_sets, and converts to SimResult object
:return: SimResult object
... | [
"def",
"compare",
"(",
"self",
",",
"reference_classes",
":",
"List",
",",
"query_classes",
":",
"List",
",",
"method",
":",
"Optional",
"[",
"SimAlgorithm",
"]",
"=",
"SimAlgorithm",
".",
"PHENODIGM",
")",
"->",
"SimResult",
":",
"owlsim_results",
"=",
"com... | 49.4 | 0.015905 |
def file_stat_for_all(self, filters=all_true): # pragma: no cover
"""
Find out how many files, directories and total size (Include file in
it's sub-folder) it has for each folder and sub-folder.
:returns: stat, a dict like ``{"directory path": {
"file": number of files, "dir"... | [
"def",
"file_stat_for_all",
"(",
"self",
",",
"filters",
"=",
"all_true",
")",
":",
"# pragma: no cover",
"self",
".",
"assert_is_dir_and_exists",
"(",
")",
"from",
"collections",
"import",
"OrderedDict",
"stat",
"=",
"OrderedDict",
"(",
")",
"stat",
"[",
"self"... | 28.893617 | 0.001425 |
def get_balance(self):
"""
Get balance with provider.
"""
if not SMSGLOBAL_CHECK_BALANCE_COUNTRY:
raise Exception('SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.')
params = {
'user' : self.get_username(),
'password' ... | [
"def",
"get_balance",
"(",
"self",
")",
":",
"if",
"not",
"SMSGLOBAL_CHECK_BALANCE_COUNTRY",
":",
"raise",
"Exception",
"(",
"'SMSGLOBAL_CHECK_BALANCE_COUNTRY setting must be set to check balance.'",
")",
"params",
"=",
"{",
"'user'",
":",
"self",
".",
"get_username",
"... | 39.714286 | 0.014052 |
def cmd(send, msg, args):
"""Gets stats.
Syntax: {command} <--high|--low|--userhigh|--nick <nick>|command>
"""
parser = arguments.ArgParser(args['config'])
group = parser.add_mutually_exclusive_group()
group.add_argument('--high', action='store_true')
group.add_argument('--low', action='st... | [
"def",
"cmd",
"(",
"send",
",",
"msg",
",",
"args",
")",
":",
"parser",
"=",
"arguments",
".",
"ArgParser",
"(",
"args",
"[",
"'config'",
"]",
")",
"group",
"=",
"parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"group",
".",
"add_argument",
"(",
... | 37.74 | 0.001033 |
def kp_pan_set(self, viewer, event, data_x, data_y, msg=True):
"""Sets the pan position under the cursor."""
if self.canpan:
self._panset(viewer, data_x, data_y, msg=msg)
return True | [
"def",
"kp_pan_set",
"(",
"self",
",",
"viewer",
",",
"event",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
"True",
")",
":",
"if",
"self",
".",
"canpan",
":",
"self",
".",
"_panset",
"(",
"viewer",
",",
"data_x",
",",
"data_y",
",",
"msg",
"=",
... | 42.8 | 0.009174 |
def censor(input_text):
""" Returns the input string with profanity replaced with a random string
of characters plucked from the censor_characters pool.
"""
ret = input_text
words = get_words()
for word in words:
curse_word = re.compile(re.escape(word), re.IGNORECASE)
cen = "".j... | [
"def",
"censor",
"(",
"input_text",
")",
":",
"ret",
"=",
"input_text",
"words",
"=",
"get_words",
"(",
")",
"for",
"word",
"in",
"words",
":",
"curse_word",
"=",
"re",
".",
"compile",
"(",
"re",
".",
"escape",
"(",
"word",
")",
",",
"re",
".",
"IG... | 33.75 | 0.002404 |
def format_sec(s):
"""
Format seconds in a more human readable way. It supports units down to
nanoseconds.
:param s: Float of seconds to format
:return: String second representation, like 12.4 us
"""
prefixes = ["", "m", "u", "n"]
unit = 0
while s < 1 and unit + 1 < len(prefixes):... | [
"def",
"format_sec",
"(",
"s",
")",
":",
"prefixes",
"=",
"[",
"\"\"",
",",
"\"m\"",
",",
"\"u\"",
",",
"\"n\"",
"]",
"unit",
"=",
"0",
"while",
"s",
"<",
"1",
"and",
"unit",
"+",
"1",
"<",
"len",
"(",
"prefixes",
")",
":",
"s",
"*=",
"1000",
... | 23 | 0.002457 |
def predict_quantiles(self, X, quantiles=(2.5, 97.5), Y_metadata=None, likelihood=None, kern=None):
"""
Get the predictive quantiles around the prediction at X
:param X: The points at which to make a prediction
:type X: np.ndarray (Xnew x self.input_dim)
:param quantiles: tuple ... | [
"def",
"predict_quantiles",
"(",
"self",
",",
"X",
",",
"quantiles",
"=",
"(",
"2.5",
",",
"97.5",
")",
",",
"Y_metadata",
"=",
"None",
",",
"likelihood",
"=",
"None",
",",
"kern",
"=",
"None",
")",
":",
"qs",
"=",
"super",
"(",
"WarpedGP",
",",
"s... | 56.266667 | 0.008159 |
def update(self, v):
"""Add `v` to the hash, recursively if needed."""
self.md5.update(to_bytes(str(type(v))))
if isinstance(v, string_class):
self.md5.update(to_bytes(v))
elif v is None:
pass
elif isinstance(v, (int, float)):
self.md5.update(t... | [
"def",
"update",
"(",
"self",
",",
"v",
")",
":",
"self",
".",
"md5",
".",
"update",
"(",
"to_bytes",
"(",
"str",
"(",
"type",
"(",
"v",
")",
")",
")",
")",
"if",
"isinstance",
"(",
"v",
",",
"string_class",
")",
":",
"self",
".",
"md5",
".",
... | 32.615385 | 0.002291 |
def exactly_n(l, n=1):
'''
Tests that exactly N items in an iterable are "truthy" (neither None,
False, nor 0).
'''
i = iter(l)
return all(any(i) for j in range(n)) and not any(i) | [
"def",
"exactly_n",
"(",
"l",
",",
"n",
"=",
"1",
")",
":",
"i",
"=",
"iter",
"(",
"l",
")",
"return",
"all",
"(",
"any",
"(",
"i",
")",
"for",
"j",
"in",
"range",
"(",
"n",
")",
")",
"and",
"not",
"any",
"(",
"i",
")"
] | 28.142857 | 0.009852 |
def _get_handler(self, node_id):
"""Get the handler of a given node."""
handler = self._get_attrs(node_id).get(self.HANDLER, self._default_handler)
# Here we make sure the handler is an instance of `BasicNodeHandler` or inherited
# types. While generally being bad Python practice, we st... | [
"def",
"_get_handler",
"(",
"self",
",",
"node_id",
")",
":",
"handler",
"=",
"self",
".",
"_get_attrs",
"(",
"node_id",
")",
".",
"get",
"(",
"self",
".",
"HANDLER",
",",
"self",
".",
"_default_handler",
")",
"# Here we make sure the handler is an instance of `... | 55.416667 | 0.008876 |
def htmlReadDoc(cur, URL, encoding, options):
"""parse an XML in-memory document and build a tree. """
ret = libxml2mod.htmlReadDoc(cur, URL, encoding, options)
if ret is None:raise treeError('htmlReadDoc() failed')
return xmlDoc(_obj=ret) | [
"def",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
":",
"ret",
"=",
"libxml2mod",
".",
"htmlReadDoc",
"(",
"cur",
",",
"URL",
",",
"encoding",
",",
"options",
")",
"if",
"ret",
"is",
"None",
":",
"raise",
"treeError",
... | 50.2 | 0.011765 |
def create_binding(site, hostheader='', ipaddress='*', port=80, protocol='http',
sslflags=None):
'''
Create an IIS Web Binding.
.. note::
This function only validates against the binding
ipaddress:port:hostheader combination, and will return True even if the
bind... | [
"def",
"create_binding",
"(",
"site",
",",
"hostheader",
"=",
"''",
",",
"ipaddress",
"=",
"'*'",
",",
"port",
"=",
"80",
",",
"protocol",
"=",
"'http'",
",",
"sslflags",
"=",
"None",
")",
":",
"protocol",
"=",
"six",
".",
"text_type",
"(",
"protocol",... | 36.025 | 0.001689 |
def set_params(self, **params):
"""Set parameters on this object
Safe setter method - attributes should not be modified directly as some
changes are not valid.
Valid parameters:
- n_jobs
- random_state
- verbose
Invalid parameters: (these would require mo... | [
"def",
"set_params",
"(",
"self",
",",
"*",
"*",
"params",
")",
":",
"if",
"'knn'",
"in",
"params",
"and",
"params",
"[",
"'knn'",
"]",
"!=",
"self",
".",
"knn",
":",
"raise",
"ValueError",
"(",
"\"Cannot update knn. Please create a new graph\"",
")",
"if",
... | 38.792453 | 0.000949 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.