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 register (self, target):
""" Registers a new virtual target. Checks if there's already registered target, with the same name, type, project and subvariant pr... |
assert isinstance(target, VirtualTarget)
if target.path():
signature = target.path() + "-" + target.name()
else:
signature = "-" + target.name()
result = None
if signature not in self.cache_:
self.cache_ [signature] = []
for t in sel... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def depends (self, d):
""" Adds additional instances of 'VirtualTarget' that this one depends on. """ |
self.dependencies_ = unique (self.dependencies_ + d).sort () |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def actualize (self, scanner = None):
""" Generates all the actual targets and sets up build actions for this target. If 'scanner' is specified, creates an addit... |
if __debug__:
from .scanner import Scanner
assert scanner is None or isinstance(scanner, Scanner)
actual_name = self.actualize_no_scanner ()
if self.always_:
bjam.call("ALWAYS", actual_name)
if not scanner:
return actual_name
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 set_path (self, path):
""" Sets the path. When generating target name, it will override any path computation from properties. """ |
assert isinstance(path, basestring)
self.path_ = os.path.normpath(path) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def grist (self):
"""Helper to 'actual_name', above. Compute unique prefix used to distinguish this target from other targets with the same name which create dif... |
# Depending on target, there may be different approaches to generating
# unique prefixes. We'll generate prefixes in the form
# <one letter approach code> <the actual prefix>
path = self.path ()
if path:
# The target will be generated to a known path. Just use the 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 path (self):
""" Returns the directory for this target. """ |
if not self.path_:
if self.action_:
p = self.action_.properties ()
(target_path, relative_to_build_dir) = p.target_path ()
if relative_to_build_dir:
# Indicates that the path is relative to
# build dir.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def actualize (self):
""" Generates actual build instructions. """ |
if self.actualized_:
return
self.actualized_ = True
ps = self.properties ()
properties = self.adjust_properties (ps)
actual_targets = []
for i in self.targets ():
actual_targets.append (i.actualize ())
self.actualize_sources (self.so... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def actualize_source_type (self, sources, prop_set):
""" Helper for 'actualize_sources'. For each passed source, actualizes it with the appropriate scanner. Retu... |
assert is_iterable_typed(sources, VirtualTarget)
assert isinstance(prop_set, property_set.PropertySet)
result = []
for i in sources:
scanner = None
# FIXME: what's this?
# if isinstance (i, str):
# i = self.manager_.get_object (i)
if 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 all_referenced_targets(self, result):
"""Returns all targets referenced by this subvariant, either directly or indirectly, and either as sources, or as depen... |
if __debug__:
from .property import Property
assert is_iterable_typed(result, (VirtualTarget, Property))
# Find directly referenced targets.
deps = self.build_properties().dependency()
all_targets = self.sources_ + deps
# Find other subvariants.
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def cmp_ast(node1, node2):
'''
Compare if two nodes are equal.
'''
if type(node1) != type(node2):
return False
if isinstance(node1, (list, tuple)):
if len(node1) != len(node2):
return False
for left, right in zip(node1, node2):
if not cmp_ast(left, ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_more_container_files(sourceDir, suffix, maxElements, containers, containers2):
"""Creates additional files for the individual MPL-containers.""" |
# Create files for each MPL-container with 20 to 'maxElements' elements
# which will be used during generation.
for container in containers:
for i in range(20, maxElements, 10):
# Create copy of "template"-file.
newFile = os.path.join( sourceDir, container, container + str(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_input_for_numbered_sequences(headerDir, sourceDir, containers, maxElements):
"""Creates additional source- and header-files for the numbered sequence ... |
# Create additional container-list without "map".
containersWithoutMap = containers[:]
try:
containersWithoutMap.remove('map')
except ValueError:
# We can safely ignore if "map" is not contained in 'containers'!
pass
# Create header/source-files.
create_more_container_fi... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_container_limits_for_variadic_sequences(headerDir, containers, maxElements):
"""Adjusts the limits of variadic sequence MPL-containers.""" |
for container in containers:
headerFile = os.path.join( headerDir, "limits", container + ".hpp" )
regexMatch = r'(define\s+BOOST_MPL_LIMIT_' + container.upper() + r'_SIZE\s+)[0-9]+'
regexReplace = r'\g<1>' + re.escape( str(maxElements) )
for line in fileinput.input( headerFile, in... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_inner_product(self, name, W, b, input_channels, output_channels, has_bias, input_name, output_name, **kwargs):
""" Add an inner product layer to the mode... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.innerProduct
# Fill in t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_resize_bilinear(self, name, input_name, output_name, target_height=1, target_width=1, mode='ALIGN_ENDPOINTS_MODE'):
""" Add resize bilinear layer to the ... |
spec = self.spec
nn_spec = self.nn_spec
# Add a new inner-product layer
spec_layer = nn_spec.layers.add()
spec_layer.name = name
spec_layer.input.append(input_name)
spec_layer.output.append(output_name)
spec_layer_params = spec_layer.resizeBilinear
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _toolkit_serialize_summary_struct(model, sections, section_titles):
""" Serialize model summary into a dict with ordered lists of sections and section titles... |
output_dict = dict()
output_dict['sections'] = [ [ ( field[0], __extract_model_summary_value(model, field[1]) ) \
for field in section ]
for section in section... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_only_column_of_type(sframe, target_type, type_name, col_name):
""" Finds the only column in `SFrame` with a type specified by `target_type`. If there a... |
image_column_name = None
if type(target_type) != list:
target_type = [target_type]
for name, ctype in zip(sframe.column_names(), sframe.column_types()):
if ctype in target_type:
if image_column_name is not None:
raise ToolkitError('No "{col_name}" column specifie... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _find_only_image_column(sframe):
""" Finds the only column in `sframe` with a type of turicreate.Image. If there are zero or more than one image columns, an ... |
from turicreate import Image
return _find_only_column_of_type(sframe, target_type=Image,
type_name='image', col_name='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 _SGraphFromJsonTree(json_str):
""" Convert the Json Tree to SGraph """ |
g = json.loads(json_str)
vertices = [_Vertex(x['id'],
dict([(str(k), v) for k, v in _six.iteritems(x) if k != 'id']))
for x in g['vertices']]
edges = [_Edge(x['src'], x['dst'],
dict([(str(k), v) for k, v in _six.iteritems(x)... |
<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_coefficients(top_coefs, bottom_coefs):
""" Return a tuple of sections and section titles. Sections are pretty print of model coefficients Paramete... |
def get_row_name(row):
if row['index'] is None:
return row['name']
else:
return "%s[%s]" % (row['name'], row['index'])
if len(top_coefs) == 0:
top_coefs_list = [('No Positive Coefficients', _precomputed_field('') )]
else:
top_coefs_list = [ (get_row... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _toolkit_get_topk_bottomk(values, k=5):
""" Returns a tuple of the top k values from the positive and negative values in a SArray Parameters values : SFrame ... |
top_values = values.topk('value', k=k)
top_values = top_values[top_values['value'] > 0]
bottom_values = values.topk('value', k=k, reverse=True)
bottom_values = bottom_values[bottom_values['value'] < 0]
return (top_values, bottom_values) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def __extract_model_summary_value(model, value):
""" Extract a model summary field value """ |
field_value = None
if isinstance(value, _precomputed_field):
field_value = value.field
else:
field_value = model._get(value)
if isinstance(field_value, float):
try:
field_value = round(field_value, 4)
except:
pass
return field_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 _make_repr_table_from_sframe(X):
""" Serializes an SFrame to a list of strings, that, when printed, creates a well-formatted table. """ |
assert isinstance(X, _SFrame)
column_names = X.column_names()
out_data = [ [None]*len(column_names) for i in range(X.num_rows())]
column_sizes = [len(s) for s in column_names]
for i, c in enumerate(column_names):
for j, e in enumerate(X[c]):
out_data[j][i] = str(e)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _toolkit_repr_print(model, fields, section_titles, width = None):
""" Display a toolkit repr according to some simple rules. Parameters model : Turi Create m... |
assert len(section_titles) == len(fields), \
"The number of section titles ({0}) ".format(len(section_titles)) +\
"doesn't match the number of groups of fields, {0}.".format(len(fields))
out_fields = [ ("Class", model.__class__.__name__), ""]
# Record the max_width so that if width is 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 _map_unity_proxy_to_object(value):
""" Map returning value, if it is unity SFrame, SArray, map it """ |
vtype = type(value)
if vtype in _proxy_map:
return _proxy_map[vtype](value)
elif vtype == list:
return [_map_unity_proxy_to_object(v) for v in value]
elif vtype == dict:
return {k:_map_unity_proxy_to_object(v) for k,v in value.items()}
else:
return 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 _toolkits_select_columns(dataset, columns):
""" Same as select columns but redirect runtime error to ToolkitError. """ |
try:
return dataset.select_columns(columns)
except RuntimeError:
missing_features = list(set(columns).difference(set(dataset.column_names())))
raise ToolkitError("Input data does not contain the following columns: " +
"{}".format(missing_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 _raise_error_if_column_exists(dataset, column_name = 'dataset', dataset_variable_name = 'dataset', column_name_error_message_name = 'column_name'):
""" Check... |
err_msg = 'The SFrame {0} must contain the column {1}.'.format(
dataset_variable_name,
column_name_error_message_name)
if column_name not in dataset.column_names():
raise ToolkitError(str(err_msg)) |
<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_categorical_option_type(option_name, option_value, possible_values):
""" Check whether or not the requested option is one of the allowed values. """ |
err_msg = '{0} is not a valid option for {1}. '.format(option_value, option_name)
err_msg += ' Expected one of: '.format(possible_values)
err_msg += ', '.join(map(str, possible_values))
if option_value not in possible_values:
raise ToolkitError(err_msg) |
<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_sarray(dataset, variable_name="SArray"):
""" Check if the input is an SArray. Provide a proper error message otherwise. """ |
err_msg = "Input %s is not an SArray."
if not isinstance(dataset, _SArray):
raise ToolkitError(err_msg % variable_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 _raise_error_if_sframe_empty(dataset, variable_name="SFrame"):
""" Check if the input is empty. """ |
err_msg = "Input %s either has no rows or no columns. A non-empty SFrame "
err_msg += "is required."
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ToolkitError(err_msg % variable_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 _numeric_param_check_range(variable_name, variable_value, range_bottom, range_top):
""" Checks if numeric parameter is within given range """ |
err_msg = "%s must be between %i and %i"
if variable_value < range_bottom or variable_value > range_top:
raise ToolkitError(err_msg % (variable_name, range_bottom, range_top)) |
<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_data(dataset, target, features=None, validation_set='auto'):
""" Validate and canonicalize training and validation data. Parameters dataset : SFram... |
_raise_error_if_not_sframe(dataset, "training dataset")
# Determine columns to keep
if features is None:
features = [feat for feat in dataset.column_names() if feat != target]
if not hasattr(features, '__iter__'):
raise TypeError("Input 'features' must be a list.")
if not all([isi... |
<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(dataset, label=None, default_label='__id'):
""" Validate a row label column. If the row label is not specified, a column is created with ... |
## If no label is provided, set it to be a default and add a row number to
# dataset. Check that this new name does not conflict with an existing
# name.
if not label:
## Try a bunch of variations of the default label to find one that's not
# already a column name.
label_nam... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _mac_ver():
""" Returns Mac version as a tuple of integers, making it easy to do proper version comparisons. On non-Macs, it returns an empty tuple. """ |
import platform
import sys
if sys.platform == 'darwin':
ver_str = platform.mac_ver()[0]
return tuple([int(v) for v in ver_str.split('.')])
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 _print_neural_compute_device(cuda_gpus, use_mps, cuda_mem_req=None, has_mps_impl=True):
""" Print a message making it clear to the user what compute resource... |
num_cuda_gpus = len(cuda_gpus)
if num_cuda_gpus >= 1:
gpu_names = ', '.join(gpu['name'] for gpu in cuda_gpus)
if use_mps:
from ._mps_utils import mps_device_name
print('Using GPU to create model ({})'.format(mps_device_name()))
elif num_cuda_gpus >= 1:
from . import _mx... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _GetMessageFromFactory(factory, full_name):
"""Get a proto class from the MessageFactory by name. Args: factory: a MessageFactory instance. full_name: str, t... |
proto_descriptor = factory.pool.FindMessageTypeByName(full_name)
proto_cls = factory.GetPrototype(proto_descriptor)
return proto_cls |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def MakeSimpleProtoClass(fields, full_name=None, pool=None):
"""Create a Protobuf class whose fields are basic types. Note: this doesn't validate field names! Ar... |
factory = message_factory.MessageFactory(pool=pool)
if full_name is not None:
try:
proto_cls = _GetMessageFromFactory(factory, full_name)
return proto_cls
except KeyError:
# The factory's DescriptorPool doesn't know about this class yet.
pass
# Get a list of (name, field_type) t... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _MakeFileDescriptorProto(proto_file_name, full_name, field_items):
"""Populate FileDescriptorProto for MessageFactory's DescriptorPool.""" |
package, name = full_name.rsplit('.', 1)
file_proto = descriptor_pb2.FileDescriptorProto()
file_proto.name = os.path.join(package.replace('.', '/'), proto_file_name)
file_proto.package = package
desc_proto = file_proto.message_type.add()
desc_proto.name = name
for f_number, (f_name, f_type) in enumerate(... |
<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_model_metadata(model_class, metadata, version=None):
""" Returns user-defined metadata, making sure information all models should have is also available... |
from turicreate import __version__
info = {
'turicreate_version': __version__,
'type': model_class,
}
if version is not None:
info['version'] = str(version)
info.update(metadata)
return info |
<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_model_metadata(mlmodel, model_class, metadata, version=None):
""" Sets user-defined metadata, making sure information all models should have is also ava... |
info = _get_model_metadata(model_class, metadata, version)
mlmodel.user_defined_metadata.update(info) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _ToCamelCase(name):
"""Converts name to camel-case and returns it.""" |
capitalize_next = False
result = []
for c in name:
if c == '_':
if result:
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
# Lower-case the first letter.
if result and result[0].isupper():
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 _ToJsonName(name):
"""Converts name to Json name and returns it.""" |
capitalize_next = False
result = []
for c in name:
if c == '_':
capitalize_next = True
elif capitalize_next:
result.append(c.upper())
capitalize_next = False
else:
result += c
return ''.join(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 _SetOptions(self, options, options_class_name):
"""Sets the descriptor's options This function is used in generated proto2 files to update descriptor options... |
self._options = options
self._options_class_name = options_class_name
# Does this descriptor have non-default options?
self.has_options = options is not 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 GetOptions(self):
"""Retrieves descriptor options. This method returns the options set or creates the default options for the descriptor. """ |
if self._options:
return self._options
from google.protobuf import descriptor_pb2
try:
options_class = getattr(descriptor_pb2, self._options_class_name)
except AttributeError:
raise RuntimeError('Unknown options class name %s!' %
(self._options_class_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 CopyToProto(self, proto):
"""Copies this to the matching proto in descriptor_pb2. Args: proto: An empty proto instance from descriptor_pb2. Raises: Error: If... |
if (self.file is not None and
self._serialized_start is not None and
self._serialized_end is not None):
proto.ParseFromString(self.file.serialized_pb[
self._serialized_start:self._serialized_end])
else:
raise Error('Descriptor does not contain serialization.') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def EnumValueName(self, enum, value):
"""Returns the string name of an enum value. This is just a small helper method to simplify a common operation. Args: enum:... |
return self.enum_types_by_name[enum].values_by_number[value].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 resolve_reference(target_reference, project):
""" Given a target_reference, made in context of 'project', returns the AbstractTarget instance that is referre... |
# Separate target name from properties override
assert isinstance(target_reference, basestring)
assert isinstance(project, ProjectTarget)
split = _re_separate_target_from_properties.match (target_reference)
if not split:
raise BaseException ("Invalid reference: '%s'" % target_reference)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main_target_alternative (self, target):
""" Registers the specified target as a main target alternatives. Returns 'target'. """ |
assert isinstance(target, AbstractTarget)
target.project ().add_alternative (target)
return target |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def main_target_requirements(self, specification, project):
"""Returns the requirement to use when declaring a main target, which are obtained by - translating a... |
assert is_iterable_typed(specification, basestring)
assert isinstance(project, ProjectTarget)
# create a copy since the list is being modified
specification = list(specification)
specification.extend(toolset.requirements())
requirements = property_set.refine_from_user_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 start_building (self, main_target_instance):
""" Helper rules to detect cycles in main target references. """ |
assert isinstance(main_target_instance, MainTarget)
if id(main_target_instance) in self.targets_being_built_:
names = []
for t in self.targets_being_built_.values() + [main_target_instance]:
names.append (t.full_name())
get_manager().errors()("Recurs... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_typed_target (self, type, project, name, sources, requirements, default_build, usage_requirements):
""" Creates a TypedTarget with the specified prope... |
assert isinstance(type, basestring)
assert isinstance(project, ProjectTarget)
assert is_iterable_typed(sources, basestring)
assert is_iterable_typed(requirements, basestring)
assert is_iterable_typed(default_build, basestring)
return self.main_target_alternative (TypedTa... |
<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 (self, ps):
""" Generates all possible targets contained in this project. """ |
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets().log(
"Building project '%s' with '%s'" % (self.name (), str(ps)))
self.manager_.targets().increase_indent ()
result = GenerateResult ()
for t in self.targets_to_build ():
g = t.gene... |
<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_build (self):
""" Computes and returns a list of AbstractTarget instances which must be built when this project is built. """ |
result = []
if not self.built_main_targets_:
self.build_main_targets ()
# Collect all main targets here, except for "explicit" ones.
for n, t in self.main_target_.iteritems ():
if not t.name () in self.explicit_targets_:
result.append (t)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def mark_targets_as_explicit (self, target_names):
"""Add 'target' to the list of targets in this project that should be build only by explicit request.""" |
# Record the name of the target, not instance, since this
# rule is called before main target instaces are created.
assert is_iterable_typed(target_names, basestring)
self.explicit_targets_.update(target_names) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_alternative (self, target_instance):
""" Add new target alternative. """ |
assert isinstance(target_instance, AbstractTarget)
if self.built_main_targets_:
raise IllegalOperation ("add-alternative called when main targets are already created for project '%s'" % self.full_name ())
self.alternatives_.append (target_instance) |
<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_main_target (self, name):
"""Tells if a main target with the specified name exists.""" |
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets()
return name in self.main_target_ |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_main_target (self, name):
""" Returns a 'MainTarget' class instance corresponding to the 'name'. """ |
assert isinstance(name, basestring)
if not self.built_main_targets_:
self.build_main_targets ()
return self.main_targets_.get (name, 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 find_really(self, id):
""" Find and return the target with the specified id, treated relative to self. """ |
assert isinstance(id, basestring)
result = None
current_location = self.get ('location')
__re_split_project_target = re.compile (r'(.*)//(.*)')
split = __re_split_project_target.match (id)
project_part = None
target_part = None
if split:
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 add_constant(self, name, value, path=0):
"""Adds a new constant for this project. The constant will be available for use in Jamfile module for this project. ... |
assert isinstance(name, basestring)
assert is_iterable_typed(value, basestring)
assert isinstance(path, int) # will also match bools
if path:
l = self.location_
if not l:
# Project corresponding to config files do not have
# 'loca... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def add_alternative (self, target):
""" Add a new alternative for this target. """ |
assert isinstance(target, BasicTarget)
d = target.default_build ()
if self.alternatives_ and self.default_build_ != d:
get_manager().errors()("default build must be identical in all alternatives\n"
"main target is '%s'\n"
"with '%s'\n"
"dif... |
<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 (self, ps):
""" Select an alternative for this main target, by finding all alternatives which requirements are satisfied by 'properties' and picking... |
assert isinstance(ps, property_set.PropertySet)
self.manager_.targets ().start_building (self)
# We want composite properties in build request act as if
# all the properties it expands too are explicitly specified.
ps = ps.expand ()
all_property_sets = self.apply_defau... |
<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_really (self, prop_set):
""" Generates the main target with the given property set and returns a list which first element is property_set object c... |
assert isinstance(prop_set, property_set.PropertySet)
best_alternative = self.__select_alternatives (prop_set, debug=0)
self.best_alternative = best_alternative
if not best_alternative:
# FIXME: revive.
# self.__select_alternatives(prop_set, debug=1)
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def common_properties (self, build_request, requirements):
""" Given build request and requirements, return properties common to dependency build request and tar... |
# For optimization, we add free unconditional requirements directly,
# without using complex algorithsm.
# This gives the complex algorithm better chance of caching results.
# The exact effect of this "optimization" is no longer clear
assert isinstance(build_request, property_se... |
<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, property_set_, debug):
""" Returns the alternative condition for this alternative, if the condition is satisfied by 'property_set'. """ |
# The condition is composed of all base non-conditional properties.
# It's not clear if we should expand 'self.requirements_' or not.
# For one thing, it would be nice to be able to put
# <toolset>msvc-6.0
# in requirements.
# On the other hand, if we have <variant>re... |
<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_dependency_properties(self, properties, ps):
""" Takes a target reference, which might be either target id or a dependency property, and generates t... |
assert is_iterable_typed(properties, property.Property)
assert isinstance(ps, property_set.PropertySet)
result_properties = []
usage_requirements = []
for p in properties:
result = generate_from_reference(p.value, self.project_, ps)
for t in result.targ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def compute_usage_requirements (self, subvariant):
""" Given the set of generated targets, and refined build properties, determines and sets appripriate usage re... |
assert isinstance(subvariant, virtual_target.Subvariant)
rproperties = subvariant.build_properties ()
xusage_requirements =self.evaluate_requirements(
self.usage_requirements_, rproperties, "added")
# We generate all dependency properties and add them,
# as well as ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create_subvariant (self, root_targets, all_targets, build_request, sources, rproperties, usage_requirements):
"""Creates a new subvariant-dg instances for 't... |
assert is_iterable_typed(root_targets, virtual_target.VirtualTarget)
assert is_iterable_typed(all_targets, virtual_target.VirtualTarget)
assert isinstance(build_request, property_set.PropertySet)
assert is_iterable_typed(sources, virtual_target.VirtualTarget)
assert isinstance(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 variant (name, parents_or_properties, explicit_properties = []):
""" Declares a new variant. First determines explicit properties for this variant, by refini... |
parents = []
if not explicit_properties:
explicit_properties = parents_or_properties
else:
parents = parents_or_properties
inherited = property_set.empty()
if parents:
# If we allow multiple parents, we'd have to to check for conflicts
# between base variants, and ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def adjust_properties (self, prop_set):
""" For all virtual targets for the same dependency graph as self, i.e. which belong to the same main target, add their d... |
assert isinstance(prop_set, property_set.PropertySet)
s = self.targets () [0].creating_subvariant ()
return prop_set.add_raw (s.implicit_includes ('include', 'H')) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def create(observation_data, user_id='user_id', item_id='item_id', target=None, user_data=None, item_data=None, random_seed=0, verbose=True):
""" Create a model ... |
from turicreate._cython.cy_server import QuietProgress
opts = {}
model_proxy = _turicreate.extensions.popularity()
model_proxy.init_options(opts)
if user_data is None:
user_data = _turicreate.SFrame()
if item_data is None:
item_data = _turicreate.SFrame()
nearest_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 get_params(self, deep=False):
"""Get parameter.s""" |
params = super(XGBModel, self).get_params(deep=deep)
if params['missing'] is np.nan:
params['missing'] = None # sklearn doesn't handle nan. see #4725
if not params.get('eval_metric', True):
del params['eval_metric'] # don't give as None param to Booster
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 replace_grist (features, new_grist):
""" Replaces the grist of a string by a new one. Returns the string with the new grist. """ |
assert is_iterable_typed(features, basestring) or isinstance(features, basestring)
assert isinstance(new_grist, basestring)
# this function is used a lot in the build phase and the original implementation
# was extremely slow; thus some of the weird-looking optimizations for this function.
single_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 get_value (property):
""" Gets the value of a property, that is, the part following the grist, if any. """ |
assert is_iterable_typed(property, basestring) or isinstance(property, basestring)
return replace_grist (property, '') |
<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_grist (value):
""" Returns the grist of a string. If value is a sequence, does it for every value and returns the result as a sequence. """ |
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def get_grist_one (name):
split = __re_grist_and_value.match (name)
if not split:
return ''
else:
return split.group (1)
if isinstance (value, str):
return get_grist_one (va... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def ungrist (value):
""" Returns the value without grist. If value is a sequence, does it for every value and returns the result as a sequence. """ |
assert is_iterable_typed(value, basestring) or isinstance(value, basestring)
def ungrist_one (value):
stripped = __re_grist_content.match (value)
if not stripped:
raise BaseException ("in ungrist: '%s' is not of the form <.*>" % value)
return stripped.group (1)
if isin... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def replace_suffix (name, new_suffix):
""" Replaces the suffix of name by new_suffix. If no suffix exists, the new one is added. """ |
assert isinstance(name, basestring)
assert isinstance(new_suffix, basestring)
split = os.path.splitext (name)
return split [0] + new_suffix |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def on_windows ():
""" Returns true if running on windows, whether in cygwin or not. """ |
if bjam.variable("NT"):
return True
elif bjam.variable("UNIX"):
uname = bjam.variable("JAMUNAME")
if uname and uname[0].startswith("CYGWIN"):
return True
return 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 _validate_dataset(dataset):
""" Validate the main Kmeans dataset. Parameters dataset: SFrame Input dataset. """ |
if not (isinstance(dataset, _SFrame)):
raise TypeError("Input 'dataset' must be an SFrame.")
if dataset.num_rows() == 0 or dataset.num_columns() == 0:
raise ValueError("Input 'dataset' has no 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 _validate_initial_centers(initial_centers):
""" Validate the initial centers. Parameters initial_centers : SFrame Initial cluster center locations, in SFrame... |
if not (isinstance(initial_centers, _SFrame)):
raise TypeError("Input 'initial_centers' must be an SFrame.")
if initial_centers.num_rows() == 0 or initial_centers.num_columns() == 0:
raise ValueError("An 'initial_centers' argument is provided " +
"but has no 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 _validate_num_clusters(num_clusters, initial_centers, num_rows):
""" Validate the combination of the `num_clusters` and `initial_centers` parameters in the K... |
## Basic validation
if num_clusters is not None and not isinstance(num_clusters, int):
raise _ToolkitError("Parameter 'num_clusters' must be an integer.")
## Determine the correct number of clusters.
if initial_centers is None:
if num_clusters is None:
raise ValueError("Nu... |
<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_features(features, column_type_map, valid_types, label):
""" Identify the subset of desired `features` that are valid for the Kmeans model. A warni... |
if not isinstance(features, list):
raise TypeError("Input 'features' must be a list, if specified.")
if len(features) == 0:
raise ValueError("If specified, input 'features' must contain " +
"at least one column name.")
## Remove duplicates
num_original_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 create(dataset, num_clusters=None, features=None, label=None, initial_centers=None, max_iterations=10, batch_size=None, verbose=True):
""" Create a k-means c... |
opts = {'model_name': 'kmeans',
'max_iterations': max_iterations,
}
## Validate the input dataset and initial centers.
_validate_dataset(dataset)
if initial_centers is not None:
_validate_initial_centers(initial_centers)
## Validate and determine the correct numbe... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def predict(self, dataset, output_type='cluster_id', verbose=True):
""" Return predicted cluster label for instances in the new 'dataset'. K-means predictions ar... |
## Validate the input dataset.
_tkutl._raise_error_if_not_sframe(dataset, "dataset")
_tkutl._raise_error_if_sframe_empty(dataset, "dataset")
## Validate the output type.
if not isinstance(output_type, str):
raise TypeError("The 'output_type' parameter must be a str... |
<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 of a given field. | Field | Description | +=======================+==============================================+ | ... |
opts = {'model': self.__proxy__,
'model_name': self.__name__,
'field': field}
response = _tc.extensions._kmeans.get_value(opts)
return response['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 count_words(text, to_lower=True, delimiters=DEFAULT_DELIMITERS):
""" If `text` is an SArray of strings or an SArray of lists of strings, the occurances of wo... |
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.WordCounter(features='docs',
to_lower=to_lower,
delimiters=delimiters... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def count_ngrams(text, n=2, method="word", to_lower=True, delimiters=DEFAULT_DELIMITERS, ignore_punct=True, ignore_space=True):
""" Return an SArray of ``dict`` ... |
_raise_error_if_not_sarray(text, "text")
# Compute ngrams counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.NGramCounter(features='docs',
n=n,
method=method,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tf_idf(text):
""" Compute the TF-IDF scores for each word in each document. The collection of documents must be in bag-of-words format. .. math:: \mbox{TF-ID... |
_raise_error_if_not_sarray(text, "text")
if len(text) == 0:
return _turicreate.SArray()
dataset = _turicreate.SFrame({'docs': text})
scores = _feature_engineering.TFIDF('docs').fit_transform(dataset)
return scores['docs'] |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def drop_words(text, threshold=2, to_lower=True, delimiters=DEFAULT_DELIMITERS,
stop_words=None):
'''
Remove words that occur below a certain number of times in an SArray.
This is a common method of cleaning text before it is used, and can increase the
quality and explainability of the mo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def tokenize(text, to_lower=False, delimiters=DEFAULT_DELIMITERS):
""" Tokenize the input SArray of text strings and return the list of tokens. Parameters text :... |
_raise_error_if_not_sarray(text, "text")
## Compute word counts
sf = _turicreate.SFrame({'docs': text})
fe = _feature_engineering.Tokenizer(features='docs',
to_lower=to_lower,
delimiters=delimiters,
... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cv(params, dtrain, num_boost_round=10, nfold=3, metrics=(), obj=None, feval=None, fpreproc=None, as_pandas=True, show_progress=None, show_stdv=True, seed=0):
... |
results = []
cvfolds = mknfold(dtrain, nfold, params, seed, metrics, fpreproc)
for i in range(num_boost_round):
for fold in cvfolds:
fold.update(i, obj)
res = aggcv([f.eval(i, feval) for f in cvfolds],
show_stdv=show_stdv, show_progress=show_progress,
... |
<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_layer_and_reconnect(self, layer):
""" Remove the layer, and reconnect each of its predecessor to each of its successor """ |
successors = self.get_successors(layer)
predecessors = self.get_predecessors(layer)
# remove layer's edges
for succ in successors:
self._remove_edge(layer, succ)
for pred in predecessors:
self._remove_edge(pred, layer)
# connect predecessors and ... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def date_range(cls,start_time,end_time,freq):
'''
Returns a new SArray that represents a fixed frequency datetime index.
Parameters
----------
start_time : datetime.datetime
Left bound for generating dates.
end_time : datetime.datetime
Right bound fo... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def from_const(cls, value, size, dtype=type(None)):
""" Constructs an SArray of size with a const value. Parameters value : [int | float | str | array.array | li... |
assert isinstance(size, (int, long)) and size >= 0, "size must be a positive int"
if not isinstance(value, (type(None), int, float, str, array.array, list, dict, datetime.datetime)):
raise TypeError('Cannot create sarray of value type %s' % str(type(value)))
proxy = UnitySArrayProxy... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def read_json(cls, filename):
""" Construct an SArray from a json file or glob of json files. The json file must contain a list of dictionaries. The returned SAr... |
proxy = UnitySArrayProxy()
proxy.load_from_json_record_files(_make_internal_url(filename))
return cls(_proxy = proxy) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def where(cls, condition, istrue, isfalse, dtype=None):
""" Selects elements from either istrue or isfalse depending on the value of the condition SArray. Parame... |
true_is_sarray = isinstance(istrue, SArray)
false_is_sarray = isinstance(isfalse, SArray)
if not true_is_sarray and false_is_sarray:
istrue = cls(_proxy=condition.__proxy__.to_const(istrue, isfalse.dtype))
if true_is_sarray and not false_is_sarray:
isfalse = cls(... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def save(self, filename, format=None):
""" Saves the SArray to file. The saved SArray will be in a directory named with the `targetfile` parameter. Parameters fi... |
from .sframe import SFrame as _SFrame
if format is None:
if filename.endswith(('.csv', '.csv.gz', 'txt')):
format = 'text'
else:
format = 'binary'
if format == 'binary':
with cython_context():
self.__proxy__.sa... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _count_words(self, to_lower=True, delimiters=["\r", "\v", "\n", "\f", "\t", " "]):
""" This returns an SArray with, for each input string, a dict from the un... |
if (self.dtype != str):
raise TypeError("Only SArray of string type is supported for counting bag of words")
if (not all([len(delim) == 1 for delim in delimiters])):
raise ValueError("Delimiters must be single-character strings")
# construct options, will extend over... |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_has_any_keys(self, keys):
""" Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the ... |
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_any_keys(keys)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def dict_has_all_keys(self, keys):
""" Create a boolean SArray by checking the keys of an SArray of dictionaries. An element of the output SArray is True if the ... |
if not _is_non_string_iterable(keys):
keys = [keys]
with cython_context():
return SArray(_proxy=self.__proxy__.dict_has_all_keys(keys)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def filter(self, fn, skip_na=True, seed=None):
""" Filter this SArray by a function. Returns a new SArray filtered by this SArray. If `fn` evaluates an element t... |
assert callable(fn), "Input must be callable"
if seed is None:
seed = abs(hash("%0.20f" % time.time())) % (2 ** 31)
with cython_context():
return SArray(_proxy=self.__proxy__.filter(fn, skip_na, seed)) |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.