text stringlengths 89 104k | code_tokens list | avg_line_len float64 7.91 980 | score float64 0 630 |
|---|---|---|---|
def add_record(self, record):
"""Add a record to the community.
:param record: Record object.
:type record: `invenio_records.api.Record`
"""
key = current_app.config['COMMUNITIES_RECORD_KEY']
record.setdefault(key, [])
if self.has_record(record):
current_app.logger.warning(
'Community addition: record {uuid} is already in community '
'"{comm}"'.format(uuid=record.id, comm=self.id))
else:
record[key].append(self.id)
record[key] = sorted(record[key])
if current_app.config['COMMUNITIES_OAI_ENABLED']:
if not self.oaiset.has_record(record):
self.oaiset.add_record(record) | [
"def",
"add_record",
"(",
"self",
",",
"record",
")",
":",
"key",
"=",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_RECORD_KEY'",
"]",
"record",
".",
"setdefault",
"(",
"key",
",",
"[",
"]",
")",
"if",
"self",
".",
"has_record",
"(",
"record",
")",
":",
"current_app",
".",
"logger",
".",
"warning",
"(",
"'Community addition: record {uuid} is already in community '",
"'\"{comm}\"'",
".",
"format",
"(",
"uuid",
"=",
"record",
".",
"id",
",",
"comm",
"=",
"self",
".",
"id",
")",
")",
"else",
":",
"record",
"[",
"key",
"]",
".",
"append",
"(",
"self",
".",
"id",
")",
"record",
"[",
"key",
"]",
"=",
"sorted",
"(",
"record",
"[",
"key",
"]",
")",
"if",
"current_app",
".",
"config",
"[",
"'COMMUNITIES_OAI_ENABLED'",
"]",
":",
"if",
"not",
"self",
".",
"oaiset",
".",
"has_record",
"(",
"record",
")",
":",
"self",
".",
"oaiset",
".",
"add_record",
"(",
"record",
")"
] | 38.105263 | 13.684211 |
def issue_command(self, cmd, *args):
""" Sends and receives a message to/from the server """
self._writeline(cmd)
self._writeline(str(len(args)))
for arg in args:
arg = str(arg)
self._writeline(str(len(arg)))
self._sock.sendall(arg.encode("utf-8"))
return self._read_response() | [
"def",
"issue_command",
"(",
"self",
",",
"cmd",
",",
"*",
"args",
")",
":",
"self",
".",
"_writeline",
"(",
"cmd",
")",
"self",
".",
"_writeline",
"(",
"str",
"(",
"len",
"(",
"args",
")",
")",
")",
"for",
"arg",
"in",
"args",
":",
"arg",
"=",
"str",
"(",
"arg",
")",
"self",
".",
"_writeline",
"(",
"str",
"(",
"len",
"(",
"arg",
")",
")",
")",
"self",
".",
"_sock",
".",
"sendall",
"(",
"arg",
".",
"encode",
"(",
"\"utf-8\"",
")",
")",
"return",
"self",
".",
"_read_response",
"(",
")"
] | 30.7 | 12.2 |
def analytics_query(self, query, host, *args, **kwargs):
"""
Execute an Analytics query.
This method is mainly a wrapper around the :class:`~.AnalyticsQuery`
and :class:`~.AnalyticsRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.AnalyticsQuery`::
query = AnalyticsQuery(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing")
for row in cb.analytics_query(query, "127.0.0.1"):
print('Entry: {0}'.format(row))
Using an implicit :class:`~.AnalyticsQuery`::
for row in cb.analytics_query(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"):
print('Entry: {0}'.format(row))
:param query: The query to execute. This may either be a
:class:`.AnalyticsQuery` object, or a string (which will be
implicitly converted to one).
:param host: The host to send the request to.
:param args: Positional arguments for :class:`.AnalyticsQuery`.
:param kwargs: Named arguments for :class:`.AnalyticsQuery`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result
"""
if not isinstance(query, AnalyticsQuery):
query = AnalyticsQuery(query, *args, **kwargs)
else:
query.update(*args, **kwargs)
return couchbase.analytics.gen_request(query, host, self) | [
"def",
"analytics_query",
"(",
"self",
",",
"query",
",",
"host",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"query",
",",
"AnalyticsQuery",
")",
":",
"query",
"=",
"AnalyticsQuery",
"(",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"query",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"couchbase",
".",
"analytics",
".",
"gen_request",
"(",
"query",
",",
"host",
",",
"self",
")"
] | 42.388889 | 22 |
def clear_secure_boot_keys(self):
"""Reset all keys.
:raises: IloError, on an error from iLO.
:raises: IloCommandNotSupportedError, if the command is not supported
on the server.
"""
if self._is_boot_mode_uefi():
self._change_secure_boot_settings('ResetAllKeys', True)
else:
msg = ('System is not in UEFI boot mode. "SecureBoot" related '
'resources cannot be changed.')
raise exception.IloCommandNotSupportedInBiosError(msg) | [
"def",
"clear_secure_boot_keys",
"(",
"self",
")",
":",
"if",
"self",
".",
"_is_boot_mode_uefi",
"(",
")",
":",
"self",
".",
"_change_secure_boot_settings",
"(",
"'ResetAllKeys'",
",",
"True",
")",
"else",
":",
"msg",
"=",
"(",
"'System is not in UEFI boot mode. \"SecureBoot\" related '",
"'resources cannot be changed.'",
")",
"raise",
"exception",
".",
"IloCommandNotSupportedInBiosError",
"(",
"msg",
")"
] | 41.076923 | 17.615385 |
def compute_stats(self, incremental=False):
"""
Invoke Impala COMPUTE STATS command to compute column, table, and
partition statistics.
See also ImpalaClient.compute_stats
"""
return self._client.compute_stats(
self._qualified_name, incremental=incremental
) | [
"def",
"compute_stats",
"(",
"self",
",",
"incremental",
"=",
"False",
")",
":",
"return",
"self",
".",
"_client",
".",
"compute_stats",
"(",
"self",
".",
"_qualified_name",
",",
"incremental",
"=",
"incremental",
")"
] | 31.8 | 14 |
def find_template_from_path(filepath, paths=None):
"""
Return resolved path of given template file
:param filepath: (Base) filepath of template file
:param paths: A list of template search paths
"""
if paths is None or not paths:
paths = [os.path.dirname(filepath), os.curdir]
for path in paths:
candidate = os.path.join(path, filepath)
if os.path.exists(candidate):
return candidate
LOGGER.warning("Could not find template=%s in paths=%s", filepath, paths)
return None | [
"def",
"find_template_from_path",
"(",
"filepath",
",",
"paths",
"=",
"None",
")",
":",
"if",
"paths",
"is",
"None",
"or",
"not",
"paths",
":",
"paths",
"=",
"[",
"os",
".",
"path",
".",
"dirname",
"(",
"filepath",
")",
",",
"os",
".",
"curdir",
"]",
"for",
"path",
"in",
"paths",
":",
"candidate",
"=",
"os",
".",
"path",
".",
"join",
"(",
"path",
",",
"filepath",
")",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"candidate",
")",
":",
"return",
"candidate",
"LOGGER",
".",
"warning",
"(",
"\"Could not find template=%s in paths=%s\"",
",",
"filepath",
",",
"paths",
")",
"return",
"None"
] | 31.058824 | 16.588235 |
def check_sla(self, sla, diff_metric):
"""
Check whether the SLA has passed or failed
"""
try:
if sla.display is '%':
diff_val = float(diff_metric['percent_diff'])
else:
diff_val = float(diff_metric['absolute_diff'])
except ValueError:
return False
if not (sla.check_sla_passed(diff_val)):
self.sla_failures += 1
self.sla_failure_list.append(DiffSLAFailure(sla, diff_metric))
return True | [
"def",
"check_sla",
"(",
"self",
",",
"sla",
",",
"diff_metric",
")",
":",
"try",
":",
"if",
"sla",
".",
"display",
"is",
"'%'",
":",
"diff_val",
"=",
"float",
"(",
"diff_metric",
"[",
"'percent_diff'",
"]",
")",
"else",
":",
"diff_val",
"=",
"float",
"(",
"diff_metric",
"[",
"'absolute_diff'",
"]",
")",
"except",
"ValueError",
":",
"return",
"False",
"if",
"not",
"(",
"sla",
".",
"check_sla_passed",
"(",
"diff_val",
")",
")",
":",
"self",
".",
"sla_failures",
"+=",
"1",
"self",
".",
"sla_failure_list",
".",
"append",
"(",
"DiffSLAFailure",
"(",
"sla",
",",
"diff_metric",
")",
")",
"return",
"True"
] | 29.8 | 14.466667 |
def period(self):
"""Period of the orbit as a timedelta
"""
return timedelta(seconds=2 * np.pi * np.sqrt(self.kep.a ** 3 / self.mu)) | [
"def",
"period",
"(",
"self",
")",
":",
"return",
"timedelta",
"(",
"seconds",
"=",
"2",
"*",
"np",
".",
"pi",
"*",
"np",
".",
"sqrt",
"(",
"self",
".",
"kep",
".",
"a",
"**",
"3",
"/",
"self",
".",
"mu",
")",
")"
] | 38.25 | 15.75 |
def secret_key_name(path, key, opt):
"""Renders a Secret key name appropriately"""
value = key
if opt.merge_path:
norm_path = [x for x in path.split('/') if x]
value = "%s_%s" % ('_'.join(norm_path), key)
if opt.add_prefix:
value = "%s%s" % (opt.add_prefix, value)
if opt.add_suffix:
value = "%s%s" % (value, opt.add_suffix)
return value | [
"def",
"secret_key_name",
"(",
"path",
",",
"key",
",",
"opt",
")",
":",
"value",
"=",
"key",
"if",
"opt",
".",
"merge_path",
":",
"norm_path",
"=",
"[",
"x",
"for",
"x",
"in",
"path",
".",
"split",
"(",
"'/'",
")",
"if",
"x",
"]",
"value",
"=",
"\"%s_%s\"",
"%",
"(",
"'_'",
".",
"join",
"(",
"norm_path",
")",
",",
"key",
")",
"if",
"opt",
".",
"add_prefix",
":",
"value",
"=",
"\"%s%s\"",
"%",
"(",
"opt",
".",
"add_prefix",
",",
"value",
")",
"if",
"opt",
".",
"add_suffix",
":",
"value",
"=",
"\"%s%s\"",
"%",
"(",
"value",
",",
"opt",
".",
"add_suffix",
")",
"return",
"value"
] | 27.357143 | 19.142857 |
def create(context, name, type, canonical_project_name, data,
title, message, url, topic_id, export_control, active):
"""create(context, name, type, canonical_project_name, data, title, message, url, topic_id, export_control, active) # noqa
Create a component.
>>> dcictl component-create [OPTIONS]
:param string name: Name of the component [required]
:param string type: Type of the component [required]
:param string topic_id: ID of the topic to associate with [required]
:param string canonical_project_name: Project name
:param json data: JSON to pass to the component
:param string title: Title of the component
:param string message: Message for the component
:param string url: URL resource to monitor
:param boolean export_control: Set the component visible for users
:param boolean active: Set the component in the (in)active state
"""
state = utils.active_string(active)
result = component.create(
context, name=name, type=type,
canonical_project_name=canonical_project_name,
data=data,
title=title, message=message, url=url,
topic_id=topic_id, export_control=export_control,
state=state
)
utils.format_output(result, context.format) | [
"def",
"create",
"(",
"context",
",",
"name",
",",
"type",
",",
"canonical_project_name",
",",
"data",
",",
"title",
",",
"message",
",",
"url",
",",
"topic_id",
",",
"export_control",
",",
"active",
")",
":",
"state",
"=",
"utils",
".",
"active_string",
"(",
"active",
")",
"result",
"=",
"component",
".",
"create",
"(",
"context",
",",
"name",
"=",
"name",
",",
"type",
"=",
"type",
",",
"canonical_project_name",
"=",
"canonical_project_name",
",",
"data",
"=",
"data",
",",
"title",
"=",
"title",
",",
"message",
"=",
"message",
",",
"url",
"=",
"url",
",",
"topic_id",
"=",
"topic_id",
",",
"export_control",
"=",
"export_control",
",",
"state",
"=",
"state",
")",
"utils",
".",
"format_output",
"(",
"result",
",",
"context",
".",
"format",
")"
] | 41.666667 | 17.733333 |
def parse(self, lines = None):
'''Parses the PDB file into a indexed representation (a tagged list of lines, see constructor docstring).
A set of Atoms is created, including x, y, z coordinates when applicable. These atoms are grouped into Residues.
Finally, the limits of the 3D space are calculated to be used for Atom binning.
ATOM serial numbers appear to be sequential within a model regardless of alternate locations (altLoc, see 1ABE). This
code assumes that this holds as this serial number is used as an index.
If an ATOM has a corresponding ANISOU record, the latter record uses the same serial number.
'''
indexed_lines = []
MODEL_count = 0
records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM', 'TER', 'ANISOU'])
removable_records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM', 'ANISOU'])
removable_xyz_records_types_with_atom_serial_numbers = set(['ATOM', 'HETATM'])
xs, ys, zs = [], [], []
# atoms maps ATOM/HETATM serial numbers to Atom objects. Atom objects know which Residue object they belong to and Residue objects maintain a list of their Atoms.
atoms = {}
# atoms maps chain -> residue IDs to Residue objects. Residue objects remember which ATOM/HETATM/ANISOU records (stored as Atom objects) belong to them
residues = {}
atom_name_to_group = {}
for line in self.lines:
record_type = line[:6].strip()
if record_type in removable_records_types_with_atom_serial_numbers:
#altLoc = line[16]
atom_name = line[12:16].strip()
chain = line[21]
resid = line[22:27] # residue ID + insertion code
serial_number = int(line[6:11])
element_name = None
if record_type == 'ATOM':
element_name = line[12:14].strip() # see the ATOM section of PDB format documentation. The element name is stored in these positions, right-justified.
element_name = ''.join([w for w in element_name if w.isalpha()]) # e.g. 1
if atom_name not in atom_name_to_group:
atom_name_to_group[atom_name] = element_name
else:
assert(atom_name_to_group[atom_name] == element_name)
residues[chain] = residues.get(chain, {})
residues[chain][resid] = residues[chain].get(resid, Residue(chain, resid, line[17:20]))
new_atom = Atom(residues[chain][resid], atom_name, element_name, serial_number, line[16])
residues[chain][resid].add(record_type.strip(), new_atom)
if record_type in removable_xyz_records_types_with_atom_serial_numbers:
x, y, z = float(line[30:38]), float(line[38:46]), float(line[46:54])
xs.append(x)
ys.append(y)
zs.append(z)
assert(serial_number not in atoms) # the logic of this class relies on this assertion - that placed records have a unique identifier
atoms[serial_number] = new_atom
atoms[serial_number].place(x, y, z, record_type)
indexed_lines.append((record_type, serial_number, line, new_atom))
else:
indexed_lines.append((record_type, serial_number, line))
else:
if record_type == 'MODEL ':
MODEL_count += 1
if MODEL_count > 1:
raise Exception('This code needs to be updated to properly handle NMR structures.')
indexed_lines.append((None, line))
if not xs:
raise Exception('No coordinates found.')
# Calculate the side size needed for a cube to contain all of the points, with buffers to account for edge-cases
min_x, min_y, min_z, max_x, max_y, max_z = min(xs), min(ys), min(zs), max(xs), max(ys), max(zs)
self.min_x, self.min_y, self.min_z, self.max_x, self.max_y, self.max_z = min(xs)-self.buffer, min(ys)-self.buffer, min(zs)-self.buffer, max(xs)+self.buffer, max(ys)+self.buffer, max(zs)+self.buffer
self.max_dimension = (self.buffer * 4) + max(self.max_x - self.min_x, self.max_y - self.min_y, self.max_z - self.min_z)
self.residues = residues
self.atoms = atoms
self.indexed_lines = indexed_lines
self.atom_name_to_group = atom_name_to_group | [
"def",
"parse",
"(",
"self",
",",
"lines",
"=",
"None",
")",
":",
"indexed_lines",
"=",
"[",
"]",
"MODEL_count",
"=",
"0",
"records_types_with_atom_serial_numbers",
"=",
"set",
"(",
"[",
"'ATOM'",
",",
"'HETATM'",
",",
"'TER'",
",",
"'ANISOU'",
"]",
")",
"removable_records_types_with_atom_serial_numbers",
"=",
"set",
"(",
"[",
"'ATOM'",
",",
"'HETATM'",
",",
"'ANISOU'",
"]",
")",
"removable_xyz_records_types_with_atom_serial_numbers",
"=",
"set",
"(",
"[",
"'ATOM'",
",",
"'HETATM'",
"]",
")",
"xs",
",",
"ys",
",",
"zs",
"=",
"[",
"]",
",",
"[",
"]",
",",
"[",
"]",
"# atoms maps ATOM/HETATM serial numbers to Atom objects. Atom objects know which Residue object they belong to and Residue objects maintain a list of their Atoms.",
"atoms",
"=",
"{",
"}",
"# atoms maps chain -> residue IDs to Residue objects. Residue objects remember which ATOM/HETATM/ANISOU records (stored as Atom objects) belong to them",
"residues",
"=",
"{",
"}",
"atom_name_to_group",
"=",
"{",
"}",
"for",
"line",
"in",
"self",
".",
"lines",
":",
"record_type",
"=",
"line",
"[",
":",
"6",
"]",
".",
"strip",
"(",
")",
"if",
"record_type",
"in",
"removable_records_types_with_atom_serial_numbers",
":",
"#altLoc = line[16]",
"atom_name",
"=",
"line",
"[",
"12",
":",
"16",
"]",
".",
"strip",
"(",
")",
"chain",
"=",
"line",
"[",
"21",
"]",
"resid",
"=",
"line",
"[",
"22",
":",
"27",
"]",
"# residue ID + insertion code",
"serial_number",
"=",
"int",
"(",
"line",
"[",
"6",
":",
"11",
"]",
")",
"element_name",
"=",
"None",
"if",
"record_type",
"==",
"'ATOM'",
":",
"element_name",
"=",
"line",
"[",
"12",
":",
"14",
"]",
".",
"strip",
"(",
")",
"# see the ATOM section of PDB format documentation. The element name is stored in these positions, right-justified.",
"element_name",
"=",
"''",
".",
"join",
"(",
"[",
"w",
"for",
"w",
"in",
"element_name",
"if",
"w",
".",
"isalpha",
"(",
")",
"]",
")",
"# e.g. 1",
"if",
"atom_name",
"not",
"in",
"atom_name_to_group",
":",
"atom_name_to_group",
"[",
"atom_name",
"]",
"=",
"element_name",
"else",
":",
"assert",
"(",
"atom_name_to_group",
"[",
"atom_name",
"]",
"==",
"element_name",
")",
"residues",
"[",
"chain",
"]",
"=",
"residues",
".",
"get",
"(",
"chain",
",",
"{",
"}",
")",
"residues",
"[",
"chain",
"]",
"[",
"resid",
"]",
"=",
"residues",
"[",
"chain",
"]",
".",
"get",
"(",
"resid",
",",
"Residue",
"(",
"chain",
",",
"resid",
",",
"line",
"[",
"17",
":",
"20",
"]",
")",
")",
"new_atom",
"=",
"Atom",
"(",
"residues",
"[",
"chain",
"]",
"[",
"resid",
"]",
",",
"atom_name",
",",
"element_name",
",",
"serial_number",
",",
"line",
"[",
"16",
"]",
")",
"residues",
"[",
"chain",
"]",
"[",
"resid",
"]",
".",
"add",
"(",
"record_type",
".",
"strip",
"(",
")",
",",
"new_atom",
")",
"if",
"record_type",
"in",
"removable_xyz_records_types_with_atom_serial_numbers",
":",
"x",
",",
"y",
",",
"z",
"=",
"float",
"(",
"line",
"[",
"30",
":",
"38",
"]",
")",
",",
"float",
"(",
"line",
"[",
"38",
":",
"46",
"]",
")",
",",
"float",
"(",
"line",
"[",
"46",
":",
"54",
"]",
")",
"xs",
".",
"append",
"(",
"x",
")",
"ys",
".",
"append",
"(",
"y",
")",
"zs",
".",
"append",
"(",
"z",
")",
"assert",
"(",
"serial_number",
"not",
"in",
"atoms",
")",
"# the logic of this class relies on this assertion - that placed records have a unique identifier",
"atoms",
"[",
"serial_number",
"]",
"=",
"new_atom",
"atoms",
"[",
"serial_number",
"]",
".",
"place",
"(",
"x",
",",
"y",
",",
"z",
",",
"record_type",
")",
"indexed_lines",
".",
"append",
"(",
"(",
"record_type",
",",
"serial_number",
",",
"line",
",",
"new_atom",
")",
")",
"else",
":",
"indexed_lines",
".",
"append",
"(",
"(",
"record_type",
",",
"serial_number",
",",
"line",
")",
")",
"else",
":",
"if",
"record_type",
"==",
"'MODEL '",
":",
"MODEL_count",
"+=",
"1",
"if",
"MODEL_count",
">",
"1",
":",
"raise",
"Exception",
"(",
"'This code needs to be updated to properly handle NMR structures.'",
")",
"indexed_lines",
".",
"append",
"(",
"(",
"None",
",",
"line",
")",
")",
"if",
"not",
"xs",
":",
"raise",
"Exception",
"(",
"'No coordinates found.'",
")",
"# Calculate the side size needed for a cube to contain all of the points, with buffers to account for edge-cases",
"min_x",
",",
"min_y",
",",
"min_z",
",",
"max_x",
",",
"max_y",
",",
"max_z",
"=",
"min",
"(",
"xs",
")",
",",
"min",
"(",
"ys",
")",
",",
"min",
"(",
"zs",
")",
",",
"max",
"(",
"xs",
")",
",",
"max",
"(",
"ys",
")",
",",
"max",
"(",
"zs",
")",
"self",
".",
"min_x",
",",
"self",
".",
"min_y",
",",
"self",
".",
"min_z",
",",
"self",
".",
"max_x",
",",
"self",
".",
"max_y",
",",
"self",
".",
"max_z",
"=",
"min",
"(",
"xs",
")",
"-",
"self",
".",
"buffer",
",",
"min",
"(",
"ys",
")",
"-",
"self",
".",
"buffer",
",",
"min",
"(",
"zs",
")",
"-",
"self",
".",
"buffer",
",",
"max",
"(",
"xs",
")",
"+",
"self",
".",
"buffer",
",",
"max",
"(",
"ys",
")",
"+",
"self",
".",
"buffer",
",",
"max",
"(",
"zs",
")",
"+",
"self",
".",
"buffer",
"self",
".",
"max_dimension",
"=",
"(",
"self",
".",
"buffer",
"*",
"4",
")",
"+",
"max",
"(",
"self",
".",
"max_x",
"-",
"self",
".",
"min_x",
",",
"self",
".",
"max_y",
"-",
"self",
".",
"min_y",
",",
"self",
".",
"max_z",
"-",
"self",
".",
"min_z",
")",
"self",
".",
"residues",
"=",
"residues",
"self",
".",
"atoms",
"=",
"atoms",
"self",
".",
"indexed_lines",
"=",
"indexed_lines",
"self",
".",
"atom_name_to_group",
"=",
"atom_name_to_group"
] | 60.04 | 37.293333 |
def set_unit_property(self, unit_id, property_name, value):
'''This function adds a unit property data set under the given property
name to the given unit.
Parameters
----------
unit_id: int
The unit id for which the property will be set
property_name: str
The name of the property to be stored
value
The data associated with the given property name. Could be many
formats as specified by the user.
'''
if isinstance(unit_id, (int, np.integer)):
if unit_id in self.get_unit_ids():
if unit_id not in self._unit_properties:
self._unit_properties[unit_id] = {}
if isinstance(property_name, str):
self._unit_properties[unit_id][property_name] = value
else:
raise ValueError(str(property_name) + " must be a string")
else:
raise ValueError(str(unit_id) + " is not a valid unit_id")
else:
raise ValueError(str(unit_id) + " must be an int") | [
"def",
"set_unit_property",
"(",
"self",
",",
"unit_id",
",",
"property_name",
",",
"value",
")",
":",
"if",
"isinstance",
"(",
"unit_id",
",",
"(",
"int",
",",
"np",
".",
"integer",
")",
")",
":",
"if",
"unit_id",
"in",
"self",
".",
"get_unit_ids",
"(",
")",
":",
"if",
"unit_id",
"not",
"in",
"self",
".",
"_unit_properties",
":",
"self",
".",
"_unit_properties",
"[",
"unit_id",
"]",
"=",
"{",
"}",
"if",
"isinstance",
"(",
"property_name",
",",
"str",
")",
":",
"self",
".",
"_unit_properties",
"[",
"unit_id",
"]",
"[",
"property_name",
"]",
"=",
"value",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"property_name",
")",
"+",
"\" must be a string\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"unit_id",
")",
"+",
"\" is not a valid unit_id\"",
")",
"else",
":",
"raise",
"ValueError",
"(",
"str",
"(",
"unit_id",
")",
"+",
"\" must be an int\"",
")"
] | 42.192308 | 21.576923 |
def main(opts):
"""Program entry point."""
term = Terminal()
style = Style()
# if the terminal supports colors, use a Style instance with some
# standout colors (magenta, cyan).
if term.number_of_colors:
style = Style(attr_major=term.magenta,
attr_minor=term.bright_cyan,
alignment=opts['--alignment'])
style.name_len = term.width - 15
screen = Screen(term, style, wide=opts['--wide'])
pager = Pager(term, screen, opts['character_factory'])
with term.location(), term.cbreak(), \
term.fullscreen(), term.hidden_cursor():
pager.run(writer=echo, reader=term.inkey)
return 0 | [
"def",
"main",
"(",
"opts",
")",
":",
"term",
"=",
"Terminal",
"(",
")",
"style",
"=",
"Style",
"(",
")",
"# if the terminal supports colors, use a Style instance with some",
"# standout colors (magenta, cyan).",
"if",
"term",
".",
"number_of_colors",
":",
"style",
"=",
"Style",
"(",
"attr_major",
"=",
"term",
".",
"magenta",
",",
"attr_minor",
"=",
"term",
".",
"bright_cyan",
",",
"alignment",
"=",
"opts",
"[",
"'--alignment'",
"]",
")",
"style",
".",
"name_len",
"=",
"term",
".",
"width",
"-",
"15",
"screen",
"=",
"Screen",
"(",
"term",
",",
"style",
",",
"wide",
"=",
"opts",
"[",
"'--wide'",
"]",
")",
"pager",
"=",
"Pager",
"(",
"term",
",",
"screen",
",",
"opts",
"[",
"'character_factory'",
"]",
")",
"with",
"term",
".",
"location",
"(",
")",
",",
"term",
".",
"cbreak",
"(",
")",
",",
"term",
".",
"fullscreen",
"(",
")",
",",
"term",
".",
"hidden_cursor",
"(",
")",
":",
"pager",
".",
"run",
"(",
"writer",
"=",
"echo",
",",
"reader",
"=",
"term",
".",
"inkey",
")",
"return",
"0"
] | 33.55 | 17.05 |
def pawn_from_dummy(self, dummy):
"""Make a real thing and its pawn from a dummy pawn.
Create a new :class:`board.Pawn` instance, along with the
underlying :class:`LiSE.Place` instance, and give it the name,
location, and imagery of the provided dummy.
"""
dummy.pos = self.to_local(*dummy.pos)
for spot in self.board.spotlayout.children:
if spot.collide_widget(dummy):
whereat = spot
break
else:
return
whereat.add_widget(
self.board.make_pawn(
self.board.character.new_thing(
dummy.name,
whereat.place.name,
_image_paths=list(dummy.paths)
)
)
)
dummy.num += 1 | [
"def",
"pawn_from_dummy",
"(",
"self",
",",
"dummy",
")",
":",
"dummy",
".",
"pos",
"=",
"self",
".",
"to_local",
"(",
"*",
"dummy",
".",
"pos",
")",
"for",
"spot",
"in",
"self",
".",
"board",
".",
"spotlayout",
".",
"children",
":",
"if",
"spot",
".",
"collide_widget",
"(",
"dummy",
")",
":",
"whereat",
"=",
"spot",
"break",
"else",
":",
"return",
"whereat",
".",
"add_widget",
"(",
"self",
".",
"board",
".",
"make_pawn",
"(",
"self",
".",
"board",
".",
"character",
".",
"new_thing",
"(",
"dummy",
".",
"name",
",",
"whereat",
".",
"place",
".",
"name",
",",
"_image_paths",
"=",
"list",
"(",
"dummy",
".",
"paths",
")",
")",
")",
")",
"dummy",
".",
"num",
"+=",
"1"
] | 31.96 | 15.84 |
def download_gcs_file(path, out_fname=None, prefix_filter=None):
"""Download a file from GCS, optionally to a file."""
url = posixpath.join(GCS_BUCKET, path)
if prefix_filter:
url += "?prefix=%s" % prefix_filter
stream = bool(out_fname)
resp = requests.get(url, stream=stream)
if not resp.ok:
raise ValueError("GCS bucket inaccessible")
if out_fname:
with tf.io.gfile.GFile(out_fname, "wb") as f:
for chunk in resp.iter_content(1024):
f.write(chunk)
else:
return resp.content | [
"def",
"download_gcs_file",
"(",
"path",
",",
"out_fname",
"=",
"None",
",",
"prefix_filter",
"=",
"None",
")",
":",
"url",
"=",
"posixpath",
".",
"join",
"(",
"GCS_BUCKET",
",",
"path",
")",
"if",
"prefix_filter",
":",
"url",
"+=",
"\"?prefix=%s\"",
"%",
"prefix_filter",
"stream",
"=",
"bool",
"(",
"out_fname",
")",
"resp",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"stream",
"=",
"stream",
")",
"if",
"not",
"resp",
".",
"ok",
":",
"raise",
"ValueError",
"(",
"\"GCS bucket inaccessible\"",
")",
"if",
"out_fname",
":",
"with",
"tf",
".",
"io",
".",
"gfile",
".",
"GFile",
"(",
"out_fname",
",",
"\"wb\"",
")",
"as",
"f",
":",
"for",
"chunk",
"in",
"resp",
".",
"iter_content",
"(",
"1024",
")",
":",
"f",
".",
"write",
"(",
"chunk",
")",
"else",
":",
"return",
"resp",
".",
"content"
] | 33.8 | 13.066667 |
def status(self, head):
"""Get status from server.
head - Ping the the head node if True.
"""
sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if head:
sock.connect((self.server, self.port))
else:
sock.connect((self.server2, self.port2))
self._hello(sock)
comms.send_message(sock, "<Status/>".encode())
status = comms.recv_message(sock).decode('utf-8')
sock.close()
return status | [
"def",
"status",
"(",
"self",
",",
"head",
")",
":",
"sock",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"if",
"head",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server",
",",
"self",
".",
"port",
")",
")",
"else",
":",
"sock",
".",
"connect",
"(",
"(",
"self",
".",
"server2",
",",
"self",
".",
"port2",
")",
")",
"self",
".",
"_hello",
"(",
"sock",
")",
"comms",
".",
"send_message",
"(",
"sock",
",",
"\"<Status/>\"",
".",
"encode",
"(",
")",
")",
"status",
"=",
"comms",
".",
"recv_message",
"(",
"sock",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"sock",
".",
"close",
"(",
")",
"return",
"status"
] | 32.4 | 16.333333 |
def segment_allocation_find(context, lock_mode=False, **filters):
"""Query for segment allocations."""
range_ids = filters.pop("segment_allocation_range_ids", None)
query = context.session.query(models.SegmentAllocation)
if lock_mode:
query = query.with_lockmode("update")
query = query.filter_by(**filters)
# Optionally filter by given list of range ids
if range_ids:
query.filter(
models.SegmentAllocation.segment_allocation_range_id.in_(
range_ids))
return query | [
"def",
"segment_allocation_find",
"(",
"context",
",",
"lock_mode",
"=",
"False",
",",
"*",
"*",
"filters",
")",
":",
"range_ids",
"=",
"filters",
".",
"pop",
"(",
"\"segment_allocation_range_ids\"",
",",
"None",
")",
"query",
"=",
"context",
".",
"session",
".",
"query",
"(",
"models",
".",
"SegmentAllocation",
")",
"if",
"lock_mode",
":",
"query",
"=",
"query",
".",
"with_lockmode",
"(",
"\"update\"",
")",
"query",
"=",
"query",
".",
"filter_by",
"(",
"*",
"*",
"filters",
")",
"# Optionally filter by given list of range ids",
"if",
"range_ids",
":",
"query",
".",
"filter",
"(",
"models",
".",
"SegmentAllocation",
".",
"segment_allocation_range_id",
".",
"in_",
"(",
"range_ids",
")",
")",
"return",
"query"
] | 33.0625 | 21.0625 |
def calculate_simple_interest(entries, rate_pct: Decimal, interest_date: date or None=None, begin: date or None=None) -> Decimal:
"""
Calculates simple interest of specified entries over time.
Does not accumulate interest to interest.
:param entries: AccountEntry iterable (e.g. list/QuerySet) ordered by timestamp (ascending)
:param rate_pct: Interest rate %, e.g. 8.00 for 8%
:param interest_date: Interest end date. Default is current date.
:param begin: Optional begin date for the interest. Default is whole range from the timestamp of account entries.
:return: Decimal accumulated interest
"""
if interest_date is None:
interest_date = now().date()
bal = None
cur_date = None
daily_rate = rate_pct / Decimal(36500)
accum_interest = Decimal('0.00')
done = False
entries_list = list(entries)
nentries = len(entries_list)
if nentries > 0:
# make sure we calculate interest over whole range until interest_date
last = entries_list[nentries-1]
assert isinstance(last, AccountEntry)
if last.timestamp.date() < interest_date:
timestamp = pytz.utc.localize(datetime.combine(interest_date, time(0, 0)))
e = AccountEntry(timestamp=timestamp, amount=Decimal('0.00'), type=last.type)
entries_list.append(e)
# initial values from the first account entry
e = entries_list[0]
bal = e.amount
cur_date = e.timestamp.date()
if begin and begin > cur_date:
cur_date = begin
for e in entries_list[1:]:
assert isinstance(e, AccountEntry)
next_date = e.timestamp.date()
if begin and begin > next_date:
next_date = begin
if next_date > interest_date:
next_date = interest_date
done = True
time_days = (next_date - cur_date).days
if time_days > 0:
day_interest = bal * daily_rate
interval_interest = day_interest * Decimal(time_days)
accum_interest += interval_interest
cur_date = next_date
bal += e.amount
if done:
break
return accum_interest | [
"def",
"calculate_simple_interest",
"(",
"entries",
",",
"rate_pct",
":",
"Decimal",
",",
"interest_date",
":",
"date",
"or",
"None",
"=",
"None",
",",
"begin",
":",
"date",
"or",
"None",
"=",
"None",
")",
"->",
"Decimal",
":",
"if",
"interest_date",
"is",
"None",
":",
"interest_date",
"=",
"now",
"(",
")",
".",
"date",
"(",
")",
"bal",
"=",
"None",
"cur_date",
"=",
"None",
"daily_rate",
"=",
"rate_pct",
"/",
"Decimal",
"(",
"36500",
")",
"accum_interest",
"=",
"Decimal",
"(",
"'0.00'",
")",
"done",
"=",
"False",
"entries_list",
"=",
"list",
"(",
"entries",
")",
"nentries",
"=",
"len",
"(",
"entries_list",
")",
"if",
"nentries",
">",
"0",
":",
"# make sure we calculate interest over whole range until interest_date",
"last",
"=",
"entries_list",
"[",
"nentries",
"-",
"1",
"]",
"assert",
"isinstance",
"(",
"last",
",",
"AccountEntry",
")",
"if",
"last",
".",
"timestamp",
".",
"date",
"(",
")",
"<",
"interest_date",
":",
"timestamp",
"=",
"pytz",
".",
"utc",
".",
"localize",
"(",
"datetime",
".",
"combine",
"(",
"interest_date",
",",
"time",
"(",
"0",
",",
"0",
")",
")",
")",
"e",
"=",
"AccountEntry",
"(",
"timestamp",
"=",
"timestamp",
",",
"amount",
"=",
"Decimal",
"(",
"'0.00'",
")",
",",
"type",
"=",
"last",
".",
"type",
")",
"entries_list",
".",
"append",
"(",
"e",
")",
"# initial values from the first account entry",
"e",
"=",
"entries_list",
"[",
"0",
"]",
"bal",
"=",
"e",
".",
"amount",
"cur_date",
"=",
"e",
".",
"timestamp",
".",
"date",
"(",
")",
"if",
"begin",
"and",
"begin",
">",
"cur_date",
":",
"cur_date",
"=",
"begin",
"for",
"e",
"in",
"entries_list",
"[",
"1",
":",
"]",
":",
"assert",
"isinstance",
"(",
"e",
",",
"AccountEntry",
")",
"next_date",
"=",
"e",
".",
"timestamp",
".",
"date",
"(",
")",
"if",
"begin",
"and",
"begin",
">",
"next_date",
":",
"next_date",
"=",
"begin",
"if",
"next_date",
">",
"interest_date",
":",
"next_date",
"=",
"interest_date",
"done",
"=",
"True",
"time_days",
"=",
"(",
"next_date",
"-",
"cur_date",
")",
".",
"days",
"if",
"time_days",
">",
"0",
":",
"day_interest",
"=",
"bal",
"*",
"daily_rate",
"interval_interest",
"=",
"day_interest",
"*",
"Decimal",
"(",
"time_days",
")",
"accum_interest",
"+=",
"interval_interest",
"cur_date",
"=",
"next_date",
"bal",
"+=",
"e",
".",
"amount",
"if",
"done",
":",
"break",
"return",
"accum_interest"
] | 38.25 | 18.357143 |
def round_to_quarter(start_time, end_time):
"""
Return the duration between `start_time` and `end_time` :class:`datetime.time` objects, rounded to 15 minutes.
"""
# We don't care about the date (only about the time) but Python
# can substract only datetime objects, not time ones
today = datetime.date.today()
start_date = datetime.datetime.combine(today, start_time)
end_date = datetime.datetime.combine(today, end_time)
difference_minutes = (end_date - start_date).seconds / 60
remainder = difference_minutes % 15
# Round up
difference_minutes += 15 - remainder if remainder > 0 else 0
return (
start_date + datetime.timedelta(minutes=difference_minutes)
).time() | [
"def",
"round_to_quarter",
"(",
"start_time",
",",
"end_time",
")",
":",
"# We don't care about the date (only about the time) but Python",
"# can substract only datetime objects, not time ones",
"today",
"=",
"datetime",
".",
"date",
".",
"today",
"(",
")",
"start_date",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"today",
",",
"start_time",
")",
"end_date",
"=",
"datetime",
".",
"datetime",
".",
"combine",
"(",
"today",
",",
"end_time",
")",
"difference_minutes",
"=",
"(",
"end_date",
"-",
"start_date",
")",
".",
"seconds",
"/",
"60",
"remainder",
"=",
"difference_minutes",
"%",
"15",
"# Round up",
"difference_minutes",
"+=",
"15",
"-",
"remainder",
"if",
"remainder",
">",
"0",
"else",
"0",
"return",
"(",
"start_date",
"+",
"datetime",
".",
"timedelta",
"(",
"minutes",
"=",
"difference_minutes",
")",
")",
".",
"time",
"(",
")"
] | 39.666667 | 22.222222 |
def get(feature, obj, **kwargs):
'''Obtain a feature from a set of morphology objects
Parameters:
feature(string): feature to extract
obj: a neuron, population or neurite tree
**kwargs: parameters to forward to underlying worker functions
Returns:
features as a 1D or 2D numpy array.
'''
feature = (NEURITEFEATURES[feature] if feature in NEURITEFEATURES
else NEURONFEATURES[feature])
return _np.array(list(feature(obj, **kwargs))) | [
"def",
"get",
"(",
"feature",
",",
"obj",
",",
"*",
"*",
"kwargs",
")",
":",
"feature",
"=",
"(",
"NEURITEFEATURES",
"[",
"feature",
"]",
"if",
"feature",
"in",
"NEURITEFEATURES",
"else",
"NEURONFEATURES",
"[",
"feature",
"]",
")",
"return",
"_np",
".",
"array",
"(",
"list",
"(",
"feature",
"(",
"obj",
",",
"*",
"*",
"kwargs",
")",
")",
")"
] | 28.823529 | 23.411765 |
def get_json_shift(year, month, day, unit, count, period, symbol):
""" Gets JSON from shifted date by the Poloniex API
Args:
year: Int between 1 and 9999.
month: Int between 1 and 12.
day: Int between 1 and 31.
unit: String of time period unit for count argument.
How far back to check historical market data.
Valid values: 'hour', 'day', 'week', 'month', 'year'
count: Int of units.
How far back to check historical market data.
period: Int defining width of each chart candlestick in seconds.
symbol: String of currency pair, like a ticker symbol.
Returns: JSON, list of dates where each entry is a dict of raw market data.
"""
epochs = date.get_end_start_epochs(year, month, day, 'last', unit, count)
return chart_json(epochs['shifted'], epochs['initial'],
period, symbol)[0] | [
"def",
"get_json_shift",
"(",
"year",
",",
"month",
",",
"day",
",",
"unit",
",",
"count",
",",
"period",
",",
"symbol",
")",
":",
"epochs",
"=",
"date",
".",
"get_end_start_epochs",
"(",
"year",
",",
"month",
",",
"day",
",",
"'last'",
",",
"unit",
",",
"count",
")",
"return",
"chart_json",
"(",
"epochs",
"[",
"'shifted'",
"]",
",",
"epochs",
"[",
"'initial'",
"]",
",",
"period",
",",
"symbol",
")",
"[",
"0",
"]"
] | 44.95 | 19.45 |
def compute_performance(SC, verbose=True, output='dict'):
"""
Return some performance value for comparison.
Parameters
-------
SC: SortingComparison instance
The SortingComparison
verbose: bool
Display on console or not
output: dict or pandas
Returns
----------
performance: dict or pandas.Serie depending output param
"""
counts = SC._counts
tp_rate = float(counts['TP']) / counts['TOT_ST1'] * 100
cl_rate = float(counts['CL']) / counts['TOT_ST1'] * 100
fn_rate = float(counts['FN']) / counts['TOT_ST1'] * 100
fp_st1 = float(counts['FP']) / counts['TOT_ST1'] * 100
fp_st2 = float(counts['FP']) / counts['TOT_ST2'] * 100
accuracy = tp_rate / (tp_rate + fn_rate + fp_st1) * 100
sensitivity = tp_rate / (tp_rate + fn_rate) * 100
miss_rate = fn_rate / (tp_rate + fn_rate) * 100
precision = tp_rate / (tp_rate + fp_st1) * 100
false_discovery_rate = fp_st1 / (tp_rate + fp_st1) * 100
performance = {'tp': tp_rate, 'cl': cl_rate, 'fn': fn_rate, 'fp_st1': fp_st1, 'fp_st2': fp_st2,
'accuracy': accuracy, 'sensitivity': sensitivity, 'precision': precision, 'miss_rate': miss_rate,
'false_disc_rate': false_discovery_rate}
if verbose:
txt = _txt_performance.format(**performance)
print(txt)
if output == 'dict':
return performance
elif output == 'pandas':
return pd.Series(performance) | [
"def",
"compute_performance",
"(",
"SC",
",",
"verbose",
"=",
"True",
",",
"output",
"=",
"'dict'",
")",
":",
"counts",
"=",
"SC",
".",
"_counts",
"tp_rate",
"=",
"float",
"(",
"counts",
"[",
"'TP'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST1'",
"]",
"*",
"100",
"cl_rate",
"=",
"float",
"(",
"counts",
"[",
"'CL'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST1'",
"]",
"*",
"100",
"fn_rate",
"=",
"float",
"(",
"counts",
"[",
"'FN'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST1'",
"]",
"*",
"100",
"fp_st1",
"=",
"float",
"(",
"counts",
"[",
"'FP'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST1'",
"]",
"*",
"100",
"fp_st2",
"=",
"float",
"(",
"counts",
"[",
"'FP'",
"]",
")",
"/",
"counts",
"[",
"'TOT_ST2'",
"]",
"*",
"100",
"accuracy",
"=",
"tp_rate",
"/",
"(",
"tp_rate",
"+",
"fn_rate",
"+",
"fp_st1",
")",
"*",
"100",
"sensitivity",
"=",
"tp_rate",
"/",
"(",
"tp_rate",
"+",
"fn_rate",
")",
"*",
"100",
"miss_rate",
"=",
"fn_rate",
"/",
"(",
"tp_rate",
"+",
"fn_rate",
")",
"*",
"100",
"precision",
"=",
"tp_rate",
"/",
"(",
"tp_rate",
"+",
"fp_st1",
")",
"*",
"100",
"false_discovery_rate",
"=",
"fp_st1",
"/",
"(",
"tp_rate",
"+",
"fp_st1",
")",
"*",
"100",
"performance",
"=",
"{",
"'tp'",
":",
"tp_rate",
",",
"'cl'",
":",
"cl_rate",
",",
"'fn'",
":",
"fn_rate",
",",
"'fp_st1'",
":",
"fp_st1",
",",
"'fp_st2'",
":",
"fp_st2",
",",
"'accuracy'",
":",
"accuracy",
",",
"'sensitivity'",
":",
"sensitivity",
",",
"'precision'",
":",
"precision",
",",
"'miss_rate'",
":",
"miss_rate",
",",
"'false_disc_rate'",
":",
"false_discovery_rate",
"}",
"if",
"verbose",
":",
"txt",
"=",
"_txt_performance",
".",
"format",
"(",
"*",
"*",
"performance",
")",
"print",
"(",
"txt",
")",
"if",
"output",
"==",
"'dict'",
":",
"return",
"performance",
"elif",
"output",
"==",
"'pandas'",
":",
"return",
"pd",
".",
"Series",
"(",
"performance",
")"
] | 30.468085 | 24.212766 |
def extract(self, high_bit, low_bit):
"""
Operation extract
- A cheap hack is implemented: a copy of self is returned if (high_bit - low_bit + 1 == self.bits), which is a
ValueSet instance. Otherwise a StridedInterval is returned.
:param high_bit:
:param low_bit:
:return: A ValueSet or a StridedInterval
"""
if high_bit - low_bit + 1 == self.bits:
return self.copy()
if ('global' in self._regions and len(self._regions.keys()) > 1) or \
len(self._regions.keys()) > 0:
si_ret = StridedInterval.top(high_bit - low_bit + 1)
else:
if 'global' in self._regions:
si = self._regions['global']
si_ret = si.extract(high_bit, low_bit)
else:
si_ret = StridedInterval.empty(high_bit - low_bit + 1)
return si_ret | [
"def",
"extract",
"(",
"self",
",",
"high_bit",
",",
"low_bit",
")",
":",
"if",
"high_bit",
"-",
"low_bit",
"+",
"1",
"==",
"self",
".",
"bits",
":",
"return",
"self",
".",
"copy",
"(",
")",
"if",
"(",
"'global'",
"in",
"self",
".",
"_regions",
"and",
"len",
"(",
"self",
".",
"_regions",
".",
"keys",
"(",
")",
")",
">",
"1",
")",
"or",
"len",
"(",
"self",
".",
"_regions",
".",
"keys",
"(",
")",
")",
">",
"0",
":",
"si_ret",
"=",
"StridedInterval",
".",
"top",
"(",
"high_bit",
"-",
"low_bit",
"+",
"1",
")",
"else",
":",
"if",
"'global'",
"in",
"self",
".",
"_regions",
":",
"si",
"=",
"self",
".",
"_regions",
"[",
"'global'",
"]",
"si_ret",
"=",
"si",
".",
"extract",
"(",
"high_bit",
",",
"low_bit",
")",
"else",
":",
"si_ret",
"=",
"StridedInterval",
".",
"empty",
"(",
"high_bit",
"-",
"low_bit",
"+",
"1",
")",
"return",
"si_ret"
] | 31.714286 | 23.071429 |
def get_file(self, filename):
"""Get file source from cache"""
import linecache
# Hack for frozen importlib bootstrap
if filename == '<frozen importlib._bootstrap>':
filename = os.path.join(
os.path.dirname(linecache.__file__), 'importlib',
'_bootstrap.py'
)
return to_unicode_string(
''.join(linecache.getlines(filename)), filename
) | [
"def",
"get_file",
"(",
"self",
",",
"filename",
")",
":",
"import",
"linecache",
"# Hack for frozen importlib bootstrap",
"if",
"filename",
"==",
"'<frozen importlib._bootstrap>'",
":",
"filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"linecache",
".",
"__file__",
")",
",",
"'importlib'",
",",
"'_bootstrap.py'",
")",
"return",
"to_unicode_string",
"(",
"''",
".",
"join",
"(",
"linecache",
".",
"getlines",
"(",
"filename",
")",
")",
",",
"filename",
")"
] | 36.583333 | 14.083333 |
def read_map(fname):
"""
reads a saved text file to list
"""
lst = []
with open(fname, "r") as f:
for line in f:
lst.append(line)
return lst | [
"def",
"read_map",
"(",
"fname",
")",
":",
"lst",
"=",
"[",
"]",
"with",
"open",
"(",
"fname",
",",
"\"r\"",
")",
"as",
"f",
":",
"for",
"line",
"in",
"f",
":",
"lst",
".",
"append",
"(",
"line",
")",
"return",
"lst"
] | 19.555556 | 13.111111 |
def search_show_top_unite(self, category, genre=None, area=None,
year=None, orderby=None, headnum=1,
tailnum=1, onesiteflag=None,
page=1, count=20):
"""doc: http://open.youku.com/docs/doc?id=86
"""
url = 'https://openapi.youku.com/v2/searches/show/top_unite.json'
params = {
'client_id': self.client_id,
'category': category,
'genre': genre,
'area': area,
'year': year,
'orderby': orderby,
'headnum': headnum,
'tailnum': tailnum,
'onesiteflag': onesiteflag,
'page': page,
'count': count
}
params = remove_none_value(params)
r = requests.get(url, params=params)
check_error(r)
return r.json() | [
"def",
"search_show_top_unite",
"(",
"self",
",",
"category",
",",
"genre",
"=",
"None",
",",
"area",
"=",
"None",
",",
"year",
"=",
"None",
",",
"orderby",
"=",
"None",
",",
"headnum",
"=",
"1",
",",
"tailnum",
"=",
"1",
",",
"onesiteflag",
"=",
"None",
",",
"page",
"=",
"1",
",",
"count",
"=",
"20",
")",
":",
"url",
"=",
"'https://openapi.youku.com/v2/searches/show/top_unite.json'",
"params",
"=",
"{",
"'client_id'",
":",
"self",
".",
"client_id",
",",
"'category'",
":",
"category",
",",
"'genre'",
":",
"genre",
",",
"'area'",
":",
"area",
",",
"'year'",
":",
"year",
",",
"'orderby'",
":",
"orderby",
",",
"'headnum'",
":",
"headnum",
",",
"'tailnum'",
":",
"tailnum",
",",
"'onesiteflag'",
":",
"onesiteflag",
",",
"'page'",
":",
"page",
",",
"'count'",
":",
"count",
"}",
"params",
"=",
"remove_none_value",
"(",
"params",
")",
"r",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"params",
"=",
"params",
")",
"check_error",
"(",
"r",
")",
"return",
"r",
".",
"json",
"(",
")"
] | 35.916667 | 12.875 |
def maximum_size_estimated(self, sz):
"""
Set the CoRE Link Format sz attribute of the resource.
:param sz: the CoRE Link Format sz attribute
"""
if not isinstance(sz, str):
sz = str(sz)
self._attributes["sz"] = sz | [
"def",
"maximum_size_estimated",
"(",
"self",
",",
"sz",
")",
":",
"if",
"not",
"isinstance",
"(",
"sz",
",",
"str",
")",
":",
"sz",
"=",
"str",
"(",
"sz",
")",
"self",
".",
"_attributes",
"[",
"\"sz\"",
"]",
"=",
"sz"
] | 29.666667 | 11.444444 |
def skypipe_input_stream(endpoint, name=None):
"""Returns a context manager for streaming data into skypipe"""
name = name or ''
class context_manager(object):
def __enter__(self):
self.socket = ctx.socket(zmq.DEALER)
self.socket.connect(endpoint)
return self
def send(self, data):
data_msg = sp_msg(SP_CMD_DATA, name, data)
self.socket.send_multipart(data_msg)
def __exit__(self, *args, **kwargs):
eof_msg = sp_msg(SP_CMD_DATA, name, SP_DATA_EOF)
self.socket.send_multipart(eof_msg)
self.socket.close()
return context_manager() | [
"def",
"skypipe_input_stream",
"(",
"endpoint",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"''",
"class",
"context_manager",
"(",
"object",
")",
":",
"def",
"__enter__",
"(",
"self",
")",
":",
"self",
".",
"socket",
"=",
"ctx",
".",
"socket",
"(",
"zmq",
".",
"DEALER",
")",
"self",
".",
"socket",
".",
"connect",
"(",
"endpoint",
")",
"return",
"self",
"def",
"send",
"(",
"self",
",",
"data",
")",
":",
"data_msg",
"=",
"sp_msg",
"(",
"SP_CMD_DATA",
",",
"name",
",",
"data",
")",
"self",
".",
"socket",
".",
"send_multipart",
"(",
"data_msg",
")",
"def",
"__exit__",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"eof_msg",
"=",
"sp_msg",
"(",
"SP_CMD_DATA",
",",
"name",
",",
"SP_DATA_EOF",
")",
"self",
".",
"socket",
".",
"send_multipart",
"(",
"eof_msg",
")",
"self",
".",
"socket",
".",
"close",
"(",
")",
"return",
"context_manager",
"(",
")"
] | 34.157895 | 14.421053 |
def get_rejected_variables(self, threshold=0.9):
"""Return a list of variable names being rejected for high
correlation with one of remaining variables.
Parameters:
----------
threshold : float
Correlation value which is above the threshold are rejected
Returns
-------
list
The list of rejected variables or an empty list if the correlation has not been computed.
"""
variable_profile = self.description_set['variables']
result = []
if hasattr(variable_profile, 'correlation'):
result = variable_profile.index[variable_profile.correlation > threshold].tolist()
return result | [
"def",
"get_rejected_variables",
"(",
"self",
",",
"threshold",
"=",
"0.9",
")",
":",
"variable_profile",
"=",
"self",
".",
"description_set",
"[",
"'variables'",
"]",
"result",
"=",
"[",
"]",
"if",
"hasattr",
"(",
"variable_profile",
",",
"'correlation'",
")",
":",
"result",
"=",
"variable_profile",
".",
"index",
"[",
"variable_profile",
".",
"correlation",
">",
"threshold",
"]",
".",
"tolist",
"(",
")",
"return",
"result"
] | 37.263158 | 23.421053 |
def update(self) -> None:
"""Reference the actual |Indexer.timeofyear| array of the
|Indexer| object available in module |pub|.
>>> from hydpy import pub
>>> pub.timegrids = '27.02.2004', '3.03.2004', '1d'
>>> from hydpy.core.parametertools import TOYParameter
>>> toyparameter = TOYParameter(None)
>>> toyparameter.update()
>>> toyparameter
toyparameter(57, 58, 59, 60, 61)
"""
indexarray = hydpy.pub.indexer.timeofyear
self.shape = indexarray.shape
self.values = indexarray | [
"def",
"update",
"(",
"self",
")",
"->",
"None",
":",
"indexarray",
"=",
"hydpy",
".",
"pub",
".",
"indexer",
".",
"timeofyear",
"self",
".",
"shape",
"=",
"indexarray",
".",
"shape",
"self",
".",
"values",
"=",
"indexarray"
] | 37.733333 | 10.8 |
def _get_condition_instances(data):
"""
Returns a list of OrderingCondition instances created from the passed data structure.
The structure should be a list of dicts containing the necessary information:
[
dict(
name='featureA',
subject='featureB',
ctype='after'
),
]
Example says: featureA needs to be after featureB.
:param data:
:return:
"""
conditions = list()
for cond in data:
conditions.append(OrderingCondition(
name=cond.get('name'),
subject=cond.get('subject'),
ctype=cond.get('ctype')
))
return conditions | [
"def",
"_get_condition_instances",
"(",
"data",
")",
":",
"conditions",
"=",
"list",
"(",
")",
"for",
"cond",
"in",
"data",
":",
"conditions",
".",
"append",
"(",
"OrderingCondition",
"(",
"name",
"=",
"cond",
".",
"get",
"(",
"'name'",
")",
",",
"subject",
"=",
"cond",
".",
"get",
"(",
"'subject'",
")",
",",
"ctype",
"=",
"cond",
".",
"get",
"(",
"'ctype'",
")",
")",
")",
"return",
"conditions"
] | 28.086957 | 18.434783 |
def do_OP_LEFT(vm):
"""
>>> s = [b'abcdef', b'\3']
>>> do_OP_LEFT(s, require_minimal=True)
>>> print(len(s)==1 and s[0]==b'abc')
True
>>> s = [b'abcdef', b'']
>>> do_OP_LEFT(s, require_minimal=True)
>>> print(len(s) ==1 and s[0]==b'')
True
"""
pos = vm.pop_nonnegative()
vm.append(vm.pop()[:pos]) | [
"def",
"do_OP_LEFT",
"(",
"vm",
")",
":",
"pos",
"=",
"vm",
".",
"pop_nonnegative",
"(",
")",
"vm",
".",
"append",
"(",
"vm",
".",
"pop",
"(",
")",
"[",
":",
"pos",
"]",
")"
] | 25.538462 | 10.461538 |
def _split_tidy(self, string, maxsplit=None):
"""Rstrips string for \n and splits string for \t"""
if maxsplit is None:
return string.rstrip("\n").split("\t")
else:
return string.rstrip("\n").split("\t", maxsplit) | [
"def",
"_split_tidy",
"(",
"self",
",",
"string",
",",
"maxsplit",
"=",
"None",
")",
":",
"if",
"maxsplit",
"is",
"None",
":",
"return",
"string",
".",
"rstrip",
"(",
"\"\\n\"",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"else",
":",
"return",
"string",
".",
"rstrip",
"(",
"\"\\n\"",
")",
".",
"split",
"(",
"\"\\t\"",
",",
"maxsplit",
")"
] | 36.571429 | 16.285714 |
def __setup_remote_paths(self):
"""
Actually create the working directory and copy the module into it.
Note: the script has to be readable by Hadoop; though this may not
generally be a problem on HDFS, where the Hadoop user is usually
the superuser, things may be different if our working directory is
on a shared POSIX filesystem. Therefore, we make the directory
and the script accessible by all.
"""
self.logger.debug("remote_wd: %s", self.remote_wd)
self.logger.debug("remote_exe: %s", self.remote_exe)
self.logger.debug("remotes: %s", self.files_to_upload)
if self.args.module:
self.logger.debug(
'Generated pipes_code:\n\n %s', self._generate_pipes_code()
)
if not self.args.pretend:
hdfs.mkdir(self.remote_wd)
hdfs.chmod(self.remote_wd, "a+rx")
self.logger.debug("created and chmod-ed: %s", self.remote_wd)
pipes_code = self._generate_pipes_code()
hdfs.dump(pipes_code, self.remote_exe)
self.logger.debug("dumped pipes_code to: %s", self.remote_exe)
hdfs.chmod(self.remote_exe, "a+rx")
self.__warn_user_if_wd_maybe_unreadable(self.remote_wd)
for (l, h, _) in self.files_to_upload:
self.logger.debug("uploading: %s to %s", l, h)
hdfs.cp(l, h)
self.logger.debug("Created%sremote paths:" %
(' [simulation] ' if self.args.pretend else ' ')) | [
"def",
"__setup_remote_paths",
"(",
"self",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"remote_wd: %s\"",
",",
"self",
".",
"remote_wd",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"remote_exe: %s\"",
",",
"self",
".",
"remote_exe",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"remotes: %s\"",
",",
"self",
".",
"files_to_upload",
")",
"if",
"self",
".",
"args",
".",
"module",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'Generated pipes_code:\\n\\n %s'",
",",
"self",
".",
"_generate_pipes_code",
"(",
")",
")",
"if",
"not",
"self",
".",
"args",
".",
"pretend",
":",
"hdfs",
".",
"mkdir",
"(",
"self",
".",
"remote_wd",
")",
"hdfs",
".",
"chmod",
"(",
"self",
".",
"remote_wd",
",",
"\"a+rx\"",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"created and chmod-ed: %s\"",
",",
"self",
".",
"remote_wd",
")",
"pipes_code",
"=",
"self",
".",
"_generate_pipes_code",
"(",
")",
"hdfs",
".",
"dump",
"(",
"pipes_code",
",",
"self",
".",
"remote_exe",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"dumped pipes_code to: %s\"",
",",
"self",
".",
"remote_exe",
")",
"hdfs",
".",
"chmod",
"(",
"self",
".",
"remote_exe",
",",
"\"a+rx\"",
")",
"self",
".",
"__warn_user_if_wd_maybe_unreadable",
"(",
"self",
".",
"remote_wd",
")",
"for",
"(",
"l",
",",
"h",
",",
"_",
")",
"in",
"self",
".",
"files_to_upload",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"\"uploading: %s to %s\"",
",",
"l",
",",
"h",
")",
"hdfs",
".",
"cp",
"(",
"l",
",",
"h",
")",
"self",
".",
"logger",
".",
"debug",
"(",
"\"Created%sremote paths:\"",
"%",
"(",
"' [simulation] '",
"if",
"self",
".",
"args",
".",
"pretend",
"else",
"' '",
")",
")"
] | 49.451613 | 18.935484 |
def build_absolute_uri(request, location, protocol=None):
"""request.build_absolute_uri() helper
Like request.build_absolute_uri, but gracefully handling
the case where request is None.
"""
from .account import app_settings as account_settings
if request is None:
site = Site.objects.get_current()
bits = urlsplit(location)
if not (bits.scheme and bits.netloc):
uri = '{proto}://{domain}{url}'.format(
proto=account_settings.DEFAULT_HTTP_PROTOCOL,
domain=site.domain,
url=location)
else:
uri = location
else:
uri = request.build_absolute_uri(location)
# NOTE: We only force a protocol if we are instructed to do so
# (via the `protocol` parameter, or, if the default is set to
# HTTPS. The latter keeps compatibility with the debatable use
# case of running your site under both HTTP and HTTPS, where one
# would want to make sure HTTPS links end up in password reset
# mails even while they were initiated on an HTTP password reset
# form.
if not protocol and account_settings.DEFAULT_HTTP_PROTOCOL == 'https':
protocol = account_settings.DEFAULT_HTTP_PROTOCOL
# (end NOTE)
if protocol:
uri = protocol + ':' + uri.partition(':')[2]
return uri | [
"def",
"build_absolute_uri",
"(",
"request",
",",
"location",
",",
"protocol",
"=",
"None",
")",
":",
"from",
".",
"account",
"import",
"app_settings",
"as",
"account_settings",
"if",
"request",
"is",
"None",
":",
"site",
"=",
"Site",
".",
"objects",
".",
"get_current",
"(",
")",
"bits",
"=",
"urlsplit",
"(",
"location",
")",
"if",
"not",
"(",
"bits",
".",
"scheme",
"and",
"bits",
".",
"netloc",
")",
":",
"uri",
"=",
"'{proto}://{domain}{url}'",
".",
"format",
"(",
"proto",
"=",
"account_settings",
".",
"DEFAULT_HTTP_PROTOCOL",
",",
"domain",
"=",
"site",
".",
"domain",
",",
"url",
"=",
"location",
")",
"else",
":",
"uri",
"=",
"location",
"else",
":",
"uri",
"=",
"request",
".",
"build_absolute_uri",
"(",
"location",
")",
"# NOTE: We only force a protocol if we are instructed to do so",
"# (via the `protocol` parameter, or, if the default is set to",
"# HTTPS. The latter keeps compatibility with the debatable use",
"# case of running your site under both HTTP and HTTPS, where one",
"# would want to make sure HTTPS links end up in password reset",
"# mails even while they were initiated on an HTTP password reset",
"# form.",
"if",
"not",
"protocol",
"and",
"account_settings",
".",
"DEFAULT_HTTP_PROTOCOL",
"==",
"'https'",
":",
"protocol",
"=",
"account_settings",
".",
"DEFAULT_HTTP_PROTOCOL",
"# (end NOTE)",
"if",
"protocol",
":",
"uri",
"=",
"protocol",
"+",
"':'",
"+",
"uri",
".",
"partition",
"(",
"':'",
")",
"[",
"2",
"]",
"return",
"uri"
] | 39.787879 | 18.909091 |
def set_cached_output(self, placeholder_name, instance, output):
"""
.. versionadded:: 0.9
Store the cached output for a rendered item.
This method can be overwritten to implement custom caching mechanisms.
By default, this function generates the cache key using :func:`~fluent_contents.cache.get_rendering_cache_key`
and stores the results in the configured Django cache backend (e.g. memcached).
When custom cache keys are used, also include those in :func:`get_output_cache_keys`
so the cache will be cleared when needed.
.. versionchanged:: 1.0
The received data is no longer a HTML string, but :class:`~fluent_contents.models.ContentItemOutput` object.
"""
cachekey = self.get_output_cache_key(placeholder_name, instance)
if self.cache_timeout is not DEFAULT_TIMEOUT:
cache.set(cachekey, output, self.cache_timeout)
else:
# Don't want to mix into the default 0/None issue.
cache.set(cachekey, output) | [
"def",
"set_cached_output",
"(",
"self",
",",
"placeholder_name",
",",
"instance",
",",
"output",
")",
":",
"cachekey",
"=",
"self",
".",
"get_output_cache_key",
"(",
"placeholder_name",
",",
"instance",
")",
"if",
"self",
".",
"cache_timeout",
"is",
"not",
"DEFAULT_TIMEOUT",
":",
"cache",
".",
"set",
"(",
"cachekey",
",",
"output",
",",
"self",
".",
"cache_timeout",
")",
"else",
":",
"# Don't want to mix into the default 0/None issue.",
"cache",
".",
"set",
"(",
"cachekey",
",",
"output",
")"
] | 50.333333 | 29.095238 |
def load(self, dtype_conversion=None):
"""
Load the data table and corresponding validation schema.
Parameters
----------
dtype_conversion : dict
Column names as keys and corresponding type for loading the data.
Please take a look at the `pandas documentation
<https://pandas.pydata.org/pandas-docs/stable/io.html#specifying-column-data-types>`__
for detailed explanations.
"""
if dtype_conversion is None:
dtype_conversion = {"growth": str}
super(GrowthExperiment, self).load(dtype_conversion=dtype_conversion)
self.data["growth"] = self.data["growth"].isin(self.TRUTHY) | [
"def",
"load",
"(",
"self",
",",
"dtype_conversion",
"=",
"None",
")",
":",
"if",
"dtype_conversion",
"is",
"None",
":",
"dtype_conversion",
"=",
"{",
"\"growth\"",
":",
"str",
"}",
"super",
"(",
"GrowthExperiment",
",",
"self",
")",
".",
"load",
"(",
"dtype_conversion",
"=",
"dtype_conversion",
")",
"self",
".",
"data",
"[",
"\"growth\"",
"]",
"=",
"self",
".",
"data",
"[",
"\"growth\"",
"]",
".",
"isin",
"(",
"self",
".",
"TRUTHY",
")"
] | 40.529412 | 20.529412 |
def hasReaders(self, ulBuffer):
"""inexpensively checks for readers to allow writers to fast-fail potentially expensive copies and writes."""
fn = self.function_table.hasReaders
result = fn(ulBuffer)
return result | [
"def",
"hasReaders",
"(",
"self",
",",
"ulBuffer",
")",
":",
"fn",
"=",
"self",
".",
"function_table",
".",
"hasReaders",
"result",
"=",
"fn",
"(",
"ulBuffer",
")",
"return",
"result"
] | 40.166667 | 13.666667 |
def setFigForm():
"""set the rcparams to EmulateApJ columnwidth=245.26 pts """
fig_width_pt = 245.26*2
inches_per_pt = 1.0/72.27
golden_mean = (math.sqrt(5.)-1.0)/2.0
fig_width = fig_width_pt*inches_per_pt
fig_height = fig_width*golden_mean
fig_size = [1.5*fig_width, fig_height]
params = {'backend': 'ps',
'axes.labelsize': 12,
'text.fontsize': 12,
'legend.fontsize': 7,
'xtick.labelsize': 11,
'ytick.labelsize': 11,
'text.usetex': True,
'font.family': 'serif',
'font.serif': 'Times',
'image.aspect': 'auto',
'figure.subplot.left': 0.1,
'figure.subplot.bottom': 0.1,
'figure.subplot.hspace': 0.25,
'figure.figsize': fig_size}
rcParams.update(params) | [
"def",
"setFigForm",
"(",
")",
":",
"fig_width_pt",
"=",
"245.26",
"*",
"2",
"inches_per_pt",
"=",
"1.0",
"/",
"72.27",
"golden_mean",
"=",
"(",
"math",
".",
"sqrt",
"(",
"5.",
")",
"-",
"1.0",
")",
"/",
"2.0",
"fig_width",
"=",
"fig_width_pt",
"*",
"inches_per_pt",
"fig_height",
"=",
"fig_width",
"*",
"golden_mean",
"fig_size",
"=",
"[",
"1.5",
"*",
"fig_width",
",",
"fig_height",
"]",
"params",
"=",
"{",
"'backend'",
":",
"'ps'",
",",
"'axes.labelsize'",
":",
"12",
",",
"'text.fontsize'",
":",
"12",
",",
"'legend.fontsize'",
":",
"7",
",",
"'xtick.labelsize'",
":",
"11",
",",
"'ytick.labelsize'",
":",
"11",
",",
"'text.usetex'",
":",
"True",
",",
"'font.family'",
":",
"'serif'",
",",
"'font.serif'",
":",
"'Times'",
",",
"'image.aspect'",
":",
"'auto'",
",",
"'figure.subplot.left'",
":",
"0.1",
",",
"'figure.subplot.bottom'",
":",
"0.1",
",",
"'figure.subplot.hspace'",
":",
"0.25",
",",
"'figure.figsize'",
":",
"fig_size",
"}",
"rcParams",
".",
"update",
"(",
"params",
")"
] | 32.846154 | 9.153846 |
def template_slave_hcl(cl_args, masters):
'''
Template slave config file
'''
slave_config_template = "%s/standalone/templates/slave.template.hcl" % cl_args["config_path"]
slave_config_actual = "%s/standalone/resources/slave.hcl" % cl_args["config_path"]
masters_in_quotes = ['"%s"' % master for master in masters]
template_file(slave_config_template, slave_config_actual,
{"<nomad_masters:master_port>": ", ".join(masters_in_quotes)}) | [
"def",
"template_slave_hcl",
"(",
"cl_args",
",",
"masters",
")",
":",
"slave_config_template",
"=",
"\"%s/standalone/templates/slave.template.hcl\"",
"%",
"cl_args",
"[",
"\"config_path\"",
"]",
"slave_config_actual",
"=",
"\"%s/standalone/resources/slave.hcl\"",
"%",
"cl_args",
"[",
"\"config_path\"",
"]",
"masters_in_quotes",
"=",
"[",
"'\"%s\"'",
"%",
"master",
"for",
"master",
"in",
"masters",
"]",
"template_file",
"(",
"slave_config_template",
",",
"slave_config_actual",
",",
"{",
"\"<nomad_masters:master_port>\"",
":",
"\", \"",
".",
"join",
"(",
"masters_in_quotes",
")",
"}",
")"
] | 50.666667 | 28.888889 |
def do_auth(self, block_address, force=False):
"""
Calls RFID card_auth() with saved auth information if needed.
Returns error state from method call.
"""
auth_data = (block_address, self.method, self.key, self.uid)
if (self.last_auth != auth_data) or force:
if self.debug:
print("Calling card_auth on UID " + str(self.uid))
self.last_auth = auth_data
return self.rfid.card_auth(self.method, block_address, self.key, self.uid)
else:
if self.debug:
print("Not calling card_auth - already authed")
return False | [
"def",
"do_auth",
"(",
"self",
",",
"block_address",
",",
"force",
"=",
"False",
")",
":",
"auth_data",
"=",
"(",
"block_address",
",",
"self",
".",
"method",
",",
"self",
".",
"key",
",",
"self",
".",
"uid",
")",
"if",
"(",
"self",
".",
"last_auth",
"!=",
"auth_data",
")",
"or",
"force",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Calling card_auth on UID \"",
"+",
"str",
"(",
"self",
".",
"uid",
")",
")",
"self",
".",
"last_auth",
"=",
"auth_data",
"return",
"self",
".",
"rfid",
".",
"card_auth",
"(",
"self",
".",
"method",
",",
"block_address",
",",
"self",
".",
"key",
",",
"self",
".",
"uid",
")",
"else",
":",
"if",
"self",
".",
"debug",
":",
"print",
"(",
"\"Not calling card_auth - already authed\"",
")",
"return",
"False"
] | 40.125 | 17.875 |
def serialize(self) -> dict:
"""
Serialize the message for sending to slack API
Returns:
serialized message
"""
data = {**self}
if "attachments" in self:
data["attachments"] = json.dumps(self["attachments"])
return data | [
"def",
"serialize",
"(",
"self",
")",
"->",
"dict",
":",
"data",
"=",
"{",
"*",
"*",
"self",
"}",
"if",
"\"attachments\"",
"in",
"self",
":",
"data",
"[",
"\"attachments\"",
"]",
"=",
"json",
".",
"dumps",
"(",
"self",
"[",
"\"attachments\"",
"]",
")",
"return",
"data"
] | 26.363636 | 15.454545 |
def md_to_obj(cls, file_path=None, text='', columns=None,
key_on=None, ignore_code_blocks=True, eval_cells=True):
"""
This will convert a mark down file to a seaborn table
:param file_path: str of the path to the file
:param text: str of the mark down text
:param columns: list of str of columns to use
:param key_on: list of str of columns to key on
:param ignore_code_blocks: bool if true will filter out
any lines between ```
:param eval_cells: bool if True will try to evaluate numbers
:return: SeabornTable
"""
return cls.mark_down_to_obj(file_path=file_path, text=text,
columns=columns, key_on=key_on,
ignore_code_blocks=ignore_code_blocks,
eval_cells=eval_cells) | [
"def",
"md_to_obj",
"(",
"cls",
",",
"file_path",
"=",
"None",
",",
"text",
"=",
"''",
",",
"columns",
"=",
"None",
",",
"key_on",
"=",
"None",
",",
"ignore_code_blocks",
"=",
"True",
",",
"eval_cells",
"=",
"True",
")",
":",
"return",
"cls",
".",
"mark_down_to_obj",
"(",
"file_path",
"=",
"file_path",
",",
"text",
"=",
"text",
",",
"columns",
"=",
"columns",
",",
"key_on",
"=",
"key_on",
",",
"ignore_code_blocks",
"=",
"ignore_code_blocks",
",",
"eval_cells",
"=",
"eval_cells",
")"
] | 51.705882 | 17.235294 |
def _set_lossless_priority(self, v, load=False):
"""
Setter method for lossless_priority, mapped from YANG variable /cee_map/remap/lossless_priority (container)
If this variable is read-only (config: false) in the
source YANG file, then _set_lossless_priority is considered as a private
method. Backends looking to populate this variable should
do so via calling thisObj._set_lossless_priority() directly.
"""
if hasattr(v, "_utype"):
v = v._utype(v)
try:
t = YANGDynClass(v,base=lossless_priority.lossless_priority, is_container='container', presence=False, yang_name="lossless-priority", rest_name="lossless-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u' CoS for lossless priority'}}, namespace='urn:brocade.com:mgmt:brocade-cee-map', defining_module='brocade-cee-map', yang_type='container', is_config=True)
except (TypeError, ValueError):
raise ValueError({
'error-string': """lossless_priority must be of a type compatible with container""",
'defined-type': "container",
'generated-type': """YANGDynClass(base=lossless_priority.lossless_priority, is_container='container', presence=False, yang_name="lossless-priority", rest_name="lossless-priority", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u' CoS for lossless priority'}}, namespace='urn:brocade.com:mgmt:brocade-cee-map', defining_module='brocade-cee-map', yang_type='container', is_config=True)""",
})
self.__lossless_priority = t
if hasattr(self, '_set'):
self._set() | [
"def",
"_set_lossless_priority",
"(",
"self",
",",
"v",
",",
"load",
"=",
"False",
")",
":",
"if",
"hasattr",
"(",
"v",
",",
"\"_utype\"",
")",
":",
"v",
"=",
"v",
".",
"_utype",
"(",
"v",
")",
"try",
":",
"t",
"=",
"YANGDynClass",
"(",
"v",
",",
"base",
"=",
"lossless_priority",
".",
"lossless_priority",
",",
"is_container",
"=",
"'container'",
",",
"presence",
"=",
"False",
",",
"yang_name",
"=",
"\"lossless-priority\"",
",",
"rest_name",
"=",
"\"lossless-priority\"",
",",
"parent",
"=",
"self",
",",
"path_helper",
"=",
"self",
".",
"_path_helper",
",",
"extmethods",
"=",
"self",
".",
"_extmethods",
",",
"register_paths",
"=",
"True",
",",
"extensions",
"=",
"{",
"u'tailf-common'",
":",
"{",
"u'info'",
":",
"u' CoS for lossless priority'",
"}",
"}",
",",
"namespace",
"=",
"'urn:brocade.com:mgmt:brocade-cee-map'",
",",
"defining_module",
"=",
"'brocade-cee-map'",
",",
"yang_type",
"=",
"'container'",
",",
"is_config",
"=",
"True",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"raise",
"ValueError",
"(",
"{",
"'error-string'",
":",
"\"\"\"lossless_priority must be of a type compatible with container\"\"\"",
",",
"'defined-type'",
":",
"\"container\"",
",",
"'generated-type'",
":",
"\"\"\"YANGDynClass(base=lossless_priority.lossless_priority, is_container='container', presence=False, yang_name=\"lossless-priority\", rest_name=\"lossless-priority\", parent=self, path_helper=self._path_helper, extmethods=self._extmethods, register_paths=True, extensions={u'tailf-common': {u'info': u' CoS for lossless priority'}}, namespace='urn:brocade.com:mgmt:brocade-cee-map', defining_module='brocade-cee-map', yang_type='container', is_config=True)\"\"\"",
",",
"}",
")",
"self",
".",
"__lossless_priority",
"=",
"t",
"if",
"hasattr",
"(",
"self",
",",
"'_set'",
")",
":",
"self",
".",
"_set",
"(",
")"
] | 77.681818 | 36.090909 |
def row_to_dict(cls, row):
"""
Converts a raw input record to a dictionary of observation data.
:param cls: current class
:param row: a single observation as a list or tuple
"""
comment_code = row[3]
if comment_code.lower() == 'na':
comment_code = ''
comp1 = row[4]
if comp1.lower() == 'na':
comp1 = ''
comp2 = row[5]
if comp2.lower() == 'na':
comp2 = ''
chart = row[6]
if chart.lower() == 'na':
chart = ''
notes = row[7]
if notes.lower() == 'na':
notes = ''
return {
'name': row[0],
'date': row[1],
'magnitude': row[2],
'comment_code': comment_code,
'comp1': comp1,
'comp2': comp2,
'chart': chart,
'notes': notes,
} | [
"def",
"row_to_dict",
"(",
"cls",
",",
"row",
")",
":",
"comment_code",
"=",
"row",
"[",
"3",
"]",
"if",
"comment_code",
".",
"lower",
"(",
")",
"==",
"'na'",
":",
"comment_code",
"=",
"''",
"comp1",
"=",
"row",
"[",
"4",
"]",
"if",
"comp1",
".",
"lower",
"(",
")",
"==",
"'na'",
":",
"comp1",
"=",
"''",
"comp2",
"=",
"row",
"[",
"5",
"]",
"if",
"comp2",
".",
"lower",
"(",
")",
"==",
"'na'",
":",
"comp2",
"=",
"''",
"chart",
"=",
"row",
"[",
"6",
"]",
"if",
"chart",
".",
"lower",
"(",
")",
"==",
"'na'",
":",
"chart",
"=",
"''",
"notes",
"=",
"row",
"[",
"7",
"]",
"if",
"notes",
".",
"lower",
"(",
")",
"==",
"'na'",
":",
"notes",
"=",
"''",
"return",
"{",
"'name'",
":",
"row",
"[",
"0",
"]",
",",
"'date'",
":",
"row",
"[",
"1",
"]",
",",
"'magnitude'",
":",
"row",
"[",
"2",
"]",
",",
"'comment_code'",
":",
"comment_code",
",",
"'comp1'",
":",
"comp1",
",",
"'comp2'",
":",
"comp2",
",",
"'chart'",
":",
"chart",
",",
"'notes'",
":",
"notes",
",",
"}"
] | 27.4375 | 14 |
def get_author(self):
"""Gets author
:return: author of commit
"""
author = self.commit.author
out = ""
if author.name is not None:
out += author.name
if author.email is not None:
out += " (" + author.email + ")"
return out | [
"def",
"get_author",
"(",
"self",
")",
":",
"author",
"=",
"self",
".",
"commit",
".",
"author",
"out",
"=",
"\"\"",
"if",
"author",
".",
"name",
"is",
"not",
"None",
":",
"out",
"+=",
"author",
".",
"name",
"if",
"author",
".",
"email",
"is",
"not",
"None",
":",
"out",
"+=",
"\" (\"",
"+",
"author",
".",
"email",
"+",
"\")\"",
"return",
"out"
] | 20.066667 | 17.333333 |
def get_fno_lot_sizes(self, cached=True, as_json=False):
"""
returns a dictionary with key as stock code and value as stock name.
It also implements cache functionality and hits the server only
if user insists or cache is empty
:return: dict
"""
url = self.fno_lot_size_url
req = Request(url, None, self.headers)
res_dict = {}
if cached is not True or self.__CODECACHE__ is None:
# raises HTTPError and URLError
res = self.opener.open(req)
if res is not None:
# for py3 compat covert byte file like object to
# string file like object
res = byte_adaptor(res)
for line in res.read().split('\n'):
if line != '' and re.search(',', line) and (line.casefold().find('symbol') == -1):
(code, name) = [x.strip() for x in line.split(',')[1:3]]
res_dict[code] = int(name)
# else just skip the evaluation, line may not be a valid csv
else:
raise Exception('no response received')
self.__CODECACHE__ = res_dict
return self.render_response(self.__CODECACHE__, as_json) | [
"def",
"get_fno_lot_sizes",
"(",
"self",
",",
"cached",
"=",
"True",
",",
"as_json",
"=",
"False",
")",
":",
"url",
"=",
"self",
".",
"fno_lot_size_url",
"req",
"=",
"Request",
"(",
"url",
",",
"None",
",",
"self",
".",
"headers",
")",
"res_dict",
"=",
"{",
"}",
"if",
"cached",
"is",
"not",
"True",
"or",
"self",
".",
"__CODECACHE__",
"is",
"None",
":",
"# raises HTTPError and URLError",
"res",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"req",
")",
"if",
"res",
"is",
"not",
"None",
":",
"# for py3 compat covert byte file like object to",
"# string file like object",
"res",
"=",
"byte_adaptor",
"(",
"res",
")",
"for",
"line",
"in",
"res",
".",
"read",
"(",
")",
".",
"split",
"(",
"'\\n'",
")",
":",
"if",
"line",
"!=",
"''",
"and",
"re",
".",
"search",
"(",
"','",
",",
"line",
")",
"and",
"(",
"line",
".",
"casefold",
"(",
")",
".",
"find",
"(",
"'symbol'",
")",
"==",
"-",
"1",
")",
":",
"(",
"code",
",",
"name",
")",
"=",
"[",
"x",
".",
"strip",
"(",
")",
"for",
"x",
"in",
"line",
".",
"split",
"(",
"','",
")",
"[",
"1",
":",
"3",
"]",
"]",
"res_dict",
"[",
"code",
"]",
"=",
"int",
"(",
"name",
")",
"# else just skip the evaluation, line may not be a valid csv",
"else",
":",
"raise",
"Exception",
"(",
"'no response received'",
")",
"self",
".",
"__CODECACHE__",
"=",
"res_dict",
"return",
"self",
".",
"render_response",
"(",
"self",
".",
"__CODECACHE__",
",",
"as_json",
")"
] | 47.923077 | 16.076923 |
def load_into(self, obj, name, data, inplace=True, context=None):
"""Deserialize data from primitive types updating existing object.
Raises :exc:`~lollipop.errors.ValidationError` if data is invalid.
:param obj: Object to update with deserialized data.
:param str name: Name of attribute to deserialize.
:param data: Raw data to get value to deserialize from.
:param bool inplace: If True update data inplace;
otherwise - create new data.
:param kwargs: Same keyword arguments as for :meth:`load`.
:returns: Loaded data.
:raises: :exc:`~lollipop.errors.ValidationError`
"""
if obj is None:
raise ValueError('Load target should not be None')
value = data.get(name, MISSING)
if value is MISSING:
return
target = self.get_value(name, obj, context=context)
if target is not None and target is not MISSING \
and hasattr(self.field_type, 'load_into'):
return self.field_type.load_into(target, value, inplace=inplace,
context=context)
else:
return self.field_type.load(value, context=context) | [
"def",
"load_into",
"(",
"self",
",",
"obj",
",",
"name",
",",
"data",
",",
"inplace",
"=",
"True",
",",
"context",
"=",
"None",
")",
":",
"if",
"obj",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'Load target should not be None'",
")",
"value",
"=",
"data",
".",
"get",
"(",
"name",
",",
"MISSING",
")",
"if",
"value",
"is",
"MISSING",
":",
"return",
"target",
"=",
"self",
".",
"get_value",
"(",
"name",
",",
"obj",
",",
"context",
"=",
"context",
")",
"if",
"target",
"is",
"not",
"None",
"and",
"target",
"is",
"not",
"MISSING",
"and",
"hasattr",
"(",
"self",
".",
"field_type",
",",
"'load_into'",
")",
":",
"return",
"self",
".",
"field_type",
".",
"load_into",
"(",
"target",
",",
"value",
",",
"inplace",
"=",
"inplace",
",",
"context",
"=",
"context",
")",
"else",
":",
"return",
"self",
".",
"field_type",
".",
"load",
"(",
"value",
",",
"context",
"=",
"context",
")"
] | 43.25 | 20.857143 |
def count_entities_or_keys(self, *args, forward=None):
"""Return the number of keys an entity has, if you specify an entity.
Otherwise return the number of entities.
"""
if forward is None:
forward = self.db._forward
entity = args[:-3]
branch, turn, tick = args[-3:]
if self.db._no_kc:
return len(self._get_adds_dels(self.keys[entity], branch, turn, tick)[0])
return len(self._get_keycache(entity, branch, turn, tick, forward=forward)) | [
"def",
"count_entities_or_keys",
"(",
"self",
",",
"*",
"args",
",",
"forward",
"=",
"None",
")",
":",
"if",
"forward",
"is",
"None",
":",
"forward",
"=",
"self",
".",
"db",
".",
"_forward",
"entity",
"=",
"args",
"[",
":",
"-",
"3",
"]",
"branch",
",",
"turn",
",",
"tick",
"=",
"args",
"[",
"-",
"3",
":",
"]",
"if",
"self",
".",
"db",
".",
"_no_kc",
":",
"return",
"len",
"(",
"self",
".",
"_get_adds_dels",
"(",
"self",
".",
"keys",
"[",
"entity",
"]",
",",
"branch",
",",
"turn",
",",
"tick",
")",
"[",
"0",
"]",
")",
"return",
"len",
"(",
"self",
".",
"_get_keycache",
"(",
"entity",
",",
"branch",
",",
"turn",
",",
"tick",
",",
"forward",
"=",
"forward",
")",
")"
] | 39.461538 | 18.076923 |
def delete_tenant(self, tenant_id):
"""
Asynchronously deletes a tenant and all the data associated with the tenant.
:param tenant_id: Tenant id to be sent for deletion process
"""
self._delete(self._get_single_id_url(self._get_tenants_url(), tenant_id)) | [
"def",
"delete_tenant",
"(",
"self",
",",
"tenant_id",
")",
":",
"self",
".",
"_delete",
"(",
"self",
".",
"_get_single_id_url",
"(",
"self",
".",
"_get_tenants_url",
"(",
")",
",",
"tenant_id",
")",
")"
] | 48.166667 | 19.5 |
def plot_return_on_dollar(rets, title='Return on $1', show_maxdd=0, figsize=None, ax=None, append=0, label=None, **plot_args):
""" Show the cumulative return of specified rets and max drawdowns if selected."""
crets = (1. + returns_cumulative(rets, expanding=1))
if isinstance(crets, pd.DataFrame):
tmp = crets.copy()
for c in tmp.columns:
s = tmp[c]
fv = s.first_valid_index()
fi = s.index.get_loc(fv)
if fi != 0:
tmp.ix[fi - 1, c] = 1.
else:
if not s.index.freq:
# no frequency set
freq = guess_freq(s.index)
s = s.asfreq(freq)
first = s.index.shift(-1)[0]
tmp = pd.concat([pd.DataFrame({c: [1.]}, index=[first]), tmp])
crets = tmp
if append:
toadd = crets.index.shift(1)[-1]
crets = pd.concat([crets, pd.DataFrame(np.nan, columns=crets.columns, index=[toadd])])
else:
fv = crets.first_valid_index()
fi = crets.index.get_loc(fv)
if fi != 0:
crets = crets.copy()
crets.iloc[fi - 1] = 1.
else:
if not crets.index.freq:
first = crets.asfreq(guess_freq(crets.index)).index.shift(-1)[0]
else:
first = crets.index.shift(-1)[0]
tmp = pd.Series([1.], index=[first])
tmp = tmp.append(crets)
crets = tmp
if append:
toadd = pd.Series(np.nan, index=[crets.index.shift(1)[-1]])
crets = crets.append(toadd)
ax = crets.plot(figsize=figsize, title=title, ax=ax, label=label, **plot_args)
AxesFormat().Y.apply_format(new_float_formatter()).X.label("").apply(ax)
#ax.tick_params(labelsize=14)
if show_maxdd:
# find the max drawdown available by using original rets
if isinstance(rets, pd.DataFrame):
iterator = rets.iteritems()
else:
iterator = iter([('', rets)])
for c, col in iterator:
dd, dt = max_drawdown(col, inc_date=1)
lbl = c and c + ' maxdd' or 'maxdd'
# get cret to place annotation correctly
if isinstance(crets, pd.DataFrame):
amt = crets.ix[dt, c]
else:
amt = crets[dt]
bbox_props = dict(boxstyle="round", fc="w", ec="0.5", alpha=0.7)
# sub = lambda c: c and len(c) > 2 and c[:2] or c
try:
dtstr = '{0}'.format(dt.to_period())
except:
dtstr = '{0}'.format(dt)
ax.text(dt, amt, "mdd {0}".format(dtstr).strip(), ha="center",
va="center", size=10, bbox=bbox_props)
plt.tight_layout() | [
"def",
"plot_return_on_dollar",
"(",
"rets",
",",
"title",
"=",
"'Return on $1'",
",",
"show_maxdd",
"=",
"0",
",",
"figsize",
"=",
"None",
",",
"ax",
"=",
"None",
",",
"append",
"=",
"0",
",",
"label",
"=",
"None",
",",
"*",
"*",
"plot_args",
")",
":",
"crets",
"=",
"(",
"1.",
"+",
"returns_cumulative",
"(",
"rets",
",",
"expanding",
"=",
"1",
")",
")",
"if",
"isinstance",
"(",
"crets",
",",
"pd",
".",
"DataFrame",
")",
":",
"tmp",
"=",
"crets",
".",
"copy",
"(",
")",
"for",
"c",
"in",
"tmp",
".",
"columns",
":",
"s",
"=",
"tmp",
"[",
"c",
"]",
"fv",
"=",
"s",
".",
"first_valid_index",
"(",
")",
"fi",
"=",
"s",
".",
"index",
".",
"get_loc",
"(",
"fv",
")",
"if",
"fi",
"!=",
"0",
":",
"tmp",
".",
"ix",
"[",
"fi",
"-",
"1",
",",
"c",
"]",
"=",
"1.",
"else",
":",
"if",
"not",
"s",
".",
"index",
".",
"freq",
":",
"# no frequency set",
"freq",
"=",
"guess_freq",
"(",
"s",
".",
"index",
")",
"s",
"=",
"s",
".",
"asfreq",
"(",
"freq",
")",
"first",
"=",
"s",
".",
"index",
".",
"shift",
"(",
"-",
"1",
")",
"[",
"0",
"]",
"tmp",
"=",
"pd",
".",
"concat",
"(",
"[",
"pd",
".",
"DataFrame",
"(",
"{",
"c",
":",
"[",
"1.",
"]",
"}",
",",
"index",
"=",
"[",
"first",
"]",
")",
",",
"tmp",
"]",
")",
"crets",
"=",
"tmp",
"if",
"append",
":",
"toadd",
"=",
"crets",
".",
"index",
".",
"shift",
"(",
"1",
")",
"[",
"-",
"1",
"]",
"crets",
"=",
"pd",
".",
"concat",
"(",
"[",
"crets",
",",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"nan",
",",
"columns",
"=",
"crets",
".",
"columns",
",",
"index",
"=",
"[",
"toadd",
"]",
")",
"]",
")",
"else",
":",
"fv",
"=",
"crets",
".",
"first_valid_index",
"(",
")",
"fi",
"=",
"crets",
".",
"index",
".",
"get_loc",
"(",
"fv",
")",
"if",
"fi",
"!=",
"0",
":",
"crets",
"=",
"crets",
".",
"copy",
"(",
")",
"crets",
".",
"iloc",
"[",
"fi",
"-",
"1",
"]",
"=",
"1.",
"else",
":",
"if",
"not",
"crets",
".",
"index",
".",
"freq",
":",
"first",
"=",
"crets",
".",
"asfreq",
"(",
"guess_freq",
"(",
"crets",
".",
"index",
")",
")",
".",
"index",
".",
"shift",
"(",
"-",
"1",
")",
"[",
"0",
"]",
"else",
":",
"first",
"=",
"crets",
".",
"index",
".",
"shift",
"(",
"-",
"1",
")",
"[",
"0",
"]",
"tmp",
"=",
"pd",
".",
"Series",
"(",
"[",
"1.",
"]",
",",
"index",
"=",
"[",
"first",
"]",
")",
"tmp",
"=",
"tmp",
".",
"append",
"(",
"crets",
")",
"crets",
"=",
"tmp",
"if",
"append",
":",
"toadd",
"=",
"pd",
".",
"Series",
"(",
"np",
".",
"nan",
",",
"index",
"=",
"[",
"crets",
".",
"index",
".",
"shift",
"(",
"1",
")",
"[",
"-",
"1",
"]",
"]",
")",
"crets",
"=",
"crets",
".",
"append",
"(",
"toadd",
")",
"ax",
"=",
"crets",
".",
"plot",
"(",
"figsize",
"=",
"figsize",
",",
"title",
"=",
"title",
",",
"ax",
"=",
"ax",
",",
"label",
"=",
"label",
",",
"*",
"*",
"plot_args",
")",
"AxesFormat",
"(",
")",
".",
"Y",
".",
"apply_format",
"(",
"new_float_formatter",
"(",
")",
")",
".",
"X",
".",
"label",
"(",
"\"\"",
")",
".",
"apply",
"(",
"ax",
")",
"#ax.tick_params(labelsize=14)",
"if",
"show_maxdd",
":",
"# find the max drawdown available by using original rets",
"if",
"isinstance",
"(",
"rets",
",",
"pd",
".",
"DataFrame",
")",
":",
"iterator",
"=",
"rets",
".",
"iteritems",
"(",
")",
"else",
":",
"iterator",
"=",
"iter",
"(",
"[",
"(",
"''",
",",
"rets",
")",
"]",
")",
"for",
"c",
",",
"col",
"in",
"iterator",
":",
"dd",
",",
"dt",
"=",
"max_drawdown",
"(",
"col",
",",
"inc_date",
"=",
"1",
")",
"lbl",
"=",
"c",
"and",
"c",
"+",
"' maxdd'",
"or",
"'maxdd'",
"# get cret to place annotation correctly",
"if",
"isinstance",
"(",
"crets",
",",
"pd",
".",
"DataFrame",
")",
":",
"amt",
"=",
"crets",
".",
"ix",
"[",
"dt",
",",
"c",
"]",
"else",
":",
"amt",
"=",
"crets",
"[",
"dt",
"]",
"bbox_props",
"=",
"dict",
"(",
"boxstyle",
"=",
"\"round\"",
",",
"fc",
"=",
"\"w\"",
",",
"ec",
"=",
"\"0.5\"",
",",
"alpha",
"=",
"0.7",
")",
"# sub = lambda c: c and len(c) > 2 and c[:2] or c",
"try",
":",
"dtstr",
"=",
"'{0}'",
".",
"format",
"(",
"dt",
".",
"to_period",
"(",
")",
")",
"except",
":",
"dtstr",
"=",
"'{0}'",
".",
"format",
"(",
"dt",
")",
"ax",
".",
"text",
"(",
"dt",
",",
"amt",
",",
"\"mdd {0}\"",
".",
"format",
"(",
"dtstr",
")",
".",
"strip",
"(",
")",
",",
"ha",
"=",
"\"center\"",
",",
"va",
"=",
"\"center\"",
",",
"size",
"=",
"10",
",",
"bbox",
"=",
"bbox_props",
")",
"plt",
".",
"tight_layout",
"(",
")"
] | 39 | 17.685714 |
def fitNorm_v2(self, specVals):
"""Fit the normalization given a set of spectral values
that define a spectral shape.
This version uses `scipy.optimize.fmin`.
Parameters
----------
specVals : an array of (nebin values that define a spectral shape
xlims : fit limits
Returns
-------
norm : float
Best-fit normalization value
"""
from scipy.optimize import fmin
def fToMin(x): return self.__call__(specVals * x)
result = fmin(fToMin, 0., disp=False, xtol=1e-6)
return result | [
"def",
"fitNorm_v2",
"(",
"self",
",",
"specVals",
")",
":",
"from",
"scipy",
".",
"optimize",
"import",
"fmin",
"def",
"fToMin",
"(",
"x",
")",
":",
"return",
"self",
".",
"__call__",
"(",
"specVals",
"*",
"x",
")",
"result",
"=",
"fmin",
"(",
"fToMin",
",",
"0.",
",",
"disp",
"=",
"False",
",",
"xtol",
"=",
"1e-6",
")",
"return",
"result"
] | 28.52381 | 18.380952 |
def _updateTargetFromNode(self):
""" Applies the configuration to the target axis it monitors.
The axis label will be set to the configValue. If the configValue equals
PgAxisLabelCti.NO_LABEL, the label will be hidden.
"""
rtiInfo = self.collector.rtiInfo
self.plotItem.setLabel(self.axisPosition, self.configValue.format(**rtiInfo))
self.plotItem.showLabel(self.axisPosition, self.configValue != self.NO_LABEL) | [
"def",
"_updateTargetFromNode",
"(",
"self",
")",
":",
"rtiInfo",
"=",
"self",
".",
"collector",
".",
"rtiInfo",
"self",
".",
"plotItem",
".",
"setLabel",
"(",
"self",
".",
"axisPosition",
",",
"self",
".",
"configValue",
".",
"format",
"(",
"*",
"*",
"rtiInfo",
")",
")",
"self",
".",
"plotItem",
".",
"showLabel",
"(",
"self",
".",
"axisPosition",
",",
"self",
".",
"configValue",
"!=",
"self",
".",
"NO_LABEL",
")"
] | 58.625 | 20.625 |
def _drawBullet(canvas, offset, cur_y, bulletText, style):
"""
draw a bullet text could be a simple string or a frag list
"""
tx2 = canvas.beginText(style.bulletIndent, cur_y + getattr(style, "bulletOffsetY", 0))
tx2.setFont(style.bulletFontName, style.bulletFontSize)
tx2.setFillColor(hasattr(style, 'bulletColor') and style.bulletColor or style.textColor)
if isinstance(bulletText, basestring):
tx2.textOut(bulletText)
else:
for f in bulletText:
if hasattr(f, "image"):
image = f.image
width = image.drawWidth
height = image.drawHeight
gap = style.bulletFontSize * 0.25
img = image.getImage()
# print style.bulletIndent, offset, width
canvas.drawImage(
img,
style.leftIndent - width - gap,
cur_y + getattr(style, "bulletOffsetY", 0),
width,
height)
else:
tx2.setFont(f.fontName, f.fontSize)
tx2.setFillColor(f.textColor)
tx2.textOut(f.text)
canvas.drawText(tx2)
#AR making definition lists a bit less ugly
#bulletEnd = tx2.getX()
bulletEnd = tx2.getX() + style.bulletFontSize * 0.6
offset = max(offset, bulletEnd - style.leftIndent)
return offset | [
"def",
"_drawBullet",
"(",
"canvas",
",",
"offset",
",",
"cur_y",
",",
"bulletText",
",",
"style",
")",
":",
"tx2",
"=",
"canvas",
".",
"beginText",
"(",
"style",
".",
"bulletIndent",
",",
"cur_y",
"+",
"getattr",
"(",
"style",
",",
"\"bulletOffsetY\"",
",",
"0",
")",
")",
"tx2",
".",
"setFont",
"(",
"style",
".",
"bulletFontName",
",",
"style",
".",
"bulletFontSize",
")",
"tx2",
".",
"setFillColor",
"(",
"hasattr",
"(",
"style",
",",
"'bulletColor'",
")",
"and",
"style",
".",
"bulletColor",
"or",
"style",
".",
"textColor",
")",
"if",
"isinstance",
"(",
"bulletText",
",",
"basestring",
")",
":",
"tx2",
".",
"textOut",
"(",
"bulletText",
")",
"else",
":",
"for",
"f",
"in",
"bulletText",
":",
"if",
"hasattr",
"(",
"f",
",",
"\"image\"",
")",
":",
"image",
"=",
"f",
".",
"image",
"width",
"=",
"image",
".",
"drawWidth",
"height",
"=",
"image",
".",
"drawHeight",
"gap",
"=",
"style",
".",
"bulletFontSize",
"*",
"0.25",
"img",
"=",
"image",
".",
"getImage",
"(",
")",
"# print style.bulletIndent, offset, width",
"canvas",
".",
"drawImage",
"(",
"img",
",",
"style",
".",
"leftIndent",
"-",
"width",
"-",
"gap",
",",
"cur_y",
"+",
"getattr",
"(",
"style",
",",
"\"bulletOffsetY\"",
",",
"0",
")",
",",
"width",
",",
"height",
")",
"else",
":",
"tx2",
".",
"setFont",
"(",
"f",
".",
"fontName",
",",
"f",
".",
"fontSize",
")",
"tx2",
".",
"setFillColor",
"(",
"f",
".",
"textColor",
")",
"tx2",
".",
"textOut",
"(",
"f",
".",
"text",
")",
"canvas",
".",
"drawText",
"(",
"tx2",
")",
"#AR making definition lists a bit less ugly",
"#bulletEnd = tx2.getX()",
"bulletEnd",
"=",
"tx2",
".",
"getX",
"(",
")",
"+",
"style",
".",
"bulletFontSize",
"*",
"0.6",
"offset",
"=",
"max",
"(",
"offset",
",",
"bulletEnd",
"-",
"style",
".",
"leftIndent",
")",
"return",
"offset"
] | 39.171429 | 14.714286 |
def validate(filename):
"""
Use W3C validator service: https://bitbucket.org/nmb10/py_w3c/ .
:param filename: the filename to validate
"""
import HTMLParser
from py_w3c.validators.html.validator import HTMLValidator
h = HTMLParser.HTMLParser() # for unescaping WC3 messages
vld = HTMLValidator()
LOG.info("Validating: {0}".format(filename))
# call w3c webservice
vld.validate_file(filename)
# display errors and warning
for err in vld.errors:
LOG.error(u'line: {0}; col: {1}; message: {2}'.
format(err['line'], err['col'], h.unescape(err['message']))
)
for err in vld.warnings:
LOG.warning(u'line: {0}; col: {1}; message: {2}'.
format(err['line'], err['col'], h.unescape(err['message']))
) | [
"def",
"validate",
"(",
"filename",
")",
":",
"import",
"HTMLParser",
"from",
"py_w3c",
".",
"validators",
".",
"html",
".",
"validator",
"import",
"HTMLValidator",
"h",
"=",
"HTMLParser",
".",
"HTMLParser",
"(",
")",
"# for unescaping WC3 messages",
"vld",
"=",
"HTMLValidator",
"(",
")",
"LOG",
".",
"info",
"(",
"\"Validating: {0}\"",
".",
"format",
"(",
"filename",
")",
")",
"# call w3c webservice",
"vld",
".",
"validate_file",
"(",
"filename",
")",
"# display errors and warning",
"for",
"err",
"in",
"vld",
".",
"errors",
":",
"LOG",
".",
"error",
"(",
"u'line: {0}; col: {1}; message: {2}'",
".",
"format",
"(",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'col'",
"]",
",",
"h",
".",
"unescape",
"(",
"err",
"[",
"'message'",
"]",
")",
")",
")",
"for",
"err",
"in",
"vld",
".",
"warnings",
":",
"LOG",
".",
"warning",
"(",
"u'line: {0}; col: {1}; message: {2}'",
".",
"format",
"(",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'col'",
"]",
",",
"h",
".",
"unescape",
"(",
"err",
"[",
"'message'",
"]",
")",
")",
")"
] | 32.72 | 20.08 |
def _clean_dirty(self, obj=None):
""" Recursively clean self and all child objects. """
obj = obj or self
obj.__dict__['_dirty_attributes'].clear()
obj._dirty = False
for key, val in vars(obj).items():
if isinstance(val, BaseObject):
self._clean_dirty(val)
else:
func = getattr(val, '_clean_dirty', None)
if callable(func):
func() | [
"def",
"_clean_dirty",
"(",
"self",
",",
"obj",
"=",
"None",
")",
":",
"obj",
"=",
"obj",
"or",
"self",
"obj",
".",
"__dict__",
"[",
"'_dirty_attributes'",
"]",
".",
"clear",
"(",
")",
"obj",
".",
"_dirty",
"=",
"False",
"for",
"key",
",",
"val",
"in",
"vars",
"(",
"obj",
")",
".",
"items",
"(",
")",
":",
"if",
"isinstance",
"(",
"val",
",",
"BaseObject",
")",
":",
"self",
".",
"_clean_dirty",
"(",
"val",
")",
"else",
":",
"func",
"=",
"getattr",
"(",
"val",
",",
"'_clean_dirty'",
",",
"None",
")",
"if",
"callable",
"(",
"func",
")",
":",
"func",
"(",
")"
] | 37.583333 | 9.333333 |
def clean(self, algorithm=None):
'''Create a new :class:`TimeSeries` with missing data removed or
replaced by the *algorithm* provided'''
# all dates
original_dates = list(self.dates())
series = []
all_dates = set()
for serie in self.series():
dstart, dend, vend = None, None, None
new_dates = []
new_values = []
missings = []
values = {}
for d, v in zip(original_dates, serie):
if v == v:
if dstart is None:
dstart = d
if missings:
for dx, vx in algorithm(dend, vend, d, v, missings):
new_dates.append(dx)
new_values.append(vx)
missings = []
dend = d
vend = v
values[d] = v
elif dstart is not None and algorithm:
missings.append((dt, v))
if missings:
for dx, vx in algorithm(dend, vend, None, None, missings):
new_dates.append(dx)
new_values.append(vx)
dend = dx
series.append((dstart, dend, values))
all_dates = all_dates.union(values)
cdate = []
cdata = []
for dt in sorted(all_dates):
cross = []
for start, end, values in series:
if start is None or (dt >= start and dt <= end):
value = values.get(dt)
if value is None:
cross = None
break
else:
value = nan
cross.append(value)
if cross:
cdate.append(dt)
cdata.append(cross)
return self.clone(date=cdate, data=cdata) | [
"def",
"clean",
"(",
"self",
",",
"algorithm",
"=",
"None",
")",
":",
"# all dates\r",
"original_dates",
"=",
"list",
"(",
"self",
".",
"dates",
"(",
")",
")",
"series",
"=",
"[",
"]",
"all_dates",
"=",
"set",
"(",
")",
"for",
"serie",
"in",
"self",
".",
"series",
"(",
")",
":",
"dstart",
",",
"dend",
",",
"vend",
"=",
"None",
",",
"None",
",",
"None",
"new_dates",
"=",
"[",
"]",
"new_values",
"=",
"[",
"]",
"missings",
"=",
"[",
"]",
"values",
"=",
"{",
"}",
"for",
"d",
",",
"v",
"in",
"zip",
"(",
"original_dates",
",",
"serie",
")",
":",
"if",
"v",
"==",
"v",
":",
"if",
"dstart",
"is",
"None",
":",
"dstart",
"=",
"d",
"if",
"missings",
":",
"for",
"dx",
",",
"vx",
"in",
"algorithm",
"(",
"dend",
",",
"vend",
",",
"d",
",",
"v",
",",
"missings",
")",
":",
"new_dates",
".",
"append",
"(",
"dx",
")",
"new_values",
".",
"append",
"(",
"vx",
")",
"missings",
"=",
"[",
"]",
"dend",
"=",
"d",
"vend",
"=",
"v",
"values",
"[",
"d",
"]",
"=",
"v",
"elif",
"dstart",
"is",
"not",
"None",
"and",
"algorithm",
":",
"missings",
".",
"append",
"(",
"(",
"dt",
",",
"v",
")",
")",
"if",
"missings",
":",
"for",
"dx",
",",
"vx",
"in",
"algorithm",
"(",
"dend",
",",
"vend",
",",
"None",
",",
"None",
",",
"missings",
")",
":",
"new_dates",
".",
"append",
"(",
"dx",
")",
"new_values",
".",
"append",
"(",
"vx",
")",
"dend",
"=",
"dx",
"series",
".",
"append",
"(",
"(",
"dstart",
",",
"dend",
",",
"values",
")",
")",
"all_dates",
"=",
"all_dates",
".",
"union",
"(",
"values",
")",
"cdate",
"=",
"[",
"]",
"cdata",
"=",
"[",
"]",
"for",
"dt",
"in",
"sorted",
"(",
"all_dates",
")",
":",
"cross",
"=",
"[",
"]",
"for",
"start",
",",
"end",
",",
"values",
"in",
"series",
":",
"if",
"start",
"is",
"None",
"or",
"(",
"dt",
">=",
"start",
"and",
"dt",
"<=",
"end",
")",
":",
"value",
"=",
"values",
".",
"get",
"(",
"dt",
")",
"if",
"value",
"is",
"None",
":",
"cross",
"=",
"None",
"break",
"else",
":",
"value",
"=",
"nan",
"cross",
".",
"append",
"(",
"value",
")",
"if",
"cross",
":",
"cdate",
".",
"append",
"(",
"dt",
")",
"cdata",
".",
"append",
"(",
"cross",
")",
"return",
"self",
".",
"clone",
"(",
"date",
"=",
"cdate",
",",
"data",
"=",
"cdata",
")"
] | 37.980392 | 11.196078 |
def execv(self, argv, **kwargs):
"""
Starts a new process for debugging.
This method uses a list of arguments. To use a command line string
instead, use L{execl}.
@see: L{attach}, L{detach}
@type argv: list( str... )
@param argv: List of command line arguments to pass to the debugee.
The first element must be the debugee executable filename.
@type bBreakOnEntryPoint: bool
@keyword bBreakOnEntryPoint: C{True} to automatically set a breakpoint
at the program entry point.
@type bConsole: bool
@keyword bConsole: True to inherit the console of the debugger.
Defaults to C{False}.
@type bFollow: bool
@keyword bFollow: C{True} to automatically attach to child processes.
Defaults to C{False}.
@type bInheritHandles: bool
@keyword bInheritHandles: C{True} if the new process should inherit
it's parent process' handles. Defaults to C{False}.
@type bSuspended: bool
@keyword bSuspended: C{True} to suspend the main thread before any code
is executed in the debugee. Defaults to C{False}.
@keyword dwParentProcessId: C{None} or C{0} if the debugger process
should be the parent process (default), or a process ID to
forcefully set as the debugee's parent (only available for Windows
Vista and above).
In hostile mode, the default is not the debugger process but the
process ID for "explorer.exe".
@type iTrustLevel: int or None
@keyword iTrustLevel: Trust level.
Must be one of the following values:
- 0: B{No trust}. May not access certain resources, such as
cryptographic keys and credentials. Only available since
Windows XP and 2003, desktop editions. This is the default
in hostile mode.
- 1: B{Normal trust}. Run with the same privileges as a normal
user, that is, one that doesn't have the I{Administrator} or
I{Power User} user rights. Only available since Windows XP
and 2003, desktop editions.
- 2: B{Full trust}. Run with the exact same privileges as the
current user. This is the default in normal mode.
@type bAllowElevation: bool
@keyword bAllowElevation: C{True} to allow the child process to keep
UAC elevation, if the debugger itself is running elevated. C{False}
to ensure the child process doesn't run with elevation. Defaults to
C{True}.
This flag is only meaningful on Windows Vista and above, and if the
debugger itself is running with elevation. It can be used to make
sure the child processes don't run elevated as well.
This flag DOES NOT force an elevation prompt when the debugger is
not running with elevation.
Note that running the debugger with elevation (or the Python
interpreter at all for that matter) is not normally required.
You should only need to if the target program requires elevation
to work properly (for example if you try to debug an installer).
@rtype: L{Process}
@return: A new Process object. Normally you don't need to use it now,
it's best to interact with the process from the event handler.
@raise WindowsError: Raises an exception on error.
"""
if type(argv) in (str, compat.unicode):
raise TypeError("Debug.execv expects a list, not a string")
lpCmdLine = self.system.argv_to_cmdline(argv)
return self.execl(lpCmdLine, **kwargs) | [
"def",
"execv",
"(",
"self",
",",
"argv",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"type",
"(",
"argv",
")",
"in",
"(",
"str",
",",
"compat",
".",
"unicode",
")",
":",
"raise",
"TypeError",
"(",
"\"Debug.execv expects a list, not a string\"",
")",
"lpCmdLine",
"=",
"self",
".",
"system",
".",
"argv_to_cmdline",
"(",
"argv",
")",
"return",
"self",
".",
"execl",
"(",
"lpCmdLine",
",",
"*",
"*",
"kwargs",
")"
] | 45.144578 | 25.240964 |
def parse_comments_for_file(filename):
"""
Return a list of all parsed comments in a file. Mostly for testing &
interactive use.
"""
return [parse_comment(strip_stars(comment), next_line)
for comment, next_line in get_doc_comments(read_file(filename))] | [
"def",
"parse_comments_for_file",
"(",
"filename",
")",
":",
"return",
"[",
"parse_comment",
"(",
"strip_stars",
"(",
"comment",
")",
",",
"next_line",
")",
"for",
"comment",
",",
"next_line",
"in",
"get_doc_comments",
"(",
"read_file",
"(",
"filename",
")",
")",
"]"
] | 39.857143 | 15.571429 |
def assert_text_equal(self, selector, value, testid=None, **kwargs):
"""Assert that the element's text is equal to the provided value
Args:
selector (str): the selector used to find the element
value (str): the value that will be compare
with the element.text value
test_id (str): the test_id or a str
Kwargs:
wait_until_visible (bool)
highlight (bool)
Returns:
bool: True is the assertion succeed; False otherwise.
"""
self.info_log(
"Assert text equal selector(%s) testid(%s)" % (selector, testid)
)
highlight = kwargs.get(
'highlight',
BROME_CONFIG['highlight']['highlight_on_assertion_success']
)
self.debug_log("effective highlight: %s" % highlight)
wait_until_visible = kwargs.get(
'wait_until_visible',
BROME_CONFIG['proxy_driver']['wait_until_visible_before_assert_visible'] # noqa
)
self.debug_log("effective wait_until_visible: %s" % wait_until_visible)
element = self.find(
selector,
raise_exception=False,
wait_until_visible=wait_until_visible
)
if element:
if element.text == value:
if highlight:
element.highlight(
highlight=BROME_CONFIG['highlight']['style_on_assertion_success'] # noqa
)
if testid is not None:
self.create_test_result(testid, True)
return True
else:
if highlight:
element.highlight(
style=BROME_CONFIG['highlight']['style_on_assertion_failure'] # noqa
)
if testid is not None:
self.create_test_result(testid, False)
return False
else:
if testid is not None:
self.create_test_result(testid, False)
return False | [
"def",
"assert_text_equal",
"(",
"self",
",",
"selector",
",",
"value",
",",
"testid",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"self",
".",
"info_log",
"(",
"\"Assert text equal selector(%s) testid(%s)\"",
"%",
"(",
"selector",
",",
"testid",
")",
")",
"highlight",
"=",
"kwargs",
".",
"get",
"(",
"'highlight'",
",",
"BROME_CONFIG",
"[",
"'highlight'",
"]",
"[",
"'highlight_on_assertion_success'",
"]",
")",
"self",
".",
"debug_log",
"(",
"\"effective highlight: %s\"",
"%",
"highlight",
")",
"wait_until_visible",
"=",
"kwargs",
".",
"get",
"(",
"'wait_until_visible'",
",",
"BROME_CONFIG",
"[",
"'proxy_driver'",
"]",
"[",
"'wait_until_visible_before_assert_visible'",
"]",
"# noqa",
")",
"self",
".",
"debug_log",
"(",
"\"effective wait_until_visible: %s\"",
"%",
"wait_until_visible",
")",
"element",
"=",
"self",
".",
"find",
"(",
"selector",
",",
"raise_exception",
"=",
"False",
",",
"wait_until_visible",
"=",
"wait_until_visible",
")",
"if",
"element",
":",
"if",
"element",
".",
"text",
"==",
"value",
":",
"if",
"highlight",
":",
"element",
".",
"highlight",
"(",
"highlight",
"=",
"BROME_CONFIG",
"[",
"'highlight'",
"]",
"[",
"'style_on_assertion_success'",
"]",
"# noqa",
")",
"if",
"testid",
"is",
"not",
"None",
":",
"self",
".",
"create_test_result",
"(",
"testid",
",",
"True",
")",
"return",
"True",
"else",
":",
"if",
"highlight",
":",
"element",
".",
"highlight",
"(",
"style",
"=",
"BROME_CONFIG",
"[",
"'highlight'",
"]",
"[",
"'style_on_assertion_failure'",
"]",
"# noqa",
")",
"if",
"testid",
"is",
"not",
"None",
":",
"self",
".",
"create_test_result",
"(",
"testid",
",",
"False",
")",
"return",
"False",
"else",
":",
"if",
"testid",
"is",
"not",
"None",
":",
"self",
".",
"create_test_result",
"(",
"testid",
",",
"False",
")",
"return",
"False"
] | 33.47541 | 21.327869 |
def allow_migrate(self, db, model):
"""
Make sure the auth app only appears in the 'duashttp'
database.
"""
if db == DUAS_DB_ROUTE_PREFIX:
return model._meta.app_label == 'duashttp'
elif model._meta.app_label == 'duashttp':
return False
return None | [
"def",
"allow_migrate",
"(",
"self",
",",
"db",
",",
"model",
")",
":",
"if",
"db",
"==",
"DUAS_DB_ROUTE_PREFIX",
":",
"return",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'duashttp'",
"elif",
"model",
".",
"_meta",
".",
"app_label",
"==",
"'duashttp'",
":",
"return",
"False",
"return",
"None"
] | 31.9 | 11.1 |
def get(self, id):
"""id or slug"""
info = super(Images, self).get(id)
return ImageActions(self.api, parent=self, **info) | [
"def",
"get",
"(",
"self",
",",
"id",
")",
":",
"info",
"=",
"super",
"(",
"Images",
",",
"self",
")",
".",
"get",
"(",
"id",
")",
"return",
"ImageActions",
"(",
"self",
".",
"api",
",",
"parent",
"=",
"self",
",",
"*",
"*",
"info",
")"
] | 35.5 | 10.5 |
def save_or_overwrite_slice(
self, args, slc, slice_add_perm, slice_overwrite_perm, slice_download_perm,
datasource_id, datasource_type, datasource_name):
"""Save or overwrite a slice"""
slice_name = args.get('slice_name')
action = args.get('action')
form_data = get_form_data()[0]
if action in ('saveas'):
if 'slice_id' in form_data:
form_data.pop('slice_id') # don't save old slice_id
slc = models.Slice(owners=[g.user] if g.user else [])
slc.params = json.dumps(form_data, indent=2, sort_keys=True)
slc.datasource_name = datasource_name
slc.viz_type = form_data['viz_type']
slc.datasource_type = datasource_type
slc.datasource_id = datasource_id
slc.slice_name = slice_name
if action in ('saveas') and slice_add_perm:
self.save_slice(slc)
elif action == 'overwrite' and slice_overwrite_perm:
self.overwrite_slice(slc)
# Adding slice to a dashboard if requested
dash = None
if request.args.get('add_to_dash') == 'existing':
dash = (
db.session.query(models.Dashboard)
.filter_by(id=int(request.args.get('save_to_dashboard_id')))
.one()
)
# check edit dashboard permissions
dash_overwrite_perm = check_ownership(dash, raise_if_false=False)
if not dash_overwrite_perm:
return json_error_response(
_('You don\'t have the rights to ') + _('alter this ') +
_('dashboard'),
status=400)
flash(
_('Chart [{}] was added to dashboard [{}]').format(
slc.slice_name,
dash.dashboard_title),
'info')
elif request.args.get('add_to_dash') == 'new':
# check create dashboard permissions
dash_add_perm = security_manager.can_access('can_add', 'DashboardModelView')
if not dash_add_perm:
return json_error_response(
_('You don\'t have the rights to ') + _('create a ') + _('dashboard'),
status=400)
dash = models.Dashboard(
dashboard_title=request.args.get('new_dashboard_name'),
owners=[g.user] if g.user else [])
flash(
_('Dashboard [{}] just got created and chart [{}] was added '
'to it').format(
dash.dashboard_title,
slc.slice_name),
'info')
if dash and slc not in dash.slices:
dash.slices.append(slc)
db.session.commit()
response = {
'can_add': slice_add_perm,
'can_download': slice_download_perm,
'can_overwrite': is_owner(slc, g.user),
'form_data': slc.form_data,
'slice': slc.data,
'dashboard_id': dash.id if dash else None,
}
if request.args.get('goto_dash') == 'true':
response.update({'dashboard': dash.url})
return json_success(json.dumps(response)) | [
"def",
"save_or_overwrite_slice",
"(",
"self",
",",
"args",
",",
"slc",
",",
"slice_add_perm",
",",
"slice_overwrite_perm",
",",
"slice_download_perm",
",",
"datasource_id",
",",
"datasource_type",
",",
"datasource_name",
")",
":",
"slice_name",
"=",
"args",
".",
"get",
"(",
"'slice_name'",
")",
"action",
"=",
"args",
".",
"get",
"(",
"'action'",
")",
"form_data",
"=",
"get_form_data",
"(",
")",
"[",
"0",
"]",
"if",
"action",
"in",
"(",
"'saveas'",
")",
":",
"if",
"'slice_id'",
"in",
"form_data",
":",
"form_data",
".",
"pop",
"(",
"'slice_id'",
")",
"# don't save old slice_id",
"slc",
"=",
"models",
".",
"Slice",
"(",
"owners",
"=",
"[",
"g",
".",
"user",
"]",
"if",
"g",
".",
"user",
"else",
"[",
"]",
")",
"slc",
".",
"params",
"=",
"json",
".",
"dumps",
"(",
"form_data",
",",
"indent",
"=",
"2",
",",
"sort_keys",
"=",
"True",
")",
"slc",
".",
"datasource_name",
"=",
"datasource_name",
"slc",
".",
"viz_type",
"=",
"form_data",
"[",
"'viz_type'",
"]",
"slc",
".",
"datasource_type",
"=",
"datasource_type",
"slc",
".",
"datasource_id",
"=",
"datasource_id",
"slc",
".",
"slice_name",
"=",
"slice_name",
"if",
"action",
"in",
"(",
"'saveas'",
")",
"and",
"slice_add_perm",
":",
"self",
".",
"save_slice",
"(",
"slc",
")",
"elif",
"action",
"==",
"'overwrite'",
"and",
"slice_overwrite_perm",
":",
"self",
".",
"overwrite_slice",
"(",
"slc",
")",
"# Adding slice to a dashboard if requested",
"dash",
"=",
"None",
"if",
"request",
".",
"args",
".",
"get",
"(",
"'add_to_dash'",
")",
"==",
"'existing'",
":",
"dash",
"=",
"(",
"db",
".",
"session",
".",
"query",
"(",
"models",
".",
"Dashboard",
")",
".",
"filter_by",
"(",
"id",
"=",
"int",
"(",
"request",
".",
"args",
".",
"get",
"(",
"'save_to_dashboard_id'",
")",
")",
")",
".",
"one",
"(",
")",
")",
"# check edit dashboard permissions",
"dash_overwrite_perm",
"=",
"check_ownership",
"(",
"dash",
",",
"raise_if_false",
"=",
"False",
")",
"if",
"not",
"dash_overwrite_perm",
":",
"return",
"json_error_response",
"(",
"_",
"(",
"'You don\\'t have the rights to '",
")",
"+",
"_",
"(",
"'alter this '",
")",
"+",
"_",
"(",
"'dashboard'",
")",
",",
"status",
"=",
"400",
")",
"flash",
"(",
"_",
"(",
"'Chart [{}] was added to dashboard [{}]'",
")",
".",
"format",
"(",
"slc",
".",
"slice_name",
",",
"dash",
".",
"dashboard_title",
")",
",",
"'info'",
")",
"elif",
"request",
".",
"args",
".",
"get",
"(",
"'add_to_dash'",
")",
"==",
"'new'",
":",
"# check create dashboard permissions",
"dash_add_perm",
"=",
"security_manager",
".",
"can_access",
"(",
"'can_add'",
",",
"'DashboardModelView'",
")",
"if",
"not",
"dash_add_perm",
":",
"return",
"json_error_response",
"(",
"_",
"(",
"'You don\\'t have the rights to '",
")",
"+",
"_",
"(",
"'create a '",
")",
"+",
"_",
"(",
"'dashboard'",
")",
",",
"status",
"=",
"400",
")",
"dash",
"=",
"models",
".",
"Dashboard",
"(",
"dashboard_title",
"=",
"request",
".",
"args",
".",
"get",
"(",
"'new_dashboard_name'",
")",
",",
"owners",
"=",
"[",
"g",
".",
"user",
"]",
"if",
"g",
".",
"user",
"else",
"[",
"]",
")",
"flash",
"(",
"_",
"(",
"'Dashboard [{}] just got created and chart [{}] was added '",
"'to it'",
")",
".",
"format",
"(",
"dash",
".",
"dashboard_title",
",",
"slc",
".",
"slice_name",
")",
",",
"'info'",
")",
"if",
"dash",
"and",
"slc",
"not",
"in",
"dash",
".",
"slices",
":",
"dash",
".",
"slices",
".",
"append",
"(",
"slc",
")",
"db",
".",
"session",
".",
"commit",
"(",
")",
"response",
"=",
"{",
"'can_add'",
":",
"slice_add_perm",
",",
"'can_download'",
":",
"slice_download_perm",
",",
"'can_overwrite'",
":",
"is_owner",
"(",
"slc",
",",
"g",
".",
"user",
")",
",",
"'form_data'",
":",
"slc",
".",
"form_data",
",",
"'slice'",
":",
"slc",
".",
"data",
",",
"'dashboard_id'",
":",
"dash",
".",
"id",
"if",
"dash",
"else",
"None",
",",
"}",
"if",
"request",
".",
"args",
".",
"get",
"(",
"'goto_dash'",
")",
"==",
"'true'",
":",
"response",
".",
"update",
"(",
"{",
"'dashboard'",
":",
"dash",
".",
"url",
"}",
")",
"return",
"json_success",
"(",
"json",
".",
"dumps",
"(",
"response",
")",
")"
] | 38.47561 | 17.414634 |
async def process_lander_page(session, github_api_token, ltd_product_data,
mongo_collection=None):
"""Extract, transform, and load metadata from Lander-based projects.
Parameters
----------
session : `aiohttp.ClientSession`
Your application's aiohttp client session.
See http://aiohttp.readthedocs.io/en/stable/client.html.
github_api_token : `str`
A GitHub personal API token. See the `GitHub personal access token
guide`_.
ltd_product_data : `dict`
Contents of ``metadata.yaml``, obtained via `download_metadata_yaml`.
Data for this technote from the LTD Keeper API
(``GET /products/<slug>``). Usually obtained via
`lsstprojectmeta.ltd.get_ltd_product`.
mongo_collection : `motor.motor_asyncio.AsyncIOMotorCollection`, optional
MongoDB collection. This should be the common MongoDB collection for
LSST projectmeta JSON-LD records. If provided, ths JSON-LD is upserted
into the MongoDB collection.
Returns
-------
metadata : `dict`
JSON-LD-formatted dictionary.
Raises
------
NotLanderPageError
Raised when the LTD product cannot be interpreted as a Lander page
because the ``/metadata.jsonld`` file is absent. This implies that
the LTD product *could* be of a different format.
.. `GitHub personal access token guide`: https://ls.st/41d
"""
logger = logging.getLogger(__name__)
# Try to download metadata.jsonld from the Landing page site.
published_url = ltd_product_data['published_url']
jsonld_url = urljoin(published_url, '/metadata.jsonld')
try:
async with session.get(jsonld_url) as response:
logger.debug('%s response status %r', jsonld_url, response.status)
response.raise_for_status()
json_data = await response.text()
except aiohttp.ClientResponseError as err:
logger.debug('Tried to download %s, got status %d',
jsonld_url, err.code)
raise NotLanderPageError()
# Use our own json parser to get datetimes
metadata = decode_jsonld(json_data)
if mongo_collection is not None:
await _upload_to_mongodb(mongo_collection, metadata)
return metadata | [
"async",
"def",
"process_lander_page",
"(",
"session",
",",
"github_api_token",
",",
"ltd_product_data",
",",
"mongo_collection",
"=",
"None",
")",
":",
"logger",
"=",
"logging",
".",
"getLogger",
"(",
"__name__",
")",
"# Try to download metadata.jsonld from the Landing page site.",
"published_url",
"=",
"ltd_product_data",
"[",
"'published_url'",
"]",
"jsonld_url",
"=",
"urljoin",
"(",
"published_url",
",",
"'/metadata.jsonld'",
")",
"try",
":",
"async",
"with",
"session",
".",
"get",
"(",
"jsonld_url",
")",
"as",
"response",
":",
"logger",
".",
"debug",
"(",
"'%s response status %r'",
",",
"jsonld_url",
",",
"response",
".",
"status",
")",
"response",
".",
"raise_for_status",
"(",
")",
"json_data",
"=",
"await",
"response",
".",
"text",
"(",
")",
"except",
"aiohttp",
".",
"ClientResponseError",
"as",
"err",
":",
"logger",
".",
"debug",
"(",
"'Tried to download %s, got status %d'",
",",
"jsonld_url",
",",
"err",
".",
"code",
")",
"raise",
"NotLanderPageError",
"(",
")",
"# Use our own json parser to get datetimes",
"metadata",
"=",
"decode_jsonld",
"(",
"json_data",
")",
"if",
"mongo_collection",
"is",
"not",
"None",
":",
"await",
"_upload_to_mongodb",
"(",
"mongo_collection",
",",
"metadata",
")",
"return",
"metadata"
] | 39.368421 | 20.754386 |
def relation_path_for(from_name, to_name, identifier_type, identifier_key=None):
"""
Get a path relating a thing to another.
"""
return "/{}/<{}:{}>/{}".format(
name_for(from_name),
identifier_type,
identifier_key or "{}_id".format(name_for(from_name)),
name_for(to_name),
) | [
"def",
"relation_path_for",
"(",
"from_name",
",",
"to_name",
",",
"identifier_type",
",",
"identifier_key",
"=",
"None",
")",
":",
"return",
"\"/{}/<{}:{}>/{}\"",
".",
"format",
"(",
"name_for",
"(",
"from_name",
")",
",",
"identifier_type",
",",
"identifier_key",
"or",
"\"{}_id\"",
".",
"format",
"(",
"name_for",
"(",
"from_name",
")",
")",
",",
"name_for",
"(",
"to_name",
")",
",",
")"
] | 28.818182 | 17 |
def associate_notification_template(self, job_template,
notification_template, status):
"""Associate a notification template from this job template.
=====API DOCS=====
Associate a notification template from this job template.
:param job_template: The job template to associate to.
:type job_template: str
:param notification_template: The notification template to be associated.
:type notification_template: str
:param status: type of notification this notification template should be associated to.
:type status: str
:returns: Dictionary of only one key "changed", which indicates whether the association succeeded.
:rtype: dict
=====API DOCS=====
"""
return self._assoc('notification_templates_%s' % status,
job_template, notification_template) | [
"def",
"associate_notification_template",
"(",
"self",
",",
"job_template",
",",
"notification_template",
",",
"status",
")",
":",
"return",
"self",
".",
"_assoc",
"(",
"'notification_templates_%s'",
"%",
"status",
",",
"job_template",
",",
"notification_template",
")"
] | 45.45 | 24.7 |
def parse(cls, src, dist=None):
"""Parse a single entry point from string `src`
Entry point syntax follows the form::
name = some.module:some.attr [extra1,extra2]
The entry name and module name are required, but the ``:attrs`` and
``[extras]`` parts are optional
"""
try:
attrs = extras = ()
name,value = src.split('=',1)
if '[' in value:
value,extras = value.split('[',1)
req = Requirement.parse("x["+extras)
if req.specs: raise ValueError
extras = req.extras
if ':' in value:
value,attrs = value.split(':',1)
if not MODULE(attrs.rstrip()):
raise ValueError
attrs = attrs.rstrip().split('.')
except ValueError:
raise ValueError(
"EntryPoint must be in 'name=module:attrs [extras]' format",
src
)
else:
return cls(name.strip(), value.strip(), attrs, extras, dist) | [
"def",
"parse",
"(",
"cls",
",",
"src",
",",
"dist",
"=",
"None",
")",
":",
"try",
":",
"attrs",
"=",
"extras",
"=",
"(",
")",
"name",
",",
"value",
"=",
"src",
".",
"split",
"(",
"'='",
",",
"1",
")",
"if",
"'['",
"in",
"value",
":",
"value",
",",
"extras",
"=",
"value",
".",
"split",
"(",
"'['",
",",
"1",
")",
"req",
"=",
"Requirement",
".",
"parse",
"(",
"\"x[\"",
"+",
"extras",
")",
"if",
"req",
".",
"specs",
":",
"raise",
"ValueError",
"extras",
"=",
"req",
".",
"extras",
"if",
"':'",
"in",
"value",
":",
"value",
",",
"attrs",
"=",
"value",
".",
"split",
"(",
"':'",
",",
"1",
")",
"if",
"not",
"MODULE",
"(",
"attrs",
".",
"rstrip",
"(",
")",
")",
":",
"raise",
"ValueError",
"attrs",
"=",
"attrs",
".",
"rstrip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"except",
"ValueError",
":",
"raise",
"ValueError",
"(",
"\"EntryPoint must be in 'name=module:attrs [extras]' format\"",
",",
"src",
")",
"else",
":",
"return",
"cls",
"(",
"name",
".",
"strip",
"(",
")",
",",
"value",
".",
"strip",
"(",
")",
",",
"attrs",
",",
"extras",
",",
"dist",
")"
] | 35.366667 | 15.833333 |
def create_entity_type(self,
parent,
entity_type,
language_code=None,
retry=google.api_core.gapic_v1.method.DEFAULT,
timeout=google.api_core.gapic_v1.method.DEFAULT,
metadata=None):
"""
Creates an entity type in the specified agent.
Example:
>>> import dialogflow_v2
>>>
>>> client = dialogflow_v2.EntityTypesClient()
>>>
>>> parent = client.project_agent_path('[PROJECT]')
>>>
>>> # TODO: Initialize ``entity_type``:
>>> entity_type = {}
>>>
>>> response = client.create_entity_type(parent, entity_type)
Args:
parent (str): Required. The agent to create a entity type for.
Format: ``projects/<Project ID>/agent``.
entity_type (Union[dict, ~google.cloud.dialogflow_v2.types.EntityType]): Required. The entity type to create.
If a dict is provided, it must be of the same form as the protobuf
message :class:`~google.cloud.dialogflow_v2.types.EntityType`
language_code (str): Optional. The language of entity synonyms defined in ``entity_type``. If not
specified, the agent's default language is used.
[More than a dozen
languages](https://dialogflow.com/docs/reference/language) are supported.
Note: languages must be enabled in the agent, before they can be used.
retry (Optional[google.api_core.retry.Retry]): A retry object used
to retry requests. If ``None`` is specified, requests will not
be retried.
timeout (Optional[float]): The amount of time, in seconds, to wait
for the request to complete. Note that if ``retry`` is
specified, the timeout applies to each individual attempt.
metadata (Optional[Sequence[Tuple[str, str]]]): Additional metadata
that is provided to the method.
Returns:
A :class:`~google.cloud.dialogflow_v2.types.EntityType` instance.
Raises:
google.api_core.exceptions.GoogleAPICallError: If the request
failed for any reason.
google.api_core.exceptions.RetryError: If the request failed due
to a retryable error and retry attempts failed.
ValueError: If the parameters are invalid.
"""
# Wrap the transport method to add retry and timeout logic.
if 'create_entity_type' not in self._inner_api_calls:
self._inner_api_calls[
'create_entity_type'] = google.api_core.gapic_v1.method.wrap_method(
self.transport.create_entity_type,
default_retry=self._method_configs[
'CreateEntityType'].retry,
default_timeout=self._method_configs['CreateEntityType']
.timeout,
client_info=self._client_info,
)
request = entity_type_pb2.CreateEntityTypeRequest(
parent=parent,
entity_type=entity_type,
language_code=language_code,
)
return self._inner_api_calls['create_entity_type'](
request, retry=retry, timeout=timeout, metadata=metadata) | [
"def",
"create_entity_type",
"(",
"self",
",",
"parent",
",",
"entity_type",
",",
"language_code",
"=",
"None",
",",
"retry",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"timeout",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"DEFAULT",
",",
"metadata",
"=",
"None",
")",
":",
"# Wrap the transport method to add retry and timeout logic.",
"if",
"'create_entity_type'",
"not",
"in",
"self",
".",
"_inner_api_calls",
":",
"self",
".",
"_inner_api_calls",
"[",
"'create_entity_type'",
"]",
"=",
"google",
".",
"api_core",
".",
"gapic_v1",
".",
"method",
".",
"wrap_method",
"(",
"self",
".",
"transport",
".",
"create_entity_type",
",",
"default_retry",
"=",
"self",
".",
"_method_configs",
"[",
"'CreateEntityType'",
"]",
".",
"retry",
",",
"default_timeout",
"=",
"self",
".",
"_method_configs",
"[",
"'CreateEntityType'",
"]",
".",
"timeout",
",",
"client_info",
"=",
"self",
".",
"_client_info",
",",
")",
"request",
"=",
"entity_type_pb2",
".",
"CreateEntityTypeRequest",
"(",
"parent",
"=",
"parent",
",",
"entity_type",
"=",
"entity_type",
",",
"language_code",
"=",
"language_code",
",",
")",
"return",
"self",
".",
"_inner_api_calls",
"[",
"'create_entity_type'",
"]",
"(",
"request",
",",
"retry",
"=",
"retry",
",",
"timeout",
"=",
"timeout",
",",
"metadata",
"=",
"metadata",
")"
] | 48.352113 | 24.352113 |
def set_data(self, index, data):
"""Set the complete data for a single line strip.
Parameters
----------
index : int
The index of the line strip to be replaced.
data : array-like
The data to assign to the selected line strip.
"""
self._pos_tex[index, :] = data
self.update() | [
"def",
"set_data",
"(",
"self",
",",
"index",
",",
"data",
")",
":",
"self",
".",
"_pos_tex",
"[",
"index",
",",
":",
"]",
"=",
"data",
"self",
".",
"update",
"(",
")"
] | 30 | 14.5 |
def paga_compare_paths(adata1, adata2,
adjacency_key='connectivities', adjacency_key2=None):
"""Compare paths in abstracted graphs in two datasets.
Compute the fraction of consistent paths between leafs, a measure for the
topological similarity between graphs.
By increasing the verbosity to level 4 and 5, the paths that do not agree
and the paths that agree are written to the output, respectively.
The PAGA "groups key" needs to be the same in both objects.
Parameters
----------
adata1, adata2 : AnnData
Annotated data matrices to compare.
adjacency_key : str
Key for indexing the adjacency matrices in `.uns['paga']` to be used in
adata1 and adata2.
adjacency_key2 : str, None
If provided, used for adata2.
Returns
-------
OrderedTuple with attributes ``n_steps`` (total number of steps in paths)
and ``frac_steps`` (fraction of consistent steps), ``n_paths`` and
``frac_paths``.
"""
import networkx as nx
g1 = nx.Graph(adata1.uns['paga'][adjacency_key])
g2 = nx.Graph(adata2.uns['paga'][adjacency_key2 if adjacency_key2 is not None else adjacency_key])
leaf_nodes1 = [str(x) for x in g1.nodes() if g1.degree(x) == 1]
logg.msg('leaf nodes in graph 1: {}'.format(leaf_nodes1), v=5, no_indent=True)
paga_groups = adata1.uns['paga']['groups']
asso_groups1 = utils.identify_groups(adata1.obs[paga_groups].values,
adata2.obs[paga_groups].values)
asso_groups2 = utils.identify_groups(adata2.obs[paga_groups].values,
adata1.obs[paga_groups].values)
orig_names1 = adata1.obs[paga_groups].cat.categories
orig_names2 = adata2.obs[paga_groups].cat.categories
import itertools
n_steps = 0
n_agreeing_steps = 0
n_paths = 0
n_agreeing_paths = 0
# loop over all pairs of leaf nodes in the reference adata1
for (r, s) in itertools.combinations(leaf_nodes1, r=2):
r2, s2 = asso_groups1[r][0], asso_groups1[s][0]
orig_names = [orig_names1[int(i)] for i in [r, s]]
orig_names += [orig_names2[int(i)] for i in [r2, s2]]
logg.msg('compare shortest paths between leafs ({}, {}) in graph1 and ({}, {}) in graph2:'
.format(*orig_names), v=4, no_indent=True)
no_path1 = False
try:
path1 = [str(x) for x in nx.shortest_path(g1, int(r), int(s))]
except nx.NetworkXNoPath:
no_path1 = True
no_path2 = False
try:
path2 = [str(x) for x in nx.shortest_path(g2, int(r2), int(s2))]
except nx.NetworkXNoPath:
no_path2 = True
if no_path1 and no_path2:
# consistent behavior
n_paths += 1
n_agreeing_paths += 1
n_steps += 1
n_agreeing_steps += 1
logg.msg('there are no connecting paths in both graphs', v=5, no_indent=True)
continue
elif no_path1 or no_path2:
# non-consistent result
n_paths += 1
n_steps += 1
continue
if len(path1) >= len(path2):
path_mapped = [asso_groups1[l] for l in path1]
path_compare = path2
path_compare_id = 2
path_compare_orig_names = [[orig_names2[int(s)] for s in l] for l in path_compare]
path_mapped_orig_names = [[orig_names2[int(s)] for s in l] for l in path_mapped]
else:
path_mapped = [asso_groups2[l] for l in path2]
path_compare = path1
path_compare_id = 1
path_compare_orig_names = [[orig_names1[int(s)] for s in l] for l in path_compare]
path_mapped_orig_names = [[orig_names1[int(s)] for s in l] for l in path_mapped]
n_agreeing_steps_path = 0
ip_progress = 0
for il, l in enumerate(path_compare[:-1]):
for ip, p in enumerate(path_mapped):
if ip >= ip_progress and l in p:
# check whether we can find the step forward of path_compare in path_mapped
if (ip + 1 < len(path_mapped)
and
path_compare[il + 1] in path_mapped[ip + 1]):
# make sure that a step backward leads us to the same value of l
# in case we "jumped"
logg.msg('found matching step ({} -> {}) at position {} in path{} and position {} in path_mapped'
.format(l, path_compare_orig_names[il + 1], il, path_compare_id, ip), v=6)
consistent_history = True
for iip in range(ip, ip_progress, -1):
if l not in path_mapped[iip - 1]:
consistent_history = False
if consistent_history:
# here, we take one step further back (ip_progress - 1); it's implied that this
# was ok in the previous step
logg.msg(' step(s) backward to position(s) {} in path_mapped are fine, too: valid step'
.format(list(range(ip - 1, ip_progress - 2, -1))), v=6)
n_agreeing_steps_path += 1
ip_progress = ip + 1
break
n_steps_path = len(path_compare) - 1
n_agreeing_steps += n_agreeing_steps_path
n_steps += n_steps_path
n_paths += 1
if n_agreeing_steps_path == n_steps_path: n_agreeing_paths += 1
# only for the output, use original names
path1_orig_names = [orig_names1[int(s)] for s in path1]
path2_orig_names = [orig_names2[int(s)] for s in path2]
logg.msg(' path1 = {},\n'
'path_mapped = {},\n'
' path2 = {},\n'
'-> n_agreeing_steps = {} / n_steps = {}.'
.format(path1_orig_names,
[list(p) for p in path_mapped_orig_names],
path2_orig_names,
n_agreeing_steps_path, n_steps_path), v=5, no_indent=True)
Result = namedtuple('paga_compare_paths_result',
['frac_steps', 'n_steps', 'frac_paths', 'n_paths'])
return Result(frac_steps=n_agreeing_steps/n_steps if n_steps > 0 else np.nan,
n_steps=n_steps if n_steps > 0 else np.nan,
frac_paths=n_agreeing_paths/n_paths if n_steps > 0 else np.nan,
n_paths=n_paths if n_steps > 0 else np.nan) | [
"def",
"paga_compare_paths",
"(",
"adata1",
",",
"adata2",
",",
"adjacency_key",
"=",
"'connectivities'",
",",
"adjacency_key2",
"=",
"None",
")",
":",
"import",
"networkx",
"as",
"nx",
"g1",
"=",
"nx",
".",
"Graph",
"(",
"adata1",
".",
"uns",
"[",
"'paga'",
"]",
"[",
"adjacency_key",
"]",
")",
"g2",
"=",
"nx",
".",
"Graph",
"(",
"adata2",
".",
"uns",
"[",
"'paga'",
"]",
"[",
"adjacency_key2",
"if",
"adjacency_key2",
"is",
"not",
"None",
"else",
"adjacency_key",
"]",
")",
"leaf_nodes1",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"g1",
".",
"nodes",
"(",
")",
"if",
"g1",
".",
"degree",
"(",
"x",
")",
"==",
"1",
"]",
"logg",
".",
"msg",
"(",
"'leaf nodes in graph 1: {}'",
".",
"format",
"(",
"leaf_nodes1",
")",
",",
"v",
"=",
"5",
",",
"no_indent",
"=",
"True",
")",
"paga_groups",
"=",
"adata1",
".",
"uns",
"[",
"'paga'",
"]",
"[",
"'groups'",
"]",
"asso_groups1",
"=",
"utils",
".",
"identify_groups",
"(",
"adata1",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"values",
",",
"adata2",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"values",
")",
"asso_groups2",
"=",
"utils",
".",
"identify_groups",
"(",
"adata2",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"values",
",",
"adata1",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"values",
")",
"orig_names1",
"=",
"adata1",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"cat",
".",
"categories",
"orig_names2",
"=",
"adata2",
".",
"obs",
"[",
"paga_groups",
"]",
".",
"cat",
".",
"categories",
"import",
"itertools",
"n_steps",
"=",
"0",
"n_agreeing_steps",
"=",
"0",
"n_paths",
"=",
"0",
"n_agreeing_paths",
"=",
"0",
"# loop over all pairs of leaf nodes in the reference adata1",
"for",
"(",
"r",
",",
"s",
")",
"in",
"itertools",
".",
"combinations",
"(",
"leaf_nodes1",
",",
"r",
"=",
"2",
")",
":",
"r2",
",",
"s2",
"=",
"asso_groups1",
"[",
"r",
"]",
"[",
"0",
"]",
",",
"asso_groups1",
"[",
"s",
"]",
"[",
"0",
"]",
"orig_names",
"=",
"[",
"orig_names1",
"[",
"int",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"[",
"r",
",",
"s",
"]",
"]",
"orig_names",
"+=",
"[",
"orig_names2",
"[",
"int",
"(",
"i",
")",
"]",
"for",
"i",
"in",
"[",
"r2",
",",
"s2",
"]",
"]",
"logg",
".",
"msg",
"(",
"'compare shortest paths between leafs ({}, {}) in graph1 and ({}, {}) in graph2:'",
".",
"format",
"(",
"*",
"orig_names",
")",
",",
"v",
"=",
"4",
",",
"no_indent",
"=",
"True",
")",
"no_path1",
"=",
"False",
"try",
":",
"path1",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"nx",
".",
"shortest_path",
"(",
"g1",
",",
"int",
"(",
"r",
")",
",",
"int",
"(",
"s",
")",
")",
"]",
"except",
"nx",
".",
"NetworkXNoPath",
":",
"no_path1",
"=",
"True",
"no_path2",
"=",
"False",
"try",
":",
"path2",
"=",
"[",
"str",
"(",
"x",
")",
"for",
"x",
"in",
"nx",
".",
"shortest_path",
"(",
"g2",
",",
"int",
"(",
"r2",
")",
",",
"int",
"(",
"s2",
")",
")",
"]",
"except",
"nx",
".",
"NetworkXNoPath",
":",
"no_path2",
"=",
"True",
"if",
"no_path1",
"and",
"no_path2",
":",
"# consistent behavior",
"n_paths",
"+=",
"1",
"n_agreeing_paths",
"+=",
"1",
"n_steps",
"+=",
"1",
"n_agreeing_steps",
"+=",
"1",
"logg",
".",
"msg",
"(",
"'there are no connecting paths in both graphs'",
",",
"v",
"=",
"5",
",",
"no_indent",
"=",
"True",
")",
"continue",
"elif",
"no_path1",
"or",
"no_path2",
":",
"# non-consistent result",
"n_paths",
"+=",
"1",
"n_steps",
"+=",
"1",
"continue",
"if",
"len",
"(",
"path1",
")",
">=",
"len",
"(",
"path2",
")",
":",
"path_mapped",
"=",
"[",
"asso_groups1",
"[",
"l",
"]",
"for",
"l",
"in",
"path1",
"]",
"path_compare",
"=",
"path2",
"path_compare_id",
"=",
"2",
"path_compare_orig_names",
"=",
"[",
"[",
"orig_names2",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"l",
"]",
"for",
"l",
"in",
"path_compare",
"]",
"path_mapped_orig_names",
"=",
"[",
"[",
"orig_names2",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"l",
"]",
"for",
"l",
"in",
"path_mapped",
"]",
"else",
":",
"path_mapped",
"=",
"[",
"asso_groups2",
"[",
"l",
"]",
"for",
"l",
"in",
"path2",
"]",
"path_compare",
"=",
"path1",
"path_compare_id",
"=",
"1",
"path_compare_orig_names",
"=",
"[",
"[",
"orig_names1",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"l",
"]",
"for",
"l",
"in",
"path_compare",
"]",
"path_mapped_orig_names",
"=",
"[",
"[",
"orig_names1",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"l",
"]",
"for",
"l",
"in",
"path_mapped",
"]",
"n_agreeing_steps_path",
"=",
"0",
"ip_progress",
"=",
"0",
"for",
"il",
",",
"l",
"in",
"enumerate",
"(",
"path_compare",
"[",
":",
"-",
"1",
"]",
")",
":",
"for",
"ip",
",",
"p",
"in",
"enumerate",
"(",
"path_mapped",
")",
":",
"if",
"ip",
">=",
"ip_progress",
"and",
"l",
"in",
"p",
":",
"# check whether we can find the step forward of path_compare in path_mapped",
"if",
"(",
"ip",
"+",
"1",
"<",
"len",
"(",
"path_mapped",
")",
"and",
"path_compare",
"[",
"il",
"+",
"1",
"]",
"in",
"path_mapped",
"[",
"ip",
"+",
"1",
"]",
")",
":",
"# make sure that a step backward leads us to the same value of l",
"# in case we \"jumped\"",
"logg",
".",
"msg",
"(",
"'found matching step ({} -> {}) at position {} in path{} and position {} in path_mapped'",
".",
"format",
"(",
"l",
",",
"path_compare_orig_names",
"[",
"il",
"+",
"1",
"]",
",",
"il",
",",
"path_compare_id",
",",
"ip",
")",
",",
"v",
"=",
"6",
")",
"consistent_history",
"=",
"True",
"for",
"iip",
"in",
"range",
"(",
"ip",
",",
"ip_progress",
",",
"-",
"1",
")",
":",
"if",
"l",
"not",
"in",
"path_mapped",
"[",
"iip",
"-",
"1",
"]",
":",
"consistent_history",
"=",
"False",
"if",
"consistent_history",
":",
"# here, we take one step further back (ip_progress - 1); it's implied that this",
"# was ok in the previous step",
"logg",
".",
"msg",
"(",
"' step(s) backward to position(s) {} in path_mapped are fine, too: valid step'",
".",
"format",
"(",
"list",
"(",
"range",
"(",
"ip",
"-",
"1",
",",
"ip_progress",
"-",
"2",
",",
"-",
"1",
")",
")",
")",
",",
"v",
"=",
"6",
")",
"n_agreeing_steps_path",
"+=",
"1",
"ip_progress",
"=",
"ip",
"+",
"1",
"break",
"n_steps_path",
"=",
"len",
"(",
"path_compare",
")",
"-",
"1",
"n_agreeing_steps",
"+=",
"n_agreeing_steps_path",
"n_steps",
"+=",
"n_steps_path",
"n_paths",
"+=",
"1",
"if",
"n_agreeing_steps_path",
"==",
"n_steps_path",
":",
"n_agreeing_paths",
"+=",
"1",
"# only for the output, use original names",
"path1_orig_names",
"=",
"[",
"orig_names1",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"path1",
"]",
"path2_orig_names",
"=",
"[",
"orig_names2",
"[",
"int",
"(",
"s",
")",
"]",
"for",
"s",
"in",
"path2",
"]",
"logg",
".",
"msg",
"(",
"' path1 = {},\\n'",
"'path_mapped = {},\\n'",
"' path2 = {},\\n'",
"'-> n_agreeing_steps = {} / n_steps = {}.'",
".",
"format",
"(",
"path1_orig_names",
",",
"[",
"list",
"(",
"p",
")",
"for",
"p",
"in",
"path_mapped_orig_names",
"]",
",",
"path2_orig_names",
",",
"n_agreeing_steps_path",
",",
"n_steps_path",
")",
",",
"v",
"=",
"5",
",",
"no_indent",
"=",
"True",
")",
"Result",
"=",
"namedtuple",
"(",
"'paga_compare_paths_result'",
",",
"[",
"'frac_steps'",
",",
"'n_steps'",
",",
"'frac_paths'",
",",
"'n_paths'",
"]",
")",
"return",
"Result",
"(",
"frac_steps",
"=",
"n_agreeing_steps",
"/",
"n_steps",
"if",
"n_steps",
">",
"0",
"else",
"np",
".",
"nan",
",",
"n_steps",
"=",
"n_steps",
"if",
"n_steps",
">",
"0",
"else",
"np",
".",
"nan",
",",
"frac_paths",
"=",
"n_agreeing_paths",
"/",
"n_paths",
"if",
"n_steps",
">",
"0",
"else",
"np",
".",
"nan",
",",
"n_paths",
"=",
"n_paths",
"if",
"n_steps",
">",
"0",
"else",
"np",
".",
"nan",
")"
] | 47.59854 | 22.963504 |
def build(obj: Dict[str, Any], *fns: Callable[..., Any]) -> Dict[str, Any]:
"""
Wrapper function to pipe manifest through build functions.
Does not validate the manifest by default.
"""
return pipe(obj, *fns) | [
"def",
"build",
"(",
"obj",
":",
"Dict",
"[",
"str",
",",
"Any",
"]",
",",
"*",
"fns",
":",
"Callable",
"[",
"...",
",",
"Any",
"]",
")",
"->",
"Dict",
"[",
"str",
",",
"Any",
"]",
":",
"return",
"pipe",
"(",
"obj",
",",
"*",
"fns",
")"
] | 37.166667 | 12.833333 |
def main():
"""The main function of the module.
These are the steps:
1. Reads the population file (:py:func:`readPopulations`).
2. Extracts the MDS values (:py:func:`extractData`).
3. Plots the MDS values (:py:func:`plotMDS`).
"""
# Getting and checking the options
args = parseArgs()
checkArgs(args)
# Reads the population file
populations = readPopulations(args.population_file, args.population_order)
# Acquire the data
theData, theLabels = extractData(args.file, populations,
args.population_order, args.xaxis,
args.yaxis)
# Plot the data
plotMDS(theData, args.population_order, theLabels, args.population_colors,
args.population_alpha, args.population_sizes,
args.population_markers, args) | [
"def",
"main",
"(",
")",
":",
"# Getting and checking the options",
"args",
"=",
"parseArgs",
"(",
")",
"checkArgs",
"(",
"args",
")",
"# Reads the population file",
"populations",
"=",
"readPopulations",
"(",
"args",
".",
"population_file",
",",
"args",
".",
"population_order",
")",
"# Acquire the data",
"theData",
",",
"theLabels",
"=",
"extractData",
"(",
"args",
".",
"file",
",",
"populations",
",",
"args",
".",
"population_order",
",",
"args",
".",
"xaxis",
",",
"args",
".",
"yaxis",
")",
"# Plot the data",
"plotMDS",
"(",
"theData",
",",
"args",
".",
"population_order",
",",
"theLabels",
",",
"args",
".",
"population_colors",
",",
"args",
".",
"population_alpha",
",",
"args",
".",
"population_sizes",
",",
"args",
".",
"population_markers",
",",
"args",
")"
] | 32.038462 | 22.115385 |
def is_line_layer(layer):
"""Check if a QGIS layer is vector and its geometries are lines.
:param layer: A vector layer.
:type layer: QgsVectorLayer, QgsMapLayer
:returns: True if the layer contains lines, otherwise False.
:rtype: bool
"""
try:
return (layer.type() == QgsMapLayer.VectorLayer) and (
layer.geometryType() == QgsWkbTypes.LineGeometry)
except AttributeError:
return False | [
"def",
"is_line_layer",
"(",
"layer",
")",
":",
"try",
":",
"return",
"(",
"layer",
".",
"type",
"(",
")",
"==",
"QgsMapLayer",
".",
"VectorLayer",
")",
"and",
"(",
"layer",
".",
"geometryType",
"(",
")",
"==",
"QgsWkbTypes",
".",
"LineGeometry",
")",
"except",
"AttributeError",
":",
"return",
"False"
] | 28.933333 | 20.2 |
def record_take(self, model, env_instance, device, take_number):
""" Record a single movie and store it on hard drive """
frames = []
observation = env_instance.reset()
if model.is_recurrent:
hidden_state = model.zero_state(1).to(device)
frames.append(env_instance.render('rgb_array'))
print("Evaluating environment...")
while True:
observation_array = np.expand_dims(np.array(observation), axis=0)
observation_tensor = torch.from_numpy(observation_array).to(device)
if model.is_recurrent:
output = model.step(observation_tensor, hidden_state, **self.sample_args)
hidden_state = output['state']
actions = output['actions']
else:
actions = model.step(observation_tensor, **self.sample_args)['actions']
actions = actions.detach().cpu().numpy()
observation, reward, done, epinfo = env_instance.step(actions[0])
frames.append(env_instance.render('rgb_array'))
if 'episode' in epinfo:
# End of an episode
break
takename = self.model_config.output_dir('videos', self.model_config.run_name, self.videoname.format(take_number))
pathlib.Path(os.path.dirname(takename)).mkdir(parents=True, exist_ok=True)
fourcc = cv2.VideoWriter_fourcc('M', 'J', 'P', 'G')
video = cv2.VideoWriter(takename, fourcc, self.fps, (frames[0].shape[1], frames[0].shape[0]))
for i in tqdm.trange(len(frames), file=sys.stdout):
video.write(cv2.cvtColor(frames[i], cv2.COLOR_RGB2BGR))
video.release()
print("Written {}".format(takename)) | [
"def",
"record_take",
"(",
"self",
",",
"model",
",",
"env_instance",
",",
"device",
",",
"take_number",
")",
":",
"frames",
"=",
"[",
"]",
"observation",
"=",
"env_instance",
".",
"reset",
"(",
")",
"if",
"model",
".",
"is_recurrent",
":",
"hidden_state",
"=",
"model",
".",
"zero_state",
"(",
"1",
")",
".",
"to",
"(",
"device",
")",
"frames",
".",
"append",
"(",
"env_instance",
".",
"render",
"(",
"'rgb_array'",
")",
")",
"print",
"(",
"\"Evaluating environment...\"",
")",
"while",
"True",
":",
"observation_array",
"=",
"np",
".",
"expand_dims",
"(",
"np",
".",
"array",
"(",
"observation",
")",
",",
"axis",
"=",
"0",
")",
"observation_tensor",
"=",
"torch",
".",
"from_numpy",
"(",
"observation_array",
")",
".",
"to",
"(",
"device",
")",
"if",
"model",
".",
"is_recurrent",
":",
"output",
"=",
"model",
".",
"step",
"(",
"observation_tensor",
",",
"hidden_state",
",",
"*",
"*",
"self",
".",
"sample_args",
")",
"hidden_state",
"=",
"output",
"[",
"'state'",
"]",
"actions",
"=",
"output",
"[",
"'actions'",
"]",
"else",
":",
"actions",
"=",
"model",
".",
"step",
"(",
"observation_tensor",
",",
"*",
"*",
"self",
".",
"sample_args",
")",
"[",
"'actions'",
"]",
"actions",
"=",
"actions",
".",
"detach",
"(",
")",
".",
"cpu",
"(",
")",
".",
"numpy",
"(",
")",
"observation",
",",
"reward",
",",
"done",
",",
"epinfo",
"=",
"env_instance",
".",
"step",
"(",
"actions",
"[",
"0",
"]",
")",
"frames",
".",
"append",
"(",
"env_instance",
".",
"render",
"(",
"'rgb_array'",
")",
")",
"if",
"'episode'",
"in",
"epinfo",
":",
"# End of an episode",
"break",
"takename",
"=",
"self",
".",
"model_config",
".",
"output_dir",
"(",
"'videos'",
",",
"self",
".",
"model_config",
".",
"run_name",
",",
"self",
".",
"videoname",
".",
"format",
"(",
"take_number",
")",
")",
"pathlib",
".",
"Path",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"takename",
")",
")",
".",
"mkdir",
"(",
"parents",
"=",
"True",
",",
"exist_ok",
"=",
"True",
")",
"fourcc",
"=",
"cv2",
".",
"VideoWriter_fourcc",
"(",
"'M'",
",",
"'J'",
",",
"'P'",
",",
"'G'",
")",
"video",
"=",
"cv2",
".",
"VideoWriter",
"(",
"takename",
",",
"fourcc",
",",
"self",
".",
"fps",
",",
"(",
"frames",
"[",
"0",
"]",
".",
"shape",
"[",
"1",
"]",
",",
"frames",
"[",
"0",
"]",
".",
"shape",
"[",
"0",
"]",
")",
")",
"for",
"i",
"in",
"tqdm",
".",
"trange",
"(",
"len",
"(",
"frames",
")",
",",
"file",
"=",
"sys",
".",
"stdout",
")",
":",
"video",
".",
"write",
"(",
"cv2",
".",
"cvtColor",
"(",
"frames",
"[",
"i",
"]",
",",
"cv2",
".",
"COLOR_RGB2BGR",
")",
")",
"video",
".",
"release",
"(",
")",
"print",
"(",
"\"Written {}\"",
".",
"format",
"(",
"takename",
")",
")"
] | 37.755556 | 27.755556 |
def _repack_options(options):
'''
Repack the options data
'''
return dict(
[
(six.text_type(x), _normalize(y))
for x, y in six.iteritems(salt.utils.data.repack_dictlist(options))
]
) | [
"def",
"_repack_options",
"(",
"options",
")",
":",
"return",
"dict",
"(",
"[",
"(",
"six",
".",
"text_type",
"(",
"x",
")",
",",
"_normalize",
"(",
"y",
")",
")",
"for",
"x",
",",
"y",
"in",
"six",
".",
"iteritems",
"(",
"salt",
".",
"utils",
".",
"data",
".",
"repack_dictlist",
"(",
"options",
")",
")",
"]",
")"
] | 23.3 | 25.5 |
def _paint_margins(self, event):
""" Paints the right margin after editor paint event. """
font = QtGui.QFont(self.editor.font_name, self.editor.font_size +
self.editor.zoom_level)
metrics = QtGui.QFontMetricsF(font)
painter = QtGui.QPainter(self.editor.viewport())
for pos, pen in zip(self._positions, self._pens):
if pos < 0:
# margin not visible
continue
offset = self.editor.contentOffset().x() + \
self.editor.document().documentMargin()
x_pos = round(metrics.width(' ') * pos) + offset
painter.setPen(pen)
painter.drawLine(x_pos, 0, x_pos, 2 ** 16) | [
"def",
"_paint_margins",
"(",
"self",
",",
"event",
")",
":",
"font",
"=",
"QtGui",
".",
"QFont",
"(",
"self",
".",
"editor",
".",
"font_name",
",",
"self",
".",
"editor",
".",
"font_size",
"+",
"self",
".",
"editor",
".",
"zoom_level",
")",
"metrics",
"=",
"QtGui",
".",
"QFontMetricsF",
"(",
"font",
")",
"painter",
"=",
"QtGui",
".",
"QPainter",
"(",
"self",
".",
"editor",
".",
"viewport",
"(",
")",
")",
"for",
"pos",
",",
"pen",
"in",
"zip",
"(",
"self",
".",
"_positions",
",",
"self",
".",
"_pens",
")",
":",
"if",
"pos",
"<",
"0",
":",
"# margin not visible",
"continue",
"offset",
"=",
"self",
".",
"editor",
".",
"contentOffset",
"(",
")",
".",
"x",
"(",
")",
"+",
"self",
".",
"editor",
".",
"document",
"(",
")",
".",
"documentMargin",
"(",
")",
"x_pos",
"=",
"round",
"(",
"metrics",
".",
"width",
"(",
"' '",
")",
"*",
"pos",
")",
"+",
"offset",
"painter",
".",
"setPen",
"(",
"pen",
")",
"painter",
".",
"drawLine",
"(",
"x_pos",
",",
"0",
",",
"x_pos",
",",
"2",
"**",
"16",
")"
] | 47.666667 | 13.2 |
def fmt(msg, *args, **kw):
# type: (str, *Any, **Any) -> str
""" Generate shell color opcodes from a pretty coloring syntax. """
global is_tty
if len(args) or len(kw):
msg = msg.format(*args, **kw)
opcode_subst = '\x1b[\\1m' if is_tty else ''
return re.sub(r'<(\d{1,2})>', opcode_subst, msg) | [
"def",
"fmt",
"(",
"msg",
",",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"# type: (str, *Any, **Any) -> str",
"global",
"is_tty",
"if",
"len",
"(",
"args",
")",
"or",
"len",
"(",
"kw",
")",
":",
"msg",
"=",
"msg",
".",
"format",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
"opcode_subst",
"=",
"'\\x1b[\\\\1m'",
"if",
"is_tty",
"else",
"''",
"return",
"re",
".",
"sub",
"(",
"r'<(\\d{1,2})>'",
",",
"opcode_subst",
",",
"msg",
")"
] | 31.6 | 15.5 |
def convert_to_id(s, id_set):
""" Some parts of .wxs need an Id attribute (for example: The File and
Directory directives. The charset is limited to A-Z, a-z, digits,
underscores, periods. Each Id must begin with a letter or with a
underscore. Google for "CNDL0015" for information about this.
Requirements:
* the string created must only contain chars from the target charset.
* the string created must have a minimal editing distance from the
original string.
* the string created must be unique for the whole .wxs file.
Observation:
* There are 62 chars in the charset.
Idea:
* filter out forbidden characters. Check for a collision with the help
of the id_set. Add the number of the number of the collision at the
end of the created string. Furthermore care for a correct start of
the string.
"""
charset = 'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'
if s[0] in '0123456789.':
s += '_'+s
id = [c for c in s if c in charset]
# did we already generate an id for this file?
try:
return id_set[id][s]
except KeyError:
# no we did not, so initialize with the id
if id not in id_set: id_set[id] = { s : id }
# there is a collision, generate an id which is unique by appending
# the collision number
else: id_set[id][s] = id + str(len(id_set[id]))
return id_set[id][s] | [
"def",
"convert_to_id",
"(",
"s",
",",
"id_set",
")",
":",
"charset",
"=",
"'ABCDEFGHIJKLMNOPQRSTUVWXYabcdefghijklmnopqrstuvwxyz0123456789_.'",
"if",
"s",
"[",
"0",
"]",
"in",
"'0123456789.'",
":",
"s",
"+=",
"'_'",
"+",
"s",
"id",
"=",
"[",
"c",
"for",
"c",
"in",
"s",
"if",
"c",
"in",
"charset",
"]",
"# did we already generate an id for this file?",
"try",
":",
"return",
"id_set",
"[",
"id",
"]",
"[",
"s",
"]",
"except",
"KeyError",
":",
"# no we did not, so initialize with the id",
"if",
"id",
"not",
"in",
"id_set",
":",
"id_set",
"[",
"id",
"]",
"=",
"{",
"s",
":",
"id",
"}",
"# there is a collision, generate an id which is unique by appending",
"# the collision number",
"else",
":",
"id_set",
"[",
"id",
"]",
"[",
"s",
"]",
"=",
"id",
"+",
"str",
"(",
"len",
"(",
"id_set",
"[",
"id",
"]",
")",
")",
"return",
"id_set",
"[",
"id",
"]",
"[",
"s",
"]"
] | 38.621622 | 22.810811 |
def set_project_pid(project, old_pid, new_pid):
""" Project's PID was changed. """
for datastore in _get_datastores():
datastore.save_project(project)
datastore.set_project_pid(project, old_pid, new_pid) | [
"def",
"set_project_pid",
"(",
"project",
",",
"old_pid",
",",
"new_pid",
")",
":",
"for",
"datastore",
"in",
"_get_datastores",
"(",
")",
":",
"datastore",
".",
"save_project",
"(",
"project",
")",
"datastore",
".",
"set_project_pid",
"(",
"project",
",",
"old_pid",
",",
"new_pid",
")"
] | 44.6 | 5.8 |
def save(self, *args, **kwargs):
"""
Set default for ``publish_date``. We can't use ``auto_now_add`` on
the field as it will be blank when a blog post is created from
the quick blog form in the admin dashboard.
"""
if self.publish_date is None:
self.publish_date = now()
super(Displayable, self).save(*args, **kwargs) | [
"def",
"save",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"publish_date",
"is",
"None",
":",
"self",
".",
"publish_date",
"=",
"now",
"(",
")",
"super",
"(",
"Displayable",
",",
"self",
")",
".",
"save",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | 41.888889 | 11.444444 |
def check_regularizers(regularizers, keys):
"""Checks the given regularizers.
This checks that `regularizers` is a dictionary that only contains keys in
`keys`, and furthermore the entries in `regularizers` are functions or
further dictionaries (the latter used, for example, in passing regularizers
to modules inside modules) that must satisfy the same constraints.
Args:
regularizers: Dictionary of regularizers (allowing nested dictionaries) or
None.
keys: Iterable of valid keys for `regularizers`.
Returns:
Copy of checked dictionary of regularizers. If `regularizers=None`, an empty
dictionary will be returned.
Raises:
KeyError: If an regularizers is provided for a key not in `keys`.
TypeError: If a provided regularizer is not a callable function, or
`regularizers` is not a Mapping.
"""
if regularizers is None:
return {}
_assert_is_dictlike(regularizers, valid_keys=keys)
keys = set(keys)
if not set(regularizers) <= keys:
extra_keys = set(regularizers) - keys
raise KeyError(
"Invalid regularizer keys {}, regularizers can only "
"be provided for {}".format(
", ".join("'{}'".format(key) for key in extra_keys),
", ".join("'{}'".format(key) for key in keys)))
_check_nested_callables(regularizers, "Regularizer")
return dict(regularizers) | [
"def",
"check_regularizers",
"(",
"regularizers",
",",
"keys",
")",
":",
"if",
"regularizers",
"is",
"None",
":",
"return",
"{",
"}",
"_assert_is_dictlike",
"(",
"regularizers",
",",
"valid_keys",
"=",
"keys",
")",
"keys",
"=",
"set",
"(",
"keys",
")",
"if",
"not",
"set",
"(",
"regularizers",
")",
"<=",
"keys",
":",
"extra_keys",
"=",
"set",
"(",
"regularizers",
")",
"-",
"keys",
"raise",
"KeyError",
"(",
"\"Invalid regularizer keys {}, regularizers can only \"",
"\"be provided for {}\"",
".",
"format",
"(",
"\", \"",
".",
"join",
"(",
"\"'{}'\"",
".",
"format",
"(",
"key",
")",
"for",
"key",
"in",
"extra_keys",
")",
",",
"\", \"",
".",
"join",
"(",
"\"'{}'\"",
".",
"format",
"(",
"key",
")",
"for",
"key",
"in",
"keys",
")",
")",
")",
"_check_nested_callables",
"(",
"regularizers",
",",
"\"Regularizer\"",
")",
"return",
"dict",
"(",
"regularizers",
")"
] | 34.307692 | 24 |
def exists(self, path):
"""
Check if a given path exists on the filesystem.
:type path: str
:param path: the path to look for
:rtype: bool
:return: :obj:`True` if ``path`` exists
"""
_complain_ifclosed(self.closed)
return self.fs.exists(path) | [
"def",
"exists",
"(",
"self",
",",
"path",
")",
":",
"_complain_ifclosed",
"(",
"self",
".",
"closed",
")",
"return",
"self",
".",
"fs",
".",
"exists",
"(",
"path",
")"
] | 27.727273 | 11.181818 |
def wait_with_ioloop(self, ioloop, timeout=None):
"""Do blocking wait until condition is event is set.
Parameters
----------
ioloop : tornadio.ioloop.IOLoop instance
MUST be the same ioloop that set() / clear() is called from
timeout : float, int or None
If not None, only wait up to `timeout` seconds for event to be set.
Return Value
------------
flag : True if event was set within timeout, otherwise False.
Notes
-----
This will deadlock if called in the ioloop!
"""
f = Future()
def cb():
return gen.chain_future(self.until_set(), f)
ioloop.add_callback(cb)
try:
f.result(timeout)
return True
except TimeoutError:
return self._flag | [
"def",
"wait_with_ioloop",
"(",
"self",
",",
"ioloop",
",",
"timeout",
"=",
"None",
")",
":",
"f",
"=",
"Future",
"(",
")",
"def",
"cb",
"(",
")",
":",
"return",
"gen",
".",
"chain_future",
"(",
"self",
".",
"until_set",
"(",
")",
",",
"f",
")",
"ioloop",
".",
"add_callback",
"(",
"cb",
")",
"try",
":",
"f",
".",
"result",
"(",
"timeout",
")",
"return",
"True",
"except",
"TimeoutError",
":",
"return",
"self",
".",
"_flag"
] | 28.310345 | 21.241379 |
def get_vpc_id_from_mac_address():
"""Gets the VPC ID for this EC2 instance
:return: String instance ID or None
"""
log = logging.getLogger(mod_logger + '.get_vpc_id')
# Exit if not running on AWS
if not is_aws():
log.info('This machine is not running in AWS, exiting...')
return
# Get the primary interface MAC address to query the meta data service
log.debug('Attempting to determine the primary interface MAC address...')
try:
mac_address = get_primary_mac_address()
except AWSMetaDataError:
_, ex, trace = sys.exc_info()
msg = '{n}: Unable to determine the mac address, cannot determine VPC ID:\n{e}'.format(
n=ex.__class__.__name__, e=str(ex))
log.error(msg)
return
vpc_id_url = metadata_url + 'network/interfaces/macs/' + mac_address + '/vpc-id'
try:
response = urllib.urlopen(vpc_id_url)
except(IOError, OSError) as ex:
msg = 'Unable to query URL to get VPC ID: {u}\n{e}'.format(u=vpc_id_url, e=ex)
log.error(msg)
return
# Check the code
if response.getcode() != 200:
msg = 'There was a problem querying url: {u}, returned code: {c}, unable to get the vpc-id'.format(
u=vpc_id_url, c=response.getcode())
log.error(msg)
return
vpc_id = response.read()
return vpc_id | [
"def",
"get_vpc_id_from_mac_address",
"(",
")",
":",
"log",
"=",
"logging",
".",
"getLogger",
"(",
"mod_logger",
"+",
"'.get_vpc_id'",
")",
"# Exit if not running on AWS",
"if",
"not",
"is_aws",
"(",
")",
":",
"log",
".",
"info",
"(",
"'This machine is not running in AWS, exiting...'",
")",
"return",
"# Get the primary interface MAC address to query the meta data service",
"log",
".",
"debug",
"(",
"'Attempting to determine the primary interface MAC address...'",
")",
"try",
":",
"mac_address",
"=",
"get_primary_mac_address",
"(",
")",
"except",
"AWSMetaDataError",
":",
"_",
",",
"ex",
",",
"trace",
"=",
"sys",
".",
"exc_info",
"(",
")",
"msg",
"=",
"'{n}: Unable to determine the mac address, cannot determine VPC ID:\\n{e}'",
".",
"format",
"(",
"n",
"=",
"ex",
".",
"__class__",
".",
"__name__",
",",
"e",
"=",
"str",
"(",
"ex",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"vpc_id_url",
"=",
"metadata_url",
"+",
"'network/interfaces/macs/'",
"+",
"mac_address",
"+",
"'/vpc-id'",
"try",
":",
"response",
"=",
"urllib",
".",
"urlopen",
"(",
"vpc_id_url",
")",
"except",
"(",
"IOError",
",",
"OSError",
")",
"as",
"ex",
":",
"msg",
"=",
"'Unable to query URL to get VPC ID: {u}\\n{e}'",
".",
"format",
"(",
"u",
"=",
"vpc_id_url",
",",
"e",
"=",
"ex",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"# Check the code",
"if",
"response",
".",
"getcode",
"(",
")",
"!=",
"200",
":",
"msg",
"=",
"'There was a problem querying url: {u}, returned code: {c}, unable to get the vpc-id'",
".",
"format",
"(",
"u",
"=",
"vpc_id_url",
",",
"c",
"=",
"response",
".",
"getcode",
"(",
")",
")",
"log",
".",
"error",
"(",
"msg",
")",
"return",
"vpc_id",
"=",
"response",
".",
"read",
"(",
")",
"return",
"vpc_id"
] | 34.512821 | 22.897436 |
def get_first():
"""
return first droplet
"""
client = po.connect() # this depends on the DIGITALOCEAN_API_KEY envvar
all_droplets = client.droplets.list()
id = all_droplets[0]['id'] # I'm cheating because I only have one droplet
return client.droplets.get(id) | [
"def",
"get_first",
"(",
")",
":",
"client",
"=",
"po",
".",
"connect",
"(",
")",
"# this depends on the DIGITALOCEAN_API_KEY envvar",
"all_droplets",
"=",
"client",
".",
"droplets",
".",
"list",
"(",
")",
"id",
"=",
"all_droplets",
"[",
"0",
"]",
"[",
"'id'",
"]",
"# I'm cheating because I only have one droplet",
"return",
"client",
".",
"droplets",
".",
"get",
"(",
"id",
")"
] | 35.125 | 14.875 |
def delete(self, obj):
"""Required functionality."""
del_id = obj.get_id()
if not del_id:
return
cur = self._conn().cursor()
tabname = obj.__class__.get_table_name()
query = 'delete from {0} where id = %s;'.format(tabname)
with self._conn() as conn:
with conn.cursor() as cur:
cur.execute(query, (del_id,)) | [
"def",
"delete",
"(",
"self",
",",
"obj",
")",
":",
"del_id",
"=",
"obj",
".",
"get_id",
"(",
")",
"if",
"not",
"del_id",
":",
"return",
"cur",
"=",
"self",
".",
"_conn",
"(",
")",
".",
"cursor",
"(",
")",
"tabname",
"=",
"obj",
".",
"__class__",
".",
"get_table_name",
"(",
")",
"query",
"=",
"'delete from {0} where id = %s;'",
".",
"format",
"(",
"tabname",
")",
"with",
"self",
".",
"_conn",
"(",
")",
"as",
"conn",
":",
"with",
"conn",
".",
"cursor",
"(",
")",
"as",
"cur",
":",
"cur",
".",
"execute",
"(",
"query",
",",
"(",
"del_id",
",",
")",
")"
] | 28 | 17.071429 |
def store_many(self, sql, values):
"""Abstraction over executemany method"""
cursor = self.get_cursor()
cursor.executemany(sql, values)
self.conn.commit() | [
"def",
"store_many",
"(",
"self",
",",
"sql",
",",
"values",
")",
":",
"cursor",
"=",
"self",
".",
"get_cursor",
"(",
")",
"cursor",
".",
"executemany",
"(",
"sql",
",",
"values",
")",
"self",
".",
"conn",
".",
"commit",
"(",
")"
] | 36.4 | 5.4 |
def hasoriginal(self,allowempty=False):
"""Does the correction record the old annotations prior to correction?"""
for e in self.select(Original,None,False, False):
if not allowempty and len(e) == 0: continue
return True
return False | [
"def",
"hasoriginal",
"(",
"self",
",",
"allowempty",
"=",
"False",
")",
":",
"for",
"e",
"in",
"self",
".",
"select",
"(",
"Original",
",",
"None",
",",
"False",
",",
"False",
")",
":",
"if",
"not",
"allowempty",
"and",
"len",
"(",
"e",
")",
"==",
"0",
":",
"continue",
"return",
"True",
"return",
"False"
] | 45.833333 | 11.666667 |
def find_name(name, state, high):
'''
Scan high data for the id referencing the given name and return a list of (IDs, state) tuples that match
Note: if `state` is sls, then we are looking for all IDs that match the given SLS
'''
ext_id = []
if name in high:
ext_id.append((name, state))
# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS
elif state == 'sls':
for nid, item in six.iteritems(high):
if item['__sls__'] == name:
ext_id.append((nid, next(iter(item))))
# otherwise we are requiring a single state, lets find it
else:
# We need to scan for the name
for nid in high:
if state in high[nid]:
if isinstance(high[nid][state], list):
for arg in high[nid][state]:
if not isinstance(arg, dict):
continue
if len(arg) != 1:
continue
if arg[next(iter(arg))] == name:
ext_id.append((nid, state))
return ext_id | [
"def",
"find_name",
"(",
"name",
",",
"state",
",",
"high",
")",
":",
"ext_id",
"=",
"[",
"]",
"if",
"name",
"in",
"high",
":",
"ext_id",
".",
"append",
"(",
"(",
"name",
",",
"state",
")",
")",
"# if we are requiring an entire SLS, then we need to add ourselves to everything in that SLS",
"elif",
"state",
"==",
"'sls'",
":",
"for",
"nid",
",",
"item",
"in",
"six",
".",
"iteritems",
"(",
"high",
")",
":",
"if",
"item",
"[",
"'__sls__'",
"]",
"==",
"name",
":",
"ext_id",
".",
"append",
"(",
"(",
"nid",
",",
"next",
"(",
"iter",
"(",
"item",
")",
")",
")",
")",
"# otherwise we are requiring a single state, lets find it",
"else",
":",
"# We need to scan for the name",
"for",
"nid",
"in",
"high",
":",
"if",
"state",
"in",
"high",
"[",
"nid",
"]",
":",
"if",
"isinstance",
"(",
"high",
"[",
"nid",
"]",
"[",
"state",
"]",
",",
"list",
")",
":",
"for",
"arg",
"in",
"high",
"[",
"nid",
"]",
"[",
"state",
"]",
":",
"if",
"not",
"isinstance",
"(",
"arg",
",",
"dict",
")",
":",
"continue",
"if",
"len",
"(",
"arg",
")",
"!=",
"1",
":",
"continue",
"if",
"arg",
"[",
"next",
"(",
"iter",
"(",
"arg",
")",
")",
"]",
"==",
"name",
":",
"ext_id",
".",
"append",
"(",
"(",
"nid",
",",
"state",
")",
")",
"return",
"ext_id"
] | 40.392857 | 19.321429 |
def read(fname, merge_duplicate_shots=False, encoding='windows-1252'):
"""Read a PocketTopo .TXT file and produce a `TxtFile` object which represents it"""
return PocketTopoTxtParser(fname, merge_duplicate_shots, encoding).parse() | [
"def",
"read",
"(",
"fname",
",",
"merge_duplicate_shots",
"=",
"False",
",",
"encoding",
"=",
"'windows-1252'",
")",
":",
"return",
"PocketTopoTxtParser",
"(",
"fname",
",",
"merge_duplicate_shots",
",",
"encoding",
")",
".",
"parse",
"(",
")"
] | 81.333333 | 24 |
def _add_to_spec(self, name):
"""The spec of the mirrored mock object is updated whenever the mirror
gains new attributes"""
self._spec.add(name)
self._mock.mock_add_spec(list(self._spec), True) | [
"def",
"_add_to_spec",
"(",
"self",
",",
"name",
")",
":",
"self",
".",
"_spec",
".",
"add",
"(",
"name",
")",
"self",
".",
"_mock",
".",
"mock_add_spec",
"(",
"list",
"(",
"self",
".",
"_spec",
")",
",",
"True",
")"
] | 44.4 | 7.8 |
def dereference(self, session, ref, allow_none=False):
""" Dereference a pymongo "DBRef" to this field's underlying type """
from ommongo.document import collection_registry
# TODO: namespace support
ref.type = collection_registry['global'][ref.collection]
obj = session.dereference(ref, allow_none=allow_none)
return obj | [
"def",
"dereference",
"(",
"self",
",",
"session",
",",
"ref",
",",
"allow_none",
"=",
"False",
")",
":",
"from",
"ommongo",
".",
"document",
"import",
"collection_registry",
"# TODO: namespace support",
"ref",
".",
"type",
"=",
"collection_registry",
"[",
"'global'",
"]",
"[",
"ref",
".",
"collection",
"]",
"obj",
"=",
"session",
".",
"dereference",
"(",
"ref",
",",
"allow_none",
"=",
"allow_none",
")",
"return",
"obj"
] | 51.857143 | 14.857143 |
def _convert_to_df(in_file, freq, raw_file):
"""
convert data frame into table with pandas
"""
dat = defaultdict(Counter)
if isinstance(in_file, (str, unicode)):
with open(in_file) as in_handle:
for line in in_handle:
cols = line.strip().split("\t")
counts = freq[cols[3]]
dat = _expand(dat, counts, int(cols[1]), int(cols[2]))
else:
if raw_file:
out_handle = open(raw_file, "w")
for name in in_file:
counts = freq[name]
if raw_file:
print("%s\t%s\t%s\t%s\t%s\t%s" % ("chr", in_file[name][0], in_file[name][1], name, sum(counts.values()), "+"), file=out_handle, end="")
dat = _expand(dat, counts, in_file[name][0], in_file[name][1])
for s in dat:
for p in dat[s]:
dat[s][p] = mlog2(dat[s][p] + 1)
return dat | [
"def",
"_convert_to_df",
"(",
"in_file",
",",
"freq",
",",
"raw_file",
")",
":",
"dat",
"=",
"defaultdict",
"(",
"Counter",
")",
"if",
"isinstance",
"(",
"in_file",
",",
"(",
"str",
",",
"unicode",
")",
")",
":",
"with",
"open",
"(",
"in_file",
")",
"as",
"in_handle",
":",
"for",
"line",
"in",
"in_handle",
":",
"cols",
"=",
"line",
".",
"strip",
"(",
")",
".",
"split",
"(",
"\"\\t\"",
")",
"counts",
"=",
"freq",
"[",
"cols",
"[",
"3",
"]",
"]",
"dat",
"=",
"_expand",
"(",
"dat",
",",
"counts",
",",
"int",
"(",
"cols",
"[",
"1",
"]",
")",
",",
"int",
"(",
"cols",
"[",
"2",
"]",
")",
")",
"else",
":",
"if",
"raw_file",
":",
"out_handle",
"=",
"open",
"(",
"raw_file",
",",
"\"w\"",
")",
"for",
"name",
"in",
"in_file",
":",
"counts",
"=",
"freq",
"[",
"name",
"]",
"if",
"raw_file",
":",
"print",
"(",
"\"%s\\t%s\\t%s\\t%s\\t%s\\t%s\"",
"%",
"(",
"\"chr\"",
",",
"in_file",
"[",
"name",
"]",
"[",
"0",
"]",
",",
"in_file",
"[",
"name",
"]",
"[",
"1",
"]",
",",
"name",
",",
"sum",
"(",
"counts",
".",
"values",
"(",
")",
")",
",",
"\"+\"",
")",
",",
"file",
"=",
"out_handle",
",",
"end",
"=",
"\"\"",
")",
"dat",
"=",
"_expand",
"(",
"dat",
",",
"counts",
",",
"in_file",
"[",
"name",
"]",
"[",
"0",
"]",
",",
"in_file",
"[",
"name",
"]",
"[",
"1",
"]",
")",
"for",
"s",
"in",
"dat",
":",
"for",
"p",
"in",
"dat",
"[",
"s",
"]",
":",
"dat",
"[",
"s",
"]",
"[",
"p",
"]",
"=",
"mlog2",
"(",
"dat",
"[",
"s",
"]",
"[",
"p",
"]",
"+",
"1",
")",
"return",
"dat"
] | 36.875 | 17.208333 |
def ip6_address(self):
"""Returns the IPv6 address of the network interface.
If multiple interfaces are provided,
the address of the first found is returned.
"""
if self._ip6_address is None and self.network is not None:
self._ip6_address = self._get_ip_address(
libvirt.VIR_IP_ADDR_TYPE_IPV6)
return self._ip6_address | [
"def",
"ip6_address",
"(",
"self",
")",
":",
"if",
"self",
".",
"_ip6_address",
"is",
"None",
"and",
"self",
".",
"network",
"is",
"not",
"None",
":",
"self",
".",
"_ip6_address",
"=",
"self",
".",
"_get_ip_address",
"(",
"libvirt",
".",
"VIR_IP_ADDR_TYPE_IPV6",
")",
"return",
"self",
".",
"_ip6_address"
] | 32.166667 | 17.166667 |
def seconds_str(num, prefix=None):
r"""
Returns:
str
Example:
>>> # ENABLE_DOCTEST
>>> from utool.util_str import * # NOQA
>>> import utool as ut
>>> num_list = sorted([4.2 / (10.0 ** exp_)
>>> for exp_ in range(-13, 13, 4)])
>>> secstr_list = [seconds_str(num, prefix=None) for num in num_list]
>>> result = (', '.join(secstr_list))
>>> print(result)
0.04 ns, 0.42 us, 4.20 ms, 0.04 ks, 0.42 Ms, 4.20 Gs, 42.00 Ts
"""
exponent_list = [-12, -9, -6, -3, 0, 3, 6, 9, 12]
small_prefix_list = ['p', 'n', 'u', 'm', '', 'k', 'M', 'G', 'T']
#large_prefix_list = ['pico', 'nano', 'micro', 'mili', '', 'kilo', 'mega',
# 'giga', 'tera']
#large_suffix = 'second'
small_suffix = 's'
suffix = small_suffix
prefix_list = small_prefix_list
base = 10.0
secstr = order_of_magnitude_str(num, base, prefix_list, exponent_list,
suffix, prefix=prefix)
return secstr | [
"def",
"seconds_str",
"(",
"num",
",",
"prefix",
"=",
"None",
")",
":",
"exponent_list",
"=",
"[",
"-",
"12",
",",
"-",
"9",
",",
"-",
"6",
",",
"-",
"3",
",",
"0",
",",
"3",
",",
"6",
",",
"9",
",",
"12",
"]",
"small_prefix_list",
"=",
"[",
"'p'",
",",
"'n'",
",",
"'u'",
",",
"'m'",
",",
"''",
",",
"'k'",
",",
"'M'",
",",
"'G'",
",",
"'T'",
"]",
"#large_prefix_list = ['pico', 'nano', 'micro', 'mili', '', 'kilo', 'mega',",
"# 'giga', 'tera']",
"#large_suffix = 'second'",
"small_suffix",
"=",
"'s'",
"suffix",
"=",
"small_suffix",
"prefix_list",
"=",
"small_prefix_list",
"base",
"=",
"10.0",
"secstr",
"=",
"order_of_magnitude_str",
"(",
"num",
",",
"base",
",",
"prefix_list",
",",
"exponent_list",
",",
"suffix",
",",
"prefix",
"=",
"prefix",
")",
"return",
"secstr"
] | 36.214286 | 18.892857 |
def can_read(self, timeout=0):
"Poll the socket to see if there's data that can be read."
sock = self._sock
if not sock:
self.connect()
sock = self._sock
return self._parser.can_read() or \
bool(select([sock], [], [], timeout)[0]) | [
"def",
"can_read",
"(",
"self",
",",
"timeout",
"=",
"0",
")",
":",
"sock",
"=",
"self",
".",
"_sock",
"if",
"not",
"sock",
":",
"self",
".",
"connect",
"(",
")",
"sock",
"=",
"self",
".",
"_sock",
"return",
"self",
".",
"_parser",
".",
"can_read",
"(",
")",
"or",
"bool",
"(",
"select",
"(",
"[",
"sock",
"]",
",",
"[",
"]",
",",
"[",
"]",
",",
"timeout",
")",
"[",
"0",
"]",
")"
] | 36.375 | 13.875 |
def plot_haplotype_frequencies(h, palette='Paired', singleton_color='w',
ax=None):
"""Plot haplotype frequencies.
Parameters
----------
h : array_like, int, shape (n_variants, n_haplotypes)
Haplotype array.
palette : string, optional
A Seaborn palette name.
singleton_color : string, optional
Color to paint singleton haplotypes.
ax : axes, optional
The axes on which to draw. If not provided, a new figure will be
created.
Returns
-------
ax : axes
"""
import matplotlib.pyplot as plt
import seaborn as sns
# check inputs
h = HaplotypeArray(h, copy=False)
# setup figure
if ax is None:
width = plt.rcParams['figure.figsize'][0]
height = width / 10
fig, ax = plt.subplots(figsize=(width, height))
sns.despine(ax=ax, left=True)
# count distinct haplotypes
hc = h.distinct_counts()
# setup palette
n_colors = np.count_nonzero(hc > 1)
palette = sns.color_palette(palette, n_colors)
# paint frequencies
x1 = 0
for i, c in enumerate(hc):
x2 = x1 + c
if c > 1:
color = palette[i]
else:
color = singleton_color
ax.axvspan(x1, x2, color=color)
x1 = x2
# tidy up
ax.set_xlim(0, h.shape[1])
ax.set_yticks([])
return ax | [
"def",
"plot_haplotype_frequencies",
"(",
"h",
",",
"palette",
"=",
"'Paired'",
",",
"singleton_color",
"=",
"'w'",
",",
"ax",
"=",
"None",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"import",
"seaborn",
"as",
"sns",
"# check inputs",
"h",
"=",
"HaplotypeArray",
"(",
"h",
",",
"copy",
"=",
"False",
")",
"# setup figure",
"if",
"ax",
"is",
"None",
":",
"width",
"=",
"plt",
".",
"rcParams",
"[",
"'figure.figsize'",
"]",
"[",
"0",
"]",
"height",
"=",
"width",
"/",
"10",
"fig",
",",
"ax",
"=",
"plt",
".",
"subplots",
"(",
"figsize",
"=",
"(",
"width",
",",
"height",
")",
")",
"sns",
".",
"despine",
"(",
"ax",
"=",
"ax",
",",
"left",
"=",
"True",
")",
"# count distinct haplotypes",
"hc",
"=",
"h",
".",
"distinct_counts",
"(",
")",
"# setup palette",
"n_colors",
"=",
"np",
".",
"count_nonzero",
"(",
"hc",
">",
"1",
")",
"palette",
"=",
"sns",
".",
"color_palette",
"(",
"palette",
",",
"n_colors",
")",
"# paint frequencies",
"x1",
"=",
"0",
"for",
"i",
",",
"c",
"in",
"enumerate",
"(",
"hc",
")",
":",
"x2",
"=",
"x1",
"+",
"c",
"if",
"c",
">",
"1",
":",
"color",
"=",
"palette",
"[",
"i",
"]",
"else",
":",
"color",
"=",
"singleton_color",
"ax",
".",
"axvspan",
"(",
"x1",
",",
"x2",
",",
"color",
"=",
"color",
")",
"x1",
"=",
"x2",
"# tidy up",
"ax",
".",
"set_xlim",
"(",
"0",
",",
"h",
".",
"shape",
"[",
"1",
"]",
")",
"ax",
".",
"set_yticks",
"(",
"[",
"]",
")",
"return",
"ax"
] | 23.189655 | 20.241379 |
def from_segment_xml(cls, xml_file, **kwargs):
"""
Read a ligo.segments.segmentlist from the file object file containing an
xml segment table.
Parameters
-----------
xml_file : file object
file object for segment xml file
"""
# load xmldocument and SegmentDefTable and SegmentTables
fp = open(xml_file, 'r')
xmldoc, _ = ligolw_utils.load_fileobj(fp,
gz=xml_file.endswith(".gz"),
contenthandler=ContentHandler)
seg_def_table = table.get_table(xmldoc,
lsctables.SegmentDefTable.tableName)
seg_table = table.get_table(xmldoc, lsctables.SegmentTable.tableName)
seg_sum_table = table.get_table(xmldoc,
lsctables.SegmentSumTable.tableName)
segs = segments.segmentlistdict()
seg_summ = segments.segmentlistdict()
seg_id = {}
for seg_def in seg_def_table:
# Here we want to encode ifo and segment name
full_channel_name = ':'.join([str(seg_def.ifos),
str(seg_def.name)])
seg_id[int(seg_def.segment_def_id)] = full_channel_name
segs[full_channel_name] = segments.segmentlist()
seg_summ[full_channel_name] = segments.segmentlist()
for seg in seg_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
segs[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg in seg_sum_table:
seg_obj = segments.segment(
lal.LIGOTimeGPS(seg.start_time, seg.start_time_ns),
lal.LIGOTimeGPS(seg.end_time, seg.end_time_ns))
seg_summ[seg_id[int(seg.segment_def_id)]].append(seg_obj)
for seg_name in seg_id.values():
segs[seg_name] = segs[seg_name].coalesce()
xmldoc.unlink()
fp.close()
curr_url = urlparse.urlunparse(['file', 'localhost', xml_file, None,
None, None])
return cls.from_segment_list_dict('SEGMENTS', segs, file_url=curr_url,
file_exists=True,
seg_summ_dict=seg_summ, **kwargs) | [
"def",
"from_segment_xml",
"(",
"cls",
",",
"xml_file",
",",
"*",
"*",
"kwargs",
")",
":",
"# load xmldocument and SegmentDefTable and SegmentTables",
"fp",
"=",
"open",
"(",
"xml_file",
",",
"'r'",
")",
"xmldoc",
",",
"_",
"=",
"ligolw_utils",
".",
"load_fileobj",
"(",
"fp",
",",
"gz",
"=",
"xml_file",
".",
"endswith",
"(",
"\".gz\"",
")",
",",
"contenthandler",
"=",
"ContentHandler",
")",
"seg_def_table",
"=",
"table",
".",
"get_table",
"(",
"xmldoc",
",",
"lsctables",
".",
"SegmentDefTable",
".",
"tableName",
")",
"seg_table",
"=",
"table",
".",
"get_table",
"(",
"xmldoc",
",",
"lsctables",
".",
"SegmentTable",
".",
"tableName",
")",
"seg_sum_table",
"=",
"table",
".",
"get_table",
"(",
"xmldoc",
",",
"lsctables",
".",
"SegmentSumTable",
".",
"tableName",
")",
"segs",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"seg_summ",
"=",
"segments",
".",
"segmentlistdict",
"(",
")",
"seg_id",
"=",
"{",
"}",
"for",
"seg_def",
"in",
"seg_def_table",
":",
"# Here we want to encode ifo and segment name",
"full_channel_name",
"=",
"':'",
".",
"join",
"(",
"[",
"str",
"(",
"seg_def",
".",
"ifos",
")",
",",
"str",
"(",
"seg_def",
".",
"name",
")",
"]",
")",
"seg_id",
"[",
"int",
"(",
"seg_def",
".",
"segment_def_id",
")",
"]",
"=",
"full_channel_name",
"segs",
"[",
"full_channel_name",
"]",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"seg_summ",
"[",
"full_channel_name",
"]",
"=",
"segments",
".",
"segmentlist",
"(",
")",
"for",
"seg",
"in",
"seg_table",
":",
"seg_obj",
"=",
"segments",
".",
"segment",
"(",
"lal",
".",
"LIGOTimeGPS",
"(",
"seg",
".",
"start_time",
",",
"seg",
".",
"start_time_ns",
")",
",",
"lal",
".",
"LIGOTimeGPS",
"(",
"seg",
".",
"end_time",
",",
"seg",
".",
"end_time_ns",
")",
")",
"segs",
"[",
"seg_id",
"[",
"int",
"(",
"seg",
".",
"segment_def_id",
")",
"]",
"]",
".",
"append",
"(",
"seg_obj",
")",
"for",
"seg",
"in",
"seg_sum_table",
":",
"seg_obj",
"=",
"segments",
".",
"segment",
"(",
"lal",
".",
"LIGOTimeGPS",
"(",
"seg",
".",
"start_time",
",",
"seg",
".",
"start_time_ns",
")",
",",
"lal",
".",
"LIGOTimeGPS",
"(",
"seg",
".",
"end_time",
",",
"seg",
".",
"end_time_ns",
")",
")",
"seg_summ",
"[",
"seg_id",
"[",
"int",
"(",
"seg",
".",
"segment_def_id",
")",
"]",
"]",
".",
"append",
"(",
"seg_obj",
")",
"for",
"seg_name",
"in",
"seg_id",
".",
"values",
"(",
")",
":",
"segs",
"[",
"seg_name",
"]",
"=",
"segs",
"[",
"seg_name",
"]",
".",
"coalesce",
"(",
")",
"xmldoc",
".",
"unlink",
"(",
")",
"fp",
".",
"close",
"(",
")",
"curr_url",
"=",
"urlparse",
".",
"urlunparse",
"(",
"[",
"'file'",
",",
"'localhost'",
",",
"xml_file",
",",
"None",
",",
"None",
",",
"None",
"]",
")",
"return",
"cls",
".",
"from_segment_list_dict",
"(",
"'SEGMENTS'",
",",
"segs",
",",
"file_url",
"=",
"curr_url",
",",
"file_exists",
"=",
"True",
",",
"seg_summ_dict",
"=",
"seg_summ",
",",
"*",
"*",
"kwargs",
")"
] | 42.789474 | 21.982456 |
def new(self, command, attach=""):
"""
Creates a new Process
Attach: If attach=True it will return a rendezvous connection point, for streaming stdout/stderr
Command: The actual command it will run
"""
r = self._h._http_resource(
method='POST',
resource=('apps', self.app.name, 'ps',),
data={'attach': attach, 'command': command}
)
r.raise_for_status()
return self.app.processes[r.json()['process']] | [
"def",
"new",
"(",
"self",
",",
"command",
",",
"attach",
"=",
"\"\"",
")",
":",
"r",
"=",
"self",
".",
"_h",
".",
"_http_resource",
"(",
"method",
"=",
"'POST'",
",",
"resource",
"=",
"(",
"'apps'",
",",
"self",
".",
"app",
".",
"name",
",",
"'ps'",
",",
")",
",",
"data",
"=",
"{",
"'attach'",
":",
"attach",
",",
"'command'",
":",
"command",
"}",
")",
"r",
".",
"raise_for_status",
"(",
")",
"return",
"self",
".",
"app",
".",
"processes",
"[",
"r",
".",
"json",
"(",
")",
"[",
"'process'",
"]",
"]"
] | 35.357143 | 16.5 |
def get(self, sid):
"""
Constructs a FeedbackSummaryContext
:param sid: A string that uniquely identifies this feedback summary resource
:returns: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext
:rtype: twilio.rest.api.v2010.account.call.feedback_summary.FeedbackSummaryContext
"""
return FeedbackSummaryContext(self._version, account_sid=self._solution['account_sid'], sid=sid, ) | [
"def",
"get",
"(",
"self",
",",
"sid",
")",
":",
"return",
"FeedbackSummaryContext",
"(",
"self",
".",
"_version",
",",
"account_sid",
"=",
"self",
".",
"_solution",
"[",
"'account_sid'",
"]",
",",
"sid",
"=",
"sid",
",",
")"
] | 45.6 | 31.6 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.