text_prompt stringlengths 157 13.1k | code_prompt stringlengths 7 19.8k ⌀ |
|---|---|
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def similarity_graph(self, k=5, radius=None, include_self_edges=False, output_type='SGraph', verbose=True):
""" Construct the similarity graph on the reference d... |
return self.similarity_model.similarity_graph(k, radius, include_self_edges, output_type, verbose) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SimpleSizer(compute_value_size):
"""A sizer which uses the function compute_value_size to compute the size of each value. Typically compute_value_size is _V... |
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = 0
for element in value:
result += compute_value_size(element)
return result + local_Varin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _FixedSizer(value_size):
"""Like _SimpleSizer except for a fixed-size field. The input is the size of one value.""" |
def SpecificSizer(field_number, is_repeated, is_packed):
tag_size = _TagSize(field_number)
if is_packed:
local_VarintSize = _VarintSize
def PackedFieldSize(value):
result = len(value) * value_size
return result + local_VarintSize(result) + tag_size
return PackedFieldSize
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BytesSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a bytes field.""" |
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
local_len = len
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = local_len(element)
result += local_VarintSize(l) + l
return resul... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a group field.""" |
tag_size = _TagSize(field_number) * 2
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
result += element.ByteSize()
return result
return RepeatedFieldSize
else:
def FieldSize(value):
return tag_s... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MessageSizer(field_number, is_repeated, is_packed):
"""Returns a sizer for a message field.""" |
tag_size = _TagSize(field_number)
local_VarintSize = _VarintSize
assert not is_packed
if is_repeated:
def RepeatedFieldSize(value):
result = tag_size * len(value)
for element in value:
l = element.ByteSize()
result += local_VarintSize(l) + l
return result
return Repea... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MessageSetItemSizer(field_number):
"""Returns a sizer for extensions of MessageSet. The message set message looks like this: message MessageSet { repeated gr... |
static_size = (_TagSize(1) * 2 + _TagSize(2) + _VarintSize(field_number) +
_TagSize(3))
local_VarintSize = _VarintSize
def FieldSize(value):
l = value.ByteSize()
return static_size + local_VarintSize(l) + l
return FieldSize |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MapSizer(field_descriptor, is_message_map):
"""Returns a sizer for a map field.""" |
# Can't look at field_descriptor.message_type._concrete_class because it may
# not have been initialized yet.
message_type = field_descriptor.message_type
message_sizer = MessageSizer(field_descriptor.number, False, False)
def FieldSize(map_value):
total = 0
for key in map_value:
value = map_... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _VarintBytes(value):
"""Encode the given integer as a varint and return the bytes. This is only called at startup time so it doesn't need to be fast.""" |
pieces = []
_EncodeVarint(pieces.append, value)
return b"".join(pieces) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _SimpleEncoder(wire_type, encode_value, compute_value_size):
"""Return a constructor for an encoder for fields of a particular type. Args: wire_type: The fie... |
def SpecificEncoder(field_number, is_repeated, is_packed):
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
size = 0
for element in value:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _StructPackEncoder(wire_type, format):
"""Return a constructor for an encoder for a fixed-width field. Args: wire_type: The field's wire type, for encoding t... |
value_size = struct.calcsize(format)
def SpecificEncoder(field_number, is_repeated, is_packed):
local_struct_pack = struct.pack
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _FloatingPointEncoder(wire_type, format):
"""Return a constructor for an encoder for float fields. This is like StructPackEncoder, but catches errors that ma... |
value_size = struct.calcsize(format)
if value_size == 4:
def EncodeNonFiniteOrRaise(write, value):
# Remember that the serialized form uses little-endian byte order.
if value == _POS_INF:
write(b'\x00\x00\x80\x7F')
elif value == _NEG_INF:
write(b'\x00\x00\x80\xFF')
elif... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def BoolEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a boolean field.""" |
false_byte = b'\x00'
true_byte = b'\x01'
if is_packed:
tag_bytes = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
def EncodePackedField(write, value):
write(tag_bytes)
local_EncodeVarint(write, len(value))
for element in value:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def StringEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a string field.""" |
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
local_len = len
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
encoded = element.encode('utf-8')
write(tag)
local_Encode... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def GroupEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a group field.""" |
start_tag = TagBytes(field_number, wire_format.WIRETYPE_START_GROUP)
end_tag = TagBytes(field_number, wire_format.WIRETYPE_END_GROUP)
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(start_tag)
element._InternalSerialize(write)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MessageEncoder(field_number, is_repeated, is_packed):
"""Returns an encoder for a message field.""" |
tag = TagBytes(field_number, wire_format.WIRETYPE_LENGTH_DELIMITED)
local_EncodeVarint = _EncodeVarint
assert not is_packed
if is_repeated:
def EncodeRepeatedField(write, value):
for element in value:
write(tag)
local_EncodeVarint(write, element.ByteSize())
element._InternalS... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert(model, image_input_names=[], is_bgr=False, red_bias=0.0, blue_bias=0.0, green_bias=0.0, gray_bias=0.0, image_scale=1.0, class_labels=None, predicted_f... |
from ...models import MLModel
from ...models.utils import convert_neural_network_weights_to_fp16 as convert_neural_network_weights_to_fp16
if model_precision not in _VALID_MLMODEL_PRECISION_TYPES:
raise RuntimeError('Model precision {} is not valid'.format(model_precision))
import tempfile
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _set_kernel(model, spec):
""" Takes the sklearn SVM model and returns the spec with the protobuf kernel for that model. """ |
def gamma_value(model):
if(model.gamma == 'auto'):
# auto gamma value is 1/num_features
return 1/float(len(model.support_vectors_[0]))
else:
return model.gamma
result = None
if(model.kernel == 'linear'):
spec.kernel.linearKernel.MergeFromString(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append(self, data, segment=0):
""" Append a single row to an SFrame. Throws a RuntimeError if one or more column's type is incompatible with a type appended.... |
# Assume this case refers to an SFrame with a single column
if not hasattr(data, '__iter__'):
data = [data]
self._builder.append(data, segment) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def append_multiple(self, data, segment=0):
""" Append multiple rows to an SFrame. Throws a RuntimeError if one or more column's type is incompatible with a type... |
if not hasattr(data, '__iter__'):
raise TypeError("append_multiple must be passed an iterable object")
tmp_list = []
# Avoid copy in cases that we are passed materialized data that is
# smaller than our block size
if hasattr(data, '__len__'):
if len(data... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def targets_to_stage(self, source_targets, ps):
"""Given the list of source targets explicitly passed to 'stage', returns the list of targets which must be stage... |
result = []
# Traverse the dependencies, if needed.
if ps.get('install-dependencies') == ['on']:
source_targets = self.collect_targets(source_targets)
# Filter the target types, if needed.
included_types = ps.get('install-type')
for r in source_targets:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def init_logger():
""" Initialize the logging configuration for the turicreate package. This does not affect the root logging config. """ |
import logging as _logging
import logging.config
# Package level logger
_logging.config.dictConfig({
'version': 1,
'disable_existing_loggers': False,
'formatters': {
'standard': {
'format': '%(asctime)s [%(levelname)s] %(name)s, %(lineno)s: %(message... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_environment_config():
""" Returns all the Turi Create configuration variables that can only be set via environment variables. - *TURI_FILEIO_WRITER_BUFFE... |
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.list_globals(False) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def set_log_level(level):
""" Sets the log level. Lower log levels log more. if level is 8, nothing is logged. If level is 0, everything is logged. """ |
from .._connect import main as _glconnect
unity = _glconnect.get_unity()
return unity.set_log_level(level) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_sgraph(filename, format='binary', delimiter='auto'):
""" Load SGraph from text file or previously saved SGraph binary. Parameters filename : string Loca... |
if not format in ['binary', 'snap', 'csv', 'tsv']:
raise ValueError('Invalid format: %s' % format)
with cython_context():
g = None
if format is 'binary':
proxy = glconnect.get_unity().load_graph(_make_internal_url(filename))
g = SGraph(_proxy=proxy)
el... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vertex_list_to_dataframe(ls, id_column_name):
""" Convert a list of vertices into dataframe. """ |
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.'
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
df = pd.DataFrame({id_column_name: [v.vid for v in ls]})
for c in cols:
df[c] = [v.attr.get(c) for v in ls]
return df |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _vertex_list_to_sframe(ls, id_column_name):
""" Convert a list of vertices into an SFrame. """ |
sf = SFrame()
if type(ls) == list:
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
sf[id_column_name] = [v.vid for v in ls]
for c in cols:
sf[c] = [v.attr.get(c) for v in ls]
elif type(ls) == Vertex:
sf[id_column_name] = [ls.vid]
for col, val... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _edge_list_to_dataframe(ls, src_column_name, dst_column_name):
""" Convert a list of edges into dataframe. """ |
assert HAS_PANDAS, 'Cannot use dataframe because Pandas is not available or version is too low.'
cols = reduce(set.union, (set(e.attr.keys()) for e in ls))
df = pd.DataFrame({
src_column_name: [e.src_vid for e in ls],
dst_column_name: [e.dst_vid for e in ls]})
for c in cols:
df[... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _edge_list_to_sframe(ls, src_column_name, dst_column_name):
""" Convert a list of edges into an SFrame. """ |
sf = SFrame()
if type(ls) == list:
cols = reduce(set.union, (set(v.attr.keys()) for v in ls))
sf[src_column_name] = [e.src_vid for e in ls]
sf[dst_column_name] = [e.dst_vid for e in ls]
for c in cols:
sf[c] = [e.attr.get(c) for e in ls]
elif type(ls) == Edge:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dataframe_to_vertex_list(df):
""" Convert dataframe into list of vertices, assuming that vertex ids are stored in _VID_COLUMN. """ |
cols = df.columns
if len(cols):
assert _VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _VID_COLUMN
df = df[cols].T
ret = [Vertex(None, _series=df[col]) for col in df]
return ret
else:
return [] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _dataframe_to_edge_list(df):
""" Convert dataframe into list of edges, assuming that source and target ids are stored in _SRC_VID_COLUMN, and _DST_VID_COLUMN... |
cols = df.columns
if len(cols):
assert _SRC_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _SRC_VID_COLUMN
assert _DST_VID_COLUMN in cols, "Vertex DataFrame must contain column %s" % _DST_VID_COLUMN
df = df[cols].T
ret = [Edge(None, None, _series=df[col]) for co... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select_fields(self, fields):
""" Return a new SGraph with only the selected fields. Other fields are discarded, while fields that do not exist in the SGraph ... |
if (type(fields) is str):
fields = [fields]
if not isinstance(fields, list) or not all(type(x) is str for x in fields):
raise TypeError('\"fields\" must be a str or list[str]')
vfields = self.__proxy__.get_vertex_fields()
efields = self.__proxy__.get_edge_field... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_neighborhood(self, ids, radius=1, full_subgraph=True):
""" Retrieve the graph neighborhood around a set of vertices, ignoring edge directions. Note that ... |
verts = ids
## find the vertices within radius (and the path edges)
for i in range(radius):
edges_out = self.get_edges(src_ids=verts)
edges_in = self.get_edges(dst_ids=verts)
verts = list(edges_in['__src_id']) + list(edges_in['__dst_id']) + \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get(self, field):
""" Return the value for the queried field. Get the value of a given field. The list of all queryable fields is documented in the beginnin... |
if field in self._list_fields():
return self.__proxy__.get(field)
else:
raise KeyError('Key \"%s\" not in model. Available fields are %s.' % (field, ', '.join(self._list_fields()))) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _describe_fields(cls):
""" Return a dictionary for the class fields description. Fields should NOT be wrapped by _precomputed_field, if necessary """ |
dispatch_table = {
'ShortestPathModel': 'sssp',
'GraphColoringModel': 'graph_coloring',
'PagerankModel': 'pagerank',
'ConnectedComponentsModel': 'connected_components',
'TriangleCountingModel': 'triangle_counting',
'KcoreModel': 'kcore',
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _raise_error_if_not_of_type(arg, expected_type, arg_name=None):
""" Check if the input is of expected type. Parameters arg : Input argument. expected_type : ... |
display_name = "%s " % arg_name if arg_name is not None else "Argument "
lst_expected_type = [expected_type] if \
type(expected_type) == type else expected_type
err_msg = "%smust be of type %s " % (display_name,
' or '.join([x.__name__ for x in lst_expected... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def waveform_to_examples(data, sample_rate):
"""Converts audio waveform into an array of examples for VGGish. Args: data: np.array of either one dimension (mono)... |
import resampy
# Convert to mono.
if len(data.shape) > 1:
data = np.mean(data, axis=1)
# Resample to the rate assumed by VGGish.
if sample_rate != vggish_params.SAMPLE_RATE:
data = resampy.resample(data, sample_rate, vggish_params.SAMPLE_RATE)
# Compute log mel spectrogram features.
log_mel ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def expand_no_defaults (property_sets):
""" Expand the given build request by combining all property_sets which don't specify conflicting non-free features. """ |
assert is_iterable_typed(property_sets, property_set.PropertySet)
# First make all features and subfeatures explicit
expanded_property_sets = [ps.expand_subfeatures() for ps in property_sets]
# Now combine all of the expanded property_sets
product = __x_product (expanded_property_sets)
return... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __x_product (property_sets):
""" Return the cross-product of all elements of property_sets, less any that would contain conflicting values for single-valued ... |
assert is_iterable_typed(property_sets, property_set.PropertySet)
x_product_seen = set()
return __x_product_aux (property_sets, x_product_seen)[0] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __x_product_aux (property_sets, seen_features):
"""Returns non-conflicting combinations of property sets. property_sets is a list of PropertySet instances. s... |
assert is_iterable_typed(property_sets, property_set.PropertySet)
assert isinstance(seen_features, set)
if not property_sets:
return ([], set())
properties = property_sets[0].all()
these_features = set()
for p in property_sets[0].non_free():
these_features.add(p.feature)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def looks_like_implicit_value(v):
"""Returns true if 'v' is either implicit value, or the part before the first '-' symbol is implicit value.""" |
assert isinstance(v, basestring)
if feature.is_implicit_value(v):
return 1
else:
split = v.split("-")
if feature.is_implicit_value(split[0]):
return 1
return 0 |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def regex_to_error_msg(regex):
"""Format a human-readable error message from a regex""" |
return re.sub('([^\\\\])[()]', '\\1', regex) \
.replace('[ \t]*$', '') \
.replace('^', '') \
.replace('$', '') \
.replace('[ \t]*', ' ') \
.replace('[ \t]+', ' ') \
.replace('[0-9]+', 'X') \
\
.replace('\\[', '[') \
.replace('\\]', ']') \
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def random_chars(number):
"""Generate random characters""" |
char_map = {
k: v for k, v in chars.CHARS.iteritems()
if not format_character(k).startswith('\\x')
}
char_num = sum(char_map.values())
return (
format_character(nth_char(char_map, random.randint(0, char_num - 1)))
for _ in xrange(0, number)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def templates_in(path):
"""Enumerate the templates found in path""" |
ext = '.cpp'
return (
Template(f[0:-len(ext)], load_file(os.path.join(path, f)))
for f in os.listdir(path) if f.endswith(ext)
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def nth_char(char_map, index):
"""Returns the nth character of a character->occurrence map""" |
for char in char_map:
if index < char_map[char]:
return char
index = index - char_map[char]
return None |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_character(char):
"""Returns the C-formatting of the character""" |
if \
char in string.ascii_letters \
or char in string.digits \
or char in [
'_', '.', ':', ';', ' ', '!', '?', '+', '-', '/', '=', '<',
'>', '$', '(', ')', '@', '~', '`', '|', '#', '[', ']', '{',
'}', '&', '*', '^', '%']:
return char
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def write_file(filename, content):
"""Create the file with the given content""" |
print 'Generating {0}'.format(filename)
with open(filename, 'wb') as out_f:
out_f.write(content) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def out_filename(template, n_val, mode):
"""Determine the output filename""" |
return '{0}_{1}_{2}.cpp'.format(template.name, n_val, mode.identifier) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def convert_from(self, base):
"""Convert a BOOST_METAPARSE_STRING mode document into one with this mode""" |
if self.identifier == 'bmp':
return base
elif self.identifier == 'man':
result = []
prefix = 'BOOST_METAPARSE_STRING("'
while True:
bmp_at = base.find(prefix)
if bmp_at == -1:
return ''.join(result) + ba... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def instantiate(self, value_of_n):
"""Instantiates the template""" |
template = Cheetah.Template.Template(
self.content,
searchList={'n': value_of_n}
)
template.random_string = random_string
return str(template) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def range(self):
"""Returns the range for N""" |
match = self._match(in_comment(
'n[ \t]+in[ \t]*\\[([0-9]+)\\.\\.([0-9]+)\\),[ \t]+'
'step[ \t]+([0-9]+)'
))
return range(
int(match.group(1)),
int(match.group(2)),
int(match.group(3))
) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _match(self, regex):
"""Find the first line matching regex and return the match object""" |
cregex = re.compile(regex)
for line in self.content.splitlines():
match = cregex.match(line)
if match:
return match
raise Exception('No "{0}" line in {1}.cpp'.format(
regex_to_error_msg(regex),
self.name
)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def generate_proto(source, require = True):
"""Invokes the Protocol Compiler to generate a _pb2.py from the given .proto file. Does nothing if the output already... |
if not require and not os.path.exists(source):
return
output = source.replace(".proto", "_pb2.py").replace("../src/", "")
if (not os.path.exists(output) or
(os.path.exists(source) and
os.path.getmtime(source) > os.path.getmtime(output))):
print("Generating %s..." % output)
if not os.... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _validate_row_label(label, column_type_map):
""" Validate a row label column. Parameters label : str Name of the row label column. column_type_map : dict[str... |
if not isinstance(label, str):
raise TypeError("The row label column name must be a string.")
if not label in column_type_map.keys():
raise ToolkitError("Row label column not found in the dataset.")
if not column_type_map[label] in (str, int):
raise TypeError("Row labels must be i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _robust_column_name(base_name, column_names):
""" Generate a new column name that is guaranteed not to conflict with an existing set of column names. Paramet... |
robust_name = base_name
i = 1
while robust_name in column_names:
robust_name = base_name + '.{}'.format(i)
i += 1
return robust_name |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _select_valid_features(dataset, features, valid_feature_types, target_column=None):
""" Utility function for selecting columns of only valid feature types. P... |
if features is not None:
if not hasattr(features, '__iter__'):
raise TypeError("Input 'features' must be an iterable type.")
if not all([isinstance(x, str) for x in features]):
raise TypeError("Input 'features' must contain only strings.")
## Extract the features and l... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _check_elements_equal(lst):
""" Returns true if all of the elements in the list are equal. """ |
assert isinstance(lst, list), "Input value must be a list."
return not lst or lst.count(lst[0]) == len(lst) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _summarize_accessible_fields(field_descriptions, width=40, section_title='Accessible fields'):
""" Create a summary string for the accessible fields in a mod... |
key_str = "{:<{}}: {}"
items = []
items.append(section_title)
items.append("-" * len(section_title))
for field_name, field_desc in field_descriptions.items():
items.append(key_str.format(field_name, width, field_desc))
return "\n".join(items) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _is_valid_datatype(datatype_instance):
""" Returns true if datatype_instance is a valid datatype object and false otherwise. """ |
# Remap so we can still use the python types for the simple cases
global _simple_type_remap
if datatype_instance in _simple_type_remap:
return True
# Now set the protobuf from this interface.
if isinstance(datatype_instance, (Int64, Double, String, Array)):
return True
elif i... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _normalize_datatype(datatype_instance):
""" Translates a user specified datatype to an instance of the ones defined above. Valid data types are passed throug... |
global _simple_type_remap
if datatype_instance in _simple_type_remap:
return _simple_type_remap[datatype_instance]
# Now set the protobuf from this interface.
if isinstance(datatype_instance, (Int64, Double, String, Array)):
return datatype_instance
elif isinstance(datatype_instan... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def order (self, objects):
""" Given a list of objects, reorder them so that the constains specified by 'add_pair' are satisfied. The algorithm was adopted from ... |
# The algorithm used is the same is standard transitive closure,
# except that we're not keeping in-degree for all vertices, but
# rather removing edges.
result = []
if not objects:
return result
constraints = self.__eliminate_unused_constraits (objects)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __eliminate_unused_constraits (self, objects):
""" Eliminate constraints which mention objects not in 'objects'. In graph-theory terms, this is finding subgr... |
result = []
for c in self.constraints_:
if c [0] in objects and c [1] in objects:
result.append (c)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __has_no_dependents (self, obj, constraints):
""" Returns true if there's no constraint in 'constraints' where 'obj' comes second. """ |
failed = False
while constraints and not failed:
c = constraints [0]
if c [1] == obj:
failed = True
constraints = constraints [1:]
return not failed |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_order (x, y):
""" Helper for as_path, below. Orders properties with the implicit ones first, and within the two sections in alphabetical order of featur... |
if x == y:
return 0
xg = get_grist (x)
yg = get_grist (y)
if yg and not xg:
return -1
elif xg and not yg:
return 1
else:
if not xg:
x = feature.expand_subfeatures([x])
y = feature.expand_subfeatures([y])
if x < y:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def refine (properties, requirements):
""" Refines 'properties' by overriding any non-free properties for which a different value is specified in 'requirements'.... |
assert is_iterable_typed(properties, Property)
assert is_iterable_typed(requirements, Property)
# The result has no duplicates, so we store it in a set
result = set()
# Records all requirements.
required = {}
# All the elements of requirements should be present in the result
# Record ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate_paths (properties, path):
""" Interpret all path properties in 'properties' as relative to 'path' The property values are assumed to be in system-s... |
assert is_iterable_typed(properties, Property)
result = []
for p in properties:
if p.feature.path:
values = __re_two_ampersands.split(p.value)
new_value = "&&".join(os.path.normpath(os.path.join(path, v)) for v in values)
if new_value != p.value:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def translate_indirect(properties, context_module):
"""Assumes that all feature values that start with '@' are names of rules, used in 'context-module'. Such rul... |
assert is_iterable_typed(properties, Property)
assert isinstance(context_module, basestring)
result = []
for p in properties:
if p.value[0] == '@':
q = qualify_jam_action(p.value[1:], context_module)
get_manager().engine().register_bjam_action(q)
result.appen... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def validate (properties):
""" Exit with error if any of the properties is not valid. properties may be a single property or a sequence of properties. """ |
if isinstance(properties, Property):
properties = [properties]
assert is_iterable_typed(properties, Property)
for p in properties:
__validate1(p) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def select (features, properties):
""" Selects properties which correspond to any of the given features. """ |
assert is_iterable_typed(properties, basestring)
result = []
# add any missing angle brackets
features = add_grist (features)
return [p for p in properties if get_grist(p) in features] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def evaluate_conditionals_in_context (properties, context):
""" Removes all conditional properties which conditions are not met For those with met conditions, re... |
if __debug__:
from .property_set import PropertySet
assert is_iterable_typed(properties, Property)
assert isinstance(context, PropertySet)
base = []
conditional = []
for p in properties:
if p.condition:
conditional.append (p)
else:
base.a... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def change (properties, feature, value = None):
""" Returns a modified version of properties with all values of the given feature replaced by the given value. If... |
assert is_iterable_typed(properties, basestring)
assert isinstance(feature, basestring)
assert isinstance(value, (basestring, type(None)))
result = []
feature = add_grist (feature)
for p in properties:
if get_grist (p) == feature:
if value:
result.append (r... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __validate1 (property):
""" Exit with error if property is not valid. """ |
assert isinstance(property, Property)
msg = None
if not property.feature.free:
feature.validate_value_string (property.feature, property.value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def remove(attributes, properties):
"""Returns a property sets which include all the elements in 'properties' that do not have attributes listed in 'attributes'.... |
if isinstance(attributes, basestring):
attributes = [attributes]
assert is_iterable_typed(attributes, basestring)
assert is_iterable_typed(properties, basestring)
result = []
for e in properties:
attributes_new = feature.attributes(get_grist(e))
has_common_features = 0
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def take(attributes, properties):
"""Returns a property set which include all properties in 'properties' that have any of 'attributes'.""" |
assert is_iterable_typed(attributes, basestring)
assert is_iterable_typed(properties, basestring)
result = []
for e in properties:
if b2.util.set.intersection(attributes, feature.attributes(get_grist(e))):
result.append(e)
return result |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def insert (self, properties, value):
""" Associate value with properties. """ |
assert is_iterable_typed(properties, basestring)
assert isinstance(value, basestring)
self.__properties.append(properties)
self.__values.append(value) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark_command(cmd, progress):
"""Benchmark one command execution""" |
full_cmd = '/usr/bin/time --format="%U %M" {0}'.format(cmd)
print '{0:6.2f}% Running {1}'.format(100.0 * progress, full_cmd)
(_, err) = subprocess.Popen(
['/bin/sh', '-c', full_cmd],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate('')
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark_file( filename, compiler, include_dirs, (progress_from, progress_to), iter_count, extra_flags = ''):
"""Benchmark one file""" |
time_sum = 0
mem_sum = 0
for nth_run in xrange(0, iter_count):
(time_spent, mem_used) = benchmark_command(
'{0} -std=c++11 {1} -c {2} {3}'.format(
compiler,
' '.join('-I{0}'.format(i) for i in include_dirs),
filename,
extra... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compiler_info(compiler):
"""Determine the name + version of the compiler""" |
(out, err) = subprocess.Popen(
['/bin/sh', '-c', '{0} -v'.format(compiler)],
stdin=subprocess.PIPE,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE
).communicate('')
gcc_clang = re.compile('(gcc|clang) version ([0-9]+(\\.[0-9]+)*)')
for line in (out + err).split('\n'):
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def files_in_dir(path, extension):
"""Enumartes the files in path with the given extension""" |
ends = '.{0}'.format(extension)
return (f for f in os.listdir(path) if f.endswith(ends)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_time(seconds):
"""Format a duration""" |
minute = 60
hour = minute * 60
day = hour * 24
week = day * 7
result = []
for name, dur in [
('week', week), ('day', day), ('hour', hour),
('minute', minute), ('second', 1)
]:
if seconds > dur:
value = seconds // dur
result.append(
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def benchmark(src_dir, compiler, include_dirs, iter_count):
"""Do the benchmarking""" |
files = list(files_in_dir(src_dir, 'cpp'))
random.shuffle(files)
has_string_templates = True
string_template_file_cnt = sum(1 for file in files if 'bmp' in file)
file_count = len(files) + string_template_file_cnt
started_at = time.time()
result = {}
for filename in files:
prog... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot(values, mode_names, title, (xlabel, ylabel), out_file):
"""Plot a diagram""" |
matplotlib.pyplot.clf()
for mode, mode_name in mode_names.iteritems():
vals = values[mode]
matplotlib.pyplot.plot(
[x for x, _ in vals],
[y for _, y in vals],
label=mode_name
)
matplotlib.pyplot.title(title)
matplotlib.pyplot.xlabel(xlabel)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def configs_in(src_dir):
"""Enumerate all configs in src_dir""" |
for filename in files_in_dir(src_dir, 'json'):
with open(os.path.join(src_dir, filename), 'rb') as in_f:
yield json.load(in_f) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def join_images(img_files, out_file):
"""Join the list of images into the out file""" |
images = [PIL.Image.open(f) for f in img_files]
joined = PIL.Image.new(
'RGB',
(sum(i.size[0] for i in images), max(i.size[1] for i in images))
)
left = 0
for img in images:
joined.paste(im=img, box=(left, 0))
left = left + img.size[0]
joined.save(out_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_temp_diagrams(config, results, temp_dir):
"""Plot temporary diagrams""" |
display_name = {
'time': 'Compilation time (s)',
'memory': 'Compiler memory usage (MB)',
}
files = config['files']
img_files = []
if any('slt' in result for result in results) and 'bmp' in files.values()[0]:
config['modes']['slt'] = 'Using BOOST_METAPARSE_STRING with strin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def plot_diagram(config, results, images_dir, out_filename):
"""Plot one diagram""" |
img_files = plot_temp_diagrams(config, results, images_dir)
join_images(img_files, out_filename)
for img_file in img_files:
os.remove(img_file) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def load_model(location):
""" Load any Turi Create model that was previously saved. This function assumes the model (can be any model) was previously saved in Tu... |
# Check if the location is a dir_archive, if not, use glunpickler to load
# as pure python model
# If the location is a http location, skip the check, and directly proceed
# to load model as dir_archive. This is because
# 1) exists() does not work with http protocol, and
# 2) GLUnpickler does ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _get_default_options_wrapper(unity_server_model_name, module_name='', python_class_name='', sdk_model = False):
""" Internal function to return a get_default... |
def get_default_options_for_model(output_type = 'sframe'):
"""
Get the default options for the toolkit
:class:`~turicreate.{module_name}.{python_class_name}`.
Parameters
----------
output_type : str, optional
The output can be of the following types.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_invocation_command_nodefault( toolset, tool, user_provided_command=[], additional_paths=[], path_last=False):
""" A helper rule to get the command to inv... |
assert isinstance(toolset, basestring)
assert isinstance(tool, basestring)
assert is_iterable_typed(user_provided_command, basestring)
assert is_iterable_typed(additional_paths, basestring) or additional_paths is None
assert isinstance(path_last, (int, bool))
if not user_provided_command:
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_invocation_command(toolset, tool, user_provided_command = [], additional_paths = [], path_last = False):
""" Same as get_invocation_command_nodefault, ex... |
assert isinstance(toolset, basestring)
assert isinstance(tool, basestring)
assert is_iterable_typed(user_provided_command, basestring)
assert is_iterable_typed(additional_paths, basestring) or additional_paths is None
assert isinstance(path_last, (int, bool))
result = get_invocation_command_no... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_absolute_tool_path(command):
""" Given an invocation command, return the absolute path to the command. This works even if commnad has not path element an... |
assert isinstance(command, basestring)
if os.path.dirname(command):
return os.path.dirname(command)
else:
programs = path.programs_path()
m = path.glob(programs, [command, command + '.exe' ])
if not len(m):
if __debug_configuration:
print "Could n... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_tool_aux(command):
""" Checks if 'command' can be found either in path or is a full name to an existing file. """ |
assert isinstance(command, basestring)
dirname = os.path.dirname(command)
if dirname:
if os.path.exists(command):
return command
# Both NT and Cygwin will run .exe files by their unqualified names.
elif on_windows() and os.path.exists(command + '.exe'):
retur... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def check_tool(command):
""" Checks that a tool can be invoked by 'command'. If command is not an absolute path, checks if it can be found in 'path'. If comand i... |
assert is_iterable_typed(command, basestring)
#FIXME: why do we check the first and last elements????
if check_tool_aux(command[0]) or check_tool_aux(command[-1]):
return command |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get_program_files_dir():
""" returns the location of the "program files" directory on a windows platform """ |
ProgramFiles = bjam.variable("ProgramFiles")
if ProgramFiles:
ProgramFiles = ' '.join(ProgramFiles)
else:
ProgramFiles = "c:\\Program Files"
return ProgramFiles |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def variable_setting_command(variable, value):
""" Returns the command needed to set an environment variable on the current platform. The variable setting persis... |
assert isinstance(variable, basestring)
assert isinstance(value, basestring)
if os_name() == 'NT':
return "set " + variable + "=" + value + os.linesep
else:
# (todo)
# The following does not work on CYGWIN and needs to be fixed. On
# CYGWIN the $(nl) variable holds a ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def path_variable_setting_command(variable, paths):
""" Returns a command to sets a named shell path variable to the given NATIVE paths on the current platform. ... |
assert isinstance(variable, basestring)
assert is_iterable_typed(paths, basestring)
sep = os.path.pathsep
return variable_setting_command(variable, sep.join(paths)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def prepend_path_variable_command(variable, paths):
""" Returns a command that prepends the given paths to the named path variable on the current platform. """ |
assert isinstance(variable, basestring)
assert is_iterable_typed(paths, basestring)
return path_variable_setting_command(
variable, paths + [expand_variable(variable)]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def format_name(format, name, target_type, prop_set):
""" Given a target, as given to a custom tag rule, returns a string formatted according to the passed forma... |
if __debug__:
from ..build.property_set import PropertySet
assert is_iterable_typed(format, basestring)
assert isinstance(name, basestring)
assert isinstance(target_type, basestring)
assert isinstance(prop_set, PropertySet)
# assert(isinstance(prop_set, property_set.Prop... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def register(self, id):
""" Registers a configuration. Returns True if the configuration has been added and False if it already exists. Reports an error if the c... |
assert isinstance(id, basestring)
if id in self.used_:
#FIXME
errors.error("common: the configuration '$(id)' is in use")
if id not in self.all_:
self.all_.add(id)
# Indicate that a new configuration has been added.
return True
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def get(self, id, param):
""" Returns the value of a configuration parameter. """ |
assert isinstance(id, basestring)
assert isinstance(param, basestring)
return self.params_.get(param, {}).get(id) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.