text stringlengths 75 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 0.18 |
|---|---|---|---|
def pop_empty_columns(self, empty=None):
"""
This will pop columns from the printed columns if they only contain
'' or None
:param empty: list of values to treat as empty
"""
empty = ['', None] if empty is None else empty
if len(self) == 0:
ret... | [
"def",
"pop_empty_columns",
"(",
"self",
",",
"empty",
"=",
"None",
")",
":",
"empty",
"=",
"[",
"''",
",",
"None",
"]",
"if",
"empty",
"is",
"None",
"else",
"empty",
"if",
"len",
"(",
"self",
")",
"==",
"0",
":",
"return",
"for",
"col",
"in",
"l... | 38.846154 | 0.003868 |
def to_int(value=None, hexstr=None, text=None):
"""
Converts value to it's integer representation.
Values are converted this way:
* value:
* bytes: big-endian integer
* bool: True => 1, False => 0
* hexstr: interpret hex as integer
* text: interpret as string of digits, like '... | [
"def",
"to_int",
"(",
"value",
"=",
"None",
",",
"hexstr",
"=",
"None",
",",
"text",
"=",
"None",
")",
":",
"assert_one_val",
"(",
"value",
",",
"hexstr",
"=",
"hexstr",
",",
"text",
"=",
"text",
")",
"if",
"hexstr",
"is",
"not",
"None",
":",
"retu... | 28.833333 | 0.001399 |
def _get_members(o):
"""Returns the likely members of the object by appealing to :func:`dir`
instead of using `__dict__` attribute, since that misses certain members.
"""
result = []
for n in dir(o):
if hasattr(o, n) and n not in ["__globals__", "func_globals"]:
result.append((n,... | [
"def",
"_get_members",
"(",
"o",
")",
":",
"result",
"=",
"[",
"]",
"for",
"n",
"in",
"dir",
"(",
"o",
")",
":",
"if",
"hasattr",
"(",
"o",
",",
"n",
")",
"and",
"n",
"not",
"in",
"[",
"\"__globals__\"",
",",
"\"func_globals\"",
"]",
":",
"result... | 38.444444 | 0.002825 |
def update(self, new_inputs, strip_prefix=True):
"""
Updates the inputs dictionary with the key/value pairs from new_inputs, overwriting existing keys.
"""
if strip_prefix and self.input_name_prefix is not None:
for i in new_inputs:
if i.startswith(self.input_... | [
"def",
"update",
"(",
"self",
",",
"new_inputs",
",",
"strip_prefix",
"=",
"True",
")",
":",
"if",
"strip_prefix",
"and",
"self",
".",
"input_name_prefix",
"is",
"not",
"None",
":",
"for",
"i",
"in",
"new_inputs",
":",
"if",
"i",
".",
"startswith",
"(",
... | 46.2 | 0.008493 |
def init_loopback(self, data):
"""Just initialize the object for our Pseudo Loopback"""
self.name = data["name"]
self.description = data['description']
self.win_index = data['win_index']
self.mac = data["mac"]
self.guid = data["guid"]
self.ip = "127.0.0.1" | [
"def",
"init_loopback",
"(",
"self",
",",
"data",
")",
":",
"self",
".",
"name",
"=",
"data",
"[",
"\"name\"",
"]",
"self",
".",
"description",
"=",
"data",
"[",
"'description'",
"]",
"self",
".",
"win_index",
"=",
"data",
"[",
"'win_index'",
"]",
"sel... | 38.125 | 0.00641 |
def get_fetch_response(self, raw):
"""This just makes the payload instance more HTTPClient like"""
p = Payload(raw)
p._body = p.body
return p | [
"def",
"get_fetch_response",
"(",
"self",
",",
"raw",
")",
":",
"p",
"=",
"Payload",
"(",
"raw",
")",
"p",
".",
"_body",
"=",
"p",
".",
"body",
"return",
"p"
] | 33.8 | 0.011561 |
def action_serialize(source, out_fmt="turtle", verbose=False):
"""
Util: render RDF into a different serialization
valid options are: xml, n3, turtle, nt, pretty-xml, json-ld
"""
o = Ontospy(uri_or_path=source, verbose=verbose, build_all=False)
s = o.serialize(out_fmt)
print(s) | [
"def",
"action_serialize",
"(",
"source",
",",
"out_fmt",
"=",
"\"turtle\"",
",",
"verbose",
"=",
"False",
")",
":",
"o",
"=",
"Ontospy",
"(",
"uri_or_path",
"=",
"source",
",",
"verbose",
"=",
"verbose",
",",
"build_all",
"=",
"False",
")",
"s",
"=",
... | 34.222222 | 0.006329 |
def rotate(self, angle, x=0, y=0):
"""Rotate element by given angle around given pivot.
Parameters
----------
angle : float
rotation angle in degrees
x, y : float
pivot coordinates in user coordinate system (defaults to top-left
corner of the ... | [
"def",
"rotate",
"(",
"self",
",",
"angle",
",",
"x",
"=",
"0",
",",
"y",
"=",
"0",
")",
":",
"self",
".",
"root",
".",
"set",
"(",
"\"transform\"",
",",
"\"%s rotate(%f %f %f)\"",
"%",
"(",
"self",
".",
"root",
".",
"get",
"(",
"\"transform\"",
")... | 35.153846 | 0.004264 |
def get_peers(self, id=None, endpoint=None):
"""
Get the current peers of a remote node
Args:
id: (int, optional) id to use for response tracking
endpoint: (RPCEndpoint, optional) endpoint to specify to use
Returns:
json object of the result or the er... | [
"def",
"get_peers",
"(",
"self",
",",
"id",
"=",
"None",
",",
"endpoint",
"=",
"None",
")",
":",
"return",
"self",
".",
"_call_endpoint",
"(",
"GET_PEERS",
",",
"id",
"=",
"id",
",",
"endpoint",
"=",
"endpoint",
")"
] | 38.636364 | 0.004598 |
async def get_friendly_name(self) -> Text:
"""
The friendly name is mapped to Facebook's first name. If the first
name is missing, use the last name.
"""
u = await self._get_user()
f = u.get('first_name', '').strip()
l = u.get('last_name', '').strip()
ret... | [
"async",
"def",
"get_friendly_name",
"(",
"self",
")",
"->",
"Text",
":",
"u",
"=",
"await",
"self",
".",
"_get_user",
"(",
")",
"f",
"=",
"u",
".",
"get",
"(",
"'first_name'",
",",
"''",
")",
".",
"strip",
"(",
")",
"l",
"=",
"u",
".",
"get",
... | 32.1 | 0.009091 |
def _any_would_run(func, filenames, *args):
"""True if a linter function would be called on any of filenames."""
if os.environ.get("_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING", None):
return True
for filename in filenames:
# suppress(E204)
stamp_args, stamp_kwargs = _run_lint_on_fi... | [
"def",
"_any_would_run",
"(",
"func",
",",
"filenames",
",",
"*",
"args",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"\"_POLYSQUARE_GENERIC_FILE_LINTER_NO_STAMPING\"",
",",
"None",
")",
":",
"return",
"True",
"for",
"filename",
"in",
"filenames",
... | 38.888889 | 0.001395 |
def model_type(dtype):
"Return the torch type corresponding to `dtype`."
return (torch.float32 if np.issubdtype(dtype, np.floating) else
torch.int64 if np.issubdtype(dtype, np.integer)
else None) | [
"def",
"model_type",
"(",
"dtype",
")",
":",
"return",
"(",
"torch",
".",
"float32",
"if",
"np",
".",
"issubdtype",
"(",
"dtype",
",",
"np",
".",
"floating",
")",
"else",
"torch",
".",
"int64",
"if",
"np",
".",
"issubdtype",
"(",
"dtype",
",",
"np",
... | 44.6 | 0.004405 |
def curse_add_line(self, msg, decoration="DEFAULT",
optional=False, additional=False,
splittable=False):
"""Return a dict with.
Where:
msg: string
decoration:
DEFAULT: no decoration
UNDERLINE: underlin... | [
"def",
"curse_add_line",
"(",
"self",
",",
"msg",
",",
"decoration",
"=",
"\"DEFAULT\"",
",",
"optional",
"=",
"False",
",",
"additional",
"=",
"False",
",",
"splittable",
"=",
"False",
")",
":",
"return",
"{",
"'msg'",
":",
"msg",
",",
"'decoration'",
"... | 48 | 0.005634 |
def _extract_from_bundle(b, compute, times=None, allow_oversample=False,
by_time=True, **kwargs):
"""
Extract a list of sorted times and the datasets that need to be
computed at each of those times. Any backend can then loop through
these times and see what quantities are neede... | [
"def",
"_extract_from_bundle",
"(",
"b",
",",
"compute",
",",
"times",
"=",
"None",
",",
"allow_oversample",
"=",
"False",
",",
"by_time",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"provided_times",
"=",
"times",
"times",
"=",
"[",
"]",
"infolists"... | 54.441558 | 0.005037 |
def field(self, type, field, default=None):
'''convenient function for returning an arbitrary MAVLink
field with a default'''
if not type in self.messages:
return default
return getattr(self.messages[type], field, default) | [
"def",
"field",
"(",
"self",
",",
"type",
",",
"field",
",",
"default",
"=",
"None",
")",
":",
"if",
"not",
"type",
"in",
"self",
".",
"messages",
":",
"return",
"default",
"return",
"getattr",
"(",
"self",
".",
"messages",
"[",
"type",
"]",
",",
"... | 44 | 0.011152 |
def get_sequence_rule_mdata():
"""Return default mdata map for SequenceRule"""
return {
'next_assessment_part': {
'element_label': {
'text': 'next assessment part',
'languageTypeId': str(DEFAULT_LANGUAGE_TYPE),
'scriptTypeId': str(DEFAULT_SCRIP... | [
"def",
"get_sequence_rule_mdata",
"(",
")",
":",
"return",
"{",
"'next_assessment_part'",
":",
"{",
"'element_label'",
":",
"{",
"'text'",
":",
"'next assessment part'",
",",
"'languageTypeId'",
":",
"str",
"(",
"DEFAULT_LANGUAGE_TYPE",
")",
",",
"'scriptTypeId'",
"... | 36.964286 | 0.000235 |
def kill_all(self):
"""kill all slaves and reap the monitor """
for pid in self.children:
try:
os.kill(pid, signal.SIGTRAP)
except OSError:
continue
self.join() | [
"def",
"kill_all",
"(",
"self",
")",
":",
"for",
"pid",
"in",
"self",
".",
"children",
":",
"try",
":",
"os",
".",
"kill",
"(",
"pid",
",",
"signal",
".",
"SIGTRAP",
")",
"except",
"OSError",
":",
"continue",
"self",
".",
"join",
"(",
")"
] | 29.125 | 0.008333 |
def get_elections(self, obj):
"""All elections in division."""
election_day = ElectionDay.objects.get(
date=self.context['election_date'])
elections = list(obj.elections.filter(election_day=election_day))
district = DivisionLevel.objects.get(name=DivisionLevel.DISTRICT)
... | [
"def",
"get_elections",
"(",
"self",
",",
"obj",
")",
":",
"election_day",
"=",
"ElectionDay",
".",
"objects",
".",
"get",
"(",
"date",
"=",
"self",
".",
"context",
"[",
"'election_date'",
"]",
")",
"elections",
"=",
"list",
"(",
"obj",
".",
"elections",... | 38.75 | 0.00315 |
def unregisterSdc(self, sdcObj):
"""
Unregister SDC from MDM/SIO Cluster
:param sdcObj: ScaleIO SDC object
:return: POST request response
:rtype: Requests POST response object
"""
# TODO:
# Add code that unmap volume if mapped
self.conn.connection.... | [
"def",
"unregisterSdc",
"(",
"self",
",",
"sdcObj",
")",
":",
"# TODO:",
"# Add code that unmap volume if mapped",
"self",
".",
"conn",
".",
"connection",
".",
"_check_login",
"(",
")",
"response",
"=",
"self",
".",
"conn",
".",
"connection",
".",
"_do_post",
... | 41.833333 | 0.007797 |
def ingest(self, **kwargs):
'''
a core method to ingest and validate arbitrary keyword data
**NOTE: data is always returned with this method**
for each key in the model, a value is returned according
to the following priority:
1. value in kwar... | [
"def",
"ingest",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"__name__",
"=",
"'%s.ingest'",
"%",
"self",
".",
"__class__",
".",
"__name__",
"schema_dict",
"=",
"self",
".",
"schema",
"path_to_root",
"=",
"'.'",
"valid_data",
"=",
"self",
".",
"_inge... | 34.864865 | 0.001508 |
async def addNodeTag(self, iden, tag, valu=(None, None)):
'''
Add a tag to a node specified by iden.
Args:
iden (str): A hex encoded node BUID.
tag (str): A tag string.
valu (tuple): A time interval tuple or (None, None).
'''
buid = s_common... | [
"async",
"def",
"addNodeTag",
"(",
"self",
",",
"iden",
",",
"tag",
",",
"valu",
"=",
"(",
"None",
",",
"None",
")",
")",
":",
"buid",
"=",
"s_common",
".",
"uhex",
"(",
"iden",
")",
"parts",
"=",
"tag",
".",
"split",
"(",
"'.'",
")",
"self",
"... | 33.391304 | 0.003797 |
def ajax_subcat_arr(self, pid):
'''
Get the sub category.
ToDo: The menu should display by order. Error fond in DRR.
根据父类ID(pid)获取子类,返回Json格式
'''
out_arr = {}
for catinfo in MCategory.query_sub_cat(pid):
out_arr[catinfo.uid] = catinfo.name
jso... | [
"def",
"ajax_subcat_arr",
"(",
"self",
",",
"pid",
")",
":",
"out_arr",
"=",
"{",
"}",
"for",
"catinfo",
"in",
"MCategory",
".",
"query_sub_cat",
"(",
"pid",
")",
":",
"out_arr",
"[",
"catinfo",
".",
"uid",
"]",
"=",
"catinfo",
".",
"name",
"json",
"... | 30.090909 | 0.005865 |
def register_writer(klass):
"""
Add engine to the excel writer registry.io.excel.
You must use this method to integrate with ``to_excel``.
Parameters
----------
klass : ExcelWriter
"""
if not callable(klass):
raise ValueError("Can only register callables as engines")
engine... | [
"def",
"register_writer",
"(",
"klass",
")",
":",
"if",
"not",
"callable",
"(",
"klass",
")",
":",
"raise",
"ValueError",
"(",
"\"Can only register callables as engines\"",
")",
"engine_name",
"=",
"klass",
".",
"engine",
"_writers",
"[",
"engine_name",
"]",
"="... | 25.785714 | 0.002674 |
def generate_support_dump(self, information, timeout=-1):
"""
Generates a support dump for the logical enclosure with the specified ID. A logical enclosure support dump
includes content for logical interconnects associated with that logical enclosure. By default, it also contains
applian... | [
"def",
"generate_support_dump",
"(",
"self",
",",
"information",
",",
"timeout",
"=",
"-",
"1",
")",
":",
"uri",
"=",
"\"{}/support-dumps\"",
".",
"format",
"(",
"self",
".",
"data",
"[",
"\"uri\"",
"]",
")",
"return",
"self",
".",
"_helper",
".",
"creat... | 49.8125 | 0.006158 |
def AddRow(self, values):
"""Adds a row of values.
Args:
values (list[object]): values.
Raises:
ValueError: if the number of values is out of bounds.
"""
if self._number_of_columns and len(values) != self._number_of_columns:
raise ValueError('Number of values is out of bounds.')
... | [
"def",
"AddRow",
"(",
"self",
",",
"values",
")",
":",
"if",
"self",
".",
"_number_of_columns",
"and",
"len",
"(",
"values",
")",
"!=",
"self",
".",
"_number_of_columns",
":",
"raise",
"ValueError",
"(",
"'Number of values is out of bounds.'",
")",
"self",
"."... | 26 | 0.006961 |
def edit_team(name,
description=None,
privacy=None,
permission=None,
profile="github"):
'''
Updates an existing Github team.
name
The name of the team to be edited.
description
The description of the team.
privacy
The... | [
"def",
"edit_team",
"(",
"name",
",",
"description",
"=",
"None",
",",
"privacy",
"=",
"None",
",",
"permission",
"=",
"None",
",",
"profile",
"=",
"\"github\"",
")",
":",
"team",
"=",
"get_team",
"(",
"name",
",",
"profile",
"=",
"profile",
")",
"if",... | 26.322581 | 0.001181 |
def view_bind(app, cls_url, view_cls: Type['BaseView']):
"""
将 API 绑定到 web 服务上
:param view_cls:
:param app:
:param cls_url:
:return:
"""
if view_cls._no_route: return
cls_url = cls_url or view_cls.__class__.__name__.lower()
def add_route(name, route_info, beacon_info):
f... | [
"def",
"view_bind",
"(",
"app",
",",
"cls_url",
",",
"view_cls",
":",
"Type",
"[",
"'BaseView'",
"]",
")",
":",
"if",
"view_cls",
".",
"_no_route",
":",
"return",
"cls_url",
"=",
"cls_url",
"or",
"view_cls",
".",
"__class__",
".",
"__name__",
".",
"lower... | 38.542857 | 0.004338 |
def _compute_C1_term(C, dists):
"""
Return C1 coeffs as function of Rrup as proposed by
Rodriguez-Marek et al (2013)
The C1 coeff are used to compute the single station sigma
"""
c1_dists = np.zeros_like(dists)
idx = dists < C['Rc11']
c1_dists[idx] = C['phi_11']
idx = (dists >= C['R... | [
"def",
"_compute_C1_term",
"(",
"C",
",",
"dists",
")",
":",
"c1_dists",
"=",
"np",
".",
"zeros_like",
"(",
"dists",
")",
"idx",
"=",
"dists",
"<",
"C",
"[",
"'Rc11'",
"]",
"c1_dists",
"[",
"idx",
"]",
"=",
"C",
"[",
"'phi_11'",
"]",
"idx",
"=",
... | 33.8125 | 0.001799 |
def forward(self, device_port, local_port=None):
"""Forward device port to local
Args:
device_port: port inside device
local_port: port on PC, if this value is None, a port will random pick one.
Returns:
tuple, (host, local_port)
"""
port = se... | [
"def",
"forward",
"(",
"self",
",",
"device_port",
",",
"local_port",
"=",
"None",
")",
":",
"port",
"=",
"self",
".",
"_adb_device",
".",
"forward",
"(",
"device_port",
",",
"local_port",
")",
"return",
"(",
"self",
".",
"_host",
",",
"port",
")"
] | 35.545455 | 0.007481 |
def bind(self, form):
"""Bind to filters form."""
field = self.field(default=self.default, **self.field_kwargs)
form._fields[self.name] = field.bind(form, self.name, prefix=form._prefix) | [
"def",
"bind",
"(",
"self",
",",
"form",
")",
":",
"field",
"=",
"self",
".",
"field",
"(",
"default",
"=",
"self",
".",
"default",
",",
"*",
"*",
"self",
".",
"field_kwargs",
")",
"form",
".",
"_fields",
"[",
"self",
".",
"name",
"]",
"=",
"fiel... | 51.75 | 0.014286 |
def get_agent_queue(self, queue_id, project=None, action_filter=None):
"""GetAgentQueue.
[Preview API] Get information about an agent queue.
:param int queue_id: The agent queue to get information about
:param str project: Project ID or project name
:param str action_filter: Filt... | [
"def",
"get_agent_queue",
"(",
"self",
",",
"queue_id",
",",
"project",
"=",
"None",
",",
"action_filter",
"=",
"None",
")",
":",
"route_values",
"=",
"{",
"}",
"if",
"project",
"is",
"not",
"None",
":",
"route_values",
"[",
"'project'",
"]",
"=",
"self"... | 57.909091 | 0.006178 |
def update_records(self, domain, records):
"""
Modifies an existing records for a domain.
"""
if not isinstance(records, list):
raise TypeError("Expected records of type list")
uri = "/domains/%s/records" % utils.get_id(domain)
resp, resp_body = self._async_ca... | [
"def",
"update_records",
"(",
"self",
",",
"domain",
",",
"records",
")",
":",
"if",
"not",
"isinstance",
"(",
"records",
",",
"list",
")",
":",
"raise",
"TypeError",
"(",
"\"Expected records of type list\"",
")",
"uri",
"=",
"\"/domains/%s/records\"",
"%",
"u... | 43.363636 | 0.00616 |
def format_registryfield_nodes(field_name, field, field_id, state, lineno):
"""Create a section node that documents a RegistryField config field.
Parameters
----------
field_name : `str`
Name of the configuration field (the attribute name of on the config
class).
field : ``lsst.pex.... | [
"def",
"format_registryfield_nodes",
"(",
"field_name",
",",
"field",
",",
"field_id",
",",
"state",
",",
"lineno",
")",
":",
"from",
"lsst",
".",
"pex",
".",
"config",
".",
"registry",
"import",
"ConfigurableWrapper",
"# Create a definition list for the choices",
"... | 39.836957 | 0.000266 |
def stop(self):
"""
Stop the config change monitoring thread.
"""
self.observer_thread.stop()
self.observer_thread.join()
logging.info("Configfile watcher plugin: Stopped") | [
"def",
"stop",
"(",
"self",
")",
":",
"self",
".",
"observer_thread",
".",
"stop",
"(",
")",
"self",
".",
"observer_thread",
".",
"join",
"(",
")",
"logging",
".",
"info",
"(",
"\"Configfile watcher plugin: Stopped\"",
")"
] | 26.75 | 0.00905 |
def gradient_rgb(
self, text=None, fore=None, back=None, style=None,
start=None, stop=None, step=1, linemode=True, movefactor=0):
""" Return a black and white gradient.
Arguments:
text : String to colorize.
fore : Foreground color, ... | [
"def",
"gradient_rgb",
"(",
"self",
",",
"text",
"=",
"None",
",",
"fore",
"=",
"None",
",",
"back",
"=",
"None",
",",
"style",
"=",
"None",
",",
"start",
"=",
"None",
",",
"stop",
"=",
"None",
",",
"step",
"=",
"1",
",",
"linemode",
"=",
"True",... | 33.892857 | 0.001024 |
def report_depths(self, filename, tpm=True, grp_wise=False, reorder='as-is', notes=None):
"""
Exports expected depths
:param filename: File name for output
:param grp_wise: whether the report is at isoform level or gene level
:param reorder: whether the report should be either '... | [
"def",
"report_depths",
"(",
"self",
",",
"filename",
",",
"tpm",
"=",
"True",
",",
"grp_wise",
"=",
"False",
",",
"reorder",
"=",
"'as-is'",
",",
"notes",
"=",
"None",
")",
":",
"if",
"grp_wise",
":",
"lname",
"=",
"self",
".",
"probability",
".",
"... | 43.842105 | 0.003523 |
def generate_properties(self):
"""
Means object with defined keys.
.. code-block:: python
{
'properties': {
'key': {'type': 'number'},
},
}
Valid object is containing key called 'key' and value any number.
... | [
"def",
"generate_properties",
"(",
"self",
")",
":",
"self",
".",
"create_variable_is_dict",
"(",
")",
"with",
"self",
".",
"l",
"(",
"'if {variable}_is_dict:'",
")",
":",
"self",
".",
"create_variable_keys",
"(",
")",
"for",
"key",
",",
"prop_definition",
"in... | 42.068966 | 0.004006 |
def create_item(self, item_form):
"""Creates a new ``Item``.
arg: item_form (osid.assessment.ItemForm): the form for this
``Item``
return: (osid.assessment.Item) - the new ``Item``
raise: IllegalState - ``item_form`` already used in a create
transacti... | [
"def",
"create_item",
"(",
"self",
",",
"item_form",
")",
":",
"# Implemented from template for",
"# osid.resource.ResourceAdminSession.create_resource_template",
"collection",
"=",
"JSONClientValidated",
"(",
"'assessment'",
",",
"collection",
"=",
"'Item'",
",",
"runtime",
... | 47.697674 | 0.003344 |
def train_async(train_dataset,
eval_dataset,
analysis_dir,
output_dir,
features,
model_type,
max_steps=5000,
num_epochs=None,
train_batch_size=100,
eval_batch_size=16,
... | [
"def",
"train_async",
"(",
"train_dataset",
",",
"eval_dataset",
",",
"analysis_dir",
",",
"output_dir",
",",
"features",
",",
"model_type",
",",
"max_steps",
"=",
"5000",
",",
"num_epochs",
"=",
"None",
",",
"train_batch_size",
"=",
"100",
",",
"eval_batch_size... | 41.668966 | 0.002586 |
def internal_evaluate_expression_json(py_db, request, thread_id):
'''
:param EvaluateRequest request:
'''
# : :type arguments: EvaluateArguments
arguments = request.arguments
expression = arguments.expression
frame_id = arguments.frameId
context = arguments.context
fmt = arguments.f... | [
"def",
"internal_evaluate_expression_json",
"(",
"py_db",
",",
"request",
",",
"thread_id",
")",
":",
"# : :type arguments: EvaluateArguments",
"arguments",
"=",
"request",
".",
"arguments",
"expression",
"=",
"arguments",
".",
"expression",
"frame_id",
"=",
"arguments"... | 39.213115 | 0.004486 |
def clouds(opts):
'''
Return the cloud functions
'''
# Let's bring __active_provider_name__, defaulting to None, to all cloud
# drivers. This will get temporarily updated/overridden with a context
# manager when needed.
functions = LazyLoader(
_module_dirs(opts,
... | [
"def",
"clouds",
"(",
"opts",
")",
":",
"# Let's bring __active_provider_name__, defaulting to None, to all cloud",
"# drivers. This will get temporarily updated/overridden with a context",
"# manager when needed.",
"functions",
"=",
"LazyLoader",
"(",
"_module_dirs",
"(",
"opts",
",... | 34.36 | 0.001133 |
def parseFile(self, filename):
"""Parse a single file."""
modname = self.filenameToModname(filename)
module = Module(modname, filename)
self.modules[modname] = module
if self.trackUnusedNames:
module.imported_names, module.unused_names = \
find_imports... | [
"def",
"parseFile",
"(",
"self",
",",
"filename",
")",
":",
"modname",
"=",
"self",
".",
"filenameToModname",
"(",
"filename",
")",
"module",
"=",
"Module",
"(",
"modname",
",",
"filename",
")",
"self",
".",
"modules",
"[",
"modname",
"]",
"=",
"module",... | 44.882353 | 0.002567 |
def parse_response(cls, response, device_id=None, fssapi=None, **kwargs):
"""Parse the server response for this ls command
This will parse xml of the following form::
<ls hash="hash_type">
<file path="file_path" last_modified=last_modified_time ... />
...
... | [
"def",
"parse_response",
"(",
"cls",
",",
"response",
",",
"device_id",
"=",
"None",
",",
"fssapi",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"response",
".",
"tag",
"!=",
"cls",
".",
"command_name",
":",
"raise",
"ResponseParseError",
"(",
... | 42.145161 | 0.00374 |
def create_partitions(self, new_partitions, **kwargs):
"""
Create additional partitions for the given topics.
The future result() value is None.
:param list(NewPartitions) new_partitions: New partitions to be created.
:param float operation_timeout: Set broker's operation timeo... | [
"def",
"create_partitions",
"(",
"self",
",",
"new_partitions",
",",
"*",
"*",
"kwargs",
")",
":",
"f",
",",
"futmap",
"=",
"AdminClient",
".",
"_make_futures",
"(",
"[",
"x",
".",
"topic",
"for",
"x",
"in",
"new_partitions",
"]",
",",
"None",
",",
"Ad... | 48.125 | 0.003819 |
def relaxation(T, p0, obs, times=(1), k=None, ncv=None):
r"""Relaxation experiment.
The relaxation experiment describes the time-evolution
of an expectation value starting in a non-equilibrium
situation.
Parameters
----------
T : (M, M) ndarray or scipy.sparse matrix
Transition mat... | [
"def",
"relaxation",
"(",
"T",
",",
"p0",
",",
"obs",
",",
"times",
"=",
"(",
"1",
")",
",",
"k",
"=",
"None",
",",
"ncv",
"=",
"None",
")",
":",
"# check if square matrix and remember size",
"T",
"=",
"_types",
".",
"ensure_ndarray_or_sparse",
"(",
"T",... | 33.180556 | 0.00122 |
def get_tesseract_version():
"""Try to extract version from tesseract otherwise default min version."""
config = {'libraries': ['tesseract', 'lept']}
try:
p = subprocess.Popen(['tesseract', '-v'], stderr=subprocess.PIPE, stdout=subprocess.PIPE)
stdout_version, version = p.communicate()
... | [
"def",
"get_tesseract_version",
"(",
")",
":",
"config",
"=",
"{",
"'libraries'",
":",
"[",
"'tesseract'",
",",
"'lept'",
"]",
"}",
"try",
":",
"p",
"=",
"subprocess",
".",
"Popen",
"(",
"[",
"'tesseract'",
",",
"'-v'",
"]",
",",
"stderr",
"=",
"subpro... | 49.478261 | 0.00431 |
def load(self, name):
"""[DEPRECATED] Load the polynomial series for `name` and return it."""
s = self.sets.get(name)
if s is None:
self.sets[name] = s = np.load(self.path('jpl-%s.npy' % name))
return s | [
"def",
"load",
"(",
"self",
",",
"name",
")",
":",
"s",
"=",
"self",
".",
"sets",
".",
"get",
"(",
"name",
")",
"if",
"s",
"is",
"None",
":",
"self",
".",
"sets",
"[",
"name",
"]",
"=",
"s",
"=",
"np",
".",
"load",
"(",
"self",
".",
"path",... | 40.166667 | 0.00813 |
def connect_to_ec2(region='us-east-1', access_key=None, secret_key=None):
""" Connect to AWS ec2
:type region: str
:param region: AWS region to connect to
:type access_key: str
:param access_key: AWS access key id
:type secret_key: str
:param secret_key: AWS secret access key
:returns: ... | [
"def",
"connect_to_ec2",
"(",
"region",
"=",
"'us-east-1'",
",",
"access_key",
"=",
"None",
",",
"secret_key",
"=",
"None",
")",
":",
"if",
"access_key",
":",
"# Connect using supplied credentials",
"logger",
".",
"info",
"(",
"'Connecting to AWS EC2 in {}'",
".",
... | 32.459459 | 0.000808 |
def to_unicode_string(string):
"""
Return a Unicode string out of the given string.
On Python 2, it calls ``unicode`` with ``utf-8`` encoding.
On Python 3, it just returns the given string.
Return ``None`` if ``string`` is ``None``.
:param str string: the string to convert to Unicode
... | [
"def",
"to_unicode_string",
"(",
"string",
")",
":",
"if",
"string",
"is",
"None",
":",
"return",
"None",
"if",
"is_unicode_string",
"(",
"string",
")",
":",
"return",
"string",
"# if reached here, string is a byte string ",
"if",
"PY2",
":",
"return",
"unicode",
... | 29.05 | 0.005 |
def check_2d(inp):
"""
Check input to be a matrix. Converts lists of lists to np.ndarray.
Also allows the input to be a scipy sparse matrix.
Parameters
----------
inp : obj
Input matrix
Returns
-------
numpy.ndarray, scipy.sparse or None
Input matrix or None
... | [
"def",
"check_2d",
"(",
"inp",
")",
":",
"if",
"isinstance",
"(",
"inp",
",",
"list",
")",
":",
"return",
"check_2d",
"(",
"np",
".",
"array",
"(",
"inp",
")",
")",
"if",
"isinstance",
"(",
"inp",
",",
"(",
"np",
".",
"ndarray",
",",
"np",
".",
... | 22.030303 | 0.00527 |
def _get_request_token(self):
"""
Obtain a temporary request token to authorize an access token and to
sign the request to obtain the access token
"""
if self.request_token is None:
get_params = {}
if self.parameters:
get_params.update(self... | [
"def",
"_get_request_token",
"(",
"self",
")",
":",
"if",
"self",
".",
"request_token",
"is",
"None",
":",
"get_params",
"=",
"{",
"}",
"if",
"self",
".",
"parameters",
":",
"get_params",
".",
"update",
"(",
"self",
".",
"parameters",
")",
"get_params",
... | 48.791667 | 0.001675 |
def DataRefreshRequired(self, path=None, last=None):
"""True if we need to update this path from the client.
Args:
path: The path relative to the root to check freshness of.
last: An aff4:last attribute to check freshness of.
At least one of path or last must be supplied.
Returns:
... | [
"def",
"DataRefreshRequired",
"(",
"self",
",",
"path",
"=",
"None",
",",
"last",
"=",
"None",
")",
":",
"# If we didn't get given a last attribute, use the path to get one from the",
"# object.",
"if",
"last",
"is",
"None",
":",
"if",
"path",
"is",
"None",
":",
"... | 36.209302 | 0.006254 |
def _add_in_streams(self, bolt):
"""Adds inputs to a given protobuf Bolt message"""
if self.inputs is None:
return
# sanitize inputs and get a map <GlobalStreamId -> Grouping>
input_dict = self._sanitize_inputs()
for global_streamid, gtype in input_dict.items():
in_stream = bolt.inputs.... | [
"def",
"_add_in_streams",
"(",
"self",
",",
"bolt",
")",
":",
"if",
"self",
".",
"inputs",
"is",
"None",
":",
"return",
"# sanitize inputs and get a map <GlobalStreamId -> Grouping>",
"input_dict",
"=",
"self",
".",
"_sanitize_inputs",
"(",
")",
"for",
"global_strea... | 44.454545 | 0.01001 |
def issuperset(self, other):
"""
Report whether this set contains another set.
Example:
>>> OrderedSet([1, 2]).issuperset([1, 2, 3])
False
>>> OrderedSet([1, 2, 3, 4]).issuperset({1, 2, 3})
True
>>> OrderedSet([1, 4, 3, 5]).issuperset(... | [
"def",
"issuperset",
"(",
"self",
",",
"other",
")",
":",
"if",
"len",
"(",
"self",
")",
"<",
"len",
"(",
"other",
")",
":",
"# Fast check for obvious cases",
"return",
"False",
"return",
"all",
"(",
"item",
"in",
"self",
"for",
"item",
"in",
"other",
... | 32.6 | 0.003976 |
async def fetch(self, *args, timeout=None):
r"""Execute the statement and return a list of :class:`Record` objects.
:param str query: Query text
:param args: Query arguments
:param float timeout: Optional timeout value in seconds.
:return: A list of :class:`Record` instances.
... | [
"async",
"def",
"fetch",
"(",
"self",
",",
"*",
"args",
",",
"timeout",
"=",
"None",
")",
":",
"data",
"=",
"await",
"self",
".",
"__bind_execute",
"(",
"args",
",",
"0",
",",
"timeout",
")",
"return",
"data"
] | 36.272727 | 0.00489 |
def bind(self, key, **prefs):
"""
Bind a subkey to this key.
Valid optional keyword arguments are identical to those of self-signatures for :py:meth:`PGPkey.certify`
"""
hash_algo = prefs.pop('hash', None)
if self.is_primary and not key.is_primary:
sig_type ... | [
"def",
"bind",
"(",
"self",
",",
"key",
",",
"*",
"*",
"prefs",
")",
":",
"hash_algo",
"=",
"prefs",
".",
"pop",
"(",
"'hash'",
",",
"None",
")",
"if",
"self",
".",
"is_primary",
"and",
"not",
"key",
".",
"is_primary",
":",
"sig_type",
"=",
"Signat... | 36.317073 | 0.005232 |
def expand_groups(grp):
"""Expand group names.
Args:
grp (string): group names to expand
Returns:
list of groups
Examples:
* grp[1-3] will be expanded to [grp1, grp2, grp3]
* grp1 will be expanded to [grp1]
"""
p = re.compile(r"(?P<name>.+)\[(?P<start>\d+)-(?P... | [
"def",
"expand_groups",
"(",
"grp",
")",
":",
"p",
"=",
"re",
".",
"compile",
"(",
"r\"(?P<name>.+)\\[(?P<start>\\d+)-(?P<end>\\d+)\\]\"",
")",
"m",
"=",
"p",
".",
"match",
"(",
"grp",
")",
"if",
"m",
"is",
"not",
"None",
":",
"s",
"=",
"int",
"(",
"m"... | 23.608696 | 0.00177 |
async def iterUnivRows(self, prop):
'''
Iterate (buid, valu) rows for the given universal prop
'''
penc = prop.encode()
pref = penc + b'\x00'
for _, pval in self.layrslab.scanByPref(pref, db=self.byuniv):
buid = s_msgpack.un(pval)[0]
byts = self.... | [
"async",
"def",
"iterUnivRows",
"(",
"self",
",",
"prop",
")",
":",
"penc",
"=",
"prop",
".",
"encode",
"(",
")",
"pref",
"=",
"penc",
"+",
"b'\\x00'",
"for",
"_",
",",
"pval",
"in",
"self",
".",
"layrslab",
".",
"scanByPref",
"(",
"pref",
",",
"db... | 27.882353 | 0.004082 |
def check_variable_features(self, ds):
'''
Checks the variable feature types match the dataset featureType attribute
:param netCDF4.Dataset ds: An open netCDF dataset
:rtype: list
:return: List of results
'''
ret_val = []
feature_list = ['point', 'timeSer... | [
"def",
"check_variable_features",
"(",
"self",
",",
"ds",
")",
":",
"ret_val",
"=",
"[",
"]",
"feature_list",
"=",
"[",
"'point'",
",",
"'timeSeries'",
",",
"'trajectory'",
",",
"'profile'",
",",
"'timeSeriesProfile'",
",",
"'trajectoryProfile'",
"]",
"# Don't b... | 38.655172 | 0.003045 |
def rules(ctx):
""" [bookie] List all rules
"""
rules = Rules(peerplays_instance=ctx.peerplays)
click.echo(pretty_print(rules, ctx=ctx)) | [
"def",
"rules",
"(",
"ctx",
")",
":",
"rules",
"=",
"Rules",
"(",
"peerplays_instance",
"=",
"ctx",
".",
"peerplays",
")",
"click",
".",
"echo",
"(",
"pretty_print",
"(",
"rules",
",",
"ctx",
"=",
"ctx",
")",
")"
] | 29.6 | 0.006579 |
def main():
"""Generate a badge based on command line arguments."""
# Parse command line arguments
args = parse_args()
label = args.label
threshold_text = args.args
suffix = args.suffix
# Check whether thresholds were sent as one word, and is in the
# list of templates. If so, swap in... | [
"def",
"main",
"(",
")",
":",
"# Parse command line arguments",
"args",
"=",
"parse_args",
"(",
")",
"label",
"=",
"args",
".",
"label",
"threshold_text",
"=",
"args",
".",
"args",
"suffix",
"=",
"args",
".",
"suffix",
"# Check whether thresholds were sent as one ... | 39.692308 | 0.003153 |
def fdr(pvals, alpha=0.05, method='fdr_bh'):
"""P-values FDR correction with Benjamini/Hochberg and
Benjamini/Yekutieli procedure.
This covers Benjamini/Hochberg for independent or positively correlated and
Benjamini/Yekutieli for general or negatively correlated tests.
Parameters
----------
... | [
"def",
"fdr",
"(",
"pvals",
",",
"alpha",
"=",
"0.05",
",",
"method",
"=",
"'fdr_bh'",
")",
":",
"assert",
"method",
".",
"lower",
"(",
")",
"in",
"[",
"'fdr_bh'",
",",
"'fdr_by'",
"]",
"# Convert to array and save original shape",
"pvals",
"=",
"np",
".",... | 33.770642 | 0.000264 |
def search(self, title=None, sort=None, maxresults=999999, libtype=None, **kwargs):
""" Search the library. If there are many results, they will be fetched from the server
in batches of X_PLEX_CONTAINER_SIZE amounts. If you're only looking for the first <num>
results, it would be wise to... | [
"def",
"search",
"(",
"self",
",",
"title",
"=",
"None",
",",
"sort",
"=",
"None",
",",
"maxresults",
"=",
"999999",
",",
"libtype",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"# cleanup the core arguments",
"args",
"=",
"{",
"}",
"for",
"category... | 66.925926 | 0.007636 |
def get_field_to_observations_map(generator, query_for_tag=''):
"""Return a field to `Observations` dict for the event generator.
Args:
generator: A generator over event protos.
query_for_tag: A string that if specified, only create observations for
events with this tag name.
Returns:
A dict m... | [
"def",
"get_field_to_observations_map",
"(",
"generator",
",",
"query_for_tag",
"=",
"''",
")",
":",
"def",
"increment",
"(",
"stat",
",",
"event",
",",
"tag",
"=",
"''",
")",
":",
"assert",
"stat",
"in",
"TRACKED_FIELDS",
"field_to_obs",
"[",
"stat",
"]",
... | 37.536585 | 0.0095 |
def unesc(line, language):
"""Uncomment once a commented line"""
comment = _COMMENT[language]
if line.startswith(comment + ' '):
return line[len(comment) + 1:]
if line.startswith(comment):
return line[len(comment):]
return line | [
"def",
"unesc",
"(",
"line",
",",
"language",
")",
":",
"comment",
"=",
"_COMMENT",
"[",
"language",
"]",
"if",
"line",
".",
"startswith",
"(",
"comment",
"+",
"' '",
")",
":",
"return",
"line",
"[",
"len",
"(",
"comment",
")",
"+",
"1",
":",
"]",
... | 32 | 0.003802 |
def get_radius_ranges(self, radius, mic=False):
"""Return ranges of indexes of the interacting neighboring unit cells
Interacting neighboring unit cells have at least one point in their
box volume that has a distance smaller or equal than radius to at
least one point in the cen... | [
"def",
"get_radius_ranges",
"(",
"self",
",",
"radius",
",",
"mic",
"=",
"False",
")",
":",
"result",
"=",
"np",
".",
"zeros",
"(",
"3",
",",
"int",
")",
"for",
"i",
"in",
"range",
"(",
"3",
")",
":",
"if",
"self",
".",
"spacings",
"[",
"i",
"]... | 49.142857 | 0.002852 |
def get_surname_initial_author_pattern(incl_numeration=False):
"""Match an author name of the form: 'surname initial(s)'
This is sometimes the represention of the first author found inside an author group.
This author pattern is only used to find a maximum of ONE author inside an author group.
Authors ... | [
"def",
"get_surname_initial_author_pattern",
"(",
"incl_numeration",
"=",
"False",
")",
":",
"# Possible inclusion of superscript numeration at the end of author names",
"# Will match the empty string",
"if",
"incl_numeration",
":",
"append_num_re",
"=",
"get_author_affiliation_numerat... | 54.25 | 0.011316 |
def vehicles(self, vid=None, rt=None):
"""
Get busses by route or by vehicle ID.
Arguments: either
`vid`: "Set of one or more vehicle IDs whose location should be returned."
Maximum of 10 `vid`s, either in a comma-separated list or an iterable.
... | [
"def",
"vehicles",
"(",
"self",
",",
"vid",
"=",
"None",
",",
"rt",
"=",
"None",
")",
":",
"if",
"vid",
"and",
"rt",
":",
"raise",
"ValueError",
"(",
"\"The `vid` and `route` parameters cannot be specified simultaneously.\"",
")",
"if",
"not",
"(",
"vid",
"or"... | 45.9 | 0.010667 |
def leave(group_id):
"""Leave group."""
group = Group.query.get_or_404(group_id)
if group.can_leave(current_user):
try:
group.remove_member(current_user)
except Exception as e:
flash(str(e), "error")
return redirect(url_for('.index'))
flash(
... | [
"def",
"leave",
"(",
"group_id",
")",
":",
"group",
"=",
"Group",
".",
"query",
".",
"get_or_404",
"(",
"group_id",
")",
"if",
"group",
".",
"can_leave",
"(",
"current_user",
")",
":",
"try",
":",
"group",
".",
"remove_member",
"(",
"current_user",
")",
... | 24.464286 | 0.001404 |
def _select_concept(self, line):
"""try to match a class and load it"""
g = self.current['graph']
if not line:
out = g.all_skos_concepts
using_pattern = False
else:
using_pattern = True
if line.isdigit():
line = int(line)
... | [
"def",
"_select_concept",
"(",
"self",
",",
"line",
")",
":",
"g",
"=",
"self",
".",
"current",
"[",
"'graph'",
"]",
"if",
"not",
"line",
":",
"out",
"=",
"g",
".",
"all_skos_concepts",
"using_pattern",
"=",
"False",
"else",
":",
"using_pattern",
"=",
... | 37.538462 | 0.002997 |
def two_motor_drivetrain(l_motor, r_motor, x_wheelbase=2, speed=5, deadzone=None):
"""
.. deprecated:: 2018.2.0
Use :class:`TwoMotorDrivetrain` instead
"""
return TwoMotorDrivetrain(x_wheelbase, speed, deadzone).get_vector(l_motor, r_motor) | [
"def",
"two_motor_drivetrain",
"(",
"l_motor",
",",
"r_motor",
",",
"x_wheelbase",
"=",
"2",
",",
"speed",
"=",
"5",
",",
"deadzone",
"=",
"None",
")",
":",
"return",
"TwoMotorDrivetrain",
"(",
"x_wheelbase",
",",
"speed",
",",
"deadzone",
")",
".",
"get_v... | 44.333333 | 0.01107 |
def create_thread(daemon, callback, *callbackParams):
"""创建一个线程
:param daemon: True表示线程随着主线程关闭而关闭,False表示主线程必须等待子线程结束
:param callback: 线程的回调函数
:param callbackParams: 回调函数的形式参数
:return: 一个线程类,初始状态为未启动,已经创建
"""
task = Thread(target=callback, args=callbackParams)
task.setDaemon(daemon)
... | [
"def",
"create_thread",
"(",
"daemon",
",",
"callback",
",",
"*",
"callbackParams",
")",
":",
"task",
"=",
"Thread",
"(",
"target",
"=",
"callback",
",",
"args",
"=",
"callbackParams",
")",
"task",
".",
"setDaemon",
"(",
"daemon",
")",
"return",
"task"
] | 32.2 | 0.003021 |
def to_api_data(self):
""" Returns a dict to communicate with the server
:rtype: dict
"""
data = {'@odata.type': self._gk(
'{}_attachment_type'.format(self.attachment_type)),
self._cc('name'): self.name}
if self.attachment_type == 'file':
dat... | [
"def",
"to_api_data",
"(",
"self",
")",
":",
"data",
"=",
"{",
"'@odata.type'",
":",
"self",
".",
"_gk",
"(",
"'{}_attachment_type'",
".",
"format",
"(",
"self",
".",
"attachment_type",
")",
")",
",",
"self",
".",
"_cc",
"(",
"'name'",
")",
":",
"self"... | 28.866667 | 0.004474 |
def _get_build_env(env):
'''
Get build environment overrides dictionary to use in build process
'''
env_override = ''
if env is None:
return env_override
if not isinstance(env, dict):
raise SaltInvocationError(
'\'env\' must be a Python dictionary'
)
for k... | [
"def",
"_get_build_env",
"(",
"env",
")",
":",
"env_override",
"=",
"''",
"if",
"env",
"is",
"None",
":",
"return",
"env_override",
"if",
"not",
"isinstance",
"(",
"env",
",",
"dict",
")",
":",
"raise",
"SaltInvocationError",
"(",
"'\\'env\\' must be a Python ... | 30.733333 | 0.002105 |
def format_reference(ref, max_string_length=1000):
"""
Converts an object / value into a string representation to pass along in the payload
:param ref: object or value
:param max_string_length: maximum number of characters to represent the object
:return:
"""
_pass = lambda *args: None
_... | [
"def",
"format_reference",
"(",
"ref",
",",
"max_string_length",
"=",
"1000",
")",
":",
"_pass",
"=",
"lambda",
"*",
"args",
":",
"None",
"_numpy_info",
"=",
"(",
"'dtype'",
",",
"'shape'",
",",
"'size'",
",",
"'min'",
",",
"'max'",
")",
"additionals",
"... | 35.756757 | 0.002943 |
def get_bottom_up_likelihood(tree, character, frequencies, sf, kappa=None, is_marginal=True, model=F81):
"""
Calculates the bottom-up likelihood for the given tree.
The likelihood for each node is stored in the corresponding feature,
given by get_personalised_feature_name(feature, BU_LH).
:param mo... | [
"def",
"get_bottom_up_likelihood",
"(",
"tree",
",",
"character",
",",
"frequencies",
",",
"sf",
",",
"kappa",
"=",
"None",
",",
"is_marginal",
"=",
"True",
",",
"model",
"=",
"F81",
")",
":",
"lh_sf_feature",
"=",
"get_personalized_feature_name",
"(",
"charac... | 48.960784 | 0.004711 |
def p_iteration_statement_3(self, p):
"""
iteration_statement \
: FOR LPAREN expr_noin_opt SEMI expr_opt SEMI expr_opt RPAREN \
statement
| FOR LPAREN VAR variable_declaration_list_noin SEMI expr_opt SEMI\
expr_opt RPAREN statement
"""
... | [
"def",
"p_iteration_statement_3",
"(",
"self",
",",
"p",
")",
":",
"def",
"wrap",
"(",
"node",
",",
"key",
")",
":",
"if",
"node",
"is",
"None",
":",
"# work around bug with yacc tracking of empty elements",
"# by using the previous token, and increment the",
"# positio... | 37.78125 | 0.001613 |
def edit_record(self, new_record):
"""
Update a record in ArchivesSpace using the provided new_record.
The format of new_record is identical to the format returned by get_resource_component_and_children and related methods; consult the documentation for that method in ArchivistsToolkitClient to... | [
"def",
"edit_record",
"(",
"self",
",",
"new_record",
")",
":",
"try",
":",
"record_id",
"=",
"new_record",
"[",
"\"id\"",
"]",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"No record ID provided!\"",
")",
"record",
"=",
"self",
".",
"get_record",
... | 35.651515 | 0.002068 |
def reinitialize_command(self, command, reinit_subcommands):
"""
Monkeypatch distutils.Distribution.reinitialize_command() to match behavior
of Distribution.get_command_obj()
This fixes a problem where 'pip install -e' does not reinitialise options
using the setup(options={...}) variable for the bui... | [
"def",
"reinitialize_command",
"(",
"self",
",",
"command",
",",
"reinit_subcommands",
")",
":",
"cmd_obj",
"=",
"_DISTUTILS_REINIT",
"(",
"self",
",",
"command",
",",
"reinit_subcommands",
")",
"options",
"=",
"self",
".",
"command_options",
".",
"get",
"(",
... | 37.125 | 0.001642 |
def loc_info(text, index):
'''Location of `index` in source code `text`.'''
if index > len(text):
raise ValueError('Invalid index.')
line, last_ln = text.count('\n', 0, index), text.rfind('\n', 0, index)
col = index - (last_ln + 1)
return (line, col) | [
"def",
"loc_info",
"(",
"text",
",",
"index",
")",
":",
"if",
"index",
">",
"len",
"(",
"text",
")",
":",
"raise",
"ValueError",
"(",
"'Invalid index.'",
")",
"line",
",",
"last_ln",
"=",
"text",
".",
"count",
"(",
"'\\n'",
",",
"0",
",",
"index",
... | 42.285714 | 0.006623 |
def parse(cls, value, default=_no_default):
"""Parses a flag integer or string into a Flags instance.
Accepts the following types:
- Members of this enum class. These are returned directly.
- Integers. These are converted directly into a Flags instance with the given name.
- Str... | [
"def",
"parse",
"(",
"cls",
",",
"value",
",",
"default",
"=",
"_no_default",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"cls",
")",
":",
"return",
"value",
"elif",
"isinstance",
"(",
"value",
",",
"int",
")",
":",
"e",
"=",
"cls",
".",
"_mak... | 35 | 0.002471 |
def train(input_dir, batch_size, max_steps, output_dir, checkpoint=None, cloud=None):
"""Blocking version of train_async(). The only difference is that it blocks the caller
until the job finishes, and it does not have a return value.
"""
with warnings.catch_warnings():
warnings.simplefilter("ignore")
... | [
"def",
"train",
"(",
"input_dir",
",",
"batch_size",
",",
"max_steps",
",",
"output_dir",
",",
"checkpoint",
"=",
"None",
",",
"cloud",
"=",
"None",
")",
":",
"with",
"warnings",
".",
"catch_warnings",
"(",
")",
":",
"warnings",
".",
"simplefilter",
"(",
... | 47.888889 | 0.013667 |
def in6_get_common_plen(a, b):
"""
Return common prefix length of IPv6 addresses a and b.
"""
def matching_bits(byte1, byte2):
for i in range(8):
cur_mask = 0x80 >> i
if (byte1 & cur_mask) != (byte2 & cur_mask):
return i
return 8
tmpA = inet_p... | [
"def",
"in6_get_common_plen",
"(",
"a",
",",
"b",
")",
":",
"def",
"matching_bits",
"(",
"byte1",
",",
"byte2",
")",
":",
"for",
"i",
"in",
"range",
"(",
"8",
")",
":",
"cur_mask",
"=",
"0x80",
">>",
"i",
"if",
"(",
"byte1",
"&",
"cur_mask",
")",
... | 28.888889 | 0.001862 |
def read_namespaced_pod_log(self, name, namespace, **kwargs): # noqa: E501
"""read_namespaced_pod_log # noqa: E501
read log of the specified Pod # noqa: E501
This method makes a synchronous HTTP request by default. To make an
asynchronous HTTP request, please pass async_req=True
... | [
"def",
"read_namespaced_pod_log",
"(",
"self",
",",
"name",
",",
"namespace",
",",
"*",
"*",
"kwargs",
")",
":",
"# noqa: E501",
"kwargs",
"[",
"'_return_http_data_only'",
"]",
"=",
"True",
"if",
"kwargs",
".",
"get",
"(",
"'async_req'",
")",
":",
"return",
... | 77.933333 | 0.000845 |
def recode_sam_reads(
sam_fn,
fastq_rnf_fo,
fai_fo,
genome_id,
number_of_read_tuples=10**9,
simulator_name=None,
allow_unmapped=False,
):
"""Transform a SAM file to RNF-compatible FASTQ.
Args:
sam_fn (str): SAM/BAM file - file name.
fastq_rnf_... | [
"def",
"recode_sam_reads",
"(",
"sam_fn",
",",
"fastq_rnf_fo",
",",
"fai_fo",
",",
"genome_id",
",",
"number_of_read_tuples",
"=",
"10",
"**",
"9",
",",
"simulator_name",
"=",
"None",
",",
"allow_unmapped",
"=",
"False",
",",
")",
":",
"fai_index",
"=",
"rnf... | 36.057143 | 0.00617 |
def exchange_currency(
base: T, to_currency: str, *, conversion_rate: Decimal=None) -> T:
"""
Exchanges Money, TaxedMoney and their ranges to the specified currency.
get_rate parameter is a callable taking single argument (target currency)
that returns proper conversion rate
"""
if base.... | [
"def",
"exchange_currency",
"(",
"base",
":",
"T",
",",
"to_currency",
":",
"str",
",",
"*",
",",
"conversion_rate",
":",
"Decimal",
"=",
"None",
")",
"->",
"T",
":",
"if",
"base",
".",
"currency",
"==",
"to_currency",
":",
"return",
"base",
"if",
"bas... | 43.282051 | 0.001738 |
def distance_correlation_sqr(x, y, **kwargs):
"""
distance_correlation_sqr(x, y, *, exponent=1)
Computes the usual (biased) estimator for the squared distance correlation
between two random vectors.
Parameters
----------
x: array_like
First random vector. The columns correspond wit... | [
"def",
"distance_correlation_sqr",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"_can_use_fast_algorithm",
"(",
"x",
",",
"y",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"_distance_correlation_sqr_fast",
"(",
"x",
",",
"y",
")",
"else",... | 31.258621 | 0.000535 |
def make_session(config=None, num_cpu=None, make_default=False, graph=None):
"""Returns a session that will use <num_cpu> CPU's only"""
if num_cpu is None:
num_cpu = int(os.getenv('RCALL_NUM_CPU', multiprocessing.cpu_count()))
if config is None:
config = tf.ConfigProto(
allow_sof... | [
"def",
"make_session",
"(",
"config",
"=",
"None",
",",
"num_cpu",
"=",
"None",
",",
"make_default",
"=",
"False",
",",
"graph",
"=",
"None",
")",
":",
"if",
"num_cpu",
"is",
"None",
":",
"num_cpu",
"=",
"int",
"(",
"os",
".",
"getenv",
"(",
"'RCALL_... | 41.4 | 0.001575 |
def list_tags(self):
"""
Get the tags of current object
:return: the tags
:rtype: list
"""
from highton.models.tag import Tag
return fields.ListField(
name=self.ENDPOINT,
init_class=Tag
).decode(
self.element_from_strin... | [
"def",
"list_tags",
"(",
"self",
")",
":",
"from",
"highton",
".",
"models",
".",
"tag",
"import",
"Tag",
"return",
"fields",
".",
"ListField",
"(",
"name",
"=",
"self",
".",
"ENDPOINT",
",",
"init_class",
"=",
"Tag",
")",
".",
"decode",
"(",
"self",
... | 26.277778 | 0.006122 |
def get_if(iff, cmd):
"""Ease SIOCGIF* ioctl calls"""
sck = socket.socket()
ifreq = ioctl(sck, cmd, struct.pack("16s16x", iff.encode("utf8")))
sck.close()
return ifreq | [
"def",
"get_if",
"(",
"iff",
",",
"cmd",
")",
":",
"sck",
"=",
"socket",
".",
"socket",
"(",
")",
"ifreq",
"=",
"ioctl",
"(",
"sck",
",",
"cmd",
",",
"struct",
".",
"pack",
"(",
"\"16s16x\"",
",",
"iff",
".",
"encode",
"(",
"\"utf8\"",
")",
")",
... | 26 | 0.005319 |
def minimize_dogleg(obj, free_variables, on_step=None,
maxiter=200, max_fevals=np.inf, sparse_solver='spsolve',
disp=True, e_1=1e-15, e_2=1e-15, e_3=0., delta_0=None,
treat_as_dense=False):
""""Nonlinear optimization using Powell's dogleg method.
Se... | [
"def",
"minimize_dogleg",
"(",
"obj",
",",
"free_variables",
",",
"on_step",
"=",
"None",
",",
"maxiter",
"=",
"200",
",",
"max_fevals",
"=",
"np",
".",
"inf",
",",
"sparse_solver",
"=",
"'spsolve'",
",",
"disp",
"=",
"True",
",",
"e_1",
"=",
"1e-15",
... | 48.571429 | 0.006177 |
def attach_to_tree(self):
'''
attaches the the merger cost to each branch length interpolator in the tree.
'''
for clade in self.tree.find_clades():
if clade.up is not None:
clade.branch_length_interpolator.merger_cost = self.cost | [
"def",
"attach_to_tree",
"(",
"self",
")",
":",
"for",
"clade",
"in",
"self",
".",
"tree",
".",
"find_clades",
"(",
")",
":",
"if",
"clade",
".",
"up",
"is",
"not",
"None",
":",
"clade",
".",
"branch_length_interpolator",
".",
"merger_cost",
"=",
"self",... | 40.571429 | 0.010345 |
def update_subnet(self, subnet, name=None):
'''
Updates a subnet
'''
subnet_id = self._find_subnet_id(subnet)
return self.network_conn.update_subnet(
subnet=subnet_id, body={'subnet': {'name': name}}) | [
"def",
"update_subnet",
"(",
"self",
",",
"subnet",
",",
"name",
"=",
"None",
")",
":",
"subnet_id",
"=",
"self",
".",
"_find_subnet_id",
"(",
"subnet",
")",
"return",
"self",
".",
"network_conn",
".",
"update_subnet",
"(",
"subnet",
"=",
"subnet_id",
",",... | 35.142857 | 0.007937 |
async def get_schemes(self) -> List[Scheme]:
"""Return supported uri schemes."""
return [
Scheme.make(**x)
for x in await self.services["avContent"]["getSchemeList"]()
] | [
"async",
"def",
"get_schemes",
"(",
"self",
")",
"->",
"List",
"[",
"Scheme",
"]",
":",
"return",
"[",
"Scheme",
".",
"make",
"(",
"*",
"*",
"x",
")",
"for",
"x",
"in",
"await",
"self",
".",
"services",
"[",
"\"avContent\"",
"]",
"[",
"\"getSchemeLis... | 35.333333 | 0.009217 |
def add_minute(self, minute):
"""Create a new DateTime after the minutes are added.
Args:
minute: An integer value for minutes.
"""
_moy = self.moy + int(minute)
return self.__class__.from_moy(_moy) | [
"def",
"add_minute",
"(",
"self",
",",
"minute",
")",
":",
"_moy",
"=",
"self",
".",
"moy",
"+",
"int",
"(",
"minute",
")",
"return",
"self",
".",
"__class__",
".",
"from_moy",
"(",
"_moy",
")"
] | 30.5 | 0.007968 |
def update(self, data):
""" Set given keys to their respective values
@data: #dict or :class:RedisMap of |{key: value}| entries to set
"""
if not data:
return
_rk, _dumps = self.get_key, self._dumps
data = self._client.mset({
_rk(key): _dumps(v... | [
"def",
"update",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"data",
":",
"return",
"_rk",
",",
"_dumps",
"=",
"self",
".",
"get_key",
",",
"self",
".",
"_dumps",
"data",
"=",
"self",
".",
"_client",
".",
"mset",
"(",
"{",
"_rk",
"(",
"key",... | 36.1 | 0.005405 |
def regex_find(pattern, content):
"""Find the given 'pattern' in 'content'"""
find = re.findall(pattern, content)
if not find:
cij.err("pattern <%r> is invalid, no matches!" % pattern)
cij.err("content: %r" % content)
return ''
if len(find) >= 2:
cij.err("pattern <%r> i... | [
"def",
"regex_find",
"(",
"pattern",
",",
"content",
")",
":",
"find",
"=",
"re",
".",
"findall",
"(",
"pattern",
",",
"content",
")",
"if",
"not",
"find",
":",
"cij",
".",
"err",
"(",
"\"pattern <%r> is invalid, no matches!\"",
"%",
"pattern",
")",
"cij",... | 28.733333 | 0.002247 |
def format_value(self, value, isToAlign=False, format_target="html"):
"""
Format a value nicely for human-readable output (including rounding).
@param value: the value to format
@param isToAlign: if True, spaces will be added to the returned String representation to align it to all
... | [
"def",
"format_value",
"(",
"self",
",",
"value",
",",
"isToAlign",
"=",
"False",
",",
"format_target",
"=",
"\"html\"",
")",
":",
"# Only format counts and measures",
"if",
"self",
".",
"type",
".",
"type",
"!=",
"ColumnType",
".",
"count",
"and",
"self",
"... | 43.087719 | 0.002787 |
def total_flux(F, A=None):
r"""Compute the total flux, or turnover flux, that is produced by
the flux sources and consumed by the flux sinks.
Parameters
----------
F : (M, M) ndarray
Matrix of flux values between pairs of states.
A : array_like (optional)
List of integer sta... | [
"def",
"total_flux",
"(",
"F",
",",
"A",
"=",
"None",
")",
":",
"if",
"issparse",
"(",
"F",
")",
":",
"return",
"sparse",
".",
"tpt",
".",
"total_flux",
"(",
"F",
",",
"A",
"=",
"A",
")",
"elif",
"isdense",
"(",
"F",
")",
":",
"return",
"dense"... | 28.633333 | 0.001126 |
def compute_displays_sweep(
self,
program: Union[circuits.Circuit, schedules.Schedule],
params: Optional[study.Sweepable] = None,
qubit_order: ops.QubitOrderOrList = ops.QubitOrder.DEFAULT,
initial_state: Union[int, np.ndarray] = 0,
) -> List[study.ComputeDisplaysResult]:
... | [
"def",
"compute_displays_sweep",
"(",
"self",
",",
"program",
":",
"Union",
"[",
"circuits",
".",
"Circuit",
",",
"schedules",
".",
"Schedule",
"]",
",",
"params",
":",
"Optional",
"[",
"study",
".",
"Sweepable",
"]",
"=",
"None",
",",
"qubit_order",
":",
... | 46.686567 | 0.001565 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.