repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1 value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
emilmont/pyStatParser | stat_parser/eval_parser.py | FScore.increment | def increment(self, gold_set, test_set):
"Add examples from sets."
self.gold += len(gold_set)
self.test += len(test_set)
self.correct += len(gold_set & test_set) | python | def increment(self, gold_set, test_set):
"Add examples from sets."
self.gold += len(gold_set)
self.test += len(test_set)
self.correct += len(gold_set & test_set) | [
"def",
"increment",
"(",
"self",
",",
"gold_set",
",",
"test_set",
")",
":",
"self",
".",
"gold",
"+=",
"len",
"(",
"gold_set",
")",
"self",
".",
"test",
"+=",
"len",
"(",
"test_set",
")",
"self",
".",
"correct",
"+=",
"len",
"(",
"gold_set",
"&",
... | Add examples from sets. | [
"Add",
"examples",
"from",
"sets",
"."
] | 0e4990d7c1f0e3a0e0626ea2059ffd9030edf323 | https://github.com/emilmont/pyStatParser/blob/0e4990d7c1f0e3a0e0626ea2059ffd9030edf323/stat_parser/eval_parser.py#L100-L104 | train | 28,100 |
emilmont/pyStatParser | stat_parser/eval_parser.py | FScore.output_row | def output_row(self, name):
"Output a scoring row."
print("%10s %4d %0.3f %0.3f %0.3f"%(
name, self.gold, self.precision(), self.recall(), self.fscore())) | python | def output_row(self, name):
"Output a scoring row."
print("%10s %4d %0.3f %0.3f %0.3f"%(
name, self.gold, self.precision(), self.recall(), self.fscore())) | [
"def",
"output_row",
"(",
"self",
",",
"name",
")",
":",
"print",
"(",
"\"%10s %4d %0.3f %0.3f %0.3f\"",
"%",
"(",
"name",
",",
"self",
".",
"gold",
",",
"self",
".",
"precision",
"(",
")",
",",
"self",
".",
"recall",
"(",
")",
","... | Output a scoring row. | [
"Output",
"a",
"scoring",
"row",
"."
] | 0e4990d7c1f0e3a0e0626ea2059ffd9030edf323 | https://github.com/emilmont/pyStatParser/blob/0e4990d7c1f0e3a0e0626ea2059ffd9030edf323/stat_parser/eval_parser.py#L126-L129 | train | 28,101 |
emilmont/pyStatParser | stat_parser/eval_parser.py | ParseEvaluator.output | def output(self):
"Print out the f-score table."
FScore.output_header()
nts = list(self.nt_score.keys())
nts.sort()
for nt in nts:
self.nt_score[nt].output_row(nt)
print()
self.total_score.output_row("total") | python | def output(self):
"Print out the f-score table."
FScore.output_header()
nts = list(self.nt_score.keys())
nts.sort()
for nt in nts:
self.nt_score[nt].output_row(nt)
print()
self.total_score.output_row("total") | [
"def",
"output",
"(",
"self",
")",
":",
"FScore",
".",
"output_header",
"(",
")",
"nts",
"=",
"list",
"(",
"self",
".",
"nt_score",
".",
"keys",
"(",
")",
")",
"nts",
".",
"sort",
"(",
")",
"for",
"nt",
"in",
"nts",
":",
"self",
".",
"nt_score",
... | Print out the f-score table. | [
"Print",
"out",
"the",
"f",
"-",
"score",
"table",
"."
] | 0e4990d7c1f0e3a0e0626ea2059ffd9030edf323 | https://github.com/emilmont/pyStatParser/blob/0e4990d7c1f0e3a0e0626ea2059ffd9030edf323/stat_parser/eval_parser.py#L169-L177 | train | 28,102 |
garnaat/kappa | kappa/scripts/cli.py | invoke | def invoke(ctx, data_file):
"""Invoke the command synchronously"""
click.echo('invoking')
response = ctx.invoke(data_file.read())
log_data = base64.b64decode(response['LogResult'])
click.echo(log_data)
click.echo('Response:')
click.echo(response['Payload'].read())
click.echo('done') | python | def invoke(ctx, data_file):
"""Invoke the command synchronously"""
click.echo('invoking')
response = ctx.invoke(data_file.read())
log_data = base64.b64decode(response['LogResult'])
click.echo(log_data)
click.echo('Response:')
click.echo(response['Payload'].read())
click.echo('done') | [
"def",
"invoke",
"(",
"ctx",
",",
"data_file",
")",
":",
"click",
".",
"echo",
"(",
"'invoking'",
")",
"response",
"=",
"ctx",
".",
"invoke",
"(",
"data_file",
".",
"read",
"(",
")",
")",
"log_data",
"=",
"base64",
".",
"b64decode",
"(",
"response",
... | Invoke the command synchronously | [
"Invoke",
"the",
"command",
"synchronously"
] | 46709b6b790fead13294c2c18ffa5d63ea5133c7 | https://github.com/garnaat/kappa/blob/46709b6b790fead13294c2c18ffa5d63ea5133c7/kappa/scripts/cli.py#L66-L74 | train | 28,103 |
garnaat/kappa | kappa/scripts/cli.py | tail | def tail(ctx):
"""Show the last 10 lines of the log file"""
click.echo('tailing logs')
for e in ctx.tail()[-10:]:
ts = datetime.utcfromtimestamp(e['timestamp'] // 1000).isoformat()
click.echo("{}: {}".format(ts, e['message']))
click.echo('done') | python | def tail(ctx):
"""Show the last 10 lines of the log file"""
click.echo('tailing logs')
for e in ctx.tail()[-10:]:
ts = datetime.utcfromtimestamp(e['timestamp'] // 1000).isoformat()
click.echo("{}: {}".format(ts, e['message']))
click.echo('done') | [
"def",
"tail",
"(",
"ctx",
")",
":",
"click",
".",
"echo",
"(",
"'tailing logs'",
")",
"for",
"e",
"in",
"ctx",
".",
"tail",
"(",
")",
"[",
"-",
"10",
":",
"]",
":",
"ts",
"=",
"datetime",
".",
"utcfromtimestamp",
"(",
"e",
"[",
"'timestamp'",
"]... | Show the last 10 lines of the log file | [
"Show",
"the",
"last",
"10",
"lines",
"of",
"the",
"log",
"file"
] | 46709b6b790fead13294c2c18ffa5d63ea5133c7 | https://github.com/garnaat/kappa/blob/46709b6b790fead13294c2c18ffa5d63ea5133c7/kappa/scripts/cli.py#L88-L94 | train | 28,104 |
garnaat/kappa | kappa/scripts/cli.py | status | def status(ctx):
"""Print a status of this Lambda function"""
status = ctx.status()
click.echo(click.style('Policy', bold=True))
if status['policy']:
line = ' {} ({})'.format(
status['policy']['PolicyName'],
status['policy']['Arn'])
click.echo(click.style(line, fg='green'))
click.echo(click.style('Role', bold=True))
if status['role']:
line = ' {} ({})'.format(
status['role']['RoleName'],
status['role']['Arn'])
click.echo(click.style(line, fg='green'))
click.echo(click.style('Function', bold=True))
if status['function']:
line = ' {} ({})'.format(
status['function']['Configuration']['FunctionName'],
status['function']['Configuration']['FunctionArn'])
click.echo(click.style(line, fg='green'))
else:
click.echo(click.style(' None', fg='green'))
click.echo(click.style('Event Sources', bold=True))
if status['event_sources']:
for event_source in status['event_sources']:
if event_source:
arn = event_source.get('EventSourceArn')
state = event_source.get('State', 'Enabled')
line = ' {}: {}'.format(arn, state)
click.echo(click.style(line, fg='green'))
else:
click.echo(click.style(' None', fg='green')) | python | def status(ctx):
"""Print a status of this Lambda function"""
status = ctx.status()
click.echo(click.style('Policy', bold=True))
if status['policy']:
line = ' {} ({})'.format(
status['policy']['PolicyName'],
status['policy']['Arn'])
click.echo(click.style(line, fg='green'))
click.echo(click.style('Role', bold=True))
if status['role']:
line = ' {} ({})'.format(
status['role']['RoleName'],
status['role']['Arn'])
click.echo(click.style(line, fg='green'))
click.echo(click.style('Function', bold=True))
if status['function']:
line = ' {} ({})'.format(
status['function']['Configuration']['FunctionName'],
status['function']['Configuration']['FunctionArn'])
click.echo(click.style(line, fg='green'))
else:
click.echo(click.style(' None', fg='green'))
click.echo(click.style('Event Sources', bold=True))
if status['event_sources']:
for event_source in status['event_sources']:
if event_source:
arn = event_source.get('EventSourceArn')
state = event_source.get('State', 'Enabled')
line = ' {}: {}'.format(arn, state)
click.echo(click.style(line, fg='green'))
else:
click.echo(click.style(' None', fg='green')) | [
"def",
"status",
"(",
"ctx",
")",
":",
"status",
"=",
"ctx",
".",
"status",
"(",
")",
"click",
".",
"echo",
"(",
"click",
".",
"style",
"(",
"'Policy'",
",",
"bold",
"=",
"True",
")",
")",
"if",
"status",
"[",
"'policy'",
"]",
":",
"line",
"=",
... | Print a status of this Lambda function | [
"Print",
"a",
"status",
"of",
"this",
"Lambda",
"function"
] | 46709b6b790fead13294c2c18ffa5d63ea5133c7 | https://github.com/garnaat/kappa/blob/46709b6b790fead13294c2c18ffa5d63ea5133c7/kappa/scripts/cli.py#L99-L131 | train | 28,105 |
garnaat/kappa | kappa/scripts/cli.py | event_sources | def event_sources(ctx, command):
"""List, enable, and disable event sources specified in the config file"""
if command == 'list':
click.echo('listing event sources')
event_sources = ctx.list_event_sources()
for es in event_sources:
click.echo('arn: {}'.format(es['arn']))
click.echo('starting position: {}'.format(es['starting_position']))
click.echo('batch size: {}'.format(es['batch_size']))
click.echo('enabled: {}'.format(es['enabled']))
click.echo('done')
elif command == 'enable':
click.echo('enabling event sources')
ctx.enable_event_sources()
click.echo('done')
elif command == 'disable':
click.echo('disabling event sources')
ctx.disable_event_sources()
click.echo('done') | python | def event_sources(ctx, command):
"""List, enable, and disable event sources specified in the config file"""
if command == 'list':
click.echo('listing event sources')
event_sources = ctx.list_event_sources()
for es in event_sources:
click.echo('arn: {}'.format(es['arn']))
click.echo('starting position: {}'.format(es['starting_position']))
click.echo('batch size: {}'.format(es['batch_size']))
click.echo('enabled: {}'.format(es['enabled']))
click.echo('done')
elif command == 'enable':
click.echo('enabling event sources')
ctx.enable_event_sources()
click.echo('done')
elif command == 'disable':
click.echo('disabling event sources')
ctx.disable_event_sources()
click.echo('done') | [
"def",
"event_sources",
"(",
"ctx",
",",
"command",
")",
":",
"if",
"command",
"==",
"'list'",
":",
"click",
".",
"echo",
"(",
"'listing event sources'",
")",
"event_sources",
"=",
"ctx",
".",
"list_event_sources",
"(",
")",
"for",
"es",
"in",
"event_sources... | List, enable, and disable event sources specified in the config file | [
"List",
"enable",
"and",
"disable",
"event",
"sources",
"specified",
"in",
"the",
"config",
"file"
] | 46709b6b790fead13294c2c18ffa5d63ea5133c7 | https://github.com/garnaat/kappa/blob/46709b6b790fead13294c2c18ffa5d63ea5133c7/kappa/scripts/cli.py#L147-L165 | train | 28,106 |
leonardt/fault | fault/circuit_utils.py | check_interface_is_subset | def check_interface_is_subset(circuit1, circuit2):
"""
Checks that the interface of circuit1 is a subset of circuit2
Subset is defined as circuit2 contains all the ports of circuit1. Ports are
matched by name comparison, then the types are checked to see if one could
be converted to another.
"""
circuit1_port_names = circuit1.interface.ports.keys()
for name in circuit1_port_names:
if name not in circuit2.interface.ports:
raise ValueError(f"{circuit2} (circuit2) does not have port {name}")
circuit1_kind = type(type(getattr(circuit1, name)))
circuit2_kind = type(type(getattr(circuit2, name)))
circuit1_sub_circuit2 = issubclass(circuit1_kind, circuit2_kind)
circuit2_sub_circuit1 = issubclass(circuit2_kind, circuit1_kind)
# Check that the type of one could be converted to the other
if not (circuit1_sub_circuit2 or circuit2_sub_circuit1):
raise ValueError(f"Port {name} types don't match:"
f" Type0={circuit1_kind},"
f" Type1={circuit2_kind}") | python | def check_interface_is_subset(circuit1, circuit2):
"""
Checks that the interface of circuit1 is a subset of circuit2
Subset is defined as circuit2 contains all the ports of circuit1. Ports are
matched by name comparison, then the types are checked to see if one could
be converted to another.
"""
circuit1_port_names = circuit1.interface.ports.keys()
for name in circuit1_port_names:
if name not in circuit2.interface.ports:
raise ValueError(f"{circuit2} (circuit2) does not have port {name}")
circuit1_kind = type(type(getattr(circuit1, name)))
circuit2_kind = type(type(getattr(circuit2, name)))
circuit1_sub_circuit2 = issubclass(circuit1_kind, circuit2_kind)
circuit2_sub_circuit1 = issubclass(circuit2_kind, circuit1_kind)
# Check that the type of one could be converted to the other
if not (circuit1_sub_circuit2 or circuit2_sub_circuit1):
raise ValueError(f"Port {name} types don't match:"
f" Type0={circuit1_kind},"
f" Type1={circuit2_kind}") | [
"def",
"check_interface_is_subset",
"(",
"circuit1",
",",
"circuit2",
")",
":",
"circuit1_port_names",
"=",
"circuit1",
".",
"interface",
".",
"ports",
".",
"keys",
"(",
")",
"for",
"name",
"in",
"circuit1_port_names",
":",
"if",
"name",
"not",
"in",
"circuit2... | Checks that the interface of circuit1 is a subset of circuit2
Subset is defined as circuit2 contains all the ports of circuit1. Ports are
matched by name comparison, then the types are checked to see if one could
be converted to another. | [
"Checks",
"that",
"the",
"interface",
"of",
"circuit1",
"is",
"a",
"subset",
"of",
"circuit2"
] | da1b48ab727bd85abc54ae9b52841d08188c0df5 | https://github.com/leonardt/fault/blob/da1b48ab727bd85abc54ae9b52841d08188c0df5/fault/circuit_utils.py#L1-L21 | train | 28,107 |
google/google-visualization-python | gviz_api.py | DataTable.CoerceValue | def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'.
"""
if isinstance(value, tuple):
# In case of a tuple, we run the same function on the value itself and
# add the formatted value.
if (len(value) not in [2, 3] or
(len(value) == 3 and not isinstance(value[2], dict))):
raise DataTableException("Wrong format for value and formatting - %s." %
str(value))
if not isinstance(value[1], six.string_types + (type(None),)):
raise DataTableException("Formatted value is not string, given %s." %
type(value[1]))
js_value = DataTable.CoerceValue(value[0], value_type)
return (js_value,) + value[1:]
t_value = type(value)
if value is None:
return value
if value_type == "boolean":
return bool(value)
elif value_type == "number":
if isinstance(value, six.integer_types + (float,)):
return value
raise DataTableException("Wrong type %s when expected number" % t_value)
elif value_type == "string":
if isinstance(value, six.text_type):
return value
if isinstance(value, bytes):
return six.text_type(value, encoding="utf-8")
else:
return six.text_type(value)
elif value_type == "date":
if isinstance(value, datetime.datetime):
return datetime.date(value.year, value.month, value.day)
elif isinstance(value, datetime.date):
return value
else:
raise DataTableException("Wrong type %s when expected date" % t_value)
elif value_type == "timeofday":
if isinstance(value, datetime.datetime):
return datetime.time(value.hour, value.minute, value.second)
elif isinstance(value, datetime.time):
return value
else:
raise DataTableException("Wrong type %s when expected time" % t_value)
elif value_type == "datetime":
if isinstance(value, datetime.datetime):
return value
else:
raise DataTableException("Wrong type %s when expected datetime" %
t_value)
# If we got here, it means the given value_type was not one of the
# supported types.
raise DataTableException("Unsupported type %s" % value_type) | python | def CoerceValue(value, value_type):
"""Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'.
"""
if isinstance(value, tuple):
# In case of a tuple, we run the same function on the value itself and
# add the formatted value.
if (len(value) not in [2, 3] or
(len(value) == 3 and not isinstance(value[2], dict))):
raise DataTableException("Wrong format for value and formatting - %s." %
str(value))
if not isinstance(value[1], six.string_types + (type(None),)):
raise DataTableException("Formatted value is not string, given %s." %
type(value[1]))
js_value = DataTable.CoerceValue(value[0], value_type)
return (js_value,) + value[1:]
t_value = type(value)
if value is None:
return value
if value_type == "boolean":
return bool(value)
elif value_type == "number":
if isinstance(value, six.integer_types + (float,)):
return value
raise DataTableException("Wrong type %s when expected number" % t_value)
elif value_type == "string":
if isinstance(value, six.text_type):
return value
if isinstance(value, bytes):
return six.text_type(value, encoding="utf-8")
else:
return six.text_type(value)
elif value_type == "date":
if isinstance(value, datetime.datetime):
return datetime.date(value.year, value.month, value.day)
elif isinstance(value, datetime.date):
return value
else:
raise DataTableException("Wrong type %s when expected date" % t_value)
elif value_type == "timeofday":
if isinstance(value, datetime.datetime):
return datetime.time(value.hour, value.minute, value.second)
elif isinstance(value, datetime.time):
return value
else:
raise DataTableException("Wrong type %s when expected time" % t_value)
elif value_type == "datetime":
if isinstance(value, datetime.datetime):
return value
else:
raise DataTableException("Wrong type %s when expected datetime" %
t_value)
# If we got here, it means the given value_type was not one of the
# supported types.
raise DataTableException("Unsupported type %s" % value_type) | [
"def",
"CoerceValue",
"(",
"value",
",",
"value_type",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"tuple",
")",
":",
"# In case of a tuple, we run the same function on the value itself and",
"# add the formatted value.",
"if",
"(",
"len",
"(",
"value",
")",
"not... | Coerces a single value into the type expected for its column.
Internal helper method.
Args:
value: The value which should be converted
value_type: One of "string", "number", "boolean", "date", "datetime" or
"timeofday".
Returns:
An item of the Python type appropriate to the given value_type. Strings
are also converted to Unicode using UTF-8 encoding if necessary.
If a tuple is given, it should be in one of the following forms:
- (value, formatted value)
- (value, formatted value, custom properties)
where the formatted value is a string, and custom properties is a
dictionary of the custom properties for this cell.
To specify custom properties without specifying formatted value, one can
pass None as the formatted value.
One can also have a null-valued cell with formatted value and/or custom
properties by specifying None for the value.
This method ignores the custom properties except for checking that it is a
dictionary. The custom properties are handled in the ToJSon and ToJSCode
methods.
The real type of the given value is not strictly checked. For example,
any type can be used for string - as we simply take its str( ) and for
boolean value we just check "if value".
Examples:
CoerceValue(None, "string") returns None
CoerceValue((5, "5$"), "number") returns (5, "5$")
CoerceValue(100, "string") returns "100"
CoerceValue(0, "boolean") returns False
Raises:
DataTableException: The value and type did not match in a not-recoverable
way, for example given value 'abc' for type 'number'. | [
"Coerces",
"a",
"single",
"value",
"into",
"the",
"type",
"expected",
"for",
"its",
"column",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L176-L270 | train | 28,108 |
google/google-visualization-python | gviz_api.py | DataTable.ColumnTypeParser | def ColumnTypeParser(description):
"""Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
Returns:
Dictionary with the following keys: id, label, type, and
custom_properties where:
- If label not given, it equals the id.
- If type not given, string is used by default.
- If custom properties are not given, an empty dictionary is used by
default.
Raises:
DataTableException: The column description did not match the RE, or
unsupported type was passed.
"""
if not description:
raise DataTableException("Description error: empty description given")
if not isinstance(description, (six.string_types, tuple)):
raise DataTableException("Description error: expected either string or "
"tuple, got %s." % type(description))
if isinstance(description, six.string_types):
description = (description,)
# According to the tuple's length, we fill the keys
# We verify everything is of type string
for elem in description[:3]:
if not isinstance(elem, six.string_types):
raise DataTableException("Description error: expected tuple of "
"strings, current element of type %s." %
type(elem))
desc_dict = {"id": description[0],
"label": description[0],
"type": "string",
"custom_properties": {}}
if len(description) > 1:
desc_dict["type"] = description[1].lower()
if len(description) > 2:
desc_dict["label"] = description[2]
if len(description) > 3:
if not isinstance(description[3], dict):
raise DataTableException("Description error: expected custom "
"properties of type dict, current element "
"of type %s." % type(description[3]))
desc_dict["custom_properties"] = description[3]
if len(description) > 4:
raise DataTableException("Description error: tuple of length > 4")
if desc_dict["type"] not in ["string", "number", "boolean",
"date", "datetime", "timeofday"]:
raise DataTableException(
"Description error: unsupported type '%s'" % desc_dict["type"])
return desc_dict | python | def ColumnTypeParser(description):
"""Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
Returns:
Dictionary with the following keys: id, label, type, and
custom_properties where:
- If label not given, it equals the id.
- If type not given, string is used by default.
- If custom properties are not given, an empty dictionary is used by
default.
Raises:
DataTableException: The column description did not match the RE, or
unsupported type was passed.
"""
if not description:
raise DataTableException("Description error: empty description given")
if not isinstance(description, (six.string_types, tuple)):
raise DataTableException("Description error: expected either string or "
"tuple, got %s." % type(description))
if isinstance(description, six.string_types):
description = (description,)
# According to the tuple's length, we fill the keys
# We verify everything is of type string
for elem in description[:3]:
if not isinstance(elem, six.string_types):
raise DataTableException("Description error: expected tuple of "
"strings, current element of type %s." %
type(elem))
desc_dict = {"id": description[0],
"label": description[0],
"type": "string",
"custom_properties": {}}
if len(description) > 1:
desc_dict["type"] = description[1].lower()
if len(description) > 2:
desc_dict["label"] = description[2]
if len(description) > 3:
if not isinstance(description[3], dict):
raise DataTableException("Description error: expected custom "
"properties of type dict, current element "
"of type %s." % type(description[3]))
desc_dict["custom_properties"] = description[3]
if len(description) > 4:
raise DataTableException("Description error: tuple of length > 4")
if desc_dict["type"] not in ["string", "number", "boolean",
"date", "datetime", "timeofday"]:
raise DataTableException(
"Description error: unsupported type '%s'" % desc_dict["type"])
return desc_dict | [
"def",
"ColumnTypeParser",
"(",
"description",
")",
":",
"if",
"not",
"description",
":",
"raise",
"DataTableException",
"(",
"\"Description error: empty description given\"",
")",
"if",
"not",
"isinstance",
"(",
"description",
",",
"(",
"six",
".",
"string_types",
... | Parses a single column description. Internal helper method.
Args:
description: a column description in the possible formats:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
Returns:
Dictionary with the following keys: id, label, type, and
custom_properties where:
- If label not given, it equals the id.
- If type not given, string is used by default.
- If custom properties are not given, an empty dictionary is used by
default.
Raises:
DataTableException: The column description did not match the RE, or
unsupported type was passed. | [
"Parses",
"a",
"single",
"column",
"description",
".",
"Internal",
"helper",
"method",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L316-L375 | train | 28,109 |
google/google-visualization-python | gviz_api.py | DataTable.TableDescriptionParser | def TableDescriptionParser(table_description, depth=0):
"""Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description of the table which should comply
with one of the formats described below.
depth: Optional. The depth of the first level in the current description.
Used by recursive calls to this function.
Returns:
List of columns, where each column represented by a dictionary with the
keys: id, label, type, depth, container which means the following:
- id: the id of the column
- name: The name of the column
- type: The datatype of the elements in this column. Allowed types are
described in ColumnTypeParser().
- depth: The depth of this column in the table description
- container: 'dict', 'iter' or 'scalar' for parsing the format easily.
- custom_properties: The custom properties for this column.
The returned description is flattened regardless of how it was given.
Raises:
DataTableException: Error in a column description or in the description
structure.
Examples:
A column description can be of the following forms:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
or as a dictionary:
'id': 'type'
'id': ('type',)
'id': ('type', 'label')
'id': ('type', 'label', {'custom_prop1': 'custom_val1'})
If the type is not specified, we treat it as string.
If no specific label is given, the label is simply the id.
If no custom properties are given, we use an empty dictionary.
input: [('a', 'date'), ('b', 'timeofday', 'b', {'foo': 'bar'})]
output: [{'id': 'a', 'label': 'a', 'type': 'date',
'depth': 0, 'container': 'iter', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'timeofday',
'depth': 0, 'container': 'iter',
'custom_properties': {'foo': 'bar'}}]
input: {'a': [('b', 'number'), ('c', 'string', 'column c')]}
output: [{'id': 'a', 'label': 'a', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'iter', 'custom_properties': {}},
{'id': 'c', 'label': 'column c', 'type': 'string',
'depth': 1, 'container': 'iter', 'custom_properties': {}}]
input: {('a', 'number', 'column a'): { 'b': 'number', 'c': 'string'}}
output: [{'id': 'a', 'label': 'column a', 'type': 'number',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'c', 'type': 'string',
'depth': 1, 'container': 'dict', 'custom_properties': {}}]
input: { ('w', 'string', 'word'): ('c', 'number', 'count') }
output: [{'id': 'w', 'label': 'word', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'count', 'type': 'number',
'depth': 1, 'container': 'scalar', 'custom_properties': {}}]
input: {'a': ('number', 'column a'), 'b': ('string', 'column b')}
output: [{'id': 'a', 'label': 'column a', 'type': 'number', 'depth': 0,
'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'column b', 'type': 'string', 'depth': 0,
'container': 'dict', 'custom_properties': {}}
NOTE: there might be ambiguity in the case of a dictionary representation
of a single column. For example, the following description can be parsed
in 2 different ways: {'a': ('b', 'c')} can be thought of a single column
with the id 'a', of type 'b' and the label 'c', or as 2 columns: one named
'a', and the other named 'b' of type 'c'. We choose the first option by
default, and in case the second option is the right one, it is possible to
make the key into a tuple (i.e. {('a',): ('b', 'c')}) or add more info
into the tuple, thus making it look like this: {'a': ('b', 'c', 'b', {})}
-- second 'b' is the label, and {} is the custom properties field.
"""
# For the recursion step, we check for a scalar object (string or tuple)
if isinstance(table_description, (six.string_types, tuple)):
parsed_col = DataTable.ColumnTypeParser(table_description)
parsed_col["depth"] = depth
parsed_col["container"] = "scalar"
return [parsed_col]
# Since it is not scalar, table_description must be iterable.
if not hasattr(table_description, "__iter__"):
raise DataTableException("Expected an iterable object, got %s" %
type(table_description))
if not isinstance(table_description, dict):
# We expects a non-dictionary iterable item.
columns = []
for desc in table_description:
parsed_col = DataTable.ColumnTypeParser(desc)
parsed_col["depth"] = depth
parsed_col["container"] = "iter"
columns.append(parsed_col)
if not columns:
raise DataTableException("Description iterable objects should not"
" be empty.")
return columns
# The other case is a dictionary
if not table_description:
raise DataTableException("Empty dictionaries are not allowed inside"
" description")
# To differentiate between the two cases of more levels below or this is
# the most inner dictionary, we consider the number of keys (more then one
# key is indication for most inner dictionary) and the type of the key and
# value in case of only 1 key (if the type of key is string and the type of
# the value is a tuple of 0-3 items, we assume this is the most inner
# dictionary).
# NOTE: this way of differentiating might create ambiguity. See docs.
if (len(table_description) != 1 or
(isinstance(next(six.iterkeys(table_description)), six.string_types) and
isinstance(next(six.itervalues(table_description)), tuple) and
len(next(six.itervalues(table_description))) < 4)):
# This is the most inner dictionary. Parsing types.
columns = []
# We sort the items, equivalent to sort the keys since they are unique
for key, value in sorted(table_description.items()):
# We parse the column type as (key, type) or (key, type, label) using
# ColumnTypeParser.
if isinstance(value, tuple):
parsed_col = DataTable.ColumnTypeParser((key,) + value)
else:
parsed_col = DataTable.ColumnTypeParser((key, value))
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
columns.append(parsed_col)
return columns
# This is an outer dictionary, must have at most one key.
parsed_col = DataTable.ColumnTypeParser(sorted(table_description.keys())[0])
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
return ([parsed_col] + DataTable.TableDescriptionParser(
sorted(table_description.values())[0], depth=depth + 1)) | python | def TableDescriptionParser(table_description, depth=0):
"""Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description of the table which should comply
with one of the formats described below.
depth: Optional. The depth of the first level in the current description.
Used by recursive calls to this function.
Returns:
List of columns, where each column represented by a dictionary with the
keys: id, label, type, depth, container which means the following:
- id: the id of the column
- name: The name of the column
- type: The datatype of the elements in this column. Allowed types are
described in ColumnTypeParser().
- depth: The depth of this column in the table description
- container: 'dict', 'iter' or 'scalar' for parsing the format easily.
- custom_properties: The custom properties for this column.
The returned description is flattened regardless of how it was given.
Raises:
DataTableException: Error in a column description or in the description
structure.
Examples:
A column description can be of the following forms:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
or as a dictionary:
'id': 'type'
'id': ('type',)
'id': ('type', 'label')
'id': ('type', 'label', {'custom_prop1': 'custom_val1'})
If the type is not specified, we treat it as string.
If no specific label is given, the label is simply the id.
If no custom properties are given, we use an empty dictionary.
input: [('a', 'date'), ('b', 'timeofday', 'b', {'foo': 'bar'})]
output: [{'id': 'a', 'label': 'a', 'type': 'date',
'depth': 0, 'container': 'iter', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'timeofday',
'depth': 0, 'container': 'iter',
'custom_properties': {'foo': 'bar'}}]
input: {'a': [('b', 'number'), ('c', 'string', 'column c')]}
output: [{'id': 'a', 'label': 'a', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'iter', 'custom_properties': {}},
{'id': 'c', 'label': 'column c', 'type': 'string',
'depth': 1, 'container': 'iter', 'custom_properties': {}}]
input: {('a', 'number', 'column a'): { 'b': 'number', 'c': 'string'}}
output: [{'id': 'a', 'label': 'column a', 'type': 'number',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'c', 'type': 'string',
'depth': 1, 'container': 'dict', 'custom_properties': {}}]
input: { ('w', 'string', 'word'): ('c', 'number', 'count') }
output: [{'id': 'w', 'label': 'word', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'count', 'type': 'number',
'depth': 1, 'container': 'scalar', 'custom_properties': {}}]
input: {'a': ('number', 'column a'), 'b': ('string', 'column b')}
output: [{'id': 'a', 'label': 'column a', 'type': 'number', 'depth': 0,
'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'column b', 'type': 'string', 'depth': 0,
'container': 'dict', 'custom_properties': {}}
NOTE: there might be ambiguity in the case of a dictionary representation
of a single column. For example, the following description can be parsed
in 2 different ways: {'a': ('b', 'c')} can be thought of a single column
with the id 'a', of type 'b' and the label 'c', or as 2 columns: one named
'a', and the other named 'b' of type 'c'. We choose the first option by
default, and in case the second option is the right one, it is possible to
make the key into a tuple (i.e. {('a',): ('b', 'c')}) or add more info
into the tuple, thus making it look like this: {'a': ('b', 'c', 'b', {})}
-- second 'b' is the label, and {} is the custom properties field.
"""
# For the recursion step, we check for a scalar object (string or tuple)
if isinstance(table_description, (six.string_types, tuple)):
parsed_col = DataTable.ColumnTypeParser(table_description)
parsed_col["depth"] = depth
parsed_col["container"] = "scalar"
return [parsed_col]
# Since it is not scalar, table_description must be iterable.
if not hasattr(table_description, "__iter__"):
raise DataTableException("Expected an iterable object, got %s" %
type(table_description))
if not isinstance(table_description, dict):
# We expects a non-dictionary iterable item.
columns = []
for desc in table_description:
parsed_col = DataTable.ColumnTypeParser(desc)
parsed_col["depth"] = depth
parsed_col["container"] = "iter"
columns.append(parsed_col)
if not columns:
raise DataTableException("Description iterable objects should not"
" be empty.")
return columns
# The other case is a dictionary
if not table_description:
raise DataTableException("Empty dictionaries are not allowed inside"
" description")
# To differentiate between the two cases of more levels below or this is
# the most inner dictionary, we consider the number of keys (more then one
# key is indication for most inner dictionary) and the type of the key and
# value in case of only 1 key (if the type of key is string and the type of
# the value is a tuple of 0-3 items, we assume this is the most inner
# dictionary).
# NOTE: this way of differentiating might create ambiguity. See docs.
if (len(table_description) != 1 or
(isinstance(next(six.iterkeys(table_description)), six.string_types) and
isinstance(next(six.itervalues(table_description)), tuple) and
len(next(six.itervalues(table_description))) < 4)):
# This is the most inner dictionary. Parsing types.
columns = []
# We sort the items, equivalent to sort the keys since they are unique
for key, value in sorted(table_description.items()):
# We parse the column type as (key, type) or (key, type, label) using
# ColumnTypeParser.
if isinstance(value, tuple):
parsed_col = DataTable.ColumnTypeParser((key,) + value)
else:
parsed_col = DataTable.ColumnTypeParser((key, value))
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
columns.append(parsed_col)
return columns
# This is an outer dictionary, must have at most one key.
parsed_col = DataTable.ColumnTypeParser(sorted(table_description.keys())[0])
parsed_col["depth"] = depth
parsed_col["container"] = "dict"
return ([parsed_col] + DataTable.TableDescriptionParser(
sorted(table_description.values())[0], depth=depth + 1)) | [
"def",
"TableDescriptionParser",
"(",
"table_description",
",",
"depth",
"=",
"0",
")",
":",
"# For the recursion step, we check for a scalar object (string or tuple)",
"if",
"isinstance",
"(",
"table_description",
",",
"(",
"six",
".",
"string_types",
",",
"tuple",
")",
... | Parses the table_description object for internal use.
Parses the user-submitted table description into an internal format used
by the Python DataTable class. Returns the flat list of parsed columns.
Args:
table_description: A description of the table which should comply
with one of the formats described below.
depth: Optional. The depth of the first level in the current description.
Used by recursive calls to this function.
Returns:
List of columns, where each column represented by a dictionary with the
keys: id, label, type, depth, container which means the following:
- id: the id of the column
- name: The name of the column
- type: The datatype of the elements in this column. Allowed types are
described in ColumnTypeParser().
- depth: The depth of this column in the table description
- container: 'dict', 'iter' or 'scalar' for parsing the format easily.
- custom_properties: The custom properties for this column.
The returned description is flattened regardless of how it was given.
Raises:
DataTableException: Error in a column description or in the description
structure.
Examples:
A column description can be of the following forms:
'id'
('id',)
('id', 'type')
('id', 'type', 'label')
('id', 'type', 'label', {'custom_prop1': 'custom_val1'})
or as a dictionary:
'id': 'type'
'id': ('type',)
'id': ('type', 'label')
'id': ('type', 'label', {'custom_prop1': 'custom_val1'})
If the type is not specified, we treat it as string.
If no specific label is given, the label is simply the id.
If no custom properties are given, we use an empty dictionary.
input: [('a', 'date'), ('b', 'timeofday', 'b', {'foo': 'bar'})]
output: [{'id': 'a', 'label': 'a', 'type': 'date',
'depth': 0, 'container': 'iter', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'timeofday',
'depth': 0, 'container': 'iter',
'custom_properties': {'foo': 'bar'}}]
input: {'a': [('b', 'number'), ('c', 'string', 'column c')]}
output: [{'id': 'a', 'label': 'a', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'iter', 'custom_properties': {}},
{'id': 'c', 'label': 'column c', 'type': 'string',
'depth': 1, 'container': 'iter', 'custom_properties': {}}]
input: {('a', 'number', 'column a'): { 'b': 'number', 'c': 'string'}}
output: [{'id': 'a', 'label': 'column a', 'type': 'number',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'b', 'type': 'number',
'depth': 1, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'c', 'type': 'string',
'depth': 1, 'container': 'dict', 'custom_properties': {}}]
input: { ('w', 'string', 'word'): ('c', 'number', 'count') }
output: [{'id': 'w', 'label': 'word', 'type': 'string',
'depth': 0, 'container': 'dict', 'custom_properties': {}},
{'id': 'c', 'label': 'count', 'type': 'number',
'depth': 1, 'container': 'scalar', 'custom_properties': {}}]
input: {'a': ('number', 'column a'), 'b': ('string', 'column b')}
output: [{'id': 'a', 'label': 'column a', 'type': 'number', 'depth': 0,
'container': 'dict', 'custom_properties': {}},
{'id': 'b', 'label': 'column b', 'type': 'string', 'depth': 0,
'container': 'dict', 'custom_properties': {}}
NOTE: there might be ambiguity in the case of a dictionary representation
of a single column. For example, the following description can be parsed
in 2 different ways: {'a': ('b', 'c')} can be thought of a single column
with the id 'a', of type 'b' and the label 'c', or as 2 columns: one named
'a', and the other named 'b' of type 'c'. We choose the first option by
default, and in case the second option is the right one, it is possible to
make the key into a tuple (i.e. {('a',): ('b', 'c')}) or add more info
into the tuple, thus making it look like this: {'a': ('b', 'c', 'b', {})}
-- second 'b' is the label, and {} is the custom properties field. | [
"Parses",
"the",
"table_description",
"object",
"for",
"internal",
"use",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L378-L525 | train | 28,110 |
google/google-visualization-python | gviz_api.py | DataTable.LoadData | def LoadData(self, data, custom_properties=None):
"""Loads new rows to the data table, clearing existing rows.
May also set the custom_properties for the added rows. The given custom
properties dictionary specifies the dictionary that will be used for *all*
given rows.
Args:
data: The rows that the table will contain.
custom_properties: A dictionary of string to string to set as the custom
properties for all rows.
"""
self.__data = []
self.AppendData(data, custom_properties) | python | def LoadData(self, data, custom_properties=None):
"""Loads new rows to the data table, clearing existing rows.
May also set the custom_properties for the added rows. The given custom
properties dictionary specifies the dictionary that will be used for *all*
given rows.
Args:
data: The rows that the table will contain.
custom_properties: A dictionary of string to string to set as the custom
properties for all rows.
"""
self.__data = []
self.AppendData(data, custom_properties) | [
"def",
"LoadData",
"(",
"self",
",",
"data",
",",
"custom_properties",
"=",
"None",
")",
":",
"self",
".",
"__data",
"=",
"[",
"]",
"self",
".",
"AppendData",
"(",
"data",
",",
"custom_properties",
")"
] | Loads new rows to the data table, clearing existing rows.
May also set the custom_properties for the added rows. The given custom
properties dictionary specifies the dictionary that will be used for *all*
given rows.
Args:
data: The rows that the table will contain.
custom_properties: A dictionary of string to string to set as the custom
properties for all rows. | [
"Loads",
"new",
"rows",
"to",
"the",
"data",
"table",
"clearing",
"existing",
"rows",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L552-L565 | train | 28,111 |
google/google-visualization-python | gviz_api.py | DataTable.AppendData | def AppendData(self, data, custom_properties=None):
"""Appends new data to the table.
Data is appended in rows. Data must comply with
the table schema passed in to __init__(). See CoerceValue() for a list
of acceptable data types. See the class documentation for more information
and examples of schema and data values.
Args:
data: The row to add to the table. The data must conform to the table
description format.
custom_properties: A dictionary of string to string, representing the
custom properties to add to all the rows.
Raises:
DataTableException: The data structure does not match the description.
"""
# If the maximal depth is 0, we simply iterate over the data table
# lines and insert them using _InnerAppendData. Otherwise, we simply
# let the _InnerAppendData handle all the levels.
if not self.__columns[-1]["depth"]:
for row in data:
self._InnerAppendData(({}, custom_properties), row, 0)
else:
self._InnerAppendData(({}, custom_properties), data, 0) | python | def AppendData(self, data, custom_properties=None):
"""Appends new data to the table.
Data is appended in rows. Data must comply with
the table schema passed in to __init__(). See CoerceValue() for a list
of acceptable data types. See the class documentation for more information
and examples of schema and data values.
Args:
data: The row to add to the table. The data must conform to the table
description format.
custom_properties: A dictionary of string to string, representing the
custom properties to add to all the rows.
Raises:
DataTableException: The data structure does not match the description.
"""
# If the maximal depth is 0, we simply iterate over the data table
# lines and insert them using _InnerAppendData. Otherwise, we simply
# let the _InnerAppendData handle all the levels.
if not self.__columns[-1]["depth"]:
for row in data:
self._InnerAppendData(({}, custom_properties), row, 0)
else:
self._InnerAppendData(({}, custom_properties), data, 0) | [
"def",
"AppendData",
"(",
"self",
",",
"data",
",",
"custom_properties",
"=",
"None",
")",
":",
"# If the maximal depth is 0, we simply iterate over the data table",
"# lines and insert them using _InnerAppendData. Otherwise, we simply",
"# let the _InnerAppendData handle all the levels.... | Appends new data to the table.
Data is appended in rows. Data must comply with
the table schema passed in to __init__(). See CoerceValue() for a list
of acceptable data types. See the class documentation for more information
and examples of schema and data values.
Args:
data: The row to add to the table. The data must conform to the table
description format.
custom_properties: A dictionary of string to string, representing the
custom properties to add to all the rows.
Raises:
DataTableException: The data structure does not match the description. | [
"Appends",
"new",
"data",
"to",
"the",
"table",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L567-L591 | train | 28,112 |
google/google-visualization-python | gviz_api.py | DataTable._InnerAppendData | def _InnerAppendData(self, prev_col_values, data, col_index):
"""Inner function to assist LoadData."""
# We first check that col_index has not exceeded the columns size
if col_index >= len(self.__columns):
raise DataTableException("The data does not match description, too deep")
# Dealing with the scalar case, the data is the last value.
if self.__columns[col_index]["container"] == "scalar":
prev_col_values[0][self.__columns[col_index]["id"]] = data
self.__data.append(prev_col_values)
return
if self.__columns[col_index]["container"] == "iter":
if not hasattr(data, "__iter__") or isinstance(data, dict):
raise DataTableException("Expected iterable object, got %s" %
type(data))
# We only need to insert the rest of the columns
# If there are less items than expected, we only add what there is.
for value in data:
if col_index >= len(self.__columns):
raise DataTableException("Too many elements given in data")
prev_col_values[0][self.__columns[col_index]["id"]] = value
col_index += 1
self.__data.append(prev_col_values)
return
# We know the current level is a dictionary, we verify the type.
if not isinstance(data, dict):
raise DataTableException("Expected dictionary at current level, got %s" %
type(data))
# We check if this is the last level
if self.__columns[col_index]["depth"] == self.__columns[-1]["depth"]:
# We need to add the keys in the dictionary as they are
for col in self.__columns[col_index:]:
if col["id"] in data:
prev_col_values[0][col["id"]] = data[col["id"]]
self.__data.append(prev_col_values)
return
# We have a dictionary in an inner depth level.
if not data.keys():
# In case this is an empty dictionary, we add a record with the columns
# filled only until this point.
self.__data.append(prev_col_values)
else:
for key in sorted(data):
col_values = dict(prev_col_values[0])
col_values[self.__columns[col_index]["id"]] = key
self._InnerAppendData((col_values, prev_col_values[1]),
data[key], col_index + 1) | python | def _InnerAppendData(self, prev_col_values, data, col_index):
"""Inner function to assist LoadData."""
# We first check that col_index has not exceeded the columns size
if col_index >= len(self.__columns):
raise DataTableException("The data does not match description, too deep")
# Dealing with the scalar case, the data is the last value.
if self.__columns[col_index]["container"] == "scalar":
prev_col_values[0][self.__columns[col_index]["id"]] = data
self.__data.append(prev_col_values)
return
if self.__columns[col_index]["container"] == "iter":
if not hasattr(data, "__iter__") or isinstance(data, dict):
raise DataTableException("Expected iterable object, got %s" %
type(data))
# We only need to insert the rest of the columns
# If there are less items than expected, we only add what there is.
for value in data:
if col_index >= len(self.__columns):
raise DataTableException("Too many elements given in data")
prev_col_values[0][self.__columns[col_index]["id"]] = value
col_index += 1
self.__data.append(prev_col_values)
return
# We know the current level is a dictionary, we verify the type.
if not isinstance(data, dict):
raise DataTableException("Expected dictionary at current level, got %s" %
type(data))
# We check if this is the last level
if self.__columns[col_index]["depth"] == self.__columns[-1]["depth"]:
# We need to add the keys in the dictionary as they are
for col in self.__columns[col_index:]:
if col["id"] in data:
prev_col_values[0][col["id"]] = data[col["id"]]
self.__data.append(prev_col_values)
return
# We have a dictionary in an inner depth level.
if not data.keys():
# In case this is an empty dictionary, we add a record with the columns
# filled only until this point.
self.__data.append(prev_col_values)
else:
for key in sorted(data):
col_values = dict(prev_col_values[0])
col_values[self.__columns[col_index]["id"]] = key
self._InnerAppendData((col_values, prev_col_values[1]),
data[key], col_index + 1) | [
"def",
"_InnerAppendData",
"(",
"self",
",",
"prev_col_values",
",",
"data",
",",
"col_index",
")",
":",
"# We first check that col_index has not exceeded the columns size",
"if",
"col_index",
">=",
"len",
"(",
"self",
".",
"__columns",
")",
":",
"raise",
"DataTableEx... | Inner function to assist LoadData. | [
"Inner",
"function",
"to",
"assist",
"LoadData",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L593-L642 | train | 28,113 |
google/google-visualization-python | gviz_api.py | DataTable._PreparedData | def _PreparedData(self, order_by=()):
"""Prepares the data for enumeration - sorting it by order_by.
Args:
order_by: Optional. Specifies the name of the column(s) to sort by, and
(optionally) which direction to sort in. Default sort direction
is asc. Following formats are accepted:
"string_col_name" -- For a single key in default (asc) order.
("string_col_name", "asc|desc") -- For a single key.
[("col_1","asc|desc"), ("col_2","asc|desc")] -- For more than
one column, an array of tuples of (col_name, "asc|desc").
Returns:
The data sorted by the keys given.
Raises:
DataTableException: Sort direction not in 'asc' or 'desc'
"""
if not order_by:
return self.__data
sorted_data = self.__data[:]
if isinstance(order_by, six.string_types) or (
isinstance(order_by, tuple) and len(order_by) == 2 and
order_by[1].lower() in ["asc", "desc"]):
order_by = (order_by,)
for key in reversed(order_by):
if isinstance(key, six.string_types):
sorted_data.sort(key=lambda x: x[0].get(key))
elif (isinstance(key, (list, tuple)) and len(key) == 2 and
key[1].lower() in ("asc", "desc")):
key_func = lambda x: x[0].get(key[0])
sorted_data.sort(key=key_func, reverse=key[1].lower() != "asc")
else:
raise DataTableException("Expected tuple with second value: "
"'asc' or 'desc'")
return sorted_data | python | def _PreparedData(self, order_by=()):
"""Prepares the data for enumeration - sorting it by order_by.
Args:
order_by: Optional. Specifies the name of the column(s) to sort by, and
(optionally) which direction to sort in. Default sort direction
is asc. Following formats are accepted:
"string_col_name" -- For a single key in default (asc) order.
("string_col_name", "asc|desc") -- For a single key.
[("col_1","asc|desc"), ("col_2","asc|desc")] -- For more than
one column, an array of tuples of (col_name, "asc|desc").
Returns:
The data sorted by the keys given.
Raises:
DataTableException: Sort direction not in 'asc' or 'desc'
"""
if not order_by:
return self.__data
sorted_data = self.__data[:]
if isinstance(order_by, six.string_types) or (
isinstance(order_by, tuple) and len(order_by) == 2 and
order_by[1].lower() in ["asc", "desc"]):
order_by = (order_by,)
for key in reversed(order_by):
if isinstance(key, six.string_types):
sorted_data.sort(key=lambda x: x[0].get(key))
elif (isinstance(key, (list, tuple)) and len(key) == 2 and
key[1].lower() in ("asc", "desc")):
key_func = lambda x: x[0].get(key[0])
sorted_data.sort(key=key_func, reverse=key[1].lower() != "asc")
else:
raise DataTableException("Expected tuple with second value: "
"'asc' or 'desc'")
return sorted_data | [
"def",
"_PreparedData",
"(",
"self",
",",
"order_by",
"=",
"(",
")",
")",
":",
"if",
"not",
"order_by",
":",
"return",
"self",
".",
"__data",
"sorted_data",
"=",
"self",
".",
"__data",
"[",
":",
"]",
"if",
"isinstance",
"(",
"order_by",
",",
"six",
"... | Prepares the data for enumeration - sorting it by order_by.
Args:
order_by: Optional. Specifies the name of the column(s) to sort by, and
(optionally) which direction to sort in. Default sort direction
is asc. Following formats are accepted:
"string_col_name" -- For a single key in default (asc) order.
("string_col_name", "asc|desc") -- For a single key.
[("col_1","asc|desc"), ("col_2","asc|desc")] -- For more than
one column, an array of tuples of (col_name, "asc|desc").
Returns:
The data sorted by the keys given.
Raises:
DataTableException: Sort direction not in 'asc' or 'desc' | [
"Prepares",
"the",
"data",
"for",
"enumeration",
"-",
"sorting",
"it",
"by",
"order_by",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L644-L681 | train | 28,114 |
google/google-visualization-python | gviz_api.py | DataTable.ToJSCode | def ToJSCode(self, name, columns_order=None, order_by=()):
"""Writes the data table as a JS code string.
This method writes a string of JS code that can be run to
generate a DataTable with the specified data. Typically used for debugging
only.
Args:
name: The name of the table. The name would be used as the DataTable's
variable name in the created JS code.
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
A string of JS code that, when run, generates a DataTable with the given
name and the data stored in the DataTable object.
Example result:
"var tab1 = new google.visualization.DataTable();
tab1.addColumn("string", "a", "a");
tab1.addColumn("number", "b", "b");
tab1.addColumn("boolean", "c", "c");
tab1.addRows(10);
tab1.setCell(0, 0, "a");
tab1.setCell(0, 1, 1, null, {"foo": "bar"});
tab1.setCell(0, 2, true);
...
tab1.setCell(9, 0, "c");
tab1.setCell(9, 1, 3, "3$");
tab1.setCell(9, 2, false);"
Raises:
DataTableException: The data does not match the type.
"""
encoder = DataTableJSONEncoder()
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
# We first create the table with the given name
jscode = "var %s = new google.visualization.DataTable();\n" % name
if self.custom_properties:
jscode += "%s.setTableProperties(%s);\n" % (
name, encoder.encode(self.custom_properties))
# We add the columns to the table
for i, col in enumerate(columns_order):
jscode += "%s.addColumn(%s, %s, %s);\n" % (
name,
encoder.encode(col_dict[col]["type"]),
encoder.encode(col_dict[col]["label"]),
encoder.encode(col_dict[col]["id"]))
if col_dict[col]["custom_properties"]:
jscode += "%s.setColumnProperties(%d, %s);\n" % (
name, i, encoder.encode(col_dict[col]["custom_properties"]))
jscode += "%s.addRows(%d);\n" % (name, len(self.__data))
# We now go over the data and add each row
for (i, (row, cp)) in enumerate(self._PreparedData(order_by)):
# We add all the elements of this row by their order
for (j, col) in enumerate(columns_order):
if col not in row or row[col] is None:
continue
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
cell_cp = ""
if len(value) == 3:
cell_cp = ", %s" % encoder.encode(row[col][2])
# We have a formatted value or custom property as well
jscode += ("%s.setCell(%d, %d, %s, %s%s);\n" %
(name, i, j,
self.EscapeForJSCode(encoder, value[0]),
self.EscapeForJSCode(encoder, value[1]), cell_cp))
else:
jscode += "%s.setCell(%d, %d, %s);\n" % (
name, i, j, self.EscapeForJSCode(encoder, value))
if cp:
jscode += "%s.setRowProperties(%d, %s);\n" % (
name, i, encoder.encode(cp))
return jscode | python | def ToJSCode(self, name, columns_order=None, order_by=()):
"""Writes the data table as a JS code string.
This method writes a string of JS code that can be run to
generate a DataTable with the specified data. Typically used for debugging
only.
Args:
name: The name of the table. The name would be used as the DataTable's
variable name in the created JS code.
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
A string of JS code that, when run, generates a DataTable with the given
name and the data stored in the DataTable object.
Example result:
"var tab1 = new google.visualization.DataTable();
tab1.addColumn("string", "a", "a");
tab1.addColumn("number", "b", "b");
tab1.addColumn("boolean", "c", "c");
tab1.addRows(10);
tab1.setCell(0, 0, "a");
tab1.setCell(0, 1, 1, null, {"foo": "bar"});
tab1.setCell(0, 2, true);
...
tab1.setCell(9, 0, "c");
tab1.setCell(9, 1, 3, "3$");
tab1.setCell(9, 2, false);"
Raises:
DataTableException: The data does not match the type.
"""
encoder = DataTableJSONEncoder()
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
# We first create the table with the given name
jscode = "var %s = new google.visualization.DataTable();\n" % name
if self.custom_properties:
jscode += "%s.setTableProperties(%s);\n" % (
name, encoder.encode(self.custom_properties))
# We add the columns to the table
for i, col in enumerate(columns_order):
jscode += "%s.addColumn(%s, %s, %s);\n" % (
name,
encoder.encode(col_dict[col]["type"]),
encoder.encode(col_dict[col]["label"]),
encoder.encode(col_dict[col]["id"]))
if col_dict[col]["custom_properties"]:
jscode += "%s.setColumnProperties(%d, %s);\n" % (
name, i, encoder.encode(col_dict[col]["custom_properties"]))
jscode += "%s.addRows(%d);\n" % (name, len(self.__data))
# We now go over the data and add each row
for (i, (row, cp)) in enumerate(self._PreparedData(order_by)):
# We add all the elements of this row by their order
for (j, col) in enumerate(columns_order):
if col not in row or row[col] is None:
continue
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
cell_cp = ""
if len(value) == 3:
cell_cp = ", %s" % encoder.encode(row[col][2])
# We have a formatted value or custom property as well
jscode += ("%s.setCell(%d, %d, %s, %s%s);\n" %
(name, i, j,
self.EscapeForJSCode(encoder, value[0]),
self.EscapeForJSCode(encoder, value[1]), cell_cp))
else:
jscode += "%s.setCell(%d, %d, %s);\n" % (
name, i, j, self.EscapeForJSCode(encoder, value))
if cp:
jscode += "%s.setRowProperties(%d, %s);\n" % (
name, i, encoder.encode(cp))
return jscode | [
"def",
"ToJSCode",
"(",
"self",
",",
"name",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"encoder",
"=",
"DataTableJSONEncoder",
"(",
")",
"if",
"columns_order",
"is",
"None",
":",
"columns_order",
"=",
"[",
"col",
"[",
... | Writes the data table as a JS code string.
This method writes a string of JS code that can be run to
generate a DataTable with the specified data. Typically used for debugging
only.
Args:
name: The name of the table. The name would be used as the DataTable's
variable name in the created JS code.
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
A string of JS code that, when run, generates a DataTable with the given
name and the data stored in the DataTable object.
Example result:
"var tab1 = new google.visualization.DataTable();
tab1.addColumn("string", "a", "a");
tab1.addColumn("number", "b", "b");
tab1.addColumn("boolean", "c", "c");
tab1.addRows(10);
tab1.setCell(0, 0, "a");
tab1.setCell(0, 1, 1, null, {"foo": "bar"});
tab1.setCell(0, 2, true);
...
tab1.setCell(9, 0, "c");
tab1.setCell(9, 1, 3, "3$");
tab1.setCell(9, 2, false);"
Raises:
DataTableException: The data does not match the type. | [
"Writes",
"the",
"data",
"table",
"as",
"a",
"JS",
"code",
"string",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L683-L768 | train | 28,115 |
google/google-visualization-python | gviz_api.py | DataTable.ToHtml | def ToHtml(self, columns_order=None, order_by=()):
"""Writes the data table as an HTML table code string.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
An HTML table code string.
Example result (the result is without the newlines):
<html><body><table border="1">
<thead><tr><th>a</th><th>b</th><th>c</th></tr></thead>
<tbody>
<tr><td>1</td><td>"z"</td><td>2</td></tr>
<tr><td>"3$"</td><td>"w"</td><td></td></tr>
</tbody>
</table></body></html>
Raises:
DataTableException: The data does not match the type.
"""
table_template = "<html><body><table border=\"1\">%s</table></body></html>"
columns_template = "<thead><tr>%s</tr></thead>"
rows_template = "<tbody>%s</tbody>"
row_template = "<tr>%s</tr>"
header_cell_template = "<th>%s</th>"
cell_template = "<td>%s</td>"
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
columns_list = []
for col in columns_order:
columns_list.append(header_cell_template %
html.escape(col_dict[col]["label"]))
columns_html = columns_template % "".join(columns_list)
rows_list = []
# We now go over the data and add each row
for row, unused_cp in self._PreparedData(order_by):
cells_list = []
# We add all the elements of this row by their order
for col in columns_order:
# For empty string we want empty quotes ("").
value = ""
if col in row and row[col] is not None:
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
# We have a formatted value and we're going to use it
cells_list.append(cell_template % html.escape(self.ToString(value[1])))
else:
cells_list.append(cell_template % html.escape(self.ToString(value)))
rows_list.append(row_template % "".join(cells_list))
rows_html = rows_template % "".join(rows_list)
return table_template % (columns_html + rows_html) | python | def ToHtml(self, columns_order=None, order_by=()):
"""Writes the data table as an HTML table code string.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
An HTML table code string.
Example result (the result is without the newlines):
<html><body><table border="1">
<thead><tr><th>a</th><th>b</th><th>c</th></tr></thead>
<tbody>
<tr><td>1</td><td>"z"</td><td>2</td></tr>
<tr><td>"3$"</td><td>"w"</td><td></td></tr>
</tbody>
</table></body></html>
Raises:
DataTableException: The data does not match the type.
"""
table_template = "<html><body><table border=\"1\">%s</table></body></html>"
columns_template = "<thead><tr>%s</tr></thead>"
rows_template = "<tbody>%s</tbody>"
row_template = "<tr>%s</tr>"
header_cell_template = "<th>%s</th>"
cell_template = "<td>%s</td>"
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
columns_list = []
for col in columns_order:
columns_list.append(header_cell_template %
html.escape(col_dict[col]["label"]))
columns_html = columns_template % "".join(columns_list)
rows_list = []
# We now go over the data and add each row
for row, unused_cp in self._PreparedData(order_by):
cells_list = []
# We add all the elements of this row by their order
for col in columns_order:
# For empty string we want empty quotes ("").
value = ""
if col in row and row[col] is not None:
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
# We have a formatted value and we're going to use it
cells_list.append(cell_template % html.escape(self.ToString(value[1])))
else:
cells_list.append(cell_template % html.escape(self.ToString(value)))
rows_list.append(row_template % "".join(cells_list))
rows_html = rows_template % "".join(rows_list)
return table_template % (columns_html + rows_html) | [
"def",
"ToHtml",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"table_template",
"=",
"\"<html><body><table border=\\\"1\\\">%s</table></body></html>\"",
"columns_template",
"=",
"\"<thead><tr>%s</tr></thead>\"",
"rows_template",
... | Writes the data table as an HTML table code string.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
Returns:
An HTML table code string.
Example result (the result is without the newlines):
<html><body><table border="1">
<thead><tr><th>a</th><th>b</th><th>c</th></tr></thead>
<tbody>
<tr><td>1</td><td>"z"</td><td>2</td></tr>
<tr><td>"3$"</td><td>"w"</td><td></td></tr>
</tbody>
</table></body></html>
Raises:
DataTableException: The data does not match the type. | [
"Writes",
"the",
"data",
"table",
"as",
"an",
"HTML",
"table",
"code",
"string",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L770-L831 | train | 28,116 |
google/google-visualization-python | gviz_api.py | DataTable.ToCsv | def ToCsv(self, columns_order=None, order_by=(), separator=","):
"""Writes the data table as a CSV string.
Output is encoded in UTF-8 because the Python "csv" module can't handle
Unicode properly according to its documentation.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
separator: Optional. The separator to use between the values.
Returns:
A CSV string representing the table.
Example result:
'a','b','c'
1,'z',2
3,'w',''
Raises:
DataTableException: The data does not match the type.
"""
csv_buffer = six.StringIO()
writer = csv.writer(csv_buffer, delimiter=separator)
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
def ensure_str(s):
"Compatibility function. Ensures using of str rather than unicode."
if isinstance(s, str):
return s
return s.encode("utf-8")
writer.writerow([ensure_str(col_dict[col]["label"])
for col in columns_order])
# We now go over the data and add each row
for row, unused_cp in self._PreparedData(order_by):
cells_list = []
# We add all the elements of this row by their order
for col in columns_order:
value = ""
if col in row and row[col] is not None:
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
# We have a formatted value. Using it only for date/time types.
if col_dict[col]["type"] in ["date", "datetime", "timeofday"]:
cells_list.append(ensure_str(self.ToString(value[1])))
else:
cells_list.append(ensure_str(self.ToString(value[0])))
else:
cells_list.append(ensure_str(self.ToString(value)))
writer.writerow(cells_list)
return csv_buffer.getvalue() | python | def ToCsv(self, columns_order=None, order_by=(), separator=","):
"""Writes the data table as a CSV string.
Output is encoded in UTF-8 because the Python "csv" module can't handle
Unicode properly according to its documentation.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
separator: Optional. The separator to use between the values.
Returns:
A CSV string representing the table.
Example result:
'a','b','c'
1,'z',2
3,'w',''
Raises:
DataTableException: The data does not match the type.
"""
csv_buffer = six.StringIO()
writer = csv.writer(csv_buffer, delimiter=separator)
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
def ensure_str(s):
"Compatibility function. Ensures using of str rather than unicode."
if isinstance(s, str):
return s
return s.encode("utf-8")
writer.writerow([ensure_str(col_dict[col]["label"])
for col in columns_order])
# We now go over the data and add each row
for row, unused_cp in self._PreparedData(order_by):
cells_list = []
# We add all the elements of this row by their order
for col in columns_order:
value = ""
if col in row and row[col] is not None:
value = self.CoerceValue(row[col], col_dict[col]["type"])
if isinstance(value, tuple):
# We have a formatted value. Using it only for date/time types.
if col_dict[col]["type"] in ["date", "datetime", "timeofday"]:
cells_list.append(ensure_str(self.ToString(value[1])))
else:
cells_list.append(ensure_str(self.ToString(value[0])))
else:
cells_list.append(ensure_str(self.ToString(value)))
writer.writerow(cells_list)
return csv_buffer.getvalue() | [
"def",
"ToCsv",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
",",
"separator",
"=",
"\",\"",
")",
":",
"csv_buffer",
"=",
"six",
".",
"StringIO",
"(",
")",
"writer",
"=",
"csv",
".",
"writer",
"(",
"csv_buffer",
","... | Writes the data table as a CSV string.
Output is encoded in UTF-8 because the Python "csv" module can't handle
Unicode properly according to its documentation.
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData.
separator: Optional. The separator to use between the values.
Returns:
A CSV string representing the table.
Example result:
'a','b','c'
1,'z',2
3,'w',''
Raises:
DataTableException: The data does not match the type. | [
"Writes",
"the",
"data",
"table",
"as",
"a",
"CSV",
"string",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L833-L893 | train | 28,117 |
google/google-visualization-python | gviz_api.py | DataTable.ToTsvExcel | def ToTsvExcel(self, columns_order=None, order_by=()):
"""Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
A tab-separated little endian UTF16 file representing the table.
"""
csv_result = self.ToCsv(columns_order, order_by, separator="\t")
if not isinstance(csv_result, six.text_type):
csv_result = csv_result.decode("utf-8")
return csv_result.encode("UTF-16LE") | python | def ToTsvExcel(self, columns_order=None, order_by=()):
"""Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
A tab-separated little endian UTF16 file representing the table.
"""
csv_result = self.ToCsv(columns_order, order_by, separator="\t")
if not isinstance(csv_result, six.text_type):
csv_result = csv_result.decode("utf-8")
return csv_result.encode("UTF-16LE") | [
"def",
"ToTsvExcel",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"csv_result",
"=",
"self",
".",
"ToCsv",
"(",
"columns_order",
",",
"order_by",
",",
"separator",
"=",
"\"\\t\"",
")",
"if",
"not",
"isinstance... | Returns a file in tab-separated-format readable by MS Excel.
Returns a file in UTF-16 little endian encoding, with tabs separating the
values.
Args:
columns_order: Delegated to ToCsv.
order_by: Delegated to ToCsv.
Returns:
A tab-separated little endian UTF16 file representing the table. | [
"Returns",
"a",
"file",
"in",
"tab",
"-",
"separated",
"-",
"format",
"readable",
"by",
"MS",
"Excel",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L895-L911 | train | 28,118 |
google/google-visualization-python | gviz_api.py | DataTable._ToJSonObj | def _ToJSonObj(self, columns_order=None, order_by=()):
"""Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs must be present.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A dictionary object for use by ToJSon or ToJSonResponse.
"""
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
# Creating the column JSON objects
col_objs = []
for col_id in columns_order:
col_obj = {"id": col_dict[col_id]["id"],
"label": col_dict[col_id]["label"],
"type": col_dict[col_id]["type"]}
if col_dict[col_id]["custom_properties"]:
col_obj["p"] = col_dict[col_id]["custom_properties"]
col_objs.append(col_obj)
# Creating the rows jsons
row_objs = []
for row, cp in self._PreparedData(order_by):
cell_objs = []
for col in columns_order:
value = self.CoerceValue(row.get(col, None), col_dict[col]["type"])
if value is None:
cell_obj = None
elif isinstance(value, tuple):
cell_obj = {"v": value[0]}
if len(value) > 1 and value[1] is not None:
cell_obj["f"] = value[1]
if len(value) == 3:
cell_obj["p"] = value[2]
else:
cell_obj = {"v": value}
cell_objs.append(cell_obj)
row_obj = {"c": cell_objs}
if cp:
row_obj["p"] = cp
row_objs.append(row_obj)
json_obj = {"cols": col_objs, "rows": row_objs}
if self.custom_properties:
json_obj["p"] = self.custom_properties
return json_obj | python | def _ToJSonObj(self, columns_order=None, order_by=()):
"""Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs must be present.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A dictionary object for use by ToJSon or ToJSonResponse.
"""
if columns_order is None:
columns_order = [col["id"] for col in self.__columns]
col_dict = dict([(col["id"], col) for col in self.__columns])
# Creating the column JSON objects
col_objs = []
for col_id in columns_order:
col_obj = {"id": col_dict[col_id]["id"],
"label": col_dict[col_id]["label"],
"type": col_dict[col_id]["type"]}
if col_dict[col_id]["custom_properties"]:
col_obj["p"] = col_dict[col_id]["custom_properties"]
col_objs.append(col_obj)
# Creating the rows jsons
row_objs = []
for row, cp in self._PreparedData(order_by):
cell_objs = []
for col in columns_order:
value = self.CoerceValue(row.get(col, None), col_dict[col]["type"])
if value is None:
cell_obj = None
elif isinstance(value, tuple):
cell_obj = {"v": value[0]}
if len(value) > 1 and value[1] is not None:
cell_obj["f"] = value[1]
if len(value) == 3:
cell_obj["p"] = value[2]
else:
cell_obj = {"v": value}
cell_objs.append(cell_obj)
row_obj = {"c": cell_objs}
if cp:
row_obj["p"] = cp
row_objs.append(row_obj)
json_obj = {"cols": col_objs, "rows": row_objs}
if self.custom_properties:
json_obj["p"] = self.custom_properties
return json_obj | [
"def",
"_ToJSonObj",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"if",
"columns_order",
"is",
"None",
":",
"columns_order",
"=",
"[",
"col",
"[",
"\"id\"",
"]",
"for",
"col",
"in",
"self",
".",
"__columns",... | Returns an object suitable to be converted to JSON.
Args:
columns_order: Optional. A list of all column IDs in the order in which
you want them created in the output table. If specified,
all column IDs must be present.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A dictionary object for use by ToJSon or ToJSonResponse. | [
"Returns",
"an",
"object",
"suitable",
"to",
"be",
"converted",
"to",
"JSON",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L913-L966 | train | 28,119 |
google/google-visualization-python | gviz_api.py | DataTable.ToJSon | def ToJSon(self, columns_order=None, order_by=()):
"""Returns a string that can be used in a JS DataTable constructor.
This method writes a JSON string that can be passed directly into a Google
Visualization API DataTable constructor. Use this output if you are
hosting the visualization HTML on your site, and want to code the data
table in Python. Pass this string into the
google.visualization.DataTable constructor, e.g,:
... on my page that hosts my visualization ...
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable(_my_JSon_string, 0.6);
myTable.draw(data);
}
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A JSon constructor string to generate a JS DataTable with the data
stored in the DataTable object.
Example result (the result is without the newlines):
{cols: [{id:"a",label:"a",type:"number"},
{id:"b",label:"b",type:"string"},
{id:"c",label:"c",type:"number"}],
rows: [{c:[{v:1},{v:"z"},{v:2}]}, c:{[{v:3,f:"3$"},{v:"w"},null]}],
p: {'foo': 'bar'}}
Raises:
DataTableException: The data does not match the type.
"""
encoded_response_str = DataTableJSONEncoder().encode(self._ToJSonObj(columns_order, order_by))
if not isinstance(encoded_response_str, str):
return encoded_response_str.encode("utf-8")
return encoded_response_str | python | def ToJSon(self, columns_order=None, order_by=()):
"""Returns a string that can be used in a JS DataTable constructor.
This method writes a JSON string that can be passed directly into a Google
Visualization API DataTable constructor. Use this output if you are
hosting the visualization HTML on your site, and want to code the data
table in Python. Pass this string into the
google.visualization.DataTable constructor, e.g,:
... on my page that hosts my visualization ...
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable(_my_JSon_string, 0.6);
myTable.draw(data);
}
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A JSon constructor string to generate a JS DataTable with the data
stored in the DataTable object.
Example result (the result is without the newlines):
{cols: [{id:"a",label:"a",type:"number"},
{id:"b",label:"b",type:"string"},
{id:"c",label:"c",type:"number"}],
rows: [{c:[{v:1},{v:"z"},{v:2}]}, c:{[{v:3,f:"3$"},{v:"w"},null]}],
p: {'foo': 'bar'}}
Raises:
DataTableException: The data does not match the type.
"""
encoded_response_str = DataTableJSONEncoder().encode(self._ToJSonObj(columns_order, order_by))
if not isinstance(encoded_response_str, str):
return encoded_response_str.encode("utf-8")
return encoded_response_str | [
"def",
"ToJSon",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
")",
":",
"encoded_response_str",
"=",
"DataTableJSONEncoder",
"(",
")",
".",
"encode",
"(",
"self",
".",
"_ToJSonObj",
"(",
"columns_order",
",",
"order_by",
... | Returns a string that can be used in a JS DataTable constructor.
This method writes a JSON string that can be passed directly into a Google
Visualization API DataTable constructor. Use this output if you are
hosting the visualization HTML on your site, and want to code the data
table in Python. Pass this string into the
google.visualization.DataTable constructor, e.g,:
... on my page that hosts my visualization ...
google.setOnLoadCallback(drawTable);
function drawTable() {
var data = new google.visualization.DataTable(_my_JSon_string, 0.6);
myTable.draw(data);
}
Args:
columns_order: Optional. Specifies the order of columns in the
output table. Specify a list of all column IDs in the order
in which you want the table created.
Note that you must list all column IDs in this parameter,
if you use it.
order_by: Optional. Specifies the name of the column(s) to sort by.
Passed as is to _PreparedData().
Returns:
A JSon constructor string to generate a JS DataTable with the data
stored in the DataTable object.
Example result (the result is without the newlines):
{cols: [{id:"a",label:"a",type:"number"},
{id:"b",label:"b",type:"string"},
{id:"c",label:"c",type:"number"}],
rows: [{c:[{v:1},{v:"z"},{v:2}]}, c:{[{v:3,f:"3$"},{v:"w"},null]}],
p: {'foo': 'bar'}}
Raises:
DataTableException: The data does not match the type. | [
"Returns",
"a",
"string",
"that",
"can",
"be",
"used",
"in",
"a",
"JS",
"DataTable",
"constructor",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L968-L1009 | train | 28,120 |
google/google-visualization-python | gviz_api.py | DataTable.ToJSonResponse | def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0,
response_handler="google.visualization.Query.setResponse"):
"""Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is used to deliver a data table to a visualization hosted on
a different page.
Args:
columns_order: Optional. Passed straight to self.ToJSon().
order_by: Optional. Passed straight to self.ToJSon().
req_id: Optional. The response id, as retrieved by the request.
response_handler: Optional. The response handler, as retrieved by the
request.
Returns:
A JSON response string to be received by JS the visualization Query
object. This response would be translated into a DataTable on the
client side.
Example result (newlines added for readability):
google.visualization.Query.setResponse({
'version':'0.6', 'reqId':'0', 'status':'OK',
'table': {cols: [...], rows: [...]}});
Note: The URL returning this string can be used as a data source by Google
Visualization Gadgets or from JS code.
"""
response_obj = {
"version": "0.6",
"reqId": str(req_id),
"table": self._ToJSonObj(columns_order, order_by),
"status": "ok"
}
encoded_response_str = DataTableJSONEncoder().encode(response_obj)
if not isinstance(encoded_response_str, str):
encoded_response_str = encoded_response_str.encode("utf-8")
return "%s(%s);" % (response_handler, encoded_response_str) | python | def ToJSonResponse(self, columns_order=None, order_by=(), req_id=0,
response_handler="google.visualization.Query.setResponse"):
"""Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is used to deliver a data table to a visualization hosted on
a different page.
Args:
columns_order: Optional. Passed straight to self.ToJSon().
order_by: Optional. Passed straight to self.ToJSon().
req_id: Optional. The response id, as retrieved by the request.
response_handler: Optional. The response handler, as retrieved by the
request.
Returns:
A JSON response string to be received by JS the visualization Query
object. This response would be translated into a DataTable on the
client side.
Example result (newlines added for readability):
google.visualization.Query.setResponse({
'version':'0.6', 'reqId':'0', 'status':'OK',
'table': {cols: [...], rows: [...]}});
Note: The URL returning this string can be used as a data source by Google
Visualization Gadgets or from JS code.
"""
response_obj = {
"version": "0.6",
"reqId": str(req_id),
"table": self._ToJSonObj(columns_order, order_by),
"status": "ok"
}
encoded_response_str = DataTableJSONEncoder().encode(response_obj)
if not isinstance(encoded_response_str, str):
encoded_response_str = encoded_response_str.encode("utf-8")
return "%s(%s);" % (response_handler, encoded_response_str) | [
"def",
"ToJSonResponse",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
",",
"req_id",
"=",
"0",
",",
"response_handler",
"=",
"\"google.visualization.Query.setResponse\"",
")",
":",
"response_obj",
"=",
"{",
"\"version\"",
":",
... | Writes a table as a JSON response that can be returned as-is to a client.
This method writes a JSON response to return to a client in response to a
Google Visualization API query. This string can be processed by the calling
page, and is used to deliver a data table to a visualization hosted on
a different page.
Args:
columns_order: Optional. Passed straight to self.ToJSon().
order_by: Optional. Passed straight to self.ToJSon().
req_id: Optional. The response id, as retrieved by the request.
response_handler: Optional. The response handler, as retrieved by the
request.
Returns:
A JSON response string to be received by JS the visualization Query
object. This response would be translated into a DataTable on the
client side.
Example result (newlines added for readability):
google.visualization.Query.setResponse({
'version':'0.6', 'reqId':'0', 'status':'OK',
'table': {cols: [...], rows: [...]}});
Note: The URL returning this string can be used as a data source by Google
Visualization Gadgets or from JS code. | [
"Writes",
"a",
"table",
"as",
"a",
"JSON",
"response",
"that",
"can",
"be",
"returned",
"as",
"-",
"is",
"to",
"a",
"client",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L1011-L1049 | train | 28,121 |
google/google-visualization-python | gviz_api.py | DataTable.ToResponse | def ToResponse(self, columns_order=None, order_by=(), tqx=""):
"""Writes the right response according to the request string passed in tqx.
This method parses the tqx request string (format of which is defined in
the documentation for implementing a data source of Google Visualization),
and returns the right response according to the request.
It parses out the "out" parameter of tqx, calls the relevant response
(ToJSonResponse() for "json", ToCsv() for "csv", ToHtml() for "html",
ToTsvExcel() for "tsv-excel") and passes the response function the rest of
the relevant request keys.
Args:
columns_order: Optional. Passed as is to the relevant response function.
order_by: Optional. Passed as is to the relevant response function.
tqx: Optional. The request string as received by HTTP GET. Should be in
the format "key1:value1;key2:value2...". All keys have a default
value, so an empty string will just do the default (which is calling
ToJSonResponse() with no extra parameters).
Returns:
A response string, as returned by the relevant response function.
Raises:
DataTableException: One of the parameters passed in tqx is not supported.
"""
tqx_dict = {}
if tqx:
tqx_dict = dict(opt.split(":") for opt in tqx.split(";"))
if tqx_dict.get("version", "0.6") != "0.6":
raise DataTableException(
"Version (%s) passed by request is not supported."
% tqx_dict["version"])
if tqx_dict.get("out", "json") == "json":
response_handler = tqx_dict.get("responseHandler",
"google.visualization.Query.setResponse")
return self.ToJSonResponse(columns_order, order_by,
req_id=tqx_dict.get("reqId", 0),
response_handler=response_handler)
elif tqx_dict["out"] == "html":
return self.ToHtml(columns_order, order_by)
elif tqx_dict["out"] == "csv":
return self.ToCsv(columns_order, order_by)
elif tqx_dict["out"] == "tsv-excel":
return self.ToTsvExcel(columns_order, order_by)
else:
raise DataTableException(
"'out' parameter: '%s' is not supported" % tqx_dict["out"]) | python | def ToResponse(self, columns_order=None, order_by=(), tqx=""):
"""Writes the right response according to the request string passed in tqx.
This method parses the tqx request string (format of which is defined in
the documentation for implementing a data source of Google Visualization),
and returns the right response according to the request.
It parses out the "out" parameter of tqx, calls the relevant response
(ToJSonResponse() for "json", ToCsv() for "csv", ToHtml() for "html",
ToTsvExcel() for "tsv-excel") and passes the response function the rest of
the relevant request keys.
Args:
columns_order: Optional. Passed as is to the relevant response function.
order_by: Optional. Passed as is to the relevant response function.
tqx: Optional. The request string as received by HTTP GET. Should be in
the format "key1:value1;key2:value2...". All keys have a default
value, so an empty string will just do the default (which is calling
ToJSonResponse() with no extra parameters).
Returns:
A response string, as returned by the relevant response function.
Raises:
DataTableException: One of the parameters passed in tqx is not supported.
"""
tqx_dict = {}
if tqx:
tqx_dict = dict(opt.split(":") for opt in tqx.split(";"))
if tqx_dict.get("version", "0.6") != "0.6":
raise DataTableException(
"Version (%s) passed by request is not supported."
% tqx_dict["version"])
if tqx_dict.get("out", "json") == "json":
response_handler = tqx_dict.get("responseHandler",
"google.visualization.Query.setResponse")
return self.ToJSonResponse(columns_order, order_by,
req_id=tqx_dict.get("reqId", 0),
response_handler=response_handler)
elif tqx_dict["out"] == "html":
return self.ToHtml(columns_order, order_by)
elif tqx_dict["out"] == "csv":
return self.ToCsv(columns_order, order_by)
elif tqx_dict["out"] == "tsv-excel":
return self.ToTsvExcel(columns_order, order_by)
else:
raise DataTableException(
"'out' parameter: '%s' is not supported" % tqx_dict["out"]) | [
"def",
"ToResponse",
"(",
"self",
",",
"columns_order",
"=",
"None",
",",
"order_by",
"=",
"(",
")",
",",
"tqx",
"=",
"\"\"",
")",
":",
"tqx_dict",
"=",
"{",
"}",
"if",
"tqx",
":",
"tqx_dict",
"=",
"dict",
"(",
"opt",
".",
"split",
"(",
"\":\"",
... | Writes the right response according to the request string passed in tqx.
This method parses the tqx request string (format of which is defined in
the documentation for implementing a data source of Google Visualization),
and returns the right response according to the request.
It parses out the "out" parameter of tqx, calls the relevant response
(ToJSonResponse() for "json", ToCsv() for "csv", ToHtml() for "html",
ToTsvExcel() for "tsv-excel") and passes the response function the rest of
the relevant request keys.
Args:
columns_order: Optional. Passed as is to the relevant response function.
order_by: Optional. Passed as is to the relevant response function.
tqx: Optional. The request string as received by HTTP GET. Should be in
the format "key1:value1;key2:value2...". All keys have a default
value, so an empty string will just do the default (which is calling
ToJSonResponse() with no extra parameters).
Returns:
A response string, as returned by the relevant response function.
Raises:
DataTableException: One of the parameters passed in tqx is not supported. | [
"Writes",
"the",
"right",
"response",
"according",
"to",
"the",
"request",
"string",
"passed",
"in",
"tqx",
"."
] | cbfb4d69ad2f4ca30dc55791629280aa3214c8e3 | https://github.com/google/google-visualization-python/blob/cbfb4d69ad2f4ca30dc55791629280aa3214c8e3/gviz_api.py#L1051-L1098 | train | 28,122 |
vvangelovski/django-audit-log | audit_log/models/managers.py | AuditLog.copy_fields | def copy_fields(self, model):
"""
Creates copies of the fields we are keeping
track of for the provided model, returning a
dictionary mapping field name to a copied field object.
"""
fields = {'__module__' : model.__module__}
for field in model._meta.fields:
if not field.name in self._exclude:
field = copy.deepcopy(field)
if isinstance(field, models.AutoField):
#we replace the AutoField of the original model
#with an IntegerField because a model can
#have only one autofield.
field.__class__ = models.IntegerField
if field.primary_key:
field.serialize = True
#OneToOne fields should really be tracked
#as ForeignKey fields
if isinstance(field, models.OneToOneField):
field.__class__ = models.ForeignKey
if field.primary_key or field.unique:
#unique fields of the original model
#can not be guaranteed to be unique
#in the audit log entry but they
#should still be indexed for faster lookups.
field.primary_key = False
field._unique = False
field.db_index = True
if field.remote_field and field.remote_field.related_name:
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.related_name
)
elif field.remote_field:
try:
if field.remote_field.get_accessor_name():
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.get_accessor_name()
)
except e:
pass
fields[field.name] = field
return fields | python | def copy_fields(self, model):
"""
Creates copies of the fields we are keeping
track of for the provided model, returning a
dictionary mapping field name to a copied field object.
"""
fields = {'__module__' : model.__module__}
for field in model._meta.fields:
if not field.name in self._exclude:
field = copy.deepcopy(field)
if isinstance(field, models.AutoField):
#we replace the AutoField of the original model
#with an IntegerField because a model can
#have only one autofield.
field.__class__ = models.IntegerField
if field.primary_key:
field.serialize = True
#OneToOne fields should really be tracked
#as ForeignKey fields
if isinstance(field, models.OneToOneField):
field.__class__ = models.ForeignKey
if field.primary_key or field.unique:
#unique fields of the original model
#can not be guaranteed to be unique
#in the audit log entry but they
#should still be indexed for faster lookups.
field.primary_key = False
field._unique = False
field.db_index = True
if field.remote_field and field.remote_field.related_name:
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.related_name
)
elif field.remote_field:
try:
if field.remote_field.get_accessor_name():
field.remote_field.related_name = '_auditlog_{}_{}'.format(
model._meta.model_name,
field.remote_field.get_accessor_name()
)
except e:
pass
fields[field.name] = field
return fields | [
"def",
"copy_fields",
"(",
"self",
",",
"model",
")",
":",
"fields",
"=",
"{",
"'__module__'",
":",
"model",
".",
"__module__",
"}",
"for",
"field",
"in",
"model",
".",
"_meta",
".",
"fields",
":",
"if",
"not",
"field",
".",
"name",
"in",
"self",
"."... | Creates copies of the fields we are keeping
track of for the provided model, returning a
dictionary mapping field name to a copied field object. | [
"Creates",
"copies",
"of",
"the",
"fields",
"we",
"are",
"keeping",
"track",
"of",
"for",
"the",
"provided",
"model",
"returning",
"a",
"dictionary",
"mapping",
"field",
"name",
"to",
"a",
"copied",
"field",
"object",
"."
] | f1bee75360a67390fbef67c110e9a245b41ebb92 | https://github.com/vvangelovski/django-audit-log/blob/f1bee75360a67390fbef67c110e9a245b41ebb92/audit_log/models/managers.py#L128-L186 | train | 28,123 |
vvangelovski/django-audit-log | audit_log/models/managers.py | AuditLog.get_logging_fields | def get_logging_fields(self, model):
"""
Returns a dictionary mapping of the fields that are used for
keeping the acutal audit log entries.
"""
rel_name = '_%s_audit_log_entry'%model._meta.object_name.lower()
def entry_instance_to_unicode(log_entry):
try:
result = '%s: %s %s at %s'%(model._meta.object_name,
log_entry.object_state,
log_entry.get_action_type_display().lower(),
log_entry.action_date,
)
except AttributeError:
result = '%s %s at %s'%(model._meta.object_name,
log_entry.get_action_type_display().lower(),
log_entry.action_date
)
return result
action_user_field = LastUserField(related_name = rel_name, editable = False)
#check if the manager has been attached to auth user model
if [model._meta.app_label, model.__name__] == getattr(settings, 'AUTH_USER_MODEL', 'auth.User').split("."):
action_user_field = LastUserField(related_name = rel_name, editable = False, to = 'self')
return {
'action_id' : models.AutoField(primary_key = True),
'action_date' : models.DateTimeField(default = datetime_now, editable = False, blank=False),
'action_user' : action_user_field,
'action_type' : models.CharField(max_length = 1, editable = False, choices = (
('I', _('Created')),
('U', _('Changed')),
('D', _('Deleted')),
)),
'object_state' : LogEntryObjectDescriptor(model),
'__unicode__' : entry_instance_to_unicode,
} | python | def get_logging_fields(self, model):
"""
Returns a dictionary mapping of the fields that are used for
keeping the acutal audit log entries.
"""
rel_name = '_%s_audit_log_entry'%model._meta.object_name.lower()
def entry_instance_to_unicode(log_entry):
try:
result = '%s: %s %s at %s'%(model._meta.object_name,
log_entry.object_state,
log_entry.get_action_type_display().lower(),
log_entry.action_date,
)
except AttributeError:
result = '%s %s at %s'%(model._meta.object_name,
log_entry.get_action_type_display().lower(),
log_entry.action_date
)
return result
action_user_field = LastUserField(related_name = rel_name, editable = False)
#check if the manager has been attached to auth user model
if [model._meta.app_label, model.__name__] == getattr(settings, 'AUTH_USER_MODEL', 'auth.User').split("."):
action_user_field = LastUserField(related_name = rel_name, editable = False, to = 'self')
return {
'action_id' : models.AutoField(primary_key = True),
'action_date' : models.DateTimeField(default = datetime_now, editable = False, blank=False),
'action_user' : action_user_field,
'action_type' : models.CharField(max_length = 1, editable = False, choices = (
('I', _('Created')),
('U', _('Changed')),
('D', _('Deleted')),
)),
'object_state' : LogEntryObjectDescriptor(model),
'__unicode__' : entry_instance_to_unicode,
} | [
"def",
"get_logging_fields",
"(",
"self",
",",
"model",
")",
":",
"rel_name",
"=",
"'_%s_audit_log_entry'",
"%",
"model",
".",
"_meta",
".",
"object_name",
".",
"lower",
"(",
")",
"def",
"entry_instance_to_unicode",
"(",
"log_entry",
")",
":",
"try",
":",
"r... | Returns a dictionary mapping of the fields that are used for
keeping the acutal audit log entries. | [
"Returns",
"a",
"dictionary",
"mapping",
"of",
"the",
"fields",
"that",
"are",
"used",
"for",
"keeping",
"the",
"acutal",
"audit",
"log",
"entries",
"."
] | f1bee75360a67390fbef67c110e9a245b41ebb92 | https://github.com/vvangelovski/django-audit-log/blob/f1bee75360a67390fbef67c110e9a245b41ebb92/audit_log/models/managers.py#L190-L231 | train | 28,124 |
vvangelovski/django-audit-log | audit_log/models/managers.py | AuditLog.get_meta_options | def get_meta_options(self, model):
"""
Returns a dictionary of Meta options for the
autdit log model.
"""
result = {
'ordering' : ('-action_date',),
'app_label' : model._meta.app_label,
}
from django.db.models.options import DEFAULT_NAMES
if 'default_permissions' in DEFAULT_NAMES:
result.update({'default_permissions': ()})
return result | python | def get_meta_options(self, model):
"""
Returns a dictionary of Meta options for the
autdit log model.
"""
result = {
'ordering' : ('-action_date',),
'app_label' : model._meta.app_label,
}
from django.db.models.options import DEFAULT_NAMES
if 'default_permissions' in DEFAULT_NAMES:
result.update({'default_permissions': ()})
return result | [
"def",
"get_meta_options",
"(",
"self",
",",
"model",
")",
":",
"result",
"=",
"{",
"'ordering'",
":",
"(",
"'-action_date'",
",",
")",
",",
"'app_label'",
":",
"model",
".",
"_meta",
".",
"app_label",
",",
"}",
"from",
"django",
".",
"db",
".",
"model... | Returns a dictionary of Meta options for the
autdit log model. | [
"Returns",
"a",
"dictionary",
"of",
"Meta",
"options",
"for",
"the",
"autdit",
"log",
"model",
"."
] | f1bee75360a67390fbef67c110e9a245b41ebb92 | https://github.com/vvangelovski/django-audit-log/blob/f1bee75360a67390fbef67c110e9a245b41ebb92/audit_log/models/managers.py#L234-L246 | train | 28,125 |
vvangelovski/django-audit-log | audit_log/models/managers.py | AuditLog.create_log_entry_model | def create_log_entry_model(self, model):
"""
Creates a log entry model that will be associated with
the model provided.
"""
attrs = self.copy_fields(model)
attrs.update(self.get_logging_fields(model))
attrs.update(Meta = type(str('Meta'), (), self.get_meta_options(model)))
name = str('%sAuditLogEntry'%model._meta.object_name)
return type(name, (models.Model,), attrs) | python | def create_log_entry_model(self, model):
"""
Creates a log entry model that will be associated with
the model provided.
"""
attrs = self.copy_fields(model)
attrs.update(self.get_logging_fields(model))
attrs.update(Meta = type(str('Meta'), (), self.get_meta_options(model)))
name = str('%sAuditLogEntry'%model._meta.object_name)
return type(name, (models.Model,), attrs) | [
"def",
"create_log_entry_model",
"(",
"self",
",",
"model",
")",
":",
"attrs",
"=",
"self",
".",
"copy_fields",
"(",
"model",
")",
"attrs",
".",
"update",
"(",
"self",
".",
"get_logging_fields",
"(",
"model",
")",
")",
"attrs",
".",
"update",
"(",
"Meta"... | Creates a log entry model that will be associated with
the model provided. | [
"Creates",
"a",
"log",
"entry",
"model",
"that",
"will",
"be",
"associated",
"with",
"the",
"model",
"provided",
"."
] | f1bee75360a67390fbef67c110e9a245b41ebb92 | https://github.com/vvangelovski/django-audit-log/blob/f1bee75360a67390fbef67c110e9a245b41ebb92/audit_log/models/managers.py#L248-L258 | train | 28,126 |
seung-lab/cloud-volume | cloudvolume/chunks.py | decode_kempressed | def decode_kempressed(bytestring):
"""subvol not bytestring since numpy conversion is done inside fpzip extension."""
subvol = fpzip.decompress(bytestring, order='F')
return np.swapaxes(subvol, 3,2) - 2.0 | python | def decode_kempressed(bytestring):
"""subvol not bytestring since numpy conversion is done inside fpzip extension."""
subvol = fpzip.decompress(bytestring, order='F')
return np.swapaxes(subvol, 3,2) - 2.0 | [
"def",
"decode_kempressed",
"(",
"bytestring",
")",
":",
"subvol",
"=",
"fpzip",
".",
"decompress",
"(",
"bytestring",
",",
"order",
"=",
"'F'",
")",
"return",
"np",
".",
"swapaxes",
"(",
"subvol",
",",
"3",
",",
"2",
")",
"-",
"2.0"
] | subvol not bytestring since numpy conversion is done inside fpzip extension. | [
"subvol",
"not",
"bytestring",
"since",
"numpy",
"conversion",
"is",
"done",
"inside",
"fpzip",
"extension",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/chunks.py#L143-L146 | train | 28,127 |
seung-lab/cloud-volume | cloudvolume/sharedmemory.py | bbox2array | def bbox2array(vol, bbox, order='F', readonly=False, lock=None, location=None):
"""Convenince method for creating a
shared memory numpy array based on a CloudVolume
and Bbox. c.f. sharedmemory.ndarray for information
on the optional lock parameter."""
location = location or vol.shared_memory_id
shape = list(bbox.size3()) + [ vol.num_channels ]
return ndarray(shape=shape, dtype=vol.dtype, location=location,
readonly=readonly, lock=lock, order=order) | python | def bbox2array(vol, bbox, order='F', readonly=False, lock=None, location=None):
"""Convenince method for creating a
shared memory numpy array based on a CloudVolume
and Bbox. c.f. sharedmemory.ndarray for information
on the optional lock parameter."""
location = location or vol.shared_memory_id
shape = list(bbox.size3()) + [ vol.num_channels ]
return ndarray(shape=shape, dtype=vol.dtype, location=location,
readonly=readonly, lock=lock, order=order) | [
"def",
"bbox2array",
"(",
"vol",
",",
"bbox",
",",
"order",
"=",
"'F'",
",",
"readonly",
"=",
"False",
",",
"lock",
"=",
"None",
",",
"location",
"=",
"None",
")",
":",
"location",
"=",
"location",
"or",
"vol",
".",
"shared_memory_id",
"shape",
"=",
... | Convenince method for creating a
shared memory numpy array based on a CloudVolume
and Bbox. c.f. sharedmemory.ndarray for information
on the optional lock parameter. | [
"Convenince",
"method",
"for",
"creating",
"a",
"shared",
"memory",
"numpy",
"array",
"based",
"on",
"a",
"CloudVolume",
"and",
"Bbox",
".",
"c",
".",
"f",
".",
"sharedmemory",
".",
"ndarray",
"for",
"information",
"on",
"the",
"optional",
"lock",
"parameter... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/sharedmemory.py#L38-L46 | train | 28,128 |
seung-lab/cloud-volume | cloudvolume/sharedmemory.py | ndarray_fs | def ndarray_fs(shape, dtype, location, lock, readonly=False, order='F', **kwargs):
"""Emulate shared memory using the filesystem."""
dbytes = np.dtype(dtype).itemsize
nbytes = Vec(*shape).rectVolume() * dbytes
directory = mkdir(EMULATED_SHM_DIRECTORY)
filename = os.path.join(directory, location)
if lock:
lock.acquire()
exists = os.path.exists(filename)
size = 0 if not exists else os.path.getsize(filename)
if readonly and not exists:
raise SharedMemoryReadError(filename + " has not been allocated. Requested " + str(nbytes) + " bytes.")
elif readonly and size != nbytes:
raise SharedMemoryReadError("{} exists, but the allocation size ({} bytes) does not match the request ({} bytes).".format(
filename, size, nbytes
))
if exists:
if size > nbytes:
with open(filename, 'wb') as f:
os.ftruncate(f.fileno(), nbytes)
elif size < nbytes:
# too small? just remake it below
# if we were being more efficient
# we could just append zeros
os.unlink(filename)
exists = os.path.exists(filename)
if not exists:
blocksize = 1024 * 1024 * 10 * dbytes
steps = int(math.ceil(float(nbytes) / float(blocksize)))
total = 0
with open(filename, 'wb') as f:
for i in range(0, steps):
write_bytes = min(blocksize, nbytes - total)
f.write(b'\x00' * write_bytes)
total += blocksize
if lock:
lock.release()
with open(filename, 'r+b') as f:
array_like = mmap.mmap(f.fileno(), 0) # map entire file
renderbuffer = np.ndarray(buffer=array_like, dtype=dtype, shape=shape, order=order, **kwargs)
renderbuffer.setflags(write=(not readonly))
return array_like, renderbuffer | python | def ndarray_fs(shape, dtype, location, lock, readonly=False, order='F', **kwargs):
"""Emulate shared memory using the filesystem."""
dbytes = np.dtype(dtype).itemsize
nbytes = Vec(*shape).rectVolume() * dbytes
directory = mkdir(EMULATED_SHM_DIRECTORY)
filename = os.path.join(directory, location)
if lock:
lock.acquire()
exists = os.path.exists(filename)
size = 0 if not exists else os.path.getsize(filename)
if readonly and not exists:
raise SharedMemoryReadError(filename + " has not been allocated. Requested " + str(nbytes) + " bytes.")
elif readonly and size != nbytes:
raise SharedMemoryReadError("{} exists, but the allocation size ({} bytes) does not match the request ({} bytes).".format(
filename, size, nbytes
))
if exists:
if size > nbytes:
with open(filename, 'wb') as f:
os.ftruncate(f.fileno(), nbytes)
elif size < nbytes:
# too small? just remake it below
# if we were being more efficient
# we could just append zeros
os.unlink(filename)
exists = os.path.exists(filename)
if not exists:
blocksize = 1024 * 1024 * 10 * dbytes
steps = int(math.ceil(float(nbytes) / float(blocksize)))
total = 0
with open(filename, 'wb') as f:
for i in range(0, steps):
write_bytes = min(blocksize, nbytes - total)
f.write(b'\x00' * write_bytes)
total += blocksize
if lock:
lock.release()
with open(filename, 'r+b') as f:
array_like = mmap.mmap(f.fileno(), 0) # map entire file
renderbuffer = np.ndarray(buffer=array_like, dtype=dtype, shape=shape, order=order, **kwargs)
renderbuffer.setflags(write=(not readonly))
return array_like, renderbuffer | [
"def",
"ndarray_fs",
"(",
"shape",
",",
"dtype",
",",
"location",
",",
"lock",
",",
"readonly",
"=",
"False",
",",
"order",
"=",
"'F'",
",",
"*",
"*",
"kwargs",
")",
":",
"dbytes",
"=",
"np",
".",
"dtype",
"(",
"dtype",
")",
".",
"itemsize",
"nbyte... | Emulate shared memory using the filesystem. | [
"Emulate",
"shared",
"memory",
"using",
"the",
"filesystem",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/sharedmemory.py#L75-L125 | train | 28,129 |
seung-lab/cloud-volume | cloudvolume/txrx.py | cutout | def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1,
shared_memory_location=None, output_to_shared_memory=False):
"""Cutout a requested bounding box from storage and return it as a numpy array."""
global fs_lock
cloudpath_bbox = requested_bbox.expand_to_chunk_size(vol.underlying, offset=vol.voxel_offset)
cloudpath_bbox = Bbox.clamp(cloudpath_bbox, vol.bounds)
cloudpaths = list(chunknames(cloudpath_bbox, vol.bounds, vol.key, vol.underlying))
shape = list(requested_bbox.size3()) + [ vol.num_channels ]
handle = None
if parallel == 1:
if output_to_shared_memory:
array_like, renderbuffer = shm.bbox2array(vol, requested_bbox,
location=shared_memory_location, lock=fs_lock)
shm.track_mmap(array_like)
else:
renderbuffer = np.zeros(shape=shape, dtype=vol.dtype, order='F')
def process(img3d, bbox):
shade(renderbuffer, requested_bbox, img3d, bbox)
download_multiple(vol, cloudpaths, fn=process)
else:
handle, renderbuffer = multi_process_cutout(vol, requested_bbox, cloudpaths, parallel,
shared_memory_location, output_to_shared_memory)
renderbuffer = renderbuffer[ ::steps.x, ::steps.y, ::steps.z, channel_slice ]
return VolumeCutout.from_volume(vol, renderbuffer, requested_bbox, handle=handle) | python | def cutout(vol, requested_bbox, steps, channel_slice=slice(None), parallel=1,
shared_memory_location=None, output_to_shared_memory=False):
"""Cutout a requested bounding box from storage and return it as a numpy array."""
global fs_lock
cloudpath_bbox = requested_bbox.expand_to_chunk_size(vol.underlying, offset=vol.voxel_offset)
cloudpath_bbox = Bbox.clamp(cloudpath_bbox, vol.bounds)
cloudpaths = list(chunknames(cloudpath_bbox, vol.bounds, vol.key, vol.underlying))
shape = list(requested_bbox.size3()) + [ vol.num_channels ]
handle = None
if parallel == 1:
if output_to_shared_memory:
array_like, renderbuffer = shm.bbox2array(vol, requested_bbox,
location=shared_memory_location, lock=fs_lock)
shm.track_mmap(array_like)
else:
renderbuffer = np.zeros(shape=shape, dtype=vol.dtype, order='F')
def process(img3d, bbox):
shade(renderbuffer, requested_bbox, img3d, bbox)
download_multiple(vol, cloudpaths, fn=process)
else:
handle, renderbuffer = multi_process_cutout(vol, requested_bbox, cloudpaths, parallel,
shared_memory_location, output_to_shared_memory)
renderbuffer = renderbuffer[ ::steps.x, ::steps.y, ::steps.z, channel_slice ]
return VolumeCutout.from_volume(vol, renderbuffer, requested_bbox, handle=handle) | [
"def",
"cutout",
"(",
"vol",
",",
"requested_bbox",
",",
"steps",
",",
"channel_slice",
"=",
"slice",
"(",
"None",
")",
",",
"parallel",
"=",
"1",
",",
"shared_memory_location",
"=",
"None",
",",
"output_to_shared_memory",
"=",
"False",
")",
":",
"global",
... | Cutout a requested bounding box from storage and return it as a numpy array. | [
"Cutout",
"a",
"requested",
"bounding",
"box",
"from",
"storage",
"and",
"return",
"it",
"as",
"a",
"numpy",
"array",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L109-L137 | train | 28,130 |
seung-lab/cloud-volume | cloudvolume/txrx.py | decode | def decode(vol, filename, content):
"""Decode content according to settings in a cloudvolume instance."""
bbox = Bbox.from_filename(filename)
content_len = len(content) if content is not None else 0
if not content:
if vol.fill_missing:
content = ''
else:
raise EmptyVolumeException(filename)
shape = list(bbox.size3()) + [ vol.num_channels ]
try:
return chunks.decode(
content,
encoding=vol.encoding,
shape=shape,
dtype=vol.dtype,
block_size=vol.compressed_segmentation_block_size,
)
except Exception as error:
print(red('File Read Error: {} bytes, {}, {}, errors: {}'.format(
content_len, bbox, filename, error)))
raise | python | def decode(vol, filename, content):
"""Decode content according to settings in a cloudvolume instance."""
bbox = Bbox.from_filename(filename)
content_len = len(content) if content is not None else 0
if not content:
if vol.fill_missing:
content = ''
else:
raise EmptyVolumeException(filename)
shape = list(bbox.size3()) + [ vol.num_channels ]
try:
return chunks.decode(
content,
encoding=vol.encoding,
shape=shape,
dtype=vol.dtype,
block_size=vol.compressed_segmentation_block_size,
)
except Exception as error:
print(red('File Read Error: {} bytes, {}, {}, errors: {}'.format(
content_len, bbox, filename, error)))
raise | [
"def",
"decode",
"(",
"vol",
",",
"filename",
",",
"content",
")",
":",
"bbox",
"=",
"Bbox",
".",
"from_filename",
"(",
"filename",
")",
"content_len",
"=",
"len",
"(",
"content",
")",
"if",
"content",
"is",
"not",
"None",
"else",
"0",
"if",
"not",
"... | Decode content according to settings in a cloudvolume instance. | [
"Decode",
"content",
"according",
"to",
"settings",
"in",
"a",
"cloudvolume",
"instance",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L173-L197 | train | 28,131 |
seung-lab/cloud-volume | cloudvolume/txrx.py | shade | def shade(renderbuffer, bufferbbox, img3d, bbox):
"""Shade a renderbuffer with a downloaded chunk.
The buffer will only be painted in the overlapping
region of the content."""
if not Bbox.intersects(bufferbbox, bbox):
return
spt = max2(bbox.minpt, bufferbbox.minpt)
ept = min2(bbox.maxpt, bufferbbox.maxpt)
ZERO3 = Vec(0,0,0)
istart = max2(spt - bbox.minpt, ZERO3)
iend = min2(ept - bbox.maxpt, ZERO3) + img3d.shape[:3]
rbox = Bbox(spt, ept) - bufferbbox.minpt
if len(img3d.shape) == 3:
img3d = img3d[ :, :, :, np.newaxis]
renderbuffer[ rbox.to_slices() ] = img3d[ istart.x:iend.x, istart.y:iend.y, istart.z:iend.z, : ] | python | def shade(renderbuffer, bufferbbox, img3d, bbox):
"""Shade a renderbuffer with a downloaded chunk.
The buffer will only be painted in the overlapping
region of the content."""
if not Bbox.intersects(bufferbbox, bbox):
return
spt = max2(bbox.minpt, bufferbbox.minpt)
ept = min2(bbox.maxpt, bufferbbox.maxpt)
ZERO3 = Vec(0,0,0)
istart = max2(spt - bbox.minpt, ZERO3)
iend = min2(ept - bbox.maxpt, ZERO3) + img3d.shape[:3]
rbox = Bbox(spt, ept) - bufferbbox.minpt
if len(img3d.shape) == 3:
img3d = img3d[ :, :, :, np.newaxis]
renderbuffer[ rbox.to_slices() ] = img3d[ istart.x:iend.x, istart.y:iend.y, istart.z:iend.z, : ] | [
"def",
"shade",
"(",
"renderbuffer",
",",
"bufferbbox",
",",
"img3d",
",",
"bbox",
")",
":",
"if",
"not",
"Bbox",
".",
"intersects",
"(",
"bufferbbox",
",",
"bbox",
")",
":",
"return",
"spt",
"=",
"max2",
"(",
"bbox",
".",
"minpt",
",",
"bufferbbox",
... | Shade a renderbuffer with a downloaded chunk.
The buffer will only be painted in the overlapping
region of the content. | [
"Shade",
"a",
"renderbuffer",
"with",
"a",
"downloaded",
"chunk",
".",
"The",
"buffer",
"will",
"only",
"be",
"painted",
"in",
"the",
"overlapping",
"region",
"of",
"the",
"content",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L199-L219 | train | 28,132 |
seung-lab/cloud-volume | cloudvolume/txrx.py | cdn_cache_control | def cdn_cache_control(val):
"""Translate cdn_cache into a Cache-Control HTTP header."""
if val is None:
return 'max-age=3600, s-max-age=3600'
elif type(val) is str:
return val
elif type(val) is bool:
if val:
return 'max-age=3600, s-max-age=3600'
else:
return 'no-cache'
elif type(val) is int:
if val < 0:
raise ValueError('cdn_cache must be a positive integer, boolean, or string. Got: ' + str(val))
if val == 0:
return 'no-cache'
else:
return 'max-age={}, s-max-age={}'.format(val, val)
else:
raise NotImplementedError(type(val) + ' is not a supported cache_control setting.') | python | def cdn_cache_control(val):
"""Translate cdn_cache into a Cache-Control HTTP header."""
if val is None:
return 'max-age=3600, s-max-age=3600'
elif type(val) is str:
return val
elif type(val) is bool:
if val:
return 'max-age=3600, s-max-age=3600'
else:
return 'no-cache'
elif type(val) is int:
if val < 0:
raise ValueError('cdn_cache must be a positive integer, boolean, or string. Got: ' + str(val))
if val == 0:
return 'no-cache'
else:
return 'max-age={}, s-max-age={}'.format(val, val)
else:
raise NotImplementedError(type(val) + ' is not a supported cache_control setting.') | [
"def",
"cdn_cache_control",
"(",
"val",
")",
":",
"if",
"val",
"is",
"None",
":",
"return",
"'max-age=3600, s-max-age=3600'",
"elif",
"type",
"(",
"val",
")",
"is",
"str",
":",
"return",
"val",
"elif",
"type",
"(",
"val",
")",
"is",
"bool",
":",
"if",
... | Translate cdn_cache into a Cache-Control HTTP header. | [
"Translate",
"cdn_cache",
"into",
"a",
"Cache",
"-",
"Control",
"HTTP",
"header",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L241-L261 | train | 28,133 |
seung-lab/cloud-volume | cloudvolume/txrx.py | upload_image | def upload_image(vol, img, offset, parallel=1,
manual_shared_memory_id=None, manual_shared_memory_bbox=None, manual_shared_memory_order='F'):
"""Upload img to vol with offset. This is the primary entry point for uploads."""
global NON_ALIGNED_WRITE
if not np.issubdtype(img.dtype, np.dtype(vol.dtype).type):
raise ValueError('The uploaded image data type must match the volume data type. volume: {}, image: {}'.format(vol.dtype, img.dtype))
(is_aligned, bounds, expanded) = check_grid_aligned(vol, img, offset)
if is_aligned:
upload_aligned(vol, img, offset, parallel=parallel,
manual_shared_memory_id=manual_shared_memory_id, manual_shared_memory_bbox=manual_shared_memory_bbox,
manual_shared_memory_order=manual_shared_memory_order)
return
elif vol.non_aligned_writes == False:
msg = NON_ALIGNED_WRITE.format(mip=vol.mip, chunk_size=vol.chunk_size, offset=vol.voxel_offset, got=bounds, check=expanded)
raise AlignmentError(msg)
# Upload the aligned core
retracted = bounds.shrink_to_chunk_size(vol.underlying, vol.voxel_offset)
core_bbox = retracted.clone() - bounds.minpt
if not core_bbox.subvoxel():
core_img = img[ core_bbox.to_slices() ]
upload_aligned(vol, core_img, retracted.minpt, parallel=parallel,
manual_shared_memory_id=manual_shared_memory_id, manual_shared_memory_bbox=manual_shared_memory_bbox,
manual_shared_memory_order=manual_shared_memory_order)
# Download the shell, paint, and upload
all_chunks = set(chunknames(expanded, vol.bounds, vol.key, vol.underlying))
core_chunks = set(chunknames(retracted, vol.bounds, vol.key, vol.underlying))
shell_chunks = all_chunks.difference(core_chunks)
def shade_and_upload(img3d, bbox):
# decode is returning non-writable chunk
# we're throwing them away so safe to write
img3d.setflags(write=1)
shade(img3d, bbox, img, bounds)
single_process_upload(vol, img3d, (( Vec(0,0,0), Vec(*img3d.shape[:3]), bbox.minpt, bbox.maxpt),), n_threads=0)
download_multiple(vol, shell_chunks, fn=shade_and_upload) | python | def upload_image(vol, img, offset, parallel=1,
manual_shared_memory_id=None, manual_shared_memory_bbox=None, manual_shared_memory_order='F'):
"""Upload img to vol with offset. This is the primary entry point for uploads."""
global NON_ALIGNED_WRITE
if not np.issubdtype(img.dtype, np.dtype(vol.dtype).type):
raise ValueError('The uploaded image data type must match the volume data type. volume: {}, image: {}'.format(vol.dtype, img.dtype))
(is_aligned, bounds, expanded) = check_grid_aligned(vol, img, offset)
if is_aligned:
upload_aligned(vol, img, offset, parallel=parallel,
manual_shared_memory_id=manual_shared_memory_id, manual_shared_memory_bbox=manual_shared_memory_bbox,
manual_shared_memory_order=manual_shared_memory_order)
return
elif vol.non_aligned_writes == False:
msg = NON_ALIGNED_WRITE.format(mip=vol.mip, chunk_size=vol.chunk_size, offset=vol.voxel_offset, got=bounds, check=expanded)
raise AlignmentError(msg)
# Upload the aligned core
retracted = bounds.shrink_to_chunk_size(vol.underlying, vol.voxel_offset)
core_bbox = retracted.clone() - bounds.minpt
if not core_bbox.subvoxel():
core_img = img[ core_bbox.to_slices() ]
upload_aligned(vol, core_img, retracted.minpt, parallel=parallel,
manual_shared_memory_id=manual_shared_memory_id, manual_shared_memory_bbox=manual_shared_memory_bbox,
manual_shared_memory_order=manual_shared_memory_order)
# Download the shell, paint, and upload
all_chunks = set(chunknames(expanded, vol.bounds, vol.key, vol.underlying))
core_chunks = set(chunknames(retracted, vol.bounds, vol.key, vol.underlying))
shell_chunks = all_chunks.difference(core_chunks)
def shade_and_upload(img3d, bbox):
# decode is returning non-writable chunk
# we're throwing them away so safe to write
img3d.setflags(write=1)
shade(img3d, bbox, img, bounds)
single_process_upload(vol, img3d, (( Vec(0,0,0), Vec(*img3d.shape[:3]), bbox.minpt, bbox.maxpt),), n_threads=0)
download_multiple(vol, shell_chunks, fn=shade_and_upload) | [
"def",
"upload_image",
"(",
"vol",
",",
"img",
",",
"offset",
",",
"parallel",
"=",
"1",
",",
"manual_shared_memory_id",
"=",
"None",
",",
"manual_shared_memory_bbox",
"=",
"None",
",",
"manual_shared_memory_order",
"=",
"'F'",
")",
":",
"global",
"NON_ALIGNED_W... | Upload img to vol with offset. This is the primary entry point for uploads. | [
"Upload",
"img",
"to",
"vol",
"with",
"offset",
".",
"This",
"is",
"the",
"primary",
"entry",
"point",
"for",
"uploads",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/txrx.py#L273-L314 | train | 28,134 |
seung-lab/cloud-volume | cloudvolume/compression.py | decompress | def decompress(content, encoding, filename='N/A'):
"""
Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported codec is specified.
compression.EncodeError if the encoder has an issue
Return: decompressed content
"""
try:
encoding = (encoding or '').lower()
if encoding == '':
return content
elif encoding == 'gzip':
return gunzip(content)
except DecompressionError as err:
print("Filename: " + str(filename))
raise
raise NotImplementedError(str(encoding) + ' is not currently supported. Supported Options: None, gzip') | python | def decompress(content, encoding, filename='N/A'):
"""
Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported codec is specified.
compression.EncodeError if the encoder has an issue
Return: decompressed content
"""
try:
encoding = (encoding or '').lower()
if encoding == '':
return content
elif encoding == 'gzip':
return gunzip(content)
except DecompressionError as err:
print("Filename: " + str(filename))
raise
raise NotImplementedError(str(encoding) + ' is not currently supported. Supported Options: None, gzip') | [
"def",
"decompress",
"(",
"content",
",",
"encoding",
",",
"filename",
"=",
"'N/A'",
")",
":",
"try",
":",
"encoding",
"=",
"(",
"encoding",
"or",
"''",
")",
".",
"lower",
"(",
")",
"if",
"encoding",
"==",
"''",
":",
"return",
"content",
"elif",
"enc... | Decompress file content.
Required:
content (bytes): a file to be compressed
encoding: None (no compression) or 'gzip'
Optional:
filename (str:default:'N/A'): Used for debugging messages
Raises:
NotImplementedError if an unsupported codec is specified.
compression.EncodeError if the encoder has an issue
Return: decompressed content | [
"Decompress",
"file",
"content",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/compression.py#L9-L34 | train | 28,135 |
seung-lab/cloud-volume | cloudvolume/compression.py | compress | def compress(content, method='gzip'):
"""
Compresses file content.
Required:
content (bytes): The information to be compressed
method (str, default: 'gzip'): None or gzip
Raises:
NotImplementedError if an unsupported codec is specified.
compression.DecodeError if the encoder has an issue
Return: compressed content
"""
if method == True:
method = 'gzip' # backwards compatibility
method = (method or '').lower()
if method == '':
return content
elif method == 'gzip':
return gzip_compress(content)
raise NotImplementedError(str(method) + ' is not currently supported. Supported Options: None, gzip') | python | def compress(content, method='gzip'):
"""
Compresses file content.
Required:
content (bytes): The information to be compressed
method (str, default: 'gzip'): None or gzip
Raises:
NotImplementedError if an unsupported codec is specified.
compression.DecodeError if the encoder has an issue
Return: compressed content
"""
if method == True:
method = 'gzip' # backwards compatibility
method = (method or '').lower()
if method == '':
return content
elif method == 'gzip':
return gzip_compress(content)
raise NotImplementedError(str(method) + ' is not currently supported. Supported Options: None, gzip') | [
"def",
"compress",
"(",
"content",
",",
"method",
"=",
"'gzip'",
")",
":",
"if",
"method",
"==",
"True",
":",
"method",
"=",
"'gzip'",
"# backwards compatibility",
"method",
"=",
"(",
"method",
"or",
"''",
")",
".",
"lower",
"(",
")",
"if",
"method",
"... | Compresses file content.
Required:
content (bytes): The information to be compressed
method (str, default: 'gzip'): None or gzip
Raises:
NotImplementedError if an unsupported codec is specified.
compression.DecodeError if the encoder has an issue
Return: compressed content | [
"Compresses",
"file",
"content",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/compression.py#L36-L58 | train | 28,136 |
seung-lab/cloud-volume | cloudvolume/compression.py | gunzip | def gunzip(content):
"""
Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped.
"""
gzip_magic_numbers = [ 0x1f, 0x8b ]
first_two_bytes = [ byte for byte in bytearray(content)[:2] ]
if first_two_bytes != gzip_magic_numbers:
raise DecompressionError('File is not in gzip format. Magic numbers {}, {} did not match {}, {}.'.format(
hex(first_two_bytes[0]), hex(first_two_bytes[1])), hex(gzip_magic_numbers[0]), hex(gzip_magic_numbers[1]))
stringio = BytesIO(content)
with gzip.GzipFile(mode='rb', fileobj=stringio) as gfile:
return gfile.read() | python | def gunzip(content):
"""
Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped.
"""
gzip_magic_numbers = [ 0x1f, 0x8b ]
first_two_bytes = [ byte for byte in bytearray(content)[:2] ]
if first_two_bytes != gzip_magic_numbers:
raise DecompressionError('File is not in gzip format. Magic numbers {}, {} did not match {}, {}.'.format(
hex(first_two_bytes[0]), hex(first_two_bytes[1])), hex(gzip_magic_numbers[0]), hex(gzip_magic_numbers[1]))
stringio = BytesIO(content)
with gzip.GzipFile(mode='rb', fileobj=stringio) as gfile:
return gfile.read() | [
"def",
"gunzip",
"(",
"content",
")",
":",
"gzip_magic_numbers",
"=",
"[",
"0x1f",
",",
"0x8b",
"]",
"first_two_bytes",
"=",
"[",
"byte",
"for",
"byte",
"in",
"bytearray",
"(",
"content",
")",
"[",
":",
"2",
"]",
"]",
"if",
"first_two_bytes",
"!=",
"gz... | Decompression is applied if the first to bytes matches with
the gzip magic numbers.
There is once chance in 65536 that a file that is not gzipped will
be ungzipped. | [
"Decompression",
"is",
"applied",
"if",
"the",
"first",
"to",
"bytes",
"matches",
"with",
"the",
"gzip",
"magic",
"numbers",
".",
"There",
"is",
"once",
"chance",
"in",
"65536",
"that",
"a",
"file",
"that",
"is",
"not",
"gzipped",
"will",
"be",
"ungzipped"... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/compression.py#L71-L86 | train | 28,137 |
seung-lab/cloud-volume | cloudvolume/cacheservice.py | CacheService.flush | def flush(self, preserve=None):
"""
Delete the cache for this dataset. Optionally preserve
a region. Helpful when working with overlaping volumes.
Warning: the preserve option is not multi-process safe.
You're liable to end up deleting the entire cache.
Optional:
preserve (Bbox: None): Preserve chunks located partially
or entirely within this bounding box.
Return: void
"""
if not os.path.exists(self.path):
return
if preserve is None:
shutil.rmtree(self.path)
return
for mip in self.vol.available_mips:
preserve_mip = self.vol.slices_from_global_coords(preserve)
preserve_mip = Bbox.from_slices(preserve_mip)
mip_path = os.path.join(self.path, self.vol.mip_key(mip))
if not os.path.exists(mip_path):
continue
for filename in os.listdir(mip_path):
bbox = Bbox.from_filename(filename)
if not Bbox.intersects(preserve_mip, bbox):
os.remove(os.path.join(mip_path, filename)) | python | def flush(self, preserve=None):
"""
Delete the cache for this dataset. Optionally preserve
a region. Helpful when working with overlaping volumes.
Warning: the preserve option is not multi-process safe.
You're liable to end up deleting the entire cache.
Optional:
preserve (Bbox: None): Preserve chunks located partially
or entirely within this bounding box.
Return: void
"""
if not os.path.exists(self.path):
return
if preserve is None:
shutil.rmtree(self.path)
return
for mip in self.vol.available_mips:
preserve_mip = self.vol.slices_from_global_coords(preserve)
preserve_mip = Bbox.from_slices(preserve_mip)
mip_path = os.path.join(self.path, self.vol.mip_key(mip))
if not os.path.exists(mip_path):
continue
for filename in os.listdir(mip_path):
bbox = Bbox.from_filename(filename)
if not Bbox.intersects(preserve_mip, bbox):
os.remove(os.path.join(mip_path, filename)) | [
"def",
"flush",
"(",
"self",
",",
"preserve",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"return",
"if",
"preserve",
"is",
"None",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"pat... | Delete the cache for this dataset. Optionally preserve
a region. Helpful when working with overlaping volumes.
Warning: the preserve option is not multi-process safe.
You're liable to end up deleting the entire cache.
Optional:
preserve (Bbox: None): Preserve chunks located partially
or entirely within this bounding box.
Return: void | [
"Delete",
"the",
"cache",
"for",
"this",
"dataset",
".",
"Optionally",
"preserve",
"a",
"region",
".",
"Helpful",
"when",
"working",
"with",
"overlaping",
"volumes",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cacheservice.py#L97-L129 | train | 28,138 |
seung-lab/cloud-volume | cloudvolume/cacheservice.py | CacheService.flush_region | def flush_region(self, region, mips=None):
"""
Delete a cache region at one or more mip levels
bounded by a Bbox for this dataset. Bbox coordinates
should be specified in mip 0 coordinates.
Required:
region (Bbox): Delete cached chunks located partially
or entirely within this bounding box.
Optional:
mip (int: None): Flush the cache from this mip. Region
is in global coordinates.
Return: void
"""
if not os.path.exists(self.path):
return
if type(region) in (list, tuple):
region = generate_slices(region, self.vol.bounds.minpt, self.vol.bounds.maxpt, bounded=False)
region = Bbox.from_slices(region)
mips = self.vol.mip if mips == None else mips
if type(mips) == int:
mips = (mips, )
for mip in mips:
mip_path = os.path.join(self.path, self.vol.mip_key(mip))
if not os.path.exists(mip_path):
continue
region_mip = self.vol.slices_from_global_coords(region)
region_mip = Bbox.from_slices(region_mip)
for filename in os.listdir(mip_path):
bbox = Bbox.from_filename(filename)
if not Bbox.intersects(region, bbox):
os.remove(os.path.join(mip_path, filename)) | python | def flush_region(self, region, mips=None):
"""
Delete a cache region at one or more mip levels
bounded by a Bbox for this dataset. Bbox coordinates
should be specified in mip 0 coordinates.
Required:
region (Bbox): Delete cached chunks located partially
or entirely within this bounding box.
Optional:
mip (int: None): Flush the cache from this mip. Region
is in global coordinates.
Return: void
"""
if not os.path.exists(self.path):
return
if type(region) in (list, tuple):
region = generate_slices(region, self.vol.bounds.minpt, self.vol.bounds.maxpt, bounded=False)
region = Bbox.from_slices(region)
mips = self.vol.mip if mips == None else mips
if type(mips) == int:
mips = (mips, )
for mip in mips:
mip_path = os.path.join(self.path, self.vol.mip_key(mip))
if not os.path.exists(mip_path):
continue
region_mip = self.vol.slices_from_global_coords(region)
region_mip = Bbox.from_slices(region_mip)
for filename in os.listdir(mip_path):
bbox = Bbox.from_filename(filename)
if not Bbox.intersects(region, bbox):
os.remove(os.path.join(mip_path, filename)) | [
"def",
"flush_region",
"(",
"self",
",",
"region",
",",
"mips",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"path",
")",
":",
"return",
"if",
"type",
"(",
"region",
")",
"in",
"(",
"list",
",",
"tuple",... | Delete a cache region at one or more mip levels
bounded by a Bbox for this dataset. Bbox coordinates
should be specified in mip 0 coordinates.
Required:
region (Bbox): Delete cached chunks located partially
or entirely within this bounding box.
Optional:
mip (int: None): Flush the cache from this mip. Region
is in global coordinates.
Return: void | [
"Delete",
"a",
"cache",
"region",
"at",
"one",
"or",
"more",
"mip",
"levels",
"bounded",
"by",
"a",
"Bbox",
"for",
"this",
"dataset",
".",
"Bbox",
"coordinates",
"should",
"be",
"specified",
"in",
"mip",
"0",
"coordinates",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cacheservice.py#L138-L175 | train | 28,139 |
seung-lab/cloud-volume | cloudvolume/volumecutout.py | VolumeCutout.save_images | def save_images(self, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'):
"""See cloudvolume.lib.save_images for more information."""
if directory is None:
directory = os.path.join('./saved_images', self.dataset_name, self.layer, str(self.mip), self.bounds.to_filename())
return save_images(self, directory, axis, channel, global_norm, image_format) | python | def save_images(self, directory=None, axis='z', channel=None, global_norm=True, image_format='PNG'):
"""See cloudvolume.lib.save_images for more information."""
if directory is None:
directory = os.path.join('./saved_images', self.dataset_name, self.layer, str(self.mip), self.bounds.to_filename())
return save_images(self, directory, axis, channel, global_norm, image_format) | [
"def",
"save_images",
"(",
"self",
",",
"directory",
"=",
"None",
",",
"axis",
"=",
"'z'",
",",
"channel",
"=",
"None",
",",
"global_norm",
"=",
"True",
",",
"image_format",
"=",
"'PNG'",
")",
":",
"if",
"directory",
"is",
"None",
":",
"directory",
"="... | See cloudvolume.lib.save_images for more information. | [
"See",
"cloudvolume",
".",
"lib",
".",
"save_images",
"for",
"more",
"information",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/volumecutout.py#L72-L77 | train | 28,140 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.from_path | def from_path(kls, vertices):
"""
Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges.
"""
if vertices.shape[0] == 0:
return PrecomputedSkeleton()
skel = PrecomputedSkeleton(vertices)
edges = np.zeros(shape=(skel.vertices.shape[0] - 1, 2), dtype=np.uint32)
edges[:,0] = np.arange(skel.vertices.shape[0] - 1)
edges[:,1] = np.arange(1, skel.vertices.shape[0])
skel.edges = edges
return skel | python | def from_path(kls, vertices):
"""
Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges.
"""
if vertices.shape[0] == 0:
return PrecomputedSkeleton()
skel = PrecomputedSkeleton(vertices)
edges = np.zeros(shape=(skel.vertices.shape[0] - 1, 2), dtype=np.uint32)
edges[:,0] = np.arange(skel.vertices.shape[0] - 1)
edges[:,1] = np.arange(1, skel.vertices.shape[0])
skel.edges = edges
return skel | [
"def",
"from_path",
"(",
"kls",
",",
"vertices",
")",
":",
"if",
"vertices",
".",
"shape",
"[",
"0",
"]",
"==",
"0",
":",
"return",
"PrecomputedSkeleton",
"(",
")",
"skel",
"=",
"PrecomputedSkeleton",
"(",
"vertices",
")",
"edges",
"=",
"np",
".",
"zer... | Given an Nx3 array of vertices that constitute a single path,
generate a skeleton with appropriate edges. | [
"Given",
"an",
"Nx3",
"array",
"of",
"vertices",
"that",
"constitute",
"a",
"single",
"path",
"generate",
"a",
"skeleton",
"with",
"appropriate",
"edges",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L63-L76 | train | 28,141 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.simple_merge | def simple_merge(kls, skeletons):
"""
Simple concatenation of skeletons into one object
without adding edges between them.
"""
if len(skeletons) == 0:
return PrecomputedSkeleton()
if type(skeletons[0]) is np.ndarray:
skeletons = [ skeletons ]
ct = 0
edges = []
for skel in skeletons:
edge = skel.edges + ct
edges.append(edge)
ct += skel.vertices.shape[0]
return PrecomputedSkeleton(
vertices=np.concatenate([ skel.vertices for skel in skeletons ], axis=0),
edges=np.concatenate(edges, axis=0),
radii=np.concatenate([ skel.radii for skel in skeletons ], axis=0),
vertex_types=np.concatenate([ skel.vertex_types for skel in skeletons ], axis=0),
segid=skeletons[0].id,
) | python | def simple_merge(kls, skeletons):
"""
Simple concatenation of skeletons into one object
without adding edges between them.
"""
if len(skeletons) == 0:
return PrecomputedSkeleton()
if type(skeletons[0]) is np.ndarray:
skeletons = [ skeletons ]
ct = 0
edges = []
for skel in skeletons:
edge = skel.edges + ct
edges.append(edge)
ct += skel.vertices.shape[0]
return PrecomputedSkeleton(
vertices=np.concatenate([ skel.vertices for skel in skeletons ], axis=0),
edges=np.concatenate(edges, axis=0),
radii=np.concatenate([ skel.radii for skel in skeletons ], axis=0),
vertex_types=np.concatenate([ skel.vertex_types for skel in skeletons ], axis=0),
segid=skeletons[0].id,
) | [
"def",
"simple_merge",
"(",
"kls",
",",
"skeletons",
")",
":",
"if",
"len",
"(",
"skeletons",
")",
"==",
"0",
":",
"return",
"PrecomputedSkeleton",
"(",
")",
"if",
"type",
"(",
"skeletons",
"[",
"0",
"]",
")",
"is",
"np",
".",
"ndarray",
":",
"skelet... | Simple concatenation of skeletons into one object
without adding edges between them. | [
"Simple",
"concatenation",
"of",
"skeletons",
"into",
"one",
"object",
"without",
"adding",
"edges",
"between",
"them",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L79-L103 | train | 28,142 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.decode | def decode(kls, skelbuf, segid=None):
"""
Convert a buffer into a PrecomputedSkeleton object.
Format:
num vertices (Nv) (uint32)
num edges (Ne) (uint32)
XYZ x Nv (float32)
edge x Ne (2x uint32)
radii x Nv (optional, float32)
vertex_type x Nv (optional, req radii, uint8) (SWC definition)
More documentation:
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Skeletons-and-Point-Clouds
"""
if len(skelbuf) < 8:
raise SkeletonDecodeError("{} bytes is fewer than needed to specify the number of verices and edges.".format(len(skelbuf)))
num_vertices, num_edges = struct.unpack('<II', skelbuf[:8])
min_format_length = 8 + 12 * num_vertices + 8 * num_edges
if len(skelbuf) < min_format_length:
raise SkeletonDecodeError("The input skeleton was {} bytes but the format requires {} bytes.".format(
len(skelbuf), format_length
))
vstart = 2 * 4 # two uint32s in
vend = vstart + num_vertices * 3 * 4 # float32s
vertbuf = skelbuf[ vstart : vend ]
estart = vend
eend = estart + num_edges * 4 * 2 # 2x uint32s
edgebuf = skelbuf[ estart : eend ]
vertices = np.frombuffer(vertbuf, dtype='<f4').reshape( (num_vertices, 3) )
edges = np.frombuffer(edgebuf, dtype='<u4').reshape( (num_edges, 2) )
if len(skelbuf) == min_format_length:
return PrecomputedSkeleton(vertices, edges, segid=segid)
radii_format_length = min_format_length + num_vertices * 4
if len(skelbuf) < radii_format_length:
raise SkeletonDecodeError("Input buffer did not have enough float32 radii to correspond to each vertex. # vertices: {}, # radii: {}".format(
num_vertices, (radii_format_length - min_format_length) / 4
))
rstart = eend
rend = rstart + num_vertices * 4 # 4 bytes np.float32
radiibuf = skelbuf[ rstart : rend ]
radii = np.frombuffer(radiibuf, dtype=np.float32)
if len(skelbuf) == radii_format_length:
return PrecomputedSkeleton(vertices, edges, radii, segid=segid)
type_format_length = radii_format_length + num_vertices * 1
if len(skelbuf) < type_format_length:
raise SkeletonDecodeError("Input buffer did not have enough uint8 SWC vertex types to correspond to each vertex. # vertices: {}, # types: {}".format(
num_vertices, (type_format_length - radii_format_length)
))
tstart = rend
tend = tstart + num_vertices
typebuf = skelbuf[ tstart:tend ]
vertex_types = np.frombuffer(typebuf, dtype=np.uint8)
return PrecomputedSkeleton(vertices, edges, radii, vertex_types, segid=segid) | python | def decode(kls, skelbuf, segid=None):
"""
Convert a buffer into a PrecomputedSkeleton object.
Format:
num vertices (Nv) (uint32)
num edges (Ne) (uint32)
XYZ x Nv (float32)
edge x Ne (2x uint32)
radii x Nv (optional, float32)
vertex_type x Nv (optional, req radii, uint8) (SWC definition)
More documentation:
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Skeletons-and-Point-Clouds
"""
if len(skelbuf) < 8:
raise SkeletonDecodeError("{} bytes is fewer than needed to specify the number of verices and edges.".format(len(skelbuf)))
num_vertices, num_edges = struct.unpack('<II', skelbuf[:8])
min_format_length = 8 + 12 * num_vertices + 8 * num_edges
if len(skelbuf) < min_format_length:
raise SkeletonDecodeError("The input skeleton was {} bytes but the format requires {} bytes.".format(
len(skelbuf), format_length
))
vstart = 2 * 4 # two uint32s in
vend = vstart + num_vertices * 3 * 4 # float32s
vertbuf = skelbuf[ vstart : vend ]
estart = vend
eend = estart + num_edges * 4 * 2 # 2x uint32s
edgebuf = skelbuf[ estart : eend ]
vertices = np.frombuffer(vertbuf, dtype='<f4').reshape( (num_vertices, 3) )
edges = np.frombuffer(edgebuf, dtype='<u4').reshape( (num_edges, 2) )
if len(skelbuf) == min_format_length:
return PrecomputedSkeleton(vertices, edges, segid=segid)
radii_format_length = min_format_length + num_vertices * 4
if len(skelbuf) < radii_format_length:
raise SkeletonDecodeError("Input buffer did not have enough float32 radii to correspond to each vertex. # vertices: {}, # radii: {}".format(
num_vertices, (radii_format_length - min_format_length) / 4
))
rstart = eend
rend = rstart + num_vertices * 4 # 4 bytes np.float32
radiibuf = skelbuf[ rstart : rend ]
radii = np.frombuffer(radiibuf, dtype=np.float32)
if len(skelbuf) == radii_format_length:
return PrecomputedSkeleton(vertices, edges, radii, segid=segid)
type_format_length = radii_format_length + num_vertices * 1
if len(skelbuf) < type_format_length:
raise SkeletonDecodeError("Input buffer did not have enough uint8 SWC vertex types to correspond to each vertex. # vertices: {}, # types: {}".format(
num_vertices, (type_format_length - radii_format_length)
))
tstart = rend
tend = tstart + num_vertices
typebuf = skelbuf[ tstart:tend ]
vertex_types = np.frombuffer(typebuf, dtype=np.uint8)
return PrecomputedSkeleton(vertices, edges, radii, vertex_types, segid=segid) | [
"def",
"decode",
"(",
"kls",
",",
"skelbuf",
",",
"segid",
"=",
"None",
")",
":",
"if",
"len",
"(",
"skelbuf",
")",
"<",
"8",
":",
"raise",
"SkeletonDecodeError",
"(",
"\"{} bytes is fewer than needed to specify the number of verices and edges.\"",
".",
"format",
... | Convert a buffer into a PrecomputedSkeleton object.
Format:
num vertices (Nv) (uint32)
num edges (Ne) (uint32)
XYZ x Nv (float32)
edge x Ne (2x uint32)
radii x Nv (optional, float32)
vertex_type x Nv (optional, req radii, uint8) (SWC definition)
More documentation:
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Skeletons-and-Point-Clouds | [
"Convert",
"a",
"buffer",
"into",
"a",
"PrecomputedSkeleton",
"object",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L142-L210 | train | 28,143 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.equivalent | def equivalent(kls, first, second):
"""
Tests that two skeletons are the same in form not merely that
their array contents are exactly the same. This test can be
made more sophisticated.
"""
if first.empty() and second.empty():
return True
elif first.vertices.shape[0] != second.vertices.shape[0]:
return False
elif first.edges.shape[0] != second.edges.shape[0]:
return False
EPSILON = 1e-7
vertex1, inv1 = np.unique(first.vertices, axis=0, return_inverse=True)
vertex2, inv2 = np.unique(second.vertices, axis=0, return_inverse=True)
vertex_match = np.all(np.abs(vertex1 - vertex2) < EPSILON)
if not vertex_match:
return False
remapping = {}
for i in range(len(inv1)):
remapping[inv1[i]] = inv2[i]
remap = np.vectorize(lambda idx: remapping[idx])
edges1 = np.sort(np.unique(first.edges, axis=0), axis=1)
edges1 = edges1[np.lexsort(edges1[:,::-1].T)]
edges2 = remap(second.edges)
edges2 = np.sort(np.unique(edges2, axis=0), axis=1)
edges2 = edges2[np.lexsort(edges2[:,::-1].T)]
edges_match = np.all(edges1 == edges2)
if not edges_match:
return False
second_verts = {}
for i, vert in enumerate(second.vertices):
second_verts[tuple(vert)] = i
for i in range(len(first.radii)):
i2 = second_verts[tuple(first.vertices[i])]
if first.radii[i] != second.radii[i2]:
return False
if first.vertex_types[i] != second.vertex_types[i2]:
return False
return True | python | def equivalent(kls, first, second):
"""
Tests that two skeletons are the same in form not merely that
their array contents are exactly the same. This test can be
made more sophisticated.
"""
if first.empty() and second.empty():
return True
elif first.vertices.shape[0] != second.vertices.shape[0]:
return False
elif first.edges.shape[0] != second.edges.shape[0]:
return False
EPSILON = 1e-7
vertex1, inv1 = np.unique(first.vertices, axis=0, return_inverse=True)
vertex2, inv2 = np.unique(second.vertices, axis=0, return_inverse=True)
vertex_match = np.all(np.abs(vertex1 - vertex2) < EPSILON)
if not vertex_match:
return False
remapping = {}
for i in range(len(inv1)):
remapping[inv1[i]] = inv2[i]
remap = np.vectorize(lambda idx: remapping[idx])
edges1 = np.sort(np.unique(first.edges, axis=0), axis=1)
edges1 = edges1[np.lexsort(edges1[:,::-1].T)]
edges2 = remap(second.edges)
edges2 = np.sort(np.unique(edges2, axis=0), axis=1)
edges2 = edges2[np.lexsort(edges2[:,::-1].T)]
edges_match = np.all(edges1 == edges2)
if not edges_match:
return False
second_verts = {}
for i, vert in enumerate(second.vertices):
second_verts[tuple(vert)] = i
for i in range(len(first.radii)):
i2 = second_verts[tuple(first.vertices[i])]
if first.radii[i] != second.radii[i2]:
return False
if first.vertex_types[i] != second.vertex_types[i2]:
return False
return True | [
"def",
"equivalent",
"(",
"kls",
",",
"first",
",",
"second",
")",
":",
"if",
"first",
".",
"empty",
"(",
")",
"and",
"second",
".",
"empty",
"(",
")",
":",
"return",
"True",
"elif",
"first",
".",
"vertices",
".",
"shape",
"[",
"0",
"]",
"!=",
"s... | Tests that two skeletons are the same in form not merely that
their array contents are exactly the same. This test can be
made more sophisticated. | [
"Tests",
"that",
"two",
"skeletons",
"are",
"the",
"same",
"in",
"form",
"not",
"merely",
"that",
"their",
"array",
"contents",
"are",
"exactly",
"the",
"same",
".",
"This",
"test",
"can",
"be",
"made",
"more",
"sophisticated",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L213-L264 | train | 28,144 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.crop | def crop(self, bbox):
"""
Crop away all vertices and edges that lie outside of the given bbox.
The edge counts as inside.
Returns: new PrecomputedSkeleton
"""
skeleton = self.clone()
bbox = Bbox.create(bbox)
if skeleton.empty():
return skeleton
nodes_valid_mask = np.array(
[ bbox.contains(vtx) for vtx in skeleton.vertices ], dtype=np.bool
)
nodes_valid_idx = np.where(nodes_valid_mask)[0]
# Set invalid vertices to be duplicates
# so they'll be removed during consolidation
if nodes_valid_idx.shape[0] == 0:
return PrecomputedSkeleton()
first_node = nodes_valid_idx[0]
skeleton.vertices[~nodes_valid_mask] = skeleton.vertices[first_node]
edges_valid_mask = np.isin(skeleton.edges, nodes_valid_idx)
edges_valid_idx = edges_valid_mask[:,0] * edges_valid_mask[:,1]
skeleton.edges = skeleton.edges[edges_valid_idx,:]
return skeleton.consolidate() | python | def crop(self, bbox):
"""
Crop away all vertices and edges that lie outside of the given bbox.
The edge counts as inside.
Returns: new PrecomputedSkeleton
"""
skeleton = self.clone()
bbox = Bbox.create(bbox)
if skeleton.empty():
return skeleton
nodes_valid_mask = np.array(
[ bbox.contains(vtx) for vtx in skeleton.vertices ], dtype=np.bool
)
nodes_valid_idx = np.where(nodes_valid_mask)[0]
# Set invalid vertices to be duplicates
# so they'll be removed during consolidation
if nodes_valid_idx.shape[0] == 0:
return PrecomputedSkeleton()
first_node = nodes_valid_idx[0]
skeleton.vertices[~nodes_valid_mask] = skeleton.vertices[first_node]
edges_valid_mask = np.isin(skeleton.edges, nodes_valid_idx)
edges_valid_idx = edges_valid_mask[:,0] * edges_valid_mask[:,1]
skeleton.edges = skeleton.edges[edges_valid_idx,:]
return skeleton.consolidate() | [
"def",
"crop",
"(",
"self",
",",
"bbox",
")",
":",
"skeleton",
"=",
"self",
".",
"clone",
"(",
")",
"bbox",
"=",
"Bbox",
".",
"create",
"(",
"bbox",
")",
"if",
"skeleton",
".",
"empty",
"(",
")",
":",
"return",
"skeleton",
"nodes_valid_mask",
"=",
... | Crop away all vertices and edges that lie outside of the given bbox.
The edge counts as inside.
Returns: new PrecomputedSkeleton | [
"Crop",
"away",
"all",
"vertices",
"and",
"edges",
"that",
"lie",
"outside",
"of",
"the",
"given",
"bbox",
".",
"The",
"edge",
"counts",
"as",
"inside",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L266-L295 | train | 28,145 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.consolidate | def consolidate(self):
"""
Remove duplicate vertices and edges from this skeleton without
side effects.
Returns: new consolidated PrecomputedSkeleton
"""
nodes = self.vertices
edges = self.edges
radii = self.radii
vertex_types = self.vertex_types
if self.empty():
return PrecomputedSkeleton()
eff_nodes, uniq_idx, idx_representative = np.unique(
nodes, axis=0, return_index=True, return_inverse=True
)
edge_vector_map = np.vectorize(lambda x: idx_representative[x])
eff_edges = edge_vector_map(edges)
eff_edges = np.sort(eff_edges, axis=1) # sort each edge [2,1] => [1,2]
eff_edges = eff_edges[np.lexsort(eff_edges[:,::-1].T)] # Sort rows
eff_edges = np.unique(eff_edges, axis=0)
eff_edges = eff_edges[ eff_edges[:,0] != eff_edges[:,1] ] # remove trivial loops
radii_vector_map = np.vectorize(lambda idx: radii[idx])
eff_radii = radii_vector_map(uniq_idx)
vertex_type_map = np.vectorize(lambda idx: vertex_types[idx])
eff_vtype = vertex_type_map(uniq_idx)
return PrecomputedSkeleton(eff_nodes, eff_edges, eff_radii, eff_vtype, segid=self.id) | python | def consolidate(self):
"""
Remove duplicate vertices and edges from this skeleton without
side effects.
Returns: new consolidated PrecomputedSkeleton
"""
nodes = self.vertices
edges = self.edges
radii = self.radii
vertex_types = self.vertex_types
if self.empty():
return PrecomputedSkeleton()
eff_nodes, uniq_idx, idx_representative = np.unique(
nodes, axis=0, return_index=True, return_inverse=True
)
edge_vector_map = np.vectorize(lambda x: idx_representative[x])
eff_edges = edge_vector_map(edges)
eff_edges = np.sort(eff_edges, axis=1) # sort each edge [2,1] => [1,2]
eff_edges = eff_edges[np.lexsort(eff_edges[:,::-1].T)] # Sort rows
eff_edges = np.unique(eff_edges, axis=0)
eff_edges = eff_edges[ eff_edges[:,0] != eff_edges[:,1] ] # remove trivial loops
radii_vector_map = np.vectorize(lambda idx: radii[idx])
eff_radii = radii_vector_map(uniq_idx)
vertex_type_map = np.vectorize(lambda idx: vertex_types[idx])
eff_vtype = vertex_type_map(uniq_idx)
return PrecomputedSkeleton(eff_nodes, eff_edges, eff_radii, eff_vtype, segid=self.id) | [
"def",
"consolidate",
"(",
"self",
")",
":",
"nodes",
"=",
"self",
".",
"vertices",
"edges",
"=",
"self",
".",
"edges",
"radii",
"=",
"self",
".",
"radii",
"vertex_types",
"=",
"self",
".",
"vertex_types",
"if",
"self",
".",
"empty",
"(",
")",
":",
"... | Remove duplicate vertices and edges from this skeleton without
side effects.
Returns: new consolidated PrecomputedSkeleton | [
"Remove",
"duplicate",
"vertices",
"and",
"edges",
"from",
"this",
"skeleton",
"without",
"side",
"effects",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L297-L329 | train | 28,146 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.downsample | def downsample(self, factor):
"""
Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton
"""
if int(factor) != factor or factor < 1:
raise ValueError("Argument `factor` must be a positive integer greater than or equal to 1. Got: <{}>({})", type(factor), factor)
paths = self.interjoint_paths()
for i, path in enumerate(paths):
paths[i] = np.concatenate(
(path[0::factor, :], path[-1:, :]) # preserve endpoints
)
ds_skel = PrecomputedSkeleton.simple_merge(
[ PrecomputedSkeleton.from_path(path) for path in paths ]
).consolidate()
ds_skel.id = self.id
# TODO: I'm sure this could be sped up if need be.
index = {}
for i, vert in enumerate(self.vertices):
vert = tuple(vert)
index[vert] = i
for i, vert in enumerate(ds_skel.vertices):
vert = tuple(vert)
ds_skel.radii[i] = self.radii[index[vert]]
ds_skel.vertex_types[i] = self.vertex_types[index[vert]]
return ds_skel | python | def downsample(self, factor):
"""
Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton
"""
if int(factor) != factor or factor < 1:
raise ValueError("Argument `factor` must be a positive integer greater than or equal to 1. Got: <{}>({})", type(factor), factor)
paths = self.interjoint_paths()
for i, path in enumerate(paths):
paths[i] = np.concatenate(
(path[0::factor, :], path[-1:, :]) # preserve endpoints
)
ds_skel = PrecomputedSkeleton.simple_merge(
[ PrecomputedSkeleton.from_path(path) for path in paths ]
).consolidate()
ds_skel.id = self.id
# TODO: I'm sure this could be sped up if need be.
index = {}
for i, vert in enumerate(self.vertices):
vert = tuple(vert)
index[vert] = i
for i, vert in enumerate(ds_skel.vertices):
vert = tuple(vert)
ds_skel.radii[i] = self.radii[index[vert]]
ds_skel.vertex_types[i] = self.vertex_types[index[vert]]
return ds_skel | [
"def",
"downsample",
"(",
"self",
",",
"factor",
")",
":",
"if",
"int",
"(",
"factor",
")",
"!=",
"factor",
"or",
"factor",
"<",
"1",
":",
"raise",
"ValueError",
"(",
"\"Argument `factor` must be a positive integer greater than or equal to 1. Got: <{}>({})\"",
",",
... | Compute a downsampled version of the skeleton by striding while
preserving endpoints.
factor: stride length for downsampling the saved skeleton paths.
Returns: downsampled PrecomputedSkeleton | [
"Compute",
"a",
"downsampled",
"version",
"of",
"the",
"skeleton",
"by",
"striding",
"while",
"preserving",
"endpoints",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L354-L389 | train | 28,147 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton._single_tree_paths | def _single_tree_paths(self, tree):
"""Get all traversal paths from a single tree."""
skel = tree.consolidate()
tree = defaultdict(list)
for edge in skel.edges:
svert = edge[0]
evert = edge[1]
tree[svert].append(evert)
tree[evert].append(svert)
def dfs(path, visited):
paths = []
stack = [ (path, visited) ]
while stack:
path, visited = stack.pop(0)
vertex = path[-1]
children = tree[vertex]
visited[vertex] = True
children = [ child for child in children if not visited[child] ]
if len(children) == 0:
paths.append(path)
for child in children:
stack.append(
(path + [child], copy.deepcopy(visited))
)
return paths
root = skel.edges[0,0]
paths = dfs([root], defaultdict(bool))
root = np.argmax([ len(_) for _ in paths ])
root = paths[root][-1]
paths = dfs([ root ], defaultdict(bool))
return [ np.flip(skel.vertices[path], axis=0) for path in paths ] | python | def _single_tree_paths(self, tree):
"""Get all traversal paths from a single tree."""
skel = tree.consolidate()
tree = defaultdict(list)
for edge in skel.edges:
svert = edge[0]
evert = edge[1]
tree[svert].append(evert)
tree[evert].append(svert)
def dfs(path, visited):
paths = []
stack = [ (path, visited) ]
while stack:
path, visited = stack.pop(0)
vertex = path[-1]
children = tree[vertex]
visited[vertex] = True
children = [ child for child in children if not visited[child] ]
if len(children) == 0:
paths.append(path)
for child in children:
stack.append(
(path + [child], copy.deepcopy(visited))
)
return paths
root = skel.edges[0,0]
paths = dfs([root], defaultdict(bool))
root = np.argmax([ len(_) for _ in paths ])
root = paths[root][-1]
paths = dfs([ root ], defaultdict(bool))
return [ np.flip(skel.vertices[path], axis=0) for path in paths ] | [
"def",
"_single_tree_paths",
"(",
"self",
",",
"tree",
")",
":",
"skel",
"=",
"tree",
".",
"consolidate",
"(",
")",
"tree",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"edge",
"in",
"skel",
".",
"edges",
":",
"svert",
"=",
"edge",
"[",
"0",
"]",
"... | Get all traversal paths from a single tree. | [
"Get",
"all",
"traversal",
"paths",
"from",
"a",
"single",
"tree",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L391-L435 | train | 28,148 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.paths | def paths(self):
"""
Assuming the skeleton is structured as a single tree, return a
list of all traversal paths across all components. For each component,
start from the first vertex, find the most distant vertex by
hops and set that as the root. Then use depth first traversal
to produce paths.
Returns: [ [(x,y,z), (x,y,z), ...], path_2, path_3, ... ]
"""
paths = []
for tree in self.components():
paths += self._single_tree_paths(tree)
return paths | python | def paths(self):
"""
Assuming the skeleton is structured as a single tree, return a
list of all traversal paths across all components. For each component,
start from the first vertex, find the most distant vertex by
hops and set that as the root. Then use depth first traversal
to produce paths.
Returns: [ [(x,y,z), (x,y,z), ...], path_2, path_3, ... ]
"""
paths = []
for tree in self.components():
paths += self._single_tree_paths(tree)
return paths | [
"def",
"paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"tree",
"in",
"self",
".",
"components",
"(",
")",
":",
"paths",
"+=",
"self",
".",
"_single_tree_paths",
"(",
"tree",
")",
"return",
"paths"
] | Assuming the skeleton is structured as a single tree, return a
list of all traversal paths across all components. For each component,
start from the first vertex, find the most distant vertex by
hops and set that as the root. Then use depth first traversal
to produce paths.
Returns: [ [(x,y,z), (x,y,z), ...], path_2, path_3, ... ] | [
"Assuming",
"the",
"skeleton",
"is",
"structured",
"as",
"a",
"single",
"tree",
"return",
"a",
"list",
"of",
"all",
"traversal",
"paths",
"across",
"all",
"components",
".",
"For",
"each",
"component",
"start",
"from",
"the",
"first",
"vertex",
"find",
"the"... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L437-L450 | train | 28,149 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.interjoint_paths | def interjoint_paths(self):
"""
Returns paths between the adjacent critical points
in the skeleton, where a critical point is the set of
terminal and branch points.
"""
paths = []
for tree in self.components():
subpaths = self._single_tree_interjoint_paths(tree)
paths.extend(subpaths)
return paths | python | def interjoint_paths(self):
"""
Returns paths between the adjacent critical points
in the skeleton, where a critical point is the set of
terminal and branch points.
"""
paths = []
for tree in self.components():
subpaths = self._single_tree_interjoint_paths(tree)
paths.extend(subpaths)
return paths | [
"def",
"interjoint_paths",
"(",
"self",
")",
":",
"paths",
"=",
"[",
"]",
"for",
"tree",
"in",
"self",
".",
"components",
"(",
")",
":",
"subpaths",
"=",
"self",
".",
"_single_tree_interjoint_paths",
"(",
"tree",
")",
"paths",
".",
"extend",
"(",
"subpat... | Returns paths between the adjacent critical points
in the skeleton, where a critical point is the set of
terminal and branch points. | [
"Returns",
"paths",
"between",
"the",
"adjacent",
"critical",
"points",
"in",
"the",
"skeleton",
"where",
"a",
"critical",
"point",
"is",
"the",
"set",
"of",
"terminal",
"and",
"branch",
"points",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L506-L517 | train | 28,150 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeleton.components | def components(self):
"""
Extract connected components from graph.
Useful for ensuring that you're working with a single tree.
Returns: [ PrecomputedSkeleton, PrecomputedSkeleton, ... ]
"""
skel, forest = self._compute_components()
if len(forest) == 0:
return []
elif len(forest) == 1:
return [ skel ]
orig_verts = { tuple(coord): i for i, coord in enumerate(skel.vertices) }
skeletons = []
for edge_list in forest:
edge_list = np.array(edge_list, dtype=np.uint32)
edge_list = np.unique(edge_list, axis=0)
vert_idx = np.unique(edge_list.flatten())
vert_list = skel.vertices[vert_idx]
radii = skel.radii[vert_idx]
vtypes = skel.vertex_types[vert_idx]
new_verts = { orig_verts[tuple(coord)]: i for i, coord in enumerate(vert_list) }
edge_vector_map = np.vectorize(lambda x: new_verts[x])
edge_list = edge_vector_map(edge_list)
skeletons.append(
PrecomputedSkeleton(vert_list, edge_list, radii, vtypes, skel.id)
)
return skeletons | python | def components(self):
"""
Extract connected components from graph.
Useful for ensuring that you're working with a single tree.
Returns: [ PrecomputedSkeleton, PrecomputedSkeleton, ... ]
"""
skel, forest = self._compute_components()
if len(forest) == 0:
return []
elif len(forest) == 1:
return [ skel ]
orig_verts = { tuple(coord): i for i, coord in enumerate(skel.vertices) }
skeletons = []
for edge_list in forest:
edge_list = np.array(edge_list, dtype=np.uint32)
edge_list = np.unique(edge_list, axis=0)
vert_idx = np.unique(edge_list.flatten())
vert_list = skel.vertices[vert_idx]
radii = skel.radii[vert_idx]
vtypes = skel.vertex_types[vert_idx]
new_verts = { orig_verts[tuple(coord)]: i for i, coord in enumerate(vert_list) }
edge_vector_map = np.vectorize(lambda x: new_verts[x])
edge_list = edge_vector_map(edge_list)
skeletons.append(
PrecomputedSkeleton(vert_list, edge_list, radii, vtypes, skel.id)
)
return skeletons | [
"def",
"components",
"(",
"self",
")",
":",
"skel",
",",
"forest",
"=",
"self",
".",
"_compute_components",
"(",
")",
"if",
"len",
"(",
"forest",
")",
"==",
"0",
":",
"return",
"[",
"]",
"elif",
"len",
"(",
"forest",
")",
"==",
"1",
":",
"return",
... | Extract connected components from graph.
Useful for ensuring that you're working with a single tree.
Returns: [ PrecomputedSkeleton, PrecomputedSkeleton, ... ] | [
"Extract",
"connected",
"components",
"from",
"graph",
".",
"Useful",
"for",
"ensuring",
"that",
"you",
"re",
"working",
"with",
"a",
"single",
"tree",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L566-L600 | train | 28,151 |
seung-lab/cloud-volume | cloudvolume/skeletonservice.py | PrecomputedSkeletonService.get | def get(self, segids):
"""
Retrieve one or more skeletons from the data layer.
Example:
skel = vol.skeleton.get(5)
skels = vol.skeleton.get([1, 2, 3])
Raises SkeletonDecodeError on missing files or decoding errors.
Required:
segids: list of integers or integer
Returns:
if segids is a list, returns list of PrecomputedSkeletons
else returns a single PrecomputedSkeleton
"""
list_return = True
if type(segids) in (int, float):
list_return = False
segids = [ int(segids) ]
paths = [ os.path.join(self.path, str(segid)) for segid in segids ]
StorageClass = Storage if len(segids) > 1 else SimpleStorage
with StorageClass(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:
results = stor.get_files(paths)
for res in results:
if res['error'] is not None:
raise res['error']
missing = [ res['filename'] for res in results if res['content'] is None ]
if len(missing):
raise SkeletonDecodeError("File(s) do not exist: {}".format(", ".join(missing)))
skeletons = []
for res in results:
segid = int(os.path.basename(res['filename']))
try:
skel = PrecomputedSkeleton.decode(
res['content'], segid=segid
)
except Exception as err:
raise SkeletonDecodeError("segid " + str(segid) + ": " + err.message)
skeletons.append(skel)
if list_return:
return skeletons
return skeletons[0] | python | def get(self, segids):
"""
Retrieve one or more skeletons from the data layer.
Example:
skel = vol.skeleton.get(5)
skels = vol.skeleton.get([1, 2, 3])
Raises SkeletonDecodeError on missing files or decoding errors.
Required:
segids: list of integers or integer
Returns:
if segids is a list, returns list of PrecomputedSkeletons
else returns a single PrecomputedSkeleton
"""
list_return = True
if type(segids) in (int, float):
list_return = False
segids = [ int(segids) ]
paths = [ os.path.join(self.path, str(segid)) for segid in segids ]
StorageClass = Storage if len(segids) > 1 else SimpleStorage
with StorageClass(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:
results = stor.get_files(paths)
for res in results:
if res['error'] is not None:
raise res['error']
missing = [ res['filename'] for res in results if res['content'] is None ]
if len(missing):
raise SkeletonDecodeError("File(s) do not exist: {}".format(", ".join(missing)))
skeletons = []
for res in results:
segid = int(os.path.basename(res['filename']))
try:
skel = PrecomputedSkeleton.decode(
res['content'], segid=segid
)
except Exception as err:
raise SkeletonDecodeError("segid " + str(segid) + ": " + err.message)
skeletons.append(skel)
if list_return:
return skeletons
return skeletons[0] | [
"def",
"get",
"(",
"self",
",",
"segids",
")",
":",
"list_return",
"=",
"True",
"if",
"type",
"(",
"segids",
")",
"in",
"(",
"int",
",",
"float",
")",
":",
"list_return",
"=",
"False",
"segids",
"=",
"[",
"int",
"(",
"segids",
")",
"]",
"paths",
... | Retrieve one or more skeletons from the data layer.
Example:
skel = vol.skeleton.get(5)
skels = vol.skeleton.get([1, 2, 3])
Raises SkeletonDecodeError on missing files or decoding errors.
Required:
segids: list of integers or integer
Returns:
if segids is a list, returns list of PrecomputedSkeletons
else returns a single PrecomputedSkeleton | [
"Retrieve",
"one",
"or",
"more",
"skeletons",
"from",
"the",
"data",
"layer",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/skeletonservice.py#L735-L787 | train | 28,152 |
seung-lab/cloud-volume | cloudvolume/threaded_queue.py | ThreadedQueue.put | def put(self, fn):
"""
Enqueue a task function for processing.
Requires:
fn: a function object that takes one argument
that is the interface associated with each
thread.
e.g. def download(api):
results.append(api.download())
self.put(download)
Returns: self
"""
self._inserted += 1
self._queue.put(fn, block=True)
return self | python | def put(self, fn):
"""
Enqueue a task function for processing.
Requires:
fn: a function object that takes one argument
that is the interface associated with each
thread.
e.g. def download(api):
results.append(api.download())
self.put(download)
Returns: self
"""
self._inserted += 1
self._queue.put(fn, block=True)
return self | [
"def",
"put",
"(",
"self",
",",
"fn",
")",
":",
"self",
".",
"_inserted",
"+=",
"1",
"self",
".",
"_queue",
".",
"put",
"(",
"fn",
",",
"block",
"=",
"True",
")",
"return",
"self"
] | Enqueue a task function for processing.
Requires:
fn: a function object that takes one argument
that is the interface associated with each
thread.
e.g. def download(api):
results.append(api.download())
self.put(download)
Returns: self | [
"Enqueue",
"a",
"task",
"function",
"for",
"processing",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/threaded_queue.py#L33-L51 | train | 28,153 |
seung-lab/cloud-volume | cloudvolume/threaded_queue.py | ThreadedQueue.start_threads | def start_threads(self, n_threads):
"""
Terminate existing threads and create a
new set if the thread number doesn't match
the desired number.
Required:
n_threads: (int) number of threads to spawn
Returns: self
"""
if n_threads == len(self._threads):
return self
# Terminate all previous tasks with the existing
# event object, then create a new one for the next
# generation of threads. The old object will hang
# around in memory until the threads actually terminate
# after another iteration.
self._terminate.set()
self._terminate = threading.Event()
threads = []
for _ in range(n_threads):
worker = threading.Thread(
target=self._consume_queue,
args=(self._terminate,)
)
worker.daemon = True
worker.start()
threads.append(worker)
self._threads = tuple(threads)
return self | python | def start_threads(self, n_threads):
"""
Terminate existing threads and create a
new set if the thread number doesn't match
the desired number.
Required:
n_threads: (int) number of threads to spawn
Returns: self
"""
if n_threads == len(self._threads):
return self
# Terminate all previous tasks with the existing
# event object, then create a new one for the next
# generation of threads. The old object will hang
# around in memory until the threads actually terminate
# after another iteration.
self._terminate.set()
self._terminate = threading.Event()
threads = []
for _ in range(n_threads):
worker = threading.Thread(
target=self._consume_queue,
args=(self._terminate,)
)
worker.daemon = True
worker.start()
threads.append(worker)
self._threads = tuple(threads)
return self | [
"def",
"start_threads",
"(",
"self",
",",
"n_threads",
")",
":",
"if",
"n_threads",
"==",
"len",
"(",
"self",
".",
"_threads",
")",
":",
"return",
"self",
"# Terminate all previous tasks with the existing",
"# event object, then create a new one for the next",
"# generati... | Terminate existing threads and create a
new set if the thread number doesn't match
the desired number.
Required:
n_threads: (int) number of threads to spawn
Returns: self | [
"Terminate",
"existing",
"threads",
"and",
"create",
"a",
"new",
"set",
"if",
"the",
"thread",
"number",
"doesn",
"t",
"match",
"the",
"desired",
"number",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/threaded_queue.py#L53-L87 | train | 28,154 |
seung-lab/cloud-volume | cloudvolume/threaded_queue.py | ThreadedQueue.kill_threads | def kill_threads(self):
"""Kill all threads."""
self._terminate.set()
while self.are_threads_alive():
time.sleep(0.001)
self._threads = ()
return self | python | def kill_threads(self):
"""Kill all threads."""
self._terminate.set()
while self.are_threads_alive():
time.sleep(0.001)
self._threads = ()
return self | [
"def",
"kill_threads",
"(",
"self",
")",
":",
"self",
".",
"_terminate",
".",
"set",
"(",
")",
"while",
"self",
".",
"are_threads_alive",
"(",
")",
":",
"time",
".",
"sleep",
"(",
"0.001",
")",
"self",
".",
"_threads",
"=",
"(",
")",
"return",
"self"... | Kill all threads. | [
"Kill",
"all",
"threads",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/threaded_queue.py#L93-L99 | train | 28,155 |
seung-lab/cloud-volume | cloudvolume/threaded_queue.py | ThreadedQueue.wait | def wait(self, progress=None):
"""
Allow background threads to process until the
task queue is empty. If there are no threads,
in theory the queue should always be empty
as processing happens immediately on the main thread.
Optional:
progress: (bool or str) show a tqdm progress bar optionally
with a description if a string is provided
Returns: self (for chaining)
Raises: The first exception recieved from threads
"""
if not len(self._threads):
return self
desc = None
if type(progress) is str:
desc = progress
last = self._inserted
with tqdm(total=self._inserted, disable=(not progress), desc=desc) as pbar:
# Allow queue to consume, but check up on
# progress and errors every tenth of a second
while not self._queue.empty():
size = self._queue.qsize()
delta = last - size
if delta != 0: # We should crash on negative numbers
pbar.update(delta)
last = size
self._check_errors()
time.sleep(0.1)
# Wait until all tasks in the queue are
# fully processed. queue.task_done must be
# called for each task.
self._queue.join()
self._check_errors()
final = self._inserted - last
if final:
pbar.update(final)
if self._queue.empty():
self._inserted = 0
return self | python | def wait(self, progress=None):
"""
Allow background threads to process until the
task queue is empty. If there are no threads,
in theory the queue should always be empty
as processing happens immediately on the main thread.
Optional:
progress: (bool or str) show a tqdm progress bar optionally
with a description if a string is provided
Returns: self (for chaining)
Raises: The first exception recieved from threads
"""
if not len(self._threads):
return self
desc = None
if type(progress) is str:
desc = progress
last = self._inserted
with tqdm(total=self._inserted, disable=(not progress), desc=desc) as pbar:
# Allow queue to consume, but check up on
# progress and errors every tenth of a second
while not self._queue.empty():
size = self._queue.qsize()
delta = last - size
if delta != 0: # We should crash on negative numbers
pbar.update(delta)
last = size
self._check_errors()
time.sleep(0.1)
# Wait until all tasks in the queue are
# fully processed. queue.task_done must be
# called for each task.
self._queue.join()
self._check_errors()
final = self._inserted - last
if final:
pbar.update(final)
if self._queue.empty():
self._inserted = 0
return self | [
"def",
"wait",
"(",
"self",
",",
"progress",
"=",
"None",
")",
":",
"if",
"not",
"len",
"(",
"self",
".",
"_threads",
")",
":",
"return",
"self",
"desc",
"=",
"None",
"if",
"type",
"(",
"progress",
")",
"is",
"str",
":",
"desc",
"=",
"progress",
... | Allow background threads to process until the
task queue is empty. If there are no threads,
in theory the queue should always be empty
as processing happens immediately on the main thread.
Optional:
progress: (bool or str) show a tqdm progress bar optionally
with a description if a string is provided
Returns: self (for chaining)
Raises: The first exception recieved from threads | [
"Allow",
"background",
"threads",
"to",
"process",
"until",
"the",
"task",
"queue",
"is",
"empty",
".",
"If",
"there",
"are",
"no",
"threads",
"in",
"theory",
"the",
"queue",
"should",
"always",
"be",
"empty",
"as",
"processing",
"happens",
"immediately",
"o... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/threaded_queue.py#L193-L241 | train | 28,156 |
seung-lab/cloud-volume | cloudvolume/storage.py | _radix_sort | def _radix_sort(L, i=0):
"""
Most significant char radix sort
"""
if len(L) <= 1:
return L
done_bucket = []
buckets = [ [] for x in range(255) ]
for s in L:
if i >= len(s):
done_bucket.append(s)
else:
buckets[ ord(s[i]) ].append(s)
buckets = [ _radix_sort(b, i + 1) for b in buckets ]
return done_bucket + [ b for blist in buckets for b in blist ] | python | def _radix_sort(L, i=0):
"""
Most significant char radix sort
"""
if len(L) <= 1:
return L
done_bucket = []
buckets = [ [] for x in range(255) ]
for s in L:
if i >= len(s):
done_bucket.append(s)
else:
buckets[ ord(s[i]) ].append(s)
buckets = [ _radix_sort(b, i + 1) for b in buckets ]
return done_bucket + [ b for blist in buckets for b in blist ] | [
"def",
"_radix_sort",
"(",
"L",
",",
"i",
"=",
"0",
")",
":",
"if",
"len",
"(",
"L",
")",
"<=",
"1",
":",
"return",
"L",
"done_bucket",
"=",
"[",
"]",
"buckets",
"=",
"[",
"[",
"]",
"for",
"x",
"in",
"range",
"(",
"255",
")",
"]",
"for",
"s... | Most significant char radix sort | [
"Most",
"significant",
"char",
"radix",
"sort"
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/storage.py#L818-L832 | train | 28,157 |
seung-lab/cloud-volume | cloudvolume/storage.py | Storage.files_exist | def files_exist(self, file_paths):
"""
Threaded exists for all file paths.
file_paths: (list) file paths to test for existence
Returns: { filepath: bool }
"""
results = {}
def exist_thunk(paths, interface):
results.update(interface.files_exist(paths))
if len(self._threads):
for block in scatter(file_paths, len(self._threads)):
self.put(partial(exist_thunk, block))
else:
exist_thunk(file_paths, self._interface)
desc = 'Existence Testing' if self.progress else None
self.wait(desc)
return results | python | def files_exist(self, file_paths):
"""
Threaded exists for all file paths.
file_paths: (list) file paths to test for existence
Returns: { filepath: bool }
"""
results = {}
def exist_thunk(paths, interface):
results.update(interface.files_exist(paths))
if len(self._threads):
for block in scatter(file_paths, len(self._threads)):
self.put(partial(exist_thunk, block))
else:
exist_thunk(file_paths, self._interface)
desc = 'Existence Testing' if self.progress else None
self.wait(desc)
return results | [
"def",
"files_exist",
"(",
"self",
",",
"file_paths",
")",
":",
"results",
"=",
"{",
"}",
"def",
"exist_thunk",
"(",
"paths",
",",
"interface",
")",
":",
"results",
".",
"update",
"(",
"interface",
".",
"files_exist",
"(",
"paths",
")",
")",
"if",
"len... | Threaded exists for all file paths.
file_paths: (list) file paths to test for existence
Returns: { filepath: bool } | [
"Threaded",
"exists",
"for",
"all",
"file",
"paths",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/storage.py#L317-L339 | train | 28,158 |
seung-lab/cloud-volume | cloudvolume/storage.py | Storage.get_files | def get_files(self, file_paths):
"""
returns a list of files faster by using threads
"""
results = []
def get_file_thunk(path, interface):
result = error = None
try:
result = interface.get_file(path)
except Exception as err:
error = err
# important to print immediately because
# errors are collected at the end
print(err)
content, encoding = result
content = compression.decompress(content, encoding)
results.append({
"filename": path,
"content": content,
"error": error,
})
for path in file_paths:
if len(self._threads):
self.put(partial(get_file_thunk, path))
else:
get_file_thunk(path, self._interface)
desc = 'Downloading' if self.progress else None
self.wait(desc)
return results | python | def get_files(self, file_paths):
"""
returns a list of files faster by using threads
"""
results = []
def get_file_thunk(path, interface):
result = error = None
try:
result = interface.get_file(path)
except Exception as err:
error = err
# important to print immediately because
# errors are collected at the end
print(err)
content, encoding = result
content = compression.decompress(content, encoding)
results.append({
"filename": path,
"content": content,
"error": error,
})
for path in file_paths:
if len(self._threads):
self.put(partial(get_file_thunk, path))
else:
get_file_thunk(path, self._interface)
desc = 'Downloading' if self.progress else None
self.wait(desc)
return results | [
"def",
"get_files",
"(",
"self",
",",
"file_paths",
")",
":",
"results",
"=",
"[",
"]",
"def",
"get_file_thunk",
"(",
"path",
",",
"interface",
")",
":",
"result",
"=",
"error",
"=",
"None",
"try",
":",
"result",
"=",
"interface",
".",
"get_file",
"(",... | returns a list of files faster by using threads | [
"returns",
"a",
"list",
"of",
"files",
"faster",
"by",
"using",
"threads"
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/storage.py#L352-L388 | train | 28,159 |
seung-lab/cloud-volume | cloudvolume/storage.py | S3Interface.get_file | def get_file(self, file_path):
"""
There are many types of execptions which can get raised
from this method. We want to make sure we only return
None when the file doesn't exist.
"""
try:
resp = self._conn.get_object(
Bucket=self._path.bucket,
Key=self.get_path_to_file(file_path),
)
encoding = ''
if 'ContentEncoding' in resp:
encoding = resp['ContentEncoding']
return resp['Body'].read(), encoding
except botocore.exceptions.ClientError as err:
if err.response['Error']['Code'] == 'NoSuchKey':
return None, None
else:
raise | python | def get_file(self, file_path):
"""
There are many types of execptions which can get raised
from this method. We want to make sure we only return
None when the file doesn't exist.
"""
try:
resp = self._conn.get_object(
Bucket=self._path.bucket,
Key=self.get_path_to_file(file_path),
)
encoding = ''
if 'ContentEncoding' in resp:
encoding = resp['ContentEncoding']
return resp['Body'].read(), encoding
except botocore.exceptions.ClientError as err:
if err.response['Error']['Code'] == 'NoSuchKey':
return None, None
else:
raise | [
"def",
"get_file",
"(",
"self",
",",
"file_path",
")",
":",
"try",
":",
"resp",
"=",
"self",
".",
"_conn",
".",
"get_object",
"(",
"Bucket",
"=",
"self",
".",
"_path",
".",
"bucket",
",",
"Key",
"=",
"self",
".",
"get_path_to_file",
"(",
"file_path",
... | There are many types of execptions which can get raised
from this method. We want to make sure we only return
None when the file doesn't exist. | [
"There",
"are",
"many",
"types",
"of",
"execptions",
"which",
"can",
"get",
"raised",
"from",
"this",
"method",
".",
"We",
"want",
"to",
"make",
"sure",
"we",
"only",
"return",
"None",
"when",
"the",
"file",
"doesn",
"t",
"exist",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/storage.py#L716-L738 | train | 28,160 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.init_submodules | def init_submodules(self, cache):
"""cache = path or bool"""
self.cache = CacheService(cache, weakref.proxy(self))
self.mesh = PrecomputedMeshService(weakref.proxy(self))
self.skeleton = PrecomputedSkeletonService(weakref.proxy(self)) | python | def init_submodules(self, cache):
"""cache = path or bool"""
self.cache = CacheService(cache, weakref.proxy(self))
self.mesh = PrecomputedMeshService(weakref.proxy(self))
self.skeleton = PrecomputedSkeletonService(weakref.proxy(self)) | [
"def",
"init_submodules",
"(",
"self",
",",
"cache",
")",
":",
"self",
".",
"cache",
"=",
"CacheService",
"(",
"cache",
",",
"weakref",
".",
"proxy",
"(",
"self",
")",
")",
"self",
".",
"mesh",
"=",
"PrecomputedMeshService",
"(",
"weakref",
".",
"proxy",... | cache = path or bool | [
"cache",
"=",
"path",
"or",
"bool"
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L239-L243 | train | 28,161 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.create_new_info | def create_new_info(cls,
num_channels, layer_type, data_type, encoding,
resolution, voxel_offset, volume_size,
mesh=None, skeletons=None, chunk_size=(64,64,64),
compressed_segmentation_block_size=(8,8,8),
max_mip=0, factor=Vec(2,2,1)
):
"""
Used for creating new neuroglancer info files.
Required:
num_channels: (int) 1 for grayscale, 3 for RGB
layer_type: (str) typically "image" or "segmentation"
data_type: (str) e.g. "uint8", "uint16", "uint32", "float32"
encoding: (str) "raw" for binaries like numpy arrays, "jpeg"
resolution: int (x,y,z), x,y,z voxel dimensions in nanometers
voxel_offset: int (x,y,z), beginning of dataset in positive cartesian space
volume_size: int (x,y,z), extent of dataset in cartesian space from voxel_offset
Optional:
mesh: (str) name of mesh directory, typically "mesh"
skeletons: (str) name of skeletons directory, typically "skeletons"
chunk_size: int (x,y,z), dimensions of each downloadable 3D image chunk in voxels
compressed_segmentation_block_size: (x,y,z) dimensions of each compressed sub-block
(only used when encoding is 'compressed_segmentation')
max_mip: (int), the maximum mip level id.
factor: (Vec), the downsampling factor for each mip level
Returns: dict representing a single mip level that's JSON encodable
"""
if not isinstance(factor, Vec):
factor = Vec(*factor)
if not isinstance(data_type, str):
data_type = np.dtype(data_type).name
info = {
"num_channels": int(num_channels),
"type": layer_type,
"data_type": data_type,
"scales": [{
"encoding": encoding,
"chunk_sizes": [chunk_size],
"key": "_".join(map(str, resolution)),
"resolution": list(map(int, resolution)),
"voxel_offset": list(map(int, voxel_offset)),
"size": list(map(int, volume_size)),
}],
}
fullres = info['scales'][0]
factor_in_mip = factor.clone()
# add mip levels
for _ in range(max_mip):
new_resolution = list(map(int, Vec(*fullres['resolution']) * factor_in_mip ))
newscale = {
u"encoding": encoding,
u"chunk_sizes": [ list(map(int, chunk_size)) ],
u"key": "_".join(map(str, new_resolution)),
u"resolution": new_resolution,
u"voxel_offset": downscale(fullres['voxel_offset'], factor_in_mip, np.floor),
u"size": downscale(fullres['size'], factor_in_mip, np.ceil),
}
info['scales'].append(newscale)
factor_in_mip *= factor
if encoding == 'compressed_segmentation':
info['scales'][0]['compressed_segmentation_block_size'] = list(map(int, compressed_segmentation_block_size))
if mesh:
info['mesh'] = 'mesh' if not isinstance(mesh, string_types) else mesh
if skeletons:
info['skeletons'] = 'skeletons' if not isinstance(skeletons, string_types) else skeletons
return info | python | def create_new_info(cls,
num_channels, layer_type, data_type, encoding,
resolution, voxel_offset, volume_size,
mesh=None, skeletons=None, chunk_size=(64,64,64),
compressed_segmentation_block_size=(8,8,8),
max_mip=0, factor=Vec(2,2,1)
):
"""
Used for creating new neuroglancer info files.
Required:
num_channels: (int) 1 for grayscale, 3 for RGB
layer_type: (str) typically "image" or "segmentation"
data_type: (str) e.g. "uint8", "uint16", "uint32", "float32"
encoding: (str) "raw" for binaries like numpy arrays, "jpeg"
resolution: int (x,y,z), x,y,z voxel dimensions in nanometers
voxel_offset: int (x,y,z), beginning of dataset in positive cartesian space
volume_size: int (x,y,z), extent of dataset in cartesian space from voxel_offset
Optional:
mesh: (str) name of mesh directory, typically "mesh"
skeletons: (str) name of skeletons directory, typically "skeletons"
chunk_size: int (x,y,z), dimensions of each downloadable 3D image chunk in voxels
compressed_segmentation_block_size: (x,y,z) dimensions of each compressed sub-block
(only used when encoding is 'compressed_segmentation')
max_mip: (int), the maximum mip level id.
factor: (Vec), the downsampling factor for each mip level
Returns: dict representing a single mip level that's JSON encodable
"""
if not isinstance(factor, Vec):
factor = Vec(*factor)
if not isinstance(data_type, str):
data_type = np.dtype(data_type).name
info = {
"num_channels": int(num_channels),
"type": layer_type,
"data_type": data_type,
"scales": [{
"encoding": encoding,
"chunk_sizes": [chunk_size],
"key": "_".join(map(str, resolution)),
"resolution": list(map(int, resolution)),
"voxel_offset": list(map(int, voxel_offset)),
"size": list(map(int, volume_size)),
}],
}
fullres = info['scales'][0]
factor_in_mip = factor.clone()
# add mip levels
for _ in range(max_mip):
new_resolution = list(map(int, Vec(*fullres['resolution']) * factor_in_mip ))
newscale = {
u"encoding": encoding,
u"chunk_sizes": [ list(map(int, chunk_size)) ],
u"key": "_".join(map(str, new_resolution)),
u"resolution": new_resolution,
u"voxel_offset": downscale(fullres['voxel_offset'], factor_in_mip, np.floor),
u"size": downscale(fullres['size'], factor_in_mip, np.ceil),
}
info['scales'].append(newscale)
factor_in_mip *= factor
if encoding == 'compressed_segmentation':
info['scales'][0]['compressed_segmentation_block_size'] = list(map(int, compressed_segmentation_block_size))
if mesh:
info['mesh'] = 'mesh' if not isinstance(mesh, string_types) else mesh
if skeletons:
info['skeletons'] = 'skeletons' if not isinstance(skeletons, string_types) else skeletons
return info | [
"def",
"create_new_info",
"(",
"cls",
",",
"num_channels",
",",
"layer_type",
",",
"data_type",
",",
"encoding",
",",
"resolution",
",",
"voxel_offset",
",",
"volume_size",
",",
"mesh",
"=",
"None",
",",
"skeletons",
"=",
"None",
",",
"chunk_size",
"=",
"(",... | Used for creating new neuroglancer info files.
Required:
num_channels: (int) 1 for grayscale, 3 for RGB
layer_type: (str) typically "image" or "segmentation"
data_type: (str) e.g. "uint8", "uint16", "uint32", "float32"
encoding: (str) "raw" for binaries like numpy arrays, "jpeg"
resolution: int (x,y,z), x,y,z voxel dimensions in nanometers
voxel_offset: int (x,y,z), beginning of dataset in positive cartesian space
volume_size: int (x,y,z), extent of dataset in cartesian space from voxel_offset
Optional:
mesh: (str) name of mesh directory, typically "mesh"
skeletons: (str) name of skeletons directory, typically "skeletons"
chunk_size: int (x,y,z), dimensions of each downloadable 3D image chunk in voxels
compressed_segmentation_block_size: (x,y,z) dimensions of each compressed sub-block
(only used when encoding is 'compressed_segmentation')
max_mip: (int), the maximum mip level id.
factor: (Vec), the downsampling factor for each mip level
Returns: dict representing a single mip level that's JSON encodable | [
"Used",
"for",
"creating",
"new",
"neuroglancer",
"info",
"files",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L266-L342 | train | 28,162 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.bbox_to_mip | def bbox_to_mip(self, bbox, mip, to_mip):
"""Convert bbox or slices from one mip level to another."""
if not type(bbox) is Bbox:
bbox = lib.generate_slices(
bbox,
self.mip_bounds(mip).minpt,
self.mip_bounds(mip).maxpt,
bounded=False
)
bbox = Bbox.from_slices(bbox)
def one_level(bbox, mip, to_mip):
original_dtype = bbox.dtype
# setting type required for Python2
downsample_ratio = self.mip_resolution(mip).astype(np.float32) / self.mip_resolution(to_mip).astype(np.float32)
bbox = bbox.astype(np.float64)
bbox *= downsample_ratio
bbox.minpt = np.floor(bbox.minpt)
bbox.maxpt = np.ceil(bbox.maxpt)
bbox = bbox.astype(original_dtype)
return bbox
delta = 1 if to_mip >= mip else -1
while (mip != to_mip):
bbox = one_level(bbox, mip, mip + delta)
mip += delta
return bbox | python | def bbox_to_mip(self, bbox, mip, to_mip):
"""Convert bbox or slices from one mip level to another."""
if not type(bbox) is Bbox:
bbox = lib.generate_slices(
bbox,
self.mip_bounds(mip).minpt,
self.mip_bounds(mip).maxpt,
bounded=False
)
bbox = Bbox.from_slices(bbox)
def one_level(bbox, mip, to_mip):
original_dtype = bbox.dtype
# setting type required for Python2
downsample_ratio = self.mip_resolution(mip).astype(np.float32) / self.mip_resolution(to_mip).astype(np.float32)
bbox = bbox.astype(np.float64)
bbox *= downsample_ratio
bbox.minpt = np.floor(bbox.minpt)
bbox.maxpt = np.ceil(bbox.maxpt)
bbox = bbox.astype(original_dtype)
return bbox
delta = 1 if to_mip >= mip else -1
while (mip != to_mip):
bbox = one_level(bbox, mip, mip + delta)
mip += delta
return bbox | [
"def",
"bbox_to_mip",
"(",
"self",
",",
"bbox",
",",
"mip",
",",
"to_mip",
")",
":",
"if",
"not",
"type",
"(",
"bbox",
")",
"is",
"Bbox",
":",
"bbox",
"=",
"lib",
".",
"generate_slices",
"(",
"bbox",
",",
"self",
".",
"mip_bounds",
"(",
"mip",
")",... | Convert bbox or slices from one mip level to another. | [
"Convert",
"bbox",
"or",
"slices",
"from",
"one",
"mip",
"level",
"to",
"another",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L743-L770 | train | 28,163 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.slices_to_global_coords | def slices_to_global_coords(self, slices):
"""
Used to convert from a higher mip level into mip 0 resolution.
"""
bbox = self.bbox_to_mip(slices, self.mip, 0)
return bbox.to_slices() | python | def slices_to_global_coords(self, slices):
"""
Used to convert from a higher mip level into mip 0 resolution.
"""
bbox = self.bbox_to_mip(slices, self.mip, 0)
return bbox.to_slices() | [
"def",
"slices_to_global_coords",
"(",
"self",
",",
"slices",
")",
":",
"bbox",
"=",
"self",
".",
"bbox_to_mip",
"(",
"slices",
",",
"self",
".",
"mip",
",",
"0",
")",
"return",
"bbox",
".",
"to_slices",
"(",
")"
] | Used to convert from a higher mip level into mip 0 resolution. | [
"Used",
"to",
"convert",
"from",
"a",
"higher",
"mip",
"level",
"into",
"mip",
"0",
"resolution",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L772-L777 | train | 28,164 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.slices_from_global_coords | def slices_from_global_coords(self, slices):
"""
Used for converting from mip 0 coordinates to upper mip level
coordinates. This is mainly useful for debugging since the neuroglancer
client displays the mip 0 coordinates for your cursor.
"""
bbox = self.bbox_to_mip(slices, 0, self.mip)
return bbox.to_slices() | python | def slices_from_global_coords(self, slices):
"""
Used for converting from mip 0 coordinates to upper mip level
coordinates. This is mainly useful for debugging since the neuroglancer
client displays the mip 0 coordinates for your cursor.
"""
bbox = self.bbox_to_mip(slices, 0, self.mip)
return bbox.to_slices() | [
"def",
"slices_from_global_coords",
"(",
"self",
",",
"slices",
")",
":",
"bbox",
"=",
"self",
".",
"bbox_to_mip",
"(",
"slices",
",",
"0",
",",
"self",
".",
"mip",
")",
"return",
"bbox",
".",
"to_slices",
"(",
")"
] | Used for converting from mip 0 coordinates to upper mip level
coordinates. This is mainly useful for debugging since the neuroglancer
client displays the mip 0 coordinates for your cursor. | [
"Used",
"for",
"converting",
"from",
"mip",
"0",
"coordinates",
"to",
"upper",
"mip",
"level",
"coordinates",
".",
"This",
"is",
"mainly",
"useful",
"for",
"debugging",
"since",
"the",
"neuroglancer",
"client",
"displays",
"the",
"mip",
"0",
"coordinates",
"fo... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L779-L786 | train | 28,165 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.__realized_bbox | def __realized_bbox(self, requested_bbox):
"""
The requested bbox might not be aligned to the underlying chunk grid
or even outside the bounds of the dataset. Convert the request into
a bbox representing something that can be actually downloaded.
Returns: Bbox
"""
realized_bbox = requested_bbox.expand_to_chunk_size(self.underlying, offset=self.voxel_offset)
return Bbox.clamp(realized_bbox, self.bounds) | python | def __realized_bbox(self, requested_bbox):
"""
The requested bbox might not be aligned to the underlying chunk grid
or even outside the bounds of the dataset. Convert the request into
a bbox representing something that can be actually downloaded.
Returns: Bbox
"""
realized_bbox = requested_bbox.expand_to_chunk_size(self.underlying, offset=self.voxel_offset)
return Bbox.clamp(realized_bbox, self.bounds) | [
"def",
"__realized_bbox",
"(",
"self",
",",
"requested_bbox",
")",
":",
"realized_bbox",
"=",
"requested_bbox",
".",
"expand_to_chunk_size",
"(",
"self",
".",
"underlying",
",",
"offset",
"=",
"self",
".",
"voxel_offset",
")",
"return",
"Bbox",
".",
"clamp",
"... | The requested bbox might not be aligned to the underlying chunk grid
or even outside the bounds of the dataset. Convert the request into
a bbox representing something that can be actually downloaded.
Returns: Bbox | [
"The",
"requested",
"bbox",
"might",
"not",
"be",
"aligned",
"to",
"the",
"underlying",
"chunk",
"grid",
"or",
"even",
"outside",
"the",
"bounds",
"of",
"the",
"dataset",
".",
"Convert",
"the",
"request",
"into",
"a",
"bbox",
"representing",
"something",
"th... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L880-L889 | train | 28,166 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.exists | def exists(self, bbox_or_slices):
"""
Produce a summary of whether all the requested chunks exist.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume.
Returns: { chunk_file_name: boolean, ... }
"""
if type(bbox_or_slices) is Bbox:
requested_bbox = bbox_or_slices
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox_or_slices)
realized_bbox = self.__realized_bbox(requested_bbox)
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
cloudpaths = list(cloudpaths)
with Storage(self.layer_cloudpath, progress=self.progress) as storage:
existence_report = storage.files_exist(cloudpaths)
return existence_report | python | def exists(self, bbox_or_slices):
"""
Produce a summary of whether all the requested chunks exist.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume.
Returns: { chunk_file_name: boolean, ... }
"""
if type(bbox_or_slices) is Bbox:
requested_bbox = bbox_or_slices
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox_or_slices)
realized_bbox = self.__realized_bbox(requested_bbox)
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
cloudpaths = list(cloudpaths)
with Storage(self.layer_cloudpath, progress=self.progress) as storage:
existence_report = storage.files_exist(cloudpaths)
return existence_report | [
"def",
"exists",
"(",
"self",
",",
"bbox_or_slices",
")",
":",
"if",
"type",
"(",
"bbox_or_slices",
")",
"is",
"Bbox",
":",
"requested_bbox",
"=",
"bbox_or_slices",
"else",
":",
"(",
"requested_bbox",
",",
"_",
",",
"_",
")",
"=",
"self",
".",
"__interpr... | Produce a summary of whether all the requested chunks exist.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume.
Returns: { chunk_file_name: boolean, ... } | [
"Produce",
"a",
"summary",
"of",
"whether",
"all",
"the",
"requested",
"chunks",
"exist",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L891-L909 | train | 28,167 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.delete | def delete(self, bbox_or_slices):
"""
Delete the files within the bounding box.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume.
"""
if type(bbox_or_slices) is Bbox:
requested_bbox = bbox_or_slices
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox_or_slices)
realized_bbox = self.__realized_bbox(requested_bbox)
if requested_bbox != realized_bbox:
raise exceptions.AlignmentError(
"Unable to delete non-chunk aligned bounding boxes. Requested: {}, Realized: {}".format(
requested_bbox, realized_bbox
))
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
cloudpaths = list(cloudpaths)
with Storage(self.layer_cloudpath, progress=self.progress) as storage:
storage.delete_files(cloudpaths)
if self.cache.enabled:
with Storage('file://' + self.cache.path, progress=self.progress) as storage:
storage.delete_files(cloudpaths) | python | def delete(self, bbox_or_slices):
"""
Delete the files within the bounding box.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume.
"""
if type(bbox_or_slices) is Bbox:
requested_bbox = bbox_or_slices
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox_or_slices)
realized_bbox = self.__realized_bbox(requested_bbox)
if requested_bbox != realized_bbox:
raise exceptions.AlignmentError(
"Unable to delete non-chunk aligned bounding boxes. Requested: {}, Realized: {}".format(
requested_bbox, realized_bbox
))
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
cloudpaths = list(cloudpaths)
with Storage(self.layer_cloudpath, progress=self.progress) as storage:
storage.delete_files(cloudpaths)
if self.cache.enabled:
with Storage('file://' + self.cache.path, progress=self.progress) as storage:
storage.delete_files(cloudpaths) | [
"def",
"delete",
"(",
"self",
",",
"bbox_or_slices",
")",
":",
"if",
"type",
"(",
"bbox_or_slices",
")",
"is",
"Bbox",
":",
"requested_bbox",
"=",
"bbox_or_slices",
"else",
":",
"(",
"requested_bbox",
",",
"_",
",",
"_",
")",
"=",
"self",
".",
"__interpr... | Delete the files within the bounding box.
bbox_or_slices: accepts either a Bbox or a tuple of slices representing
the requested volume. | [
"Delete",
"the",
"files",
"within",
"the",
"bounding",
"box",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L911-L938 | train | 28,168 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.transfer_to | def transfer_to(self, cloudpath, bbox, block_size=None, compress=True):
"""
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance over time as demand requires.
cloudpath (str): path to storage layer
bbox (Bbox object): ROI to transfer
block_size (int): number of file chunks to transfer per I/O batch.
compress (bool): Set to False to upload as uncompressed
"""
if type(bbox) is Bbox:
requested_bbox = bbox
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox)
realized_bbox = self.__realized_bbox(requested_bbox)
if requested_bbox != realized_bbox:
raise exceptions.AlignmentError(
"Unable to transfer non-chunk aligned bounding boxes. Requested: {}, Realized: {}".format(
requested_bbox, realized_bbox
))
default_block_size_MB = 50 # MB
chunk_MB = self.underlying.rectVolume() * np.dtype(self.dtype).itemsize * self.num_channels
if self.layer_type == 'image':
# kind of an average guess for some EM datasets, have seen up to 1.9x and as low as 1.1
# affinites are also images, but have very different compression ratios. e.g. 3x for kempressed
chunk_MB /= 1.3
else: # segmentation
chunk_MB /= 100.0 # compression ratios between 80 and 800....
chunk_MB /= 1024.0 * 1024.0
if block_size:
step = block_size
else:
step = int(default_block_size_MB // chunk_MB) + 1
try:
destvol = CloudVolume(cloudpath, mip=self.mip)
except exceptions.InfoUnavailableError:
destvol = CloudVolume(cloudpath, mip=self.mip, info=self.info, provenance=self.provenance.serialize())
destvol.commit_info()
destvol.commit_provenance()
except exceptions.ScaleUnavailableError:
destvol = CloudVolume(cloudpath)
for i in range(len(destvol.scales) + 1, len(self.scales)):
destvol.scales.append(
self.scales[i]
)
destvol.commit_info()
destvol.commit_provenance()
num_blocks = np.ceil(self.bounds.volume() / self.underlying.rectVolume()) / step
num_blocks = int(np.ceil(num_blocks))
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
pbar = tqdm(
desc='Transferring Blocks of {} Chunks'.format(step),
unit='blocks',
disable=(not self.progress),
total=num_blocks,
)
with pbar:
with Storage(self.layer_cloudpath) as src_stor:
with Storage(cloudpath) as dest_stor:
for _ in range(num_blocks, 0, -1):
srcpaths = list(itertools.islice(cloudpaths, step))
files = src_stor.get_files(srcpaths)
files = [ (f['filename'], f['content']) for f in files ]
dest_stor.put_files(
files=files,
compress=compress,
content_type=txrx.content_type(destvol),
)
pbar.update() | python | def transfer_to(self, cloudpath, bbox, block_size=None, compress=True):
"""
Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance over time as demand requires.
cloudpath (str): path to storage layer
bbox (Bbox object): ROI to transfer
block_size (int): number of file chunks to transfer per I/O batch.
compress (bool): Set to False to upload as uncompressed
"""
if type(bbox) is Bbox:
requested_bbox = bbox
else:
(requested_bbox, _, _) = self.__interpret_slices(bbox)
realized_bbox = self.__realized_bbox(requested_bbox)
if requested_bbox != realized_bbox:
raise exceptions.AlignmentError(
"Unable to transfer non-chunk aligned bounding boxes. Requested: {}, Realized: {}".format(
requested_bbox, realized_bbox
))
default_block_size_MB = 50 # MB
chunk_MB = self.underlying.rectVolume() * np.dtype(self.dtype).itemsize * self.num_channels
if self.layer_type == 'image':
# kind of an average guess for some EM datasets, have seen up to 1.9x and as low as 1.1
# affinites are also images, but have very different compression ratios. e.g. 3x for kempressed
chunk_MB /= 1.3
else: # segmentation
chunk_MB /= 100.0 # compression ratios between 80 and 800....
chunk_MB /= 1024.0 * 1024.0
if block_size:
step = block_size
else:
step = int(default_block_size_MB // chunk_MB) + 1
try:
destvol = CloudVolume(cloudpath, mip=self.mip)
except exceptions.InfoUnavailableError:
destvol = CloudVolume(cloudpath, mip=self.mip, info=self.info, provenance=self.provenance.serialize())
destvol.commit_info()
destvol.commit_provenance()
except exceptions.ScaleUnavailableError:
destvol = CloudVolume(cloudpath)
for i in range(len(destvol.scales) + 1, len(self.scales)):
destvol.scales.append(
self.scales[i]
)
destvol.commit_info()
destvol.commit_provenance()
num_blocks = np.ceil(self.bounds.volume() / self.underlying.rectVolume()) / step
num_blocks = int(np.ceil(num_blocks))
cloudpaths = txrx.chunknames(realized_bbox, self.bounds, self.key, self.underlying)
pbar = tqdm(
desc='Transferring Blocks of {} Chunks'.format(step),
unit='blocks',
disable=(not self.progress),
total=num_blocks,
)
with pbar:
with Storage(self.layer_cloudpath) as src_stor:
with Storage(cloudpath) as dest_stor:
for _ in range(num_blocks, 0, -1):
srcpaths = list(itertools.islice(cloudpaths, step))
files = src_stor.get_files(srcpaths)
files = [ (f['filename'], f['content']) for f in files ]
dest_stor.put_files(
files=files,
compress=compress,
content_type=txrx.content_type(destvol),
)
pbar.update() | [
"def",
"transfer_to",
"(",
"self",
",",
"cloudpath",
",",
"bbox",
",",
"block_size",
"=",
"None",
",",
"compress",
"=",
"True",
")",
":",
"if",
"type",
"(",
"bbox",
")",
"is",
"Bbox",
":",
"requested_bbox",
"=",
"bbox",
"else",
":",
"(",
"requested_bbo... | Transfer files from one storage location to another, bypassing
volume painting. This enables using a single CloudVolume instance
to transfer big volumes. In some cases, gsutil or aws s3 cli tools
may be more appropriate. This method is provided for convenience. It
may be optimized for better performance over time as demand requires.
cloudpath (str): path to storage layer
bbox (Bbox object): ROI to transfer
block_size (int): number of file chunks to transfer per I/O batch.
compress (bool): Set to False to upload as uncompressed | [
"Transfer",
"files",
"from",
"one",
"storage",
"location",
"to",
"another",
"bypassing",
"volume",
"painting",
".",
"This",
"enables",
"using",
"a",
"single",
"CloudVolume",
"instance",
"to",
"transfer",
"big",
"volumes",
".",
"In",
"some",
"cases",
"gsutil",
... | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L940-L1019 | train | 28,169 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.download_point | def download_point(self, pt, size=256, mip=None):
"""
Download to the right of point given in mip 0 coords.
Useful for quickly visualizing a neuroglancer coordinate
at an arbitary mip level.
pt: (x,y,z)
size: int or (sx,sy,sz)
Return: image
"""
if isinstance(size, int):
size = Vec(size, size, size)
else:
size = Vec(*size)
if mip is None:
mip = self.mip
size2 = size // 2
pt = self.point_to_mip(pt, mip=0, to_mip=mip)
bbox = Bbox(pt - size2, pt + size2)
saved_mip = self.mip
self.mip = mip
img = self[bbox]
self.mip = saved_mip
return img | python | def download_point(self, pt, size=256, mip=None):
"""
Download to the right of point given in mip 0 coords.
Useful for quickly visualizing a neuroglancer coordinate
at an arbitary mip level.
pt: (x,y,z)
size: int or (sx,sy,sz)
Return: image
"""
if isinstance(size, int):
size = Vec(size, size, size)
else:
size = Vec(*size)
if mip is None:
mip = self.mip
size2 = size // 2
pt = self.point_to_mip(pt, mip=0, to_mip=mip)
bbox = Bbox(pt - size2, pt + size2)
saved_mip = self.mip
self.mip = mip
img = self[bbox]
self.mip = saved_mip
return img | [
"def",
"download_point",
"(",
"self",
",",
"pt",
",",
"size",
"=",
"256",
",",
"mip",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"size",
",",
"int",
")",
":",
"size",
"=",
"Vec",
"(",
"size",
",",
"size",
",",
"size",
")",
"else",
":",
"si... | Download to the right of point given in mip 0 coords.
Useful for quickly visualizing a neuroglancer coordinate
at an arbitary mip level.
pt: (x,y,z)
size: int or (sx,sy,sz)
Return: image | [
"Download",
"to",
"the",
"right",
"of",
"point",
"given",
"in",
"mip",
"0",
"coords",
".",
"Useful",
"for",
"quickly",
"visualizing",
"a",
"neuroglancer",
"coordinate",
"at",
"an",
"arbitary",
"mip",
"level",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L1035-L1063 | train | 28,170 |
seung-lab/cloud-volume | cloudvolume/cloudvolume.py | CloudVolume.download_to_shared_memory | def download_to_shared_memory(self, slices, location=None):
"""
Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolume will merely write to it, it will not unlink the
memory automatically. To fully clear the shared memory you must unlink the
location and close any mmap file handles. You can use `cloudvolume.sharedmemory.unlink(...)`
to help you unlink the shared memory file or `vol.unlink_shared_memory()` if you do
not specify location (meaning the default instance location is used).
EXPERT MODE WARNING: If you aren't sure you need this function (e.g. to relieve
memory pressure or improve performance in some way) you should use the ordinary
download method of img = vol[:]. A typical use case is transferring arrays between
different processes without making copies. For reference, this feature was created
for downloading a 62 GB array and working with it in Julia.
Required:
slices: (Bbox or list of slices) the bounding box the shared array represents. For instance
if you have a 1024x1024x128 volume and you're uploading only a 512x512x64 corner
touching the origin, your Bbox would be `Bbox( (0,0,0), (512,512,64) )`.
Optional:
location: (str) Defaults to self.shared_memory_id. Shared memory location
e.g. 'cloudvolume-shm-RANDOM-STRING' This typically corresponds to a file
in `/dev/shm` or `/run/shm/`. It can also be a file if you're using that for mmap.
Returns: void
"""
if self.path.protocol == 'boss':
raise NotImplementedError('BOSS protocol does not support shared memory download.')
if type(slices) == Bbox:
slices = slices.to_slices()
(requested_bbox, steps, channel_slice) = self.__interpret_slices(slices)
if self.autocrop:
requested_bbox = Bbox.intersection(requested_bbox, self.bounds)
location = location or self.shared_memory_id
return txrx.cutout(self, requested_bbox, steps, channel_slice, parallel=self.parallel,
shared_memory_location=location, output_to_shared_memory=True) | python | def download_to_shared_memory(self, slices, location=None):
"""
Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolume will merely write to it, it will not unlink the
memory automatically. To fully clear the shared memory you must unlink the
location and close any mmap file handles. You can use `cloudvolume.sharedmemory.unlink(...)`
to help you unlink the shared memory file or `vol.unlink_shared_memory()` if you do
not specify location (meaning the default instance location is used).
EXPERT MODE WARNING: If you aren't sure you need this function (e.g. to relieve
memory pressure or improve performance in some way) you should use the ordinary
download method of img = vol[:]. A typical use case is transferring arrays between
different processes without making copies. For reference, this feature was created
for downloading a 62 GB array and working with it in Julia.
Required:
slices: (Bbox or list of slices) the bounding box the shared array represents. For instance
if you have a 1024x1024x128 volume and you're uploading only a 512x512x64 corner
touching the origin, your Bbox would be `Bbox( (0,0,0), (512,512,64) )`.
Optional:
location: (str) Defaults to self.shared_memory_id. Shared memory location
e.g. 'cloudvolume-shm-RANDOM-STRING' This typically corresponds to a file
in `/dev/shm` or `/run/shm/`. It can also be a file if you're using that for mmap.
Returns: void
"""
if self.path.protocol == 'boss':
raise NotImplementedError('BOSS protocol does not support shared memory download.')
if type(slices) == Bbox:
slices = slices.to_slices()
(requested_bbox, steps, channel_slice) = self.__interpret_slices(slices)
if self.autocrop:
requested_bbox = Bbox.intersection(requested_bbox, self.bounds)
location = location or self.shared_memory_id
return txrx.cutout(self, requested_bbox, steps, channel_slice, parallel=self.parallel,
shared_memory_location=location, output_to_shared_memory=True) | [
"def",
"download_to_shared_memory",
"(",
"self",
",",
"slices",
",",
"location",
"=",
"None",
")",
":",
"if",
"self",
".",
"path",
".",
"protocol",
"==",
"'boss'",
":",
"raise",
"NotImplementedError",
"(",
"'BOSS protocol does not support shared memory download.'",
... | Download images to a shared memory array.
https://github.com/seung-lab/cloud-volume/wiki/Advanced-Topic:-Shared-Memory
tip: If you want to use slice notation, np.s_[...] will help in a pinch.
MEMORY LIFECYCLE WARNING: You are responsible for managing the lifecycle of the
shared memory. CloudVolume will merely write to it, it will not unlink the
memory automatically. To fully clear the shared memory you must unlink the
location and close any mmap file handles. You can use `cloudvolume.sharedmemory.unlink(...)`
to help you unlink the shared memory file or `vol.unlink_shared_memory()` if you do
not specify location (meaning the default instance location is used).
EXPERT MODE WARNING: If you aren't sure you need this function (e.g. to relieve
memory pressure or improve performance in some way) you should use the ordinary
download method of img = vol[:]. A typical use case is transferring arrays between
different processes without making copies. For reference, this feature was created
for downloading a 62 GB array and working with it in Julia.
Required:
slices: (Bbox or list of slices) the bounding box the shared array represents. For instance
if you have a 1024x1024x128 volume and you're uploading only a 512x512x64 corner
touching the origin, your Bbox would be `Bbox( (0,0,0), (512,512,64) )`.
Optional:
location: (str) Defaults to self.shared_memory_id. Shared memory location
e.g. 'cloudvolume-shm-RANDOM-STRING' This typically corresponds to a file
in `/dev/shm` or `/run/shm/`. It can also be a file if you're using that for mmap.
Returns: void | [
"Download",
"images",
"to",
"a",
"shared",
"memory",
"array",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/cloudvolume.py#L1065-L1109 | train | 28,171 |
seung-lab/cloud-volume | cloudvolume/meshservice.py | PrecomputedMeshService.get | def get(self, segids, remove_duplicate_vertices=True, fuse=True,
chunk_size=None):
"""
Merge fragments derived from these segids into a single vertex and face list.
Why merge multiple segids into one mesh? For example, if you have a set of
segids that belong to the same neuron.
segids: (iterable or int) segids to render into a single mesh
Optional:
remove_duplicate_vertices: bool, fuse exactly matching vertices
fuse: bool, merge all downloaded meshes into a single mesh
chunk_size: [chunk_x, chunk_y, chunk_z] if pass only merge at chunk boundaries
Returns: {
num_vertices: int,
vertices: [ (x,y,z), ... ] # floats
faces: [ int, int, int, ... ] # int = vertex_index, 3 to a face
}
"""
segids = toiter(segids)
dne = self._check_missing_manifests(segids)
if dne:
missing = ', '.join([ str(segid) for segid in dne ])
raise ValueError(red(
'Segment ID(s) {} are missing corresponding mesh manifests.\nAborted.' \
.format(missing)
))
fragments = self._get_manifests(segids)
fragments = fragments.values()
fragments = list(itertools.chain.from_iterable(fragments)) # flatten
fragments = self._get_mesh_fragments(fragments)
fragments = sorted(fragments, key=lambda frag: frag['filename']) # make decoding deterministic
# decode all the fragments
meshdata = defaultdict(list)
for frag in tqdm(fragments, disable=(not self.vol.progress), desc="Decoding Mesh Buffer"):
segid = filename_to_segid(frag['filename'])
mesh = decode_mesh_buffer(frag['filename'], frag['content'])
meshdata[segid].append(mesh)
def produce_output(mdata):
vertexct = np.zeros(len(mdata) + 1, np.uint32)
vertexct[1:] = np.cumsum([ x['num_vertices'] for x in mdata ])
vertices = np.concatenate([ x['vertices'] for x in mdata ])
faces = np.concatenate([
mesh['faces'] + vertexct[i] for i, mesh in enumerate(mdata)
])
if remove_duplicate_vertices:
if chunk_size:
vertices, faces = remove_duplicate_vertices_cross_chunks(vertices,
faces,
chunk_size)
else:
vertices, faces = np.unique(vertices[faces], return_inverse=True, axis=0)
faces = faces.astype(np.uint32)
return {
'num_vertices': len(vertices),
'vertices': vertices,
'faces': faces,
}
if fuse:
meshdata = [ (segid, mdata) for segid, mdata in six.iteritems(meshdata) ]
meshdata = sorted(meshdata, key=lambda sm: sm[0])
meshdata = [ mdata for segid, mdata in meshdata ]
meshdata = list(itertools.chain.from_iterable(meshdata)) # flatten
return produce_output(meshdata)
else:
return { segid: produce_output(mdata) for segid, mdata in six.iteritems(meshdata) } | python | def get(self, segids, remove_duplicate_vertices=True, fuse=True,
chunk_size=None):
"""
Merge fragments derived from these segids into a single vertex and face list.
Why merge multiple segids into one mesh? For example, if you have a set of
segids that belong to the same neuron.
segids: (iterable or int) segids to render into a single mesh
Optional:
remove_duplicate_vertices: bool, fuse exactly matching vertices
fuse: bool, merge all downloaded meshes into a single mesh
chunk_size: [chunk_x, chunk_y, chunk_z] if pass only merge at chunk boundaries
Returns: {
num_vertices: int,
vertices: [ (x,y,z), ... ] # floats
faces: [ int, int, int, ... ] # int = vertex_index, 3 to a face
}
"""
segids = toiter(segids)
dne = self._check_missing_manifests(segids)
if dne:
missing = ', '.join([ str(segid) for segid in dne ])
raise ValueError(red(
'Segment ID(s) {} are missing corresponding mesh manifests.\nAborted.' \
.format(missing)
))
fragments = self._get_manifests(segids)
fragments = fragments.values()
fragments = list(itertools.chain.from_iterable(fragments)) # flatten
fragments = self._get_mesh_fragments(fragments)
fragments = sorted(fragments, key=lambda frag: frag['filename']) # make decoding deterministic
# decode all the fragments
meshdata = defaultdict(list)
for frag in tqdm(fragments, disable=(not self.vol.progress), desc="Decoding Mesh Buffer"):
segid = filename_to_segid(frag['filename'])
mesh = decode_mesh_buffer(frag['filename'], frag['content'])
meshdata[segid].append(mesh)
def produce_output(mdata):
vertexct = np.zeros(len(mdata) + 1, np.uint32)
vertexct[1:] = np.cumsum([ x['num_vertices'] for x in mdata ])
vertices = np.concatenate([ x['vertices'] for x in mdata ])
faces = np.concatenate([
mesh['faces'] + vertexct[i] for i, mesh in enumerate(mdata)
])
if remove_duplicate_vertices:
if chunk_size:
vertices, faces = remove_duplicate_vertices_cross_chunks(vertices,
faces,
chunk_size)
else:
vertices, faces = np.unique(vertices[faces], return_inverse=True, axis=0)
faces = faces.astype(np.uint32)
return {
'num_vertices': len(vertices),
'vertices': vertices,
'faces': faces,
}
if fuse:
meshdata = [ (segid, mdata) for segid, mdata in six.iteritems(meshdata) ]
meshdata = sorted(meshdata, key=lambda sm: sm[0])
meshdata = [ mdata for segid, mdata in meshdata ]
meshdata = list(itertools.chain.from_iterable(meshdata)) # flatten
return produce_output(meshdata)
else:
return { segid: produce_output(mdata) for segid, mdata in six.iteritems(meshdata) } | [
"def",
"get",
"(",
"self",
",",
"segids",
",",
"remove_duplicate_vertices",
"=",
"True",
",",
"fuse",
"=",
"True",
",",
"chunk_size",
"=",
"None",
")",
":",
"segids",
"=",
"toiter",
"(",
"segids",
")",
"dne",
"=",
"self",
".",
"_check_missing_manifests",
... | Merge fragments derived from these segids into a single vertex and face list.
Why merge multiple segids into one mesh? For example, if you have a set of
segids that belong to the same neuron.
segids: (iterable or int) segids to render into a single mesh
Optional:
remove_duplicate_vertices: bool, fuse exactly matching vertices
fuse: bool, merge all downloaded meshes into a single mesh
chunk_size: [chunk_x, chunk_y, chunk_z] if pass only merge at chunk boundaries
Returns: {
num_vertices: int,
vertices: [ (x,y,z), ... ] # floats
faces: [ int, int, int, ... ] # int = vertex_index, 3 to a face
} | [
"Merge",
"fragments",
"derived",
"from",
"these",
"segids",
"into",
"a",
"single",
"vertex",
"and",
"face",
"list",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/meshservice.py#L92-L166 | train | 28,172 |
seung-lab/cloud-volume | cloudvolume/meshservice.py | PrecomputedMeshService._check_missing_manifests | def _check_missing_manifests(self, segids):
"""Check if there are any missing mesh manifests prior to downloading."""
manifest_paths = [ self._manifest_path(segid) for segid in segids ]
with Storage(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:
exists = stor.files_exist(manifest_paths)
dne = []
for path, there in exists.items():
if not there:
(segid,) = re.search(r'(\d+):0$', path).groups()
dne.append(segid)
return dne | python | def _check_missing_manifests(self, segids):
"""Check if there are any missing mesh manifests prior to downloading."""
manifest_paths = [ self._manifest_path(segid) for segid in segids ]
with Storage(self.vol.layer_cloudpath, progress=self.vol.progress) as stor:
exists = stor.files_exist(manifest_paths)
dne = []
for path, there in exists.items():
if not there:
(segid,) = re.search(r'(\d+):0$', path).groups()
dne.append(segid)
return dne | [
"def",
"_check_missing_manifests",
"(",
"self",
",",
"segids",
")",
":",
"manifest_paths",
"=",
"[",
"self",
".",
"_manifest_path",
"(",
"segid",
")",
"for",
"segid",
"in",
"segids",
"]",
"with",
"Storage",
"(",
"self",
".",
"vol",
".",
"layer_cloudpath",
... | Check if there are any missing mesh manifests prior to downloading. | [
"Check",
"if",
"there",
"are",
"any",
"missing",
"mesh",
"manifests",
"prior",
"to",
"downloading",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/meshservice.py#L168-L179 | train | 28,173 |
seung-lab/cloud-volume | cloudvolume/meshservice.py | PrecomputedMeshService.save | def save(self, segids, filepath=None, file_format='ply'):
"""
Save one or more segids into a common mesh format as a single file.
segids: int, string, or list thereof
filepath: string or None (optional)
file_format: string (optional)
Supported Formats: 'obj', 'ply'
"""
if type(segids) != list:
segids = [segids]
meshdata = self.get(segids)
if not filepath:
filepath = str(segids[0]) + "." + file_format
if len(segids) > 1:
filepath = "{}_{}.{}".format(segids[0], segids[-1], file_format)
if file_format == 'obj':
objdata = mesh_to_obj(meshdata, progress=self.vol.progress)
objdata = '\n'.join(objdata) + '\n'
data = objdata.encode('utf8')
elif file_format == 'ply':
data = mesh_to_ply(meshdata)
else:
raise NotImplementedError('Only .obj and .ply is currently supported.')
with open(filepath, 'wb') as f:
f.write(data) | python | def save(self, segids, filepath=None, file_format='ply'):
"""
Save one or more segids into a common mesh format as a single file.
segids: int, string, or list thereof
filepath: string or None (optional)
file_format: string (optional)
Supported Formats: 'obj', 'ply'
"""
if type(segids) != list:
segids = [segids]
meshdata = self.get(segids)
if not filepath:
filepath = str(segids[0]) + "." + file_format
if len(segids) > 1:
filepath = "{}_{}.{}".format(segids[0], segids[-1], file_format)
if file_format == 'obj':
objdata = mesh_to_obj(meshdata, progress=self.vol.progress)
objdata = '\n'.join(objdata) + '\n'
data = objdata.encode('utf8')
elif file_format == 'ply':
data = mesh_to_ply(meshdata)
else:
raise NotImplementedError('Only .obj and .ply is currently supported.')
with open(filepath, 'wb') as f:
f.write(data) | [
"def",
"save",
"(",
"self",
",",
"segids",
",",
"filepath",
"=",
"None",
",",
"file_format",
"=",
"'ply'",
")",
":",
"if",
"type",
"(",
"segids",
")",
"!=",
"list",
":",
"segids",
"=",
"[",
"segids",
"]",
"meshdata",
"=",
"self",
".",
"get",
"(",
... | Save one or more segids into a common mesh format as a single file.
segids: int, string, or list thereof
filepath: string or None (optional)
file_format: string (optional)
Supported Formats: 'obj', 'ply' | [
"Save",
"one",
"or",
"more",
"segids",
"into",
"a",
"common",
"mesh",
"format",
"as",
"a",
"single",
"file",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/meshservice.py#L181-L211 | train | 28,174 |
seung-lab/cloud-volume | cloudvolume/py_compressed_segmentation.py | pad_block | def pad_block(block, block_size):
"""Pad a block to block_size with its most frequent value"""
unique_vals, unique_counts = np.unique(block, return_counts=True)
most_frequent_value = unique_vals[np.argmax(unique_counts)]
return np.pad(block,
tuple((0, desired_size - actual_size)
for desired_size, actual_size
in zip(block_size, block.shape)),
mode="constant", constant_values=most_frequent_value) | python | def pad_block(block, block_size):
"""Pad a block to block_size with its most frequent value"""
unique_vals, unique_counts = np.unique(block, return_counts=True)
most_frequent_value = unique_vals[np.argmax(unique_counts)]
return np.pad(block,
tuple((0, desired_size - actual_size)
for desired_size, actual_size
in zip(block_size, block.shape)),
mode="constant", constant_values=most_frequent_value) | [
"def",
"pad_block",
"(",
"block",
",",
"block_size",
")",
":",
"unique_vals",
",",
"unique_counts",
"=",
"np",
".",
"unique",
"(",
"block",
",",
"return_counts",
"=",
"True",
")",
"most_frequent_value",
"=",
"unique_vals",
"[",
"np",
".",
"argmax",
"(",
"u... | Pad a block to block_size with its most frequent value | [
"Pad",
"a",
"block",
"to",
"block_size",
"with",
"its",
"most",
"frequent",
"value"
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/py_compressed_segmentation.py#L25-L33 | train | 28,175 |
seung-lab/cloud-volume | cloudvolume/lib.py | find_closest_divisor | def find_closest_divisor(to_divide, closest_to):
"""
This is used to find the right chunk size for
importing a neuroglancer dataset that has a
chunk import size that's not evenly divisible by
64,64,64.
e.g.
neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64,64])
Required:
to_divide: (tuple) x,y,z chunk size to rechunk
closest_to: (tuple) x,y,z ideal chunk size
Return: [x,y,z] chunk size that works for ingestion
"""
def find_closest(td, ct):
min_distance = td
best = td
for divisor in divisors(td):
if abs(divisor - ct) < min_distance:
min_distance = abs(divisor - ct)
best = divisor
return best
return [ find_closest(td, ct) for td, ct in zip(to_divide, closest_to) ] | python | def find_closest_divisor(to_divide, closest_to):
"""
This is used to find the right chunk size for
importing a neuroglancer dataset that has a
chunk import size that's not evenly divisible by
64,64,64.
e.g.
neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64,64])
Required:
to_divide: (tuple) x,y,z chunk size to rechunk
closest_to: (tuple) x,y,z ideal chunk size
Return: [x,y,z] chunk size that works for ingestion
"""
def find_closest(td, ct):
min_distance = td
best = td
for divisor in divisors(td):
if abs(divisor - ct) < min_distance:
min_distance = abs(divisor - ct)
best = divisor
return best
return [ find_closest(td, ct) for td, ct in zip(to_divide, closest_to) ] | [
"def",
"find_closest_divisor",
"(",
"to_divide",
",",
"closest_to",
")",
":",
"def",
"find_closest",
"(",
"td",
",",
"ct",
")",
":",
"min_distance",
"=",
"td",
"best",
"=",
"td",
"for",
"divisor",
"in",
"divisors",
"(",
"td",
")",
":",
"if",
"abs",
"("... | This is used to find the right chunk size for
importing a neuroglancer dataset that has a
chunk import size that's not evenly divisible by
64,64,64.
e.g.
neuroglancer_chunk_size = find_closest_divisor(build_chunk_size, closest_to=[64,64,64])
Required:
to_divide: (tuple) x,y,z chunk size to rechunk
closest_to: (tuple) x,y,z ideal chunk size
Return: [x,y,z] chunk size that works for ingestion | [
"This",
"is",
"used",
"to",
"find",
"the",
"right",
"chunk",
"size",
"for",
"importing",
"a",
"neuroglancer",
"dataset",
"that",
"has",
"a",
"chunk",
"import",
"size",
"that",
"s",
"not",
"evenly",
"divisible",
"by",
"64",
"64",
"64",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L178-L204 | train | 28,176 |
seung-lab/cloud-volume | cloudvolume/lib.py | divisors | def divisors(n):
"""Generate the divisors of n"""
for i in range(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
yield n / i | python | def divisors(n):
"""Generate the divisors of n"""
for i in range(1, int(math.sqrt(n) + 1)):
if n % i == 0:
yield i
if i*i != n:
yield n / i | [
"def",
"divisors",
"(",
"n",
")",
":",
"for",
"i",
"in",
"range",
"(",
"1",
",",
"int",
"(",
"math",
".",
"sqrt",
"(",
"n",
")",
"+",
"1",
")",
")",
":",
"if",
"n",
"%",
"i",
"==",
"0",
":",
"yield",
"i",
"if",
"i",
"*",
"i",
"!=",
"n",... | Generate the divisors of n | [
"Generate",
"the",
"divisors",
"of",
"n"
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L206-L212 | train | 28,177 |
seung-lab/cloud-volume | cloudvolume/lib.py | Bbox.expand_to_chunk_size | def expand_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):
"""
Align a potentially non-axis aligned bbox to the grid by growing it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset
"""
chunk_size = np.array(chunk_size, dtype=np.float32)
result = self.clone()
result = result - offset
result.minpt = np.floor(result.minpt / chunk_size) * chunk_size
result.maxpt = np.ceil(result.maxpt / chunk_size) * chunk_size
return (result + offset).astype(self.dtype) | python | def expand_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):
"""
Align a potentially non-axis aligned bbox to the grid by growing it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset
"""
chunk_size = np.array(chunk_size, dtype=np.float32)
result = self.clone()
result = result - offset
result.minpt = np.floor(result.minpt / chunk_size) * chunk_size
result.maxpt = np.ceil(result.maxpt / chunk_size) * chunk_size
return (result + offset).astype(self.dtype) | [
"def",
"expand_to_chunk_size",
"(",
"self",
",",
"chunk_size",
",",
"offset",
"=",
"Vec",
"(",
"0",
",",
"0",
",",
"0",
",",
"dtype",
"=",
"int",
")",
")",
":",
"chunk_size",
"=",
"np",
".",
"array",
"(",
"chunk_size",
",",
"dtype",
"=",
"np",
".",... | Align a potentially non-axis aligned bbox to the grid by growing it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset | [
"Align",
"a",
"potentially",
"non",
"-",
"axis",
"aligned",
"bbox",
"to",
"the",
"grid",
"by",
"growing",
"it",
"to",
"the",
"nearest",
"grid",
"lines",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L549-L565 | train | 28,178 |
seung-lab/cloud-volume | cloudvolume/lib.py | Bbox.round_to_chunk_size | def round_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):
"""
Align a potentially non-axis aligned bbox to the grid by rounding it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset
"""
chunk_size = np.array(chunk_size, dtype=np.float32)
result = self.clone()
result = result - offset
result.minpt = np.round(result.minpt / chunk_size) * chunk_size
result.maxpt = np.round(result.maxpt / chunk_size) * chunk_size
return (result + offset).astype(self.dtype) | python | def round_to_chunk_size(self, chunk_size, offset=Vec(0,0,0, dtype=int)):
"""
Align a potentially non-axis aligned bbox to the grid by rounding it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset
"""
chunk_size = np.array(chunk_size, dtype=np.float32)
result = self.clone()
result = result - offset
result.minpt = np.round(result.minpt / chunk_size) * chunk_size
result.maxpt = np.round(result.maxpt / chunk_size) * chunk_size
return (result + offset).astype(self.dtype) | [
"def",
"round_to_chunk_size",
"(",
"self",
",",
"chunk_size",
",",
"offset",
"=",
"Vec",
"(",
"0",
",",
"0",
",",
"0",
",",
"dtype",
"=",
"int",
")",
")",
":",
"chunk_size",
"=",
"np",
".",
"array",
"(",
"chunk_size",
",",
"dtype",
"=",
"np",
".",
... | Align a potentially non-axis aligned bbox to the grid by rounding it
to the nearest grid lines.
Required:
chunk_size: arraylike (x,y,z), the size of chunks in the
dataset e.g. (64,64,64)
Optional:
offset: arraylike (x,y,z), the starting coordinate of the dataset | [
"Align",
"a",
"potentially",
"non",
"-",
"axis",
"aligned",
"bbox",
"to",
"the",
"grid",
"by",
"rounding",
"it",
"to",
"the",
"nearest",
"grid",
"lines",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L592-L608 | train | 28,179 |
seung-lab/cloud-volume | cloudvolume/lib.py | Bbox.contains | def contains(self, point):
"""
Tests if a point on or within a bounding box.
Returns: boolean
"""
return (
point[0] >= self.minpt[0]
and point[1] >= self.minpt[1]
and point[2] >= self.minpt[2]
and point[0] <= self.maxpt[0]
and point[1] <= self.maxpt[1]
and point[2] <= self.maxpt[2]
) | python | def contains(self, point):
"""
Tests if a point on or within a bounding box.
Returns: boolean
"""
return (
point[0] >= self.minpt[0]
and point[1] >= self.minpt[1]
and point[2] >= self.minpt[2]
and point[0] <= self.maxpt[0]
and point[1] <= self.maxpt[1]
and point[2] <= self.maxpt[2]
) | [
"def",
"contains",
"(",
"self",
",",
"point",
")",
":",
"return",
"(",
"point",
"[",
"0",
"]",
">=",
"self",
".",
"minpt",
"[",
"0",
"]",
"and",
"point",
"[",
"1",
"]",
">=",
"self",
".",
"minpt",
"[",
"1",
"]",
"and",
"point",
"[",
"2",
"]",... | Tests if a point on or within a bounding box.
Returns: boolean | [
"Tests",
"if",
"a",
"point",
"on",
"or",
"within",
"a",
"bounding",
"box",
"."
] | d2fd4500333f1bc3cd3e3919a8b649cec5d8e214 | https://github.com/seung-lab/cloud-volume/blob/d2fd4500333f1bc3cd3e3919a8b649cec5d8e214/cloudvolume/lib.py#L610-L623 | train | 28,180 |
wavefrontHQ/python-client | wavefront_api_client/models/message.py | Message.display | def display(self, display):
"""Sets the display of this Message.
The form of display for this message # noqa: E501
:param display: The display of this Message. # noqa: E501
:type: str
"""
if display is None:
raise ValueError("Invalid value for `display`, must not be `None`") # noqa: E501
allowed_values = ["BANNER", "TOASTER"] # noqa: E501
if display not in allowed_values:
raise ValueError(
"Invalid value for `display` ({0}), must be one of {1}" # noqa: E501
.format(display, allowed_values)
)
self._display = display | python | def display(self, display):
"""Sets the display of this Message.
The form of display for this message # noqa: E501
:param display: The display of this Message. # noqa: E501
:type: str
"""
if display is None:
raise ValueError("Invalid value for `display`, must not be `None`") # noqa: E501
allowed_values = ["BANNER", "TOASTER"] # noqa: E501
if display not in allowed_values:
raise ValueError(
"Invalid value for `display` ({0}), must be one of {1}" # noqa: E501
.format(display, allowed_values)
)
self._display = display | [
"def",
"display",
"(",
"self",
",",
"display",
")",
":",
"if",
"display",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `display`, must not be `None`\"",
")",
"# noqa: E501",
"allowed_values",
"=",
"[",
"\"BANNER\"",
",",
"\"TOASTER\"",
"]",
... | Sets the display of this Message.
The form of display for this message # noqa: E501
:param display: The display of this Message. # noqa: E501
:type: str | [
"Sets",
"the",
"display",
"of",
"this",
"Message",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/message.py#L157-L174 | train | 28,181 |
wavefrontHQ/python-client | wavefront_api_client/models/message.py | Message.scope | def scope(self, scope):
"""Sets the scope of this Message.
The audience scope that this message should reach # noqa: E501
:param scope: The scope of this Message. # noqa: E501
:type: str
"""
if scope is None:
raise ValueError("Invalid value for `scope`, must not be `None`") # noqa: E501
allowed_values = ["CLUSTER", "CUSTOMER", "USER"] # noqa: E501
if scope not in allowed_values:
raise ValueError(
"Invalid value for `scope` ({0}), must be one of {1}" # noqa: E501
.format(scope, allowed_values)
)
self._scope = scope | python | def scope(self, scope):
"""Sets the scope of this Message.
The audience scope that this message should reach # noqa: E501
:param scope: The scope of this Message. # noqa: E501
:type: str
"""
if scope is None:
raise ValueError("Invalid value for `scope`, must not be `None`") # noqa: E501
allowed_values = ["CLUSTER", "CUSTOMER", "USER"] # noqa: E501
if scope not in allowed_values:
raise ValueError(
"Invalid value for `scope` ({0}), must be one of {1}" # noqa: E501
.format(scope, allowed_values)
)
self._scope = scope | [
"def",
"scope",
"(",
"self",
",",
"scope",
")",
":",
"if",
"scope",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `scope`, must not be `None`\"",
")",
"# noqa: E501",
"allowed_values",
"=",
"[",
"\"CLUSTER\"",
",",
"\"CUSTOMER\"",
",",
"\"USE... | Sets the scope of this Message.
The audience scope that this message should reach # noqa: E501
:param scope: The scope of this Message. # noqa: E501
:type: str | [
"Sets",
"the",
"scope",
"of",
"this",
"Message",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/message.py#L257-L274 | train | 28,182 |
wavefrontHQ/python-client | wavefront_api_client/models/message.py | Message.severity | def severity(self, severity):
"""Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str
"""
if severity is None:
raise ValueError("Invalid value for `severity`, must not be `None`") # noqa: E501
allowed_values = ["MARKETING", "INFO", "WARN", "SEVERE"] # noqa: E501
if severity not in allowed_values:
raise ValueError(
"Invalid value for `severity` ({0}), must be one of {1}" # noqa: E501
.format(severity, allowed_values)
)
self._severity = severity | python | def severity(self, severity):
"""Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str
"""
if severity is None:
raise ValueError("Invalid value for `severity`, must not be `None`") # noqa: E501
allowed_values = ["MARKETING", "INFO", "WARN", "SEVERE"] # noqa: E501
if severity not in allowed_values:
raise ValueError(
"Invalid value for `severity` ({0}), must be one of {1}" # noqa: E501
.format(severity, allowed_values)
)
self._severity = severity | [
"def",
"severity",
"(",
"self",
",",
"severity",
")",
":",
"if",
"severity",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `severity`, must not be `None`\"",
")",
"# noqa: E501",
"allowed_values",
"=",
"[",
"\"MARKETING\"",
",",
"\"INFO\"",
","... | Sets the severity of this Message.
Message severity # noqa: E501
:param severity: The severity of this Message. # noqa: E501
:type: str | [
"Sets",
"the",
"severity",
"of",
"this",
"Message",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/message.py#L288-L305 | train | 28,183 |
wavefrontHQ/python-client | wavefront_api_client/models/facet_search_request_container.py | FacetSearchRequestContainer.facet_query_matching_method | def facet_query_matching_method(self, facet_query_matching_method):
"""Sets the facet_query_matching_method of this FacetSearchRequestContainer.
The matching method used to filter when 'facetQuery' is used. Defaults to CONTAINS. # noqa: E501
:param facet_query_matching_method: The facet_query_matching_method of this FacetSearchRequestContainer. # noqa: E501
:type: str
"""
allowed_values = ["CONTAINS", "STARTSWITH", "EXACT", "TAGPATH"] # noqa: E501
if facet_query_matching_method not in allowed_values:
raise ValueError(
"Invalid value for `facet_query_matching_method` ({0}), must be one of {1}" # noqa: E501
.format(facet_query_matching_method, allowed_values)
)
self._facet_query_matching_method = facet_query_matching_method | python | def facet_query_matching_method(self, facet_query_matching_method):
"""Sets the facet_query_matching_method of this FacetSearchRequestContainer.
The matching method used to filter when 'facetQuery' is used. Defaults to CONTAINS. # noqa: E501
:param facet_query_matching_method: The facet_query_matching_method of this FacetSearchRequestContainer. # noqa: E501
:type: str
"""
allowed_values = ["CONTAINS", "STARTSWITH", "EXACT", "TAGPATH"] # noqa: E501
if facet_query_matching_method not in allowed_values:
raise ValueError(
"Invalid value for `facet_query_matching_method` ({0}), must be one of {1}" # noqa: E501
.format(facet_query_matching_method, allowed_values)
)
self._facet_query_matching_method = facet_query_matching_method | [
"def",
"facet_query_matching_method",
"(",
"self",
",",
"facet_query_matching_method",
")",
":",
"allowed_values",
"=",
"[",
"\"CONTAINS\"",
",",
"\"STARTSWITH\"",
",",
"\"EXACT\"",
",",
"\"TAGPATH\"",
"]",
"# noqa: E501",
"if",
"facet_query_matching_method",
"not",
"in... | Sets the facet_query_matching_method of this FacetSearchRequestContainer.
The matching method used to filter when 'facetQuery' is used. Defaults to CONTAINS. # noqa: E501
:param facet_query_matching_method: The facet_query_matching_method of this FacetSearchRequestContainer. # noqa: E501
:type: str | [
"Sets",
"the",
"facet_query_matching_method",
"of",
"this",
"FacetSearchRequestContainer",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/facet_search_request_container.py#L107-L122 | train | 28,184 |
wavefrontHQ/python-client | wavefront_api_client/models/maintenance_window.py | MaintenanceWindow.running_state | def running_state(self, running_state):
"""Sets the running_state of this MaintenanceWindow.
:param running_state: The running_state of this MaintenanceWindow. # noqa: E501
:type: str
"""
allowed_values = ["ONGOING", "PENDING", "ENDED"] # noqa: E501
if running_state not in allowed_values:
raise ValueError(
"Invalid value for `running_state` ({0}), must be one of {1}" # noqa: E501
.format(running_state, allowed_values)
)
self._running_state = running_state | python | def running_state(self, running_state):
"""Sets the running_state of this MaintenanceWindow.
:param running_state: The running_state of this MaintenanceWindow. # noqa: E501
:type: str
"""
allowed_values = ["ONGOING", "PENDING", "ENDED"] # noqa: E501
if running_state not in allowed_values:
raise ValueError(
"Invalid value for `running_state` ({0}), must be one of {1}" # noqa: E501
.format(running_state, allowed_values)
)
self._running_state = running_state | [
"def",
"running_state",
"(",
"self",
",",
"running_state",
")",
":",
"allowed_values",
"=",
"[",
"\"ONGOING\"",
",",
"\"PENDING\"",
",",
"\"ENDED\"",
"]",
"# noqa: E501",
"if",
"running_state",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"I... | Sets the running_state of this MaintenanceWindow.
:param running_state: The running_state of this MaintenanceWindow. # noqa: E501
:type: str | [
"Sets",
"the",
"running_state",
"of",
"this",
"MaintenanceWindow",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/maintenance_window.py#L415-L429 | train | 28,185 |
wavefrontHQ/python-client | wavefront_api_client/models/dashboard_parameter_value.py | DashboardParameterValue.dynamic_field_type | def dynamic_field_type(self, dynamic_field_type):
"""Sets the dynamic_field_type of this DashboardParameterValue.
:param dynamic_field_type: The dynamic_field_type of this DashboardParameterValue. # noqa: E501
:type: str
"""
allowed_values = ["SOURCE", "SOURCE_TAG", "METRIC_NAME", "TAG_KEY", "MATCHING_SOURCE_TAG"] # noqa: E501
if dynamic_field_type not in allowed_values:
raise ValueError(
"Invalid value for `dynamic_field_type` ({0}), must be one of {1}" # noqa: E501
.format(dynamic_field_type, allowed_values)
)
self._dynamic_field_type = dynamic_field_type | python | def dynamic_field_type(self, dynamic_field_type):
"""Sets the dynamic_field_type of this DashboardParameterValue.
:param dynamic_field_type: The dynamic_field_type of this DashboardParameterValue. # noqa: E501
:type: str
"""
allowed_values = ["SOURCE", "SOURCE_TAG", "METRIC_NAME", "TAG_KEY", "MATCHING_SOURCE_TAG"] # noqa: E501
if dynamic_field_type not in allowed_values:
raise ValueError(
"Invalid value for `dynamic_field_type` ({0}), must be one of {1}" # noqa: E501
.format(dynamic_field_type, allowed_values)
)
self._dynamic_field_type = dynamic_field_type | [
"def",
"dynamic_field_type",
"(",
"self",
",",
"dynamic_field_type",
")",
":",
"allowed_values",
"=",
"[",
"\"SOURCE\"",
",",
"\"SOURCE_TAG\"",
",",
"\"METRIC_NAME\"",
",",
"\"TAG_KEY\"",
",",
"\"MATCHING_SOURCE_TAG\"",
"]",
"# noqa: E501",
"if",
"dynamic_field_type",
... | Sets the dynamic_field_type of this DashboardParameterValue.
:param dynamic_field_type: The dynamic_field_type of this DashboardParameterValue. # noqa: E501
:type: str | [
"Sets",
"the",
"dynamic_field_type",
"of",
"this",
"DashboardParameterValue",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/dashboard_parameter_value.py#L179-L193 | train | 28,186 |
wavefrontHQ/python-client | wavefront_api_client/models/dashboard_parameter_value.py | DashboardParameterValue.parameter_type | def parameter_type(self, parameter_type):
"""Sets the parameter_type of this DashboardParameterValue.
:param parameter_type: The parameter_type of this DashboardParameterValue. # noqa: E501
:type: str
"""
allowed_values = ["SIMPLE", "LIST", "DYNAMIC"] # noqa: E501
if parameter_type not in allowed_values:
raise ValueError(
"Invalid value for `parameter_type` ({0}), must be one of {1}" # noqa: E501
.format(parameter_type, allowed_values)
)
self._parameter_type = parameter_type | python | def parameter_type(self, parameter_type):
"""Sets the parameter_type of this DashboardParameterValue.
:param parameter_type: The parameter_type of this DashboardParameterValue. # noqa: E501
:type: str
"""
allowed_values = ["SIMPLE", "LIST", "DYNAMIC"] # noqa: E501
if parameter_type not in allowed_values:
raise ValueError(
"Invalid value for `parameter_type` ({0}), must be one of {1}" # noqa: E501
.format(parameter_type, allowed_values)
)
self._parameter_type = parameter_type | [
"def",
"parameter_type",
"(",
"self",
",",
"parameter_type",
")",
":",
"allowed_values",
"=",
"[",
"\"SIMPLE\"",
",",
"\"LIST\"",
",",
"\"DYNAMIC\"",
"]",
"# noqa: E501",
"if",
"parameter_type",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"... | Sets the parameter_type of this DashboardParameterValue.
:param parameter_type: The parameter_type of this DashboardParameterValue. # noqa: E501
:type: str | [
"Sets",
"the",
"parameter_type",
"of",
"this",
"DashboardParameterValue",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/dashboard_parameter_value.py#L269-L283 | train | 28,187 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.fixed_legend_filter_field | def fixed_legend_filter_field(self, fixed_legend_filter_field):
"""Sets the fixed_legend_filter_field of this ChartSettings.
Statistic to use for determining whether a series is displayed on the fixed legend # noqa: E501
:param fixed_legend_filter_field: The fixed_legend_filter_field of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["CURRENT", "MEAN", "MEDIAN", "SUM", "MIN", "MAX", "COUNT"] # noqa: E501
if fixed_legend_filter_field not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_filter_field` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_filter_field, allowed_values)
)
self._fixed_legend_filter_field = fixed_legend_filter_field | python | def fixed_legend_filter_field(self, fixed_legend_filter_field):
"""Sets the fixed_legend_filter_field of this ChartSettings.
Statistic to use for determining whether a series is displayed on the fixed legend # noqa: E501
:param fixed_legend_filter_field: The fixed_legend_filter_field of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["CURRENT", "MEAN", "MEDIAN", "SUM", "MIN", "MAX", "COUNT"] # noqa: E501
if fixed_legend_filter_field not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_filter_field` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_filter_field, allowed_values)
)
self._fixed_legend_filter_field = fixed_legend_filter_field | [
"def",
"fixed_legend_filter_field",
"(",
"self",
",",
"fixed_legend_filter_field",
")",
":",
"allowed_values",
"=",
"[",
"\"CURRENT\"",
",",
"\"MEAN\"",
",",
"\"MEDIAN\"",
",",
"\"SUM\"",
",",
"\"MIN\"",
",",
"\"MAX\"",
",",
"\"COUNT\"",
"]",
"# noqa: E501",
"if",... | Sets the fixed_legend_filter_field of this ChartSettings.
Statistic to use for determining whether a series is displayed on the fixed legend # noqa: E501
:param fixed_legend_filter_field: The fixed_legend_filter_field of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"fixed_legend_filter_field",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L479-L494 | train | 28,188 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.fixed_legend_filter_sort | def fixed_legend_filter_sort(self, fixed_legend_filter_sort):
"""Sets the fixed_legend_filter_sort of this ChartSettings.
Whether to display \"Top\"- or \"Bottom\"-ranked series in the fixed legend # noqa: E501
:param fixed_legend_filter_sort: The fixed_legend_filter_sort of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["TOP", "BOTTOM"] # noqa: E501
if fixed_legend_filter_sort not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_filter_sort` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_filter_sort, allowed_values)
)
self._fixed_legend_filter_sort = fixed_legend_filter_sort | python | def fixed_legend_filter_sort(self, fixed_legend_filter_sort):
"""Sets the fixed_legend_filter_sort of this ChartSettings.
Whether to display \"Top\"- or \"Bottom\"-ranked series in the fixed legend # noqa: E501
:param fixed_legend_filter_sort: The fixed_legend_filter_sort of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["TOP", "BOTTOM"] # noqa: E501
if fixed_legend_filter_sort not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_filter_sort` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_filter_sort, allowed_values)
)
self._fixed_legend_filter_sort = fixed_legend_filter_sort | [
"def",
"fixed_legend_filter_sort",
"(",
"self",
",",
"fixed_legend_filter_sort",
")",
":",
"allowed_values",
"=",
"[",
"\"TOP\"",
",",
"\"BOTTOM\"",
"]",
"# noqa: E501",
"if",
"fixed_legend_filter_sort",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
... | Sets the fixed_legend_filter_sort of this ChartSettings.
Whether to display \"Top\"- or \"Bottom\"-ranked series in the fixed legend # noqa: E501
:param fixed_legend_filter_sort: The fixed_legend_filter_sort of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"fixed_legend_filter_sort",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L531-L546 | train | 28,189 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.fixed_legend_position | def fixed_legend_position(self, fixed_legend_position):
"""Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["RIGHT", "TOP", "LEFT", "BOTTOM"] # noqa: E501
if fixed_legend_position not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_position` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_position, allowed_values)
)
self._fixed_legend_position = fixed_legend_position | python | def fixed_legend_position(self, fixed_legend_position):
"""Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["RIGHT", "TOP", "LEFT", "BOTTOM"] # noqa: E501
if fixed_legend_position not in allowed_values:
raise ValueError(
"Invalid value for `fixed_legend_position` ({0}), must be one of {1}" # noqa: E501
.format(fixed_legend_position, allowed_values)
)
self._fixed_legend_position = fixed_legend_position | [
"def",
"fixed_legend_position",
"(",
"self",
",",
"fixed_legend_position",
")",
":",
"allowed_values",
"=",
"[",
"\"RIGHT\"",
",",
"\"TOP\"",
",",
"\"LEFT\"",
",",
"\"BOTTOM\"",
"]",
"# noqa: E501",
"if",
"fixed_legend_position",
"not",
"in",
"allowed_values",
":",
... | Sets the fixed_legend_position of this ChartSettings.
Where the fixed legend should be displayed with respect to the chart # noqa: E501
:param fixed_legend_position: The fixed_legend_position of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"fixed_legend_position",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L583-L598 | train | 28,190 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.line_type | def line_type(self, line_type):
"""Sets the line_type of this ChartSettings.
Plot interpolation type. linear is default # noqa: E501
:param line_type: The line_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["linear", "step-before", "step-after", "basis", "cardinal", "monotone"] # noqa: E501
if line_type not in allowed_values:
raise ValueError(
"Invalid value for `line_type` ({0}), must be one of {1}" # noqa: E501
.format(line_type, allowed_values)
)
self._line_type = line_type | python | def line_type(self, line_type):
"""Sets the line_type of this ChartSettings.
Plot interpolation type. linear is default # noqa: E501
:param line_type: The line_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["linear", "step-before", "step-after", "basis", "cardinal", "monotone"] # noqa: E501
if line_type not in allowed_values:
raise ValueError(
"Invalid value for `line_type` ({0}), must be one of {1}" # noqa: E501
.format(line_type, allowed_values)
)
self._line_type = line_type | [
"def",
"line_type",
"(",
"self",
",",
"line_type",
")",
":",
"allowed_values",
"=",
"[",
"\"linear\"",
",",
"\"step-before\"",
",",
"\"step-after\"",
",",
"\"basis\"",
",",
"\"cardinal\"",
",",
"\"monotone\"",
"]",
"# noqa: E501",
"if",
"line_type",
"not",
"in",... | Sets the line_type of this ChartSettings.
Plot interpolation type. linear is default # noqa: E501
:param line_type: The line_type of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"line_type",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L681-L696 | train | 28,191 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.sparkline_display_horizontal_position | def sparkline_display_horizontal_position(self, sparkline_display_horizontal_position):
"""Sets the sparkline_display_horizontal_position of this ChartSettings.
For the single stat view, the horizontal position of the displayed text # noqa: E501
:param sparkline_display_horizontal_position: The sparkline_display_horizontal_position of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["MIDDLE", "LEFT", "RIGHT"] # noqa: E501
if sparkline_display_horizontal_position not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_display_horizontal_position` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_display_horizontal_position, allowed_values)
)
self._sparkline_display_horizontal_position = sparkline_display_horizontal_position | python | def sparkline_display_horizontal_position(self, sparkline_display_horizontal_position):
"""Sets the sparkline_display_horizontal_position of this ChartSettings.
For the single stat view, the horizontal position of the displayed text # noqa: E501
:param sparkline_display_horizontal_position: The sparkline_display_horizontal_position of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["MIDDLE", "LEFT", "RIGHT"] # noqa: E501
if sparkline_display_horizontal_position not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_display_horizontal_position` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_display_horizontal_position, allowed_values)
)
self._sparkline_display_horizontal_position = sparkline_display_horizontal_position | [
"def",
"sparkline_display_horizontal_position",
"(",
"self",
",",
"sparkline_display_horizontal_position",
")",
":",
"allowed_values",
"=",
"[",
"\"MIDDLE\"",
",",
"\"LEFT\"",
",",
"\"RIGHT\"",
"]",
"# noqa: E501",
"if",
"sparkline_display_horizontal_position",
"not",
"in",... | Sets the sparkline_display_horizontal_position of this ChartSettings.
For the single stat view, the horizontal position of the displayed text # noqa: E501
:param sparkline_display_horizontal_position: The sparkline_display_horizontal_position of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"sparkline_display_horizontal_position",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L963-L978 | train | 28,192 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.sparkline_display_value_type | def sparkline_display_value_type(self, sparkline_display_value_type):
"""Sets the sparkline_display_value_type of this ChartSettings.
For the single stat view, whether to display the name of the query or the value of query # noqa: E501
:param sparkline_display_value_type: The sparkline_display_value_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["VALUE", "LABEL"] # noqa: E501
if sparkline_display_value_type not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_display_value_type` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_display_value_type, allowed_values)
)
self._sparkline_display_value_type = sparkline_display_value_type | python | def sparkline_display_value_type(self, sparkline_display_value_type):
"""Sets the sparkline_display_value_type of this ChartSettings.
For the single stat view, whether to display the name of the query or the value of query # noqa: E501
:param sparkline_display_value_type: The sparkline_display_value_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["VALUE", "LABEL"] # noqa: E501
if sparkline_display_value_type not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_display_value_type` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_display_value_type, allowed_values)
)
self._sparkline_display_value_type = sparkline_display_value_type | [
"def",
"sparkline_display_value_type",
"(",
"self",
",",
"sparkline_display_value_type",
")",
":",
"allowed_values",
"=",
"[",
"\"VALUE\"",
",",
"\"LABEL\"",
"]",
"# noqa: E501",
"if",
"sparkline_display_value_type",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueEr... | Sets the sparkline_display_value_type of this ChartSettings.
For the single stat view, whether to display the name of the query or the value of query # noqa: E501
:param sparkline_display_value_type: The sparkline_display_value_type of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"sparkline_display_value_type",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1038-L1053 | train | 28,193 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.sparkline_size | def sparkline_size(self, sparkline_size):
"""Sets the sparkline_size of this ChartSettings.
For the single stat view, a misleadingly named property. This determines whether the sparkline of the statistic is displayed in the chart BACKGROUND, BOTTOM, or NONE # noqa: E501
:param sparkline_size: The sparkline_size of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["BACKGROUND", "BOTTOM", "NONE"] # noqa: E501
if sparkline_size not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_size` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_size, allowed_values)
)
self._sparkline_size = sparkline_size | python | def sparkline_size(self, sparkline_size):
"""Sets the sparkline_size of this ChartSettings.
For the single stat view, a misleadingly named property. This determines whether the sparkline of the statistic is displayed in the chart BACKGROUND, BOTTOM, or NONE # noqa: E501
:param sparkline_size: The sparkline_size of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["BACKGROUND", "BOTTOM", "NONE"] # noqa: E501
if sparkline_size not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_size` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_size, allowed_values)
)
self._sparkline_size = sparkline_size | [
"def",
"sparkline_size",
"(",
"self",
",",
"sparkline_size",
")",
":",
"allowed_values",
"=",
"[",
"\"BACKGROUND\"",
",",
"\"BOTTOM\"",
",",
"\"NONE\"",
"]",
"# noqa: E501",
"if",
"sparkline_size",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
... | Sets the sparkline_size of this ChartSettings.
For the single stat view, a misleadingly named property. This determines whether the sparkline of the statistic is displayed in the chart BACKGROUND, BOTTOM, or NONE # noqa: E501
:param sparkline_size: The sparkline_size of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"sparkline_size",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1136-L1151 | train | 28,194 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.sparkline_value_color_map_apply_to | def sparkline_value_color_map_apply_to(self, sparkline_value_color_map_apply_to):
"""Sets the sparkline_value_color_map_apply_to of this ChartSettings.
For the single stat view, whether to apply dynamic color settings to the displayed TEXT or BACKGROUND # noqa: E501
:param sparkline_value_color_map_apply_to: The sparkline_value_color_map_apply_to of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["TEXT", "BACKGROUND"] # noqa: E501
if sparkline_value_color_map_apply_to not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_value_color_map_apply_to` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_value_color_map_apply_to, allowed_values)
)
self._sparkline_value_color_map_apply_to = sparkline_value_color_map_apply_to | python | def sparkline_value_color_map_apply_to(self, sparkline_value_color_map_apply_to):
"""Sets the sparkline_value_color_map_apply_to of this ChartSettings.
For the single stat view, whether to apply dynamic color settings to the displayed TEXT or BACKGROUND # noqa: E501
:param sparkline_value_color_map_apply_to: The sparkline_value_color_map_apply_to of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["TEXT", "BACKGROUND"] # noqa: E501
if sparkline_value_color_map_apply_to not in allowed_values:
raise ValueError(
"Invalid value for `sparkline_value_color_map_apply_to` ({0}), must be one of {1}" # noqa: E501
.format(sparkline_value_color_map_apply_to, allowed_values)
)
self._sparkline_value_color_map_apply_to = sparkline_value_color_map_apply_to | [
"def",
"sparkline_value_color_map_apply_to",
"(",
"self",
",",
"sparkline_value_color_map_apply_to",
")",
":",
"allowed_values",
"=",
"[",
"\"TEXT\"",
",",
"\"BACKGROUND\"",
"]",
"# noqa: E501",
"if",
"sparkline_value_color_map_apply_to",
"not",
"in",
"allowed_values",
":",... | Sets the sparkline_value_color_map_apply_to of this ChartSettings.
For the single stat view, whether to apply dynamic color settings to the displayed TEXT or BACKGROUND # noqa: E501
:param sparkline_value_color_map_apply_to: The sparkline_value_color_map_apply_to of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"sparkline_value_color_map_apply_to",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1165-L1180 | train | 28,195 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.stack_type | def stack_type(self, stack_type):
"""Sets the stack_type of this ChartSettings.
Type of stacked chart (applicable only if chart type is stacked). zero (default) means stacked from y=0. expand means Normalized from 0 to 1. wiggle means Minimize weighted changes. silhouette means to Center the Stream # noqa: E501
:param stack_type: The stack_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["zero", "expand", "wiggle", "silhouette"] # noqa: E501
if stack_type not in allowed_values:
raise ValueError(
"Invalid value for `stack_type` ({0}), must be one of {1}" # noqa: E501
.format(stack_type, allowed_values)
)
self._stack_type = stack_type | python | def stack_type(self, stack_type):
"""Sets the stack_type of this ChartSettings.
Type of stacked chart (applicable only if chart type is stacked). zero (default) means stacked from y=0. expand means Normalized from 0 to 1. wiggle means Minimize weighted changes. silhouette means to Center the Stream # noqa: E501
:param stack_type: The stack_type of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["zero", "expand", "wiggle", "silhouette"] # noqa: E501
if stack_type not in allowed_values:
raise ValueError(
"Invalid value for `stack_type` ({0}), must be one of {1}" # noqa: E501
.format(stack_type, allowed_values)
)
self._stack_type = stack_type | [
"def",
"stack_type",
"(",
"self",
",",
"stack_type",
")",
":",
"allowed_values",
"=",
"[",
"\"zero\"",
",",
"\"expand\"",
",",
"\"wiggle\"",
",",
"\"silhouette\"",
"]",
"# noqa: E501",
"if",
"stack_type",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError"... | Sets the stack_type of this ChartSettings.
Type of stacked chart (applicable only if chart type is stacked). zero (default) means stacked from y=0. expand means Normalized from 0 to 1. wiggle means Minimize weighted changes. silhouette means to Center the Stream # noqa: E501
:param stack_type: The stack_type of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"stack_type",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1309-L1324 | train | 28,196 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.tag_mode | def tag_mode(self, tag_mode):
"""Sets the tag_mode of this ChartSettings.
For the tabular view, which mode to use to determine which point tags to display # noqa: E501
:param tag_mode: The tag_mode of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["all", "top", "custom"] # noqa: E501
if tag_mode not in allowed_values:
raise ValueError(
"Invalid value for `tag_mode` ({0}), must be one of {1}" # noqa: E501
.format(tag_mode, allowed_values)
)
self._tag_mode = tag_mode | python | def tag_mode(self, tag_mode):
"""Sets the tag_mode of this ChartSettings.
For the tabular view, which mode to use to determine which point tags to display # noqa: E501
:param tag_mode: The tag_mode of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["all", "top", "custom"] # noqa: E501
if tag_mode not in allowed_values:
raise ValueError(
"Invalid value for `tag_mode` ({0}), must be one of {1}" # noqa: E501
.format(tag_mode, allowed_values)
)
self._tag_mode = tag_mode | [
"def",
"tag_mode",
"(",
"self",
",",
"tag_mode",
")",
":",
"allowed_values",
"=",
"[",
"\"all\"",
",",
"\"top\"",
",",
"\"custom\"",
"]",
"# noqa: E501",
"if",
"tag_mode",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `tag_... | Sets the tag_mode of this ChartSettings.
For the tabular view, which mode to use to determine which point tags to display # noqa: E501
:param tag_mode: The tag_mode of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"tag_mode",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1338-L1353 | train | 28,197 |
wavefrontHQ/python-client | wavefront_api_client/models/chart_settings.py | ChartSettings.windowing | def windowing(self, windowing):
"""Sets the windowing of this ChartSettings.
For the tabular view, whether to use the full time window for the query or the last X minutes # noqa: E501
:param windowing: The windowing of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["full", "last"] # noqa: E501
if windowing not in allowed_values:
raise ValueError(
"Invalid value for `windowing` ({0}), must be one of {1}" # noqa: E501
.format(windowing, allowed_values)
)
self._windowing = windowing | python | def windowing(self, windowing):
"""Sets the windowing of this ChartSettings.
For the tabular view, whether to use the full time window for the query or the last X minutes # noqa: E501
:param windowing: The windowing of this ChartSettings. # noqa: E501
:type: str
"""
allowed_values = ["full", "last"] # noqa: E501
if windowing not in allowed_values:
raise ValueError(
"Invalid value for `windowing` ({0}), must be one of {1}" # noqa: E501
.format(windowing, allowed_values)
)
self._windowing = windowing | [
"def",
"windowing",
"(",
"self",
",",
"windowing",
")",
":",
"allowed_values",
"=",
"[",
"\"full\"",
",",
"\"last\"",
"]",
"# noqa: E501",
"if",
"windowing",
"not",
"in",
"allowed_values",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `windowing` ({0}), must... | Sets the windowing of this ChartSettings.
For the tabular view, whether to use the full time window for the query or the last X minutes # noqa: E501
:param windowing: The windowing of this ChartSettings. # noqa: E501
:type: str | [
"Sets",
"the",
"windowing",
"of",
"this",
"ChartSettings",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/chart_settings.py#L1444-L1459 | train | 28,198 |
wavefrontHQ/python-client | wavefront_api_client/models/response_status.py | ResponseStatus.result | def result(self, result):
"""Sets the result of this ResponseStatus.
:param result: The result of this ResponseStatus. # noqa: E501
:type: str
"""
if result is None:
raise ValueError("Invalid value for `result`, must not be `None`") # noqa: E501
allowed_values = ["OK", "ERROR"] # noqa: E501
if result not in allowed_values:
raise ValueError(
"Invalid value for `result` ({0}), must be one of {1}" # noqa: E501
.format(result, allowed_values)
)
self._result = result | python | def result(self, result):
"""Sets the result of this ResponseStatus.
:param result: The result of this ResponseStatus. # noqa: E501
:type: str
"""
if result is None:
raise ValueError("Invalid value for `result`, must not be `None`") # noqa: E501
allowed_values = ["OK", "ERROR"] # noqa: E501
if result not in allowed_values:
raise ValueError(
"Invalid value for `result` ({0}), must be one of {1}" # noqa: E501
.format(result, allowed_values)
)
self._result = result | [
"def",
"result",
"(",
"self",
",",
"result",
")",
":",
"if",
"result",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Invalid value for `result`, must not be `None`\"",
")",
"# noqa: E501",
"allowed_values",
"=",
"[",
"\"OK\"",
",",
"\"ERROR\"",
"]",
"# noqa: E... | Sets the result of this ResponseStatus.
:param result: The result of this ResponseStatus. # noqa: E501
:type: str | [
"Sets",
"the",
"result",
"of",
"this",
"ResponseStatus",
"."
] | b0f1046a8f68c2c7d69e395f7167241f224c738a | https://github.com/wavefrontHQ/python-client/blob/b0f1046a8f68c2c7d69e395f7167241f224c738a/wavefront_api_client/models/response_status.py#L117-L133 | train | 28,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.