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 _unwrap_to_layer(r, L, n=1):
"""For a set of points in a 2 dimensional periodic system, extend the set of points to tile the points up to to a given period. Parameters r: float array, shape (:, 2). Set of points. L: float array, shape (2,) System lengths. n: integer. Period to unwrap up to. Returns ------- rcu: float array, shape (:, 2). The set of points. tiled up to the periods at a distance `n` from the origin. """ |
rcu = []
for i_n in range(n + 1):
rcu.extend(_unwrap_one_layer(r, L, i_n))
return rcu |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def draw_medium(r, R, L, n=1, ax=None):
"""Draw circles representing circles in a two-dimensional periodic system. Circles may be tiled up to a number of periods. Parameters r: float array, shape (:, 2). Set of points. R: float Circle radius. L: float array, shape (2,) System lengths. n: integer. Period to unwrap up to. ax: matplotlib axes instance or None Axes to draw circles onto. If `None`, use default axes. Returns ------- None """ |
if ax is None:
ax = plt.gca()
for ru in _unwrap_to_layer(r, L, n):
c = plt.Circle(ru, radius=R, alpha=0.2)
ax.add_artist(c) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def upload(self, # pylint: disable=too-many-arguments path, name=None, resize=False, rotation=False, callback_url=None, callback_method=None, auto_align=False, ):
"""Create a new model resource in the warehouse and uploads the path contents to it""" |
if name is None:
head, tail = ntpath.split(path)
name = tail or ntpath.basename(head)
url = "http://models.{}/model/".format(self.config.host)
payload = {"name": name,
"allowed_transformations": {"resize": resize,
"rotation": rotation, },
"auto-align": auto_align}
if callback_url and callback_method:
payload["callback"] = {"url": callback_url, "method": callback_method}
post_resp = requests.post(url, json=payload, cookies={"session": self.session})
if not post_resp.ok:
raise errors.ResourceError("payload to model service invalid")
self.name = name
with open(path, "rb") as model_file:
put_resp = requests.put(post_resp.headers["x-upload-location"],
data=model_file.read(),
headers={"Content-Type": "application/octet-stream"})
if not put_resp.ok:
raise errors.ResourceError("model upload failed")
self.location = post_resp.headers["Location"]
self._state = self._get_status() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def download(self, path):
"""downloads a model resource to the path""" |
service_get_resp = requests.get(self.location, cookies={"session": self.session})
payload = service_get_resp.json()
self._state = payload["status"]
if self._state != "processed":
raise errors.ResourceError("slice resource status is: {}".format(self._state))
else:
download_get_resp = requests.get(payload["content"])
with open(path, "wb") as model_file:
model_file.write(download_get_resp.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 to_dict(obj):
"""Generate a JSON serialization for the run state object. Returns ------- Json-like object Json serialization of model run state object """ |
# Have text description of state in Json object (for readability)
json_obj = {'type' : repr(obj)}
# Add state-specific elementsTYPE_MODEL_RUN
if obj.is_failed:
json_obj['errors'] = obj.errors
elif obj.is_success:
json_obj['modelOutput'] = obj.model_output
return json_obj |
<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_object(self, name, experiment_id, model_id, argument_defs, arguments=None, properties=None):
"""Create a model run object with the given list of arguments. The initial state of the object is RUNNING. Raises ValueError if given arguments are invalid. Parameters name : string User-provided name for the model run experiment_id : string Unique identifier of associated experiment object model_id : string Unique model identifier argument_defs : list(attribute.AttributeDefinition) Definition of valid arguments for the given model List of attribute instances properties : Dictionary, optional Set of model run properties. Returns ------- PredictionHandle Object handle for created model run """ |
# Create a new object identifier.
identifier = str(uuid.uuid4()).replace('-','')
# Directory for successful model run resource files. Directories are
# simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create the directory if it doesn't exists
if not os.access(directory, os.F_OK):
os.makedirs(directory)
# By default all model runs are in IDLE state at creation
state = ModelRunIdle()
# Create the initial set of properties.
run_properties = {
datastore.PROPERTY_NAME: name,
datastore.PROPERTY_STATE: str(state),
datastore.PROPERTY_MODEL: model_id
}
if not properties is None:
for prop in properties:
if not prop in run_properties:
run_properties[prop] = properties[prop]
# If argument list is not given then the initial set of arguments is
# empty. Here we do not validate the given arguments. Definitions of
# valid argument sets are maintained in the model registry and are not
# accessible by the model run manager at this point.
run_arguments = {}
if not arguments is None:
# Convert arguments to dictionary of Atrribute instances. Will
# raise an exception if values are of invalid type.
run_arguments = attribute.to_dict(arguments, argument_defs)
# Create the image group object and store it in the database before
# returning it.
obj = ModelRunHandle(
identifier,
run_properties,
directory,
state,
experiment_id,
model_id,
run_arguments
)
self.insert_object(obj)
return obj |
<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_dict(self, document):
"""Create model run object from JSON document retrieved from database. Parameters document : JSON Json document in database Returns ------- PredictionHandle Handle for model run object """ |
# Get object identifier from Json document
identifier = str(document['_id'])
# Directories are simply named by object identifier
directory = os.path.join(self.directory, identifier)
# Create attachment descriptors
attachments = {}
for obj in document['attachments']:
attachment = Attachment.from_dict(obj)
attachments[attachment.identifier] = attachment
# Create model run handle.
return ModelRunHandle(
identifier,
document['properties'],
directory,
ModelRunState.from_dict(document['state']),
document['experiment'],
document['model'],
attribute.attributes_from_dict(document['arguments']),
attachments=attachments,
schedule=document['schedule'],
timestamp=datetime.datetime.strptime(
document['timestamp'], '%Y-%m-%dT%H:%M:%S.%f'
),
is_active=document['active']
) |
<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_data_file_attachment(self, identifier, resource_id):
"""Get path to attached data file with given resource identifer. If no data file with given id exists the result will be None. Raise ValueError if an image archive with the given resource identifier is attached to the model run instead of a data file. Parameters identifier : string Unique model run identifier resource_id : string Unique attachment identifier Returns ------- string, string Path to attached data file on disk and attachments MIME type """ |
# Get model run to ensure that it exists. If not return None
model_run = self.get_object(identifier)
if model_run is None:
return None, None
# Ensure that attachment with given resource identifier exists.
if not resource_id in model_run.attachments:
return None, None
# Raise an exception if the attached resource is not a data file
attachment = model_run.attachments[resource_id]
filename = os.path.join(model_run.attachment_directory, resource_id)
return filename, attachment.mime_type |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def to_dict(self, model_run):
"""Create a Json-like dictionary for a model run object. Extends the basic object with run state, arguments, and optional prediction results or error descriptions. Parameters model_run : PredictionHandle Returns ------- (JSON) Json-like object, i.e., dictionary. """ |
# Get the basic Json object from the super class
json_obj = super(DefaultModelRunManager, self).to_dict(model_run)
# Add run state
json_obj['state'] = ModelRunState.to_dict(model_run.state)
# Add run scheduling Timestamps
json_obj['schedule'] = model_run.schedule
# Add experiment information
json_obj['experiment'] = model_run.experiment_id
# Add model information
json_obj['model'] = model_run.model_id
# Transform dictionary of attributes into list of key-value pairs.
json_obj['arguments'] = attribute.attributes_to_dict(model_run.arguments)
# Include attachments
json_obj['attachments'] = [
attachment.to_dict()
for attachment in model_run.attachments.values()
]
return json_obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def update_state(self, identifier, state):
"""Update state of identified model run. Raises exception if state change results in invalid run life cycle. Parameters identifier : string Unique model run identifier state : ModelRunState Object representing new run state Returns ------- ModelRunHandle Modified model run handle or None if no run with given identifier exists """ |
# Get model run to ensure that it exists
model_run = self.get_object(identifier)
if model_run is None:
return None
# Set timestamp of state change. Raise exception if state change results
# in invalid life cycle
timestamp = str(datetime.datetime.utcnow().isoformat())
if state.is_idle:
raise ValueError('invalid state change: run cannot become idle')
elif state.is_running:
# Current state is required to be IDLE
if not model_run.state.is_idle:
raise ValueError('invalid state change: finished run cannot start again')
model_run.schedule[RUN_STARTED] = timestamp
elif state.is_failed:
# Current state is required to be RUNNING
if not (model_run.state.is_running or model_run.state.is_idle):
raise ValueError('invalid state change: cannot fail finished run')
model_run.schedule[RUN_FINISHED] = timestamp
elif state.is_success:
# Current state is required to be RUNNING
if not model_run.state.is_running:
raise ValueError('invalid state change: cannot finish inactive run')
model_run.schedule[RUN_FINISHED] = timestamp
# Update model run state and replace object in database
model_run.state = state
model_run.properties[datastore.PROPERTY_STATE] = str(state)
self.replace_object(model_run)
# Return modified model run
return model_run |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def partial_update(self, request, *args, **kwargs):
""" We do not include the mixin as we want only PATCH and no PUT """ |
instance = self.get_object()
serializer = self.get_serializer(instance, data=request.data, partial=True, context=self.get_serializer_context())
serializer.is_valid(raise_exception=True)
serializer.save()
if getattr(instance, '_prefetched_objects_cache', None): #pragma: no cover
instance = self.get_object()
serializer = self.get_serializer(instance)
return response.Response(serializer.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 connect(self):
''' connect to the remote host '''
vvv("ESTABLISH CONNECTION FOR USER: %s" % self.runner.remote_user, host=self.host)
self.common_args = []
extra_args = C.ANSIBLE_SSH_ARGS
if extra_args is not None:
self.common_args += shlex.split(extra_args)
else:
self.common_args += ["-o", "ControlMaster=auto",
"-o", "ControlPersist=60s",
"-o", "ControlPath=/tmp/ansible-ssh-%h-%p-%r"]
self.common_args += ["-o", "StrictHostKeyChecking=no"]
if self.port is not None:
self.common_args += ["-o", "Port=%d" % (self.port)]
if self.runner.private_key_file is not None:
self.common_args += ["-o", "IdentityFile="+os.path.expanduser(self.runner.private_key_file)]
if self.runner.remote_pass:
self.common_args += ["-o", "GSSAPIAuthentication=no",
"-o", "PubkeyAuthentication=no"]
else:
self.common_args += ["-o", "KbdInteractiveAuthentication=no",
"-o", "PasswordAuthentication=no"]
self.common_args += ["-o", "User="+self.runner.remote_user]
return self |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def fetch_file(self, in_path, out_path):
''' fetch a file from remote to local '''
vvv("FETCH %s TO %s" % (in_path, out_path), host=self.host)
cmd = self._password_cmd()
if C.DEFAULT_SCP_IF_SSH:
cmd += ["scp"] + self.common_args
cmd += [self.host + ":" + in_path, out_path]
indata = None
else:
cmd += ["sftp"] + self.common_args + [self.host]
indata = "get %s %s\n" % (in_path, out_path)
p = subprocess.Popen(cmd, stdin=subprocess.PIPE,
stdout=subprocess.PIPE, stderr=subprocess.PIPE)
self._send_password()
stdout, stderr = p.communicate(indata)
if p.returncode != 0:
raise errors.AnsibleError("failed to transfer file from %s:\n%s\n%s" % (in_path, stdout, stderr)) |
<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_form(self, request, form, change):
""" Super class ordering is important here - user must get saved first. """ |
OwnableAdmin.save_form(self, request, form, change)
return DisplayableAdmin.save_form(self, request, form, change) |
<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_module_permission(self, request):
""" Hide from the admin menu unless explicitly set in ``ADMIN_MENU_ORDER``. """ |
for (name, items) in settings.ADMIN_MENU_ORDER:
if "blog.BlogCategory" in items:
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 env(*vars, **kwargs):
"""Returns the first environment variable set. If none are non-empty, defaults to '' or keyword arg default. """ |
for v in vars:
value = os.environ.get(v)
if value:
return value
return kwargs.get('default', '') |
<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_client_class(api_name, version, version_map):
"""Returns the client class for the requested API version. :param api_name: the name of the API, e.g. 'compute', 'image', etc :param version: the requested API version :param version_map: a dict of client classes keyed by version :rtype: a client class for the requested API version """ |
try:
client_path = version_map[str(version)]
except (KeyError, ValueError):
msg = _("Invalid %(api_name)s client version '%(version)s'. must be "
"one of: %(map_keys)s")
msg = msg % {'api_name': api_name, 'version': version,
'map_keys': ', '.join(version_map.keys())}
raise exceptions.UnsupportedVersion(msg)
return importutils.import_class(client_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 get_item_properties(item, fields, mixed_case_fields=(), formatters=None):
"""Return a tuple containing the item properties. :param item: a single item resource (e.g. Server, Tenant, etc) :param fields: tuple of strings with the desired field names :param mixed_case_fields: tuple of field names to preserve case :param formatters: dictionary mapping field names to callables to format the values """ |
if formatters is None:
formatters = {}
row = []
for field in fields:
if field in formatters:
row.append(formatters[field](item))
else:
if field in mixed_case_fields:
field_name = field.replace(' ', '_')
else:
field_name = field.lower().replace(' ', '_')
if not hasattr(item, field_name) and isinstance(item, dict):
data = item[field_name]
else:
data = getattr(item, field_name, '')
if data is None:
data = ''
row.append(data)
return tuple(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 str2dict(strdict, required_keys=None, optional_keys=None):
:param strdict: string in the form of key1=value1,key2=value2 :param required_keys: list of required keys. All keys in this list must be specified. Otherwise ArgumentTypeError will be raised. If this parameter is unspecified, no required key check will be done. :param optional_keys: list of optional keys. This parameter is used for valid key check. When at least one of required_keys and optional_keys, a key must be a member of either of required_keys or optional_keys. Otherwise, ArgumentTypeError will be raised. When both required_keys and optional_keys are unspecified, no valid key check will be done. """ |
result = {}
if strdict:
for kv in strdict.split(','):
key, sep, value = kv.partition('=')
if not sep:
msg = _("invalid key-value '%s', expected format: key=value")
raise argparse.ArgumentTypeError(msg % kv)
result[key] = value
valid_keys = set(required_keys or []) | set(optional_keys or [])
if valid_keys:
invalid_keys = [k for k in result if k not in valid_keys]
if invalid_keys:
msg = _("Invalid key(s) '%(invalid_keys)s' specified. "
"Valid key(s): '%(valid_keys)s'.")
raise argparse.ArgumentTypeError(
msg % {'invalid_keys': ', '.join(sorted(invalid_keys)),
'valid_keys': ', '.join(sorted(valid_keys))})
if required_keys:
not_found_keys = [k for k in required_keys if k not in result]
if not_found_keys:
msg = _("Required key(s) '%s' not specified.")
raise argparse.ArgumentTypeError(msg % ', '.join(not_found_keys))
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 loads(cls, data):
'''Create a feature collection from a CBOR byte string.'''
rep = cbor.loads(data)
if not isinstance(rep, Sequence):
raise SerializationError('expected a CBOR list')
if len(rep) != 2:
raise SerializationError('expected a CBOR list of 2 items')
metadata = rep[0]
if 'v' not in metadata:
raise SerializationError('no version in CBOR metadata')
if metadata['v'] != 'fc01':
raise SerializationError('invalid CBOR version {!r} '
'(expected "fc01")'
.format(metadata['v']))
read_only = metadata.get('ro', False)
contents = rep[1]
return cls.from_dict(contents, read_only=read_only) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def dumps(self):
'''Create a CBOR byte string from a feature collection.'''
metadata = {'v': 'fc01'}
if self.read_only:
metadata['ro'] = 1
rep = [metadata, self.to_dict()]
return cbor.dumps(rep) |
<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_dict(cls, data, read_only=False):
'''Recreate a feature collection from a dictionary.
The dictionary is of the format dumped by :meth:`to_dict`.
Additional information, such as whether the feature collection
should be read-only, is not included in this dictionary, and
is instead passed as parameters to this function.
'''
fc = cls(read_only=read_only)
fc._features = {}
fc._from_dict_update(data)
return fc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def to_dict(self):
'''Dump a feature collection's features to a dictionary.
This does not include additional data, such as whether
or not the collection is read-only. The returned dictionary
is suitable for serialization into JSON, CBOR, or similar
data formats.
'''
def is_non_native_sc(ty, encoded):
return (ty == 'StringCounter'
and not is_native_string_counter(encoded))
fc = {}
native = ('StringCounter', 'Unicode')
for name, feat in self._features.iteritems():
if name.startswith(self.EPHEMERAL_PREFIX):
continue
if not isinstance(name, unicode):
name = name.decode('utf-8')
tyname = registry.feature_type_name(name, feat)
encoded = registry.get(tyname).dumps(feat)
# This tomfoolery is to support *native untagged* StringCounters.
if tyname not in native or is_non_native_sc(tyname, encoded):
encoded = cbor.Tag(cbor_names_to_tags[tyname], encoded)
fc[name] = encoded
return fc |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def merge_with(self, other, multiset_op, other_op=None):
'''Merge this feature collection with another.
Merges two feature collections using the given ``multiset_op``
on each corresponding multiset and returns a new
:class:`FeatureCollection`. The contents of the two original
feature collections are not modified.
For each feature name in both feature sets, if either feature
collection being merged has a :class:`collections.Counter`
instance as its value, then the two values are merged by
calling `multiset_op` with both values as parameters. If
either feature collection has something other than a
:class:`collections.Counter`, and `other_op` is not
:const:`None`, then `other_op` is called with both values to
merge them. If `other_op` is :const:`None` and a feature
is not present in either feature collection with a counter
value, then the feature will not be present in the result.
:param other: The feature collection to merge into ``self``.
:type other: :class:`FeatureCollection`
:param multiset_op: Function to merge two counters
:type multiset_op: fun(Counter, Counter) -> Counter
:param other_op: Function to merge two non-counters
:type other_op: fun(object, object) -> object
:rtype: :class:`FeatureCollection`
'''
result = FeatureCollection()
for ms_name in set(self._counters()) | set(other._counters()):
c1 = self.get(ms_name, None)
c2 = other.get(ms_name, None)
if c1 is None and c2 is not None:
c1 = c2.__class__()
if c2 is None and c1 is not None:
c2 = c1.__class__()
result[ms_name] = multiset_op(c1, c2)
if other_op is not None:
for o_name in (set(self._not_counters()) |
set(other._not_counters())):
v = other_op(self.get(o_name, None), other.get(o_name, None))
if v is not None:
result[o_name] = v
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 total(self):
'''
Returns sum of all counts in all features that are multisets.
'''
feats = imap(lambda name: self[name], self._counters())
return sum(chain(*map(lambda mset: map(abs, mset.values()), feats))) |
<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(self, name, obj):
'''Register a new feature serializer.
The feature type should be one of the fixed set of feature
representations, and `name` should be one of ``StringCounter``,
``SparseVector``, or ``DenseVector``. `obj` is a describing
object with three fields: `constructor` is a callable that
creates an empty instance of the representation; `dumps` is
a callable that takes an instance of the representation and
returns a JSON-compatible form made of purely primitive
objects (lists, dictionaries, strings, numbers); and `loads`
is a callable that takes the response from `dumps` and recreates
the original representation.
Note that ``obj.constructor()`` *must* return an
object that is an instance of one of the following
types: ``unicode``, :class:`dossier.fc.StringCounter`,
:class:`dossier.fc.SparseVector` or
:class:`dossier.fc.DenseVector`. If it isn't, a
:exc:`ValueError` is raised.
'''
ro = obj.constructor()
if name not in cbor_names_to_tags:
print(name)
raise ValueError(
'Unsupported feature type name: "%s". '
'Allowed feature type names: %r'
% (name, cbor_names_to_tags.keys()))
if not is_valid_feature_instance(ro):
raise ValueError(
'Constructor for "%s" returned "%r" which has an unknown '
'sub type "%r". (mro: %r). Object must be an instance of '
'one of the allowed types: %r'
% (name, ro, type(ro), type(ro).mro(), ALLOWED_FEATURE_TYPES))
self._registry[name] = {'obj': obj, 'ro': obj.constructor()}
self._inverse[obj.constructor] = 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 instance_contains(container, item):
"""Search into instance attributes, properties and return values of no-args methods.""" |
return item in (member for _, member in inspect.getmembers(container)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def contains(container, item):
"""Extends ``operator.contains`` by trying very hard to find ``item`` inside container.""" |
# equality counts as containment and is usually non destructive
if container == item:
return True
# testing mapping containment is usually non destructive
if isinstance(container, abc.Mapping) and mapping_contains(container, item):
return True
# standard containment except special cases
if isinstance(container, str):
# str __contains__ includes substring match that we don't count as containment
if strict_contains(container, item):
return True
else:
try:
if item in container:
return True
except Exception:
pass
# search matches in generic instances
return instance_contains(container, item) |
<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_brightness(self, brightness):
|
brightness = min([1.0, max([brightness, 0.0])]) # enforces range 0 ... 1
self.state.brightness = brightness
self._repeat_last_frame()
sequence_number = self.zmq_publisher.publish_brightness(brightness)
logging.debug("Set brightness to {brightPercent:05.1f}%".format(brightPercent=brightness*100))
return (True, sequence_number, "OK") |
<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_animation(self, animation_class):
"""Add a new animation""" |
self.state.animationClasses.append(animation_class)
return len(self.state.animationClasses) - 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 add_scene(self, animation_id, name, color, velocity, config):
"""Add a new scene, returns Scene ID""" |
# check arguments
if animation_id < 0 or animation_id >= len(self.state.animationClasses):
err_msg = "Requested to register scene with invalid Animation ID. Out of range."
logging.info(err_msg)
return(False, 0, err_msg)
if self.state.animationClasses[animation_id].check_config(config) is False:
err_msg = "Requested to register scene with invalid configuration."
logging.info(err_msg)
return(False, 0, err_msg)
self.state.sceneIdCtr += 1
self.state.scenes[self.state.sceneIdCtr] = Scene(animation_id, name, color, velocity, config)
sequence_number = self.zmq_publisher.publish_scene_add(self.state.sceneIdCtr, animation_id, name, color, velocity, config)
logging.debug("Registered new scene.")
# set this scene as active scene if none is configured yet
if self.state.activeSceneId is None:
self.set_scene_active(self.state.sceneIdCtr)
return (True, sequence_number, "OK") |
<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_scene(self, scene_id):
"""remove a scene by Scene ID""" |
if self.state.activeSceneId == scene_id:
err_msg = "Requested to delete scene {sceneNum}, which is currently active. Cannot delete active scene.".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
try:
del self.state.scenes[scene_id]
logging.debug("Deleted scene {sceneNum}".format(sceneNum=scene_id))
except KeyError:
err_msg = "Requested to delete scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
# if we are here, we deleted a scene, so publish it
sequence_number = self.zmq_publisher.publish_scene_remove(scene_id)
logging.debug("Removed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") |
<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_scene_name(self, scene_id, name):
"""rename a scene by scene ID""" |
if not scene_id in self.state.scenes: # does that scene_id exist?
err_msg = "Requested to rename scene {sceneNum}, which does not exist".format(sceneNum=scene_id)
logging.info(err_msg)
return(False, 0, err_msg)
self.state.scenes[scene_id] = self.state.scenes[scene_id]._replace(name=name) # TODO: is there a better solution?
sequence_number = self.zmq_publisher.publish_scene_name(scene_id, name)
logging.debug("Renamed scene {sceneNum}".format(sceneNum=scene_id))
return (True, sequence_number, "OK") |
<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_scene_active(self, scene_id):
"""sets the active scene by scene ID""" |
if self.state.activeSceneId != scene_id: # do nothing if scene has not changed
self._deactivate_scene()
sequence_number = self.zmq_publisher.publish_active_scene(scene_id)
self.state.activeSceneId = scene_id
if self.state.mainswitch is True: # activate scene only if we are switched on
self._activate_scene()
logging.debug("Set scene {sceneNum} as active scene".format(sceneNum=scene_id))
return (True, sequence_number, "OK")
else:
logging.debug("Scene {sceneNum} already is active scene".format(sceneNum=scene_id))
return (False, 0, "This already is the activated scene.") |
<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_mainswitch_state(self, state):
"""Turns output on or off. Also turns hardware on ir off""" |
if self.state.mainswitch == state:
err_msg = "MainSwitch unchanged, already is {sState}".format(sState="On" if state else "Off") # fo obar lorem ipsum
logging.debug(err_msg) # fo obar lorem ipsum
return (False, 0, err_msg) # because nothing changed
self.state.mainswitch = state
sequence_number = self.zmq_publisher.publish_mainswitch_state(state)
logging.debug("MainSwitch toggled, new state is {sState}".format(sState="On" if state else "Off")) # fo obar lorem ipsum
if state is True:
self.hw_communication.switch_on()
self._activate_scene() # reinit scene
else:
self._deactivate_scene()
self.hw_communication.switch_off()
return (True, sequence_number, "OK") |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def execute(self):
"""Execute Main Loop""" |
try:
logging.debug("Entering IOLoop")
self.loop.start()
logging.debug("Leaving IOLoop")
except KeyboardInterrupt:
logging.debug("Leaving IOLoop by KeyboardInterrupt")
finally:
self.hw_communication.disconnect() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def publish_brightness(self, brightness):
"""publish changed brightness""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.brightness(self.sequence_number, brightness))
return self.sequence_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 publish_mainswitch_state(self, state):
"""publish changed mainswitch state""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.mainswitch_state(self.sequence_number, state))
return self.sequence_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 publish_active_scene(self, scene_id):
"""publish changed active scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_active(self.sequence_number, scene_id))
return self.sequence_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 publish_scene_add(self, scene_id, animation_id, name, color, velocity, config):
"""publish added scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_add(self.sequence_number, scene_id, animation_id, name, color, velocity, config))
return self.sequence_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 publish_scene_remove(self, scene_id):
"""publish the removal of a scene""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_remove(self.sequence_number, scene_id))
return self.sequence_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 publish_scene_name(self, scene_id, name):
"""publish a changed scene name""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_name(self.sequence_number, scene_id, name))
return self.sequence_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 publish_scene_config(self, scene_id, config):
"""publish a changed scene configuration""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_config(self.sequence_number, scene_id, config))
return self.sequence_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 publish_scene_color(self, scene_id, color):
"""publish a changed scene color""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_color(self.sequence_number, scene_id, color))
return self.sequence_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 publish_scene_velocity(self, scene_id, velocity):
"""publish a changed scene velovity""" |
self.sequence_number += 1
self.publisher.send_multipart(msgs.MessageBuilder.scene_velocity(self.sequence_number, scene_id, velocity))
return self.sequence_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 handle_snapshot(self, msg):
"""Handles a snapshot request""" |
logging.debug("Sending state snapshot request")
identity = msg[0]
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.mainswitch_state(self.sequence_number, self.app.state.mainswitch))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.brightness(self.sequence_number, self.app.state.brightness))
for animation_id, anim in enumerate(self.app.state.animationClasses):
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.animation_add(self.sequence_number, animation_id, anim.name))
for scene_id, scene in self.app.state.scenes.items():
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_add(
self.sequence_number, scene_id, scene.animation_id, scene.name, scene.color, scene.velocity, scene.config))
self.snapshot.send_multipart([identity] + msgs.MessageBuilder.scene_active(
self.sequence_number, 0 if self.app.state.activeSceneId is None else self.app.state.activeSceneId)) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def handle_collect(self, msg):
"""handle an incoming message""" |
(success, sequence_number, comment) = self._handle_collect(msg)
self.collector.send_multipart(msgs.MessageWriter().bool(success).uint64(sequence_number).string(comment).get()) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def with_uvloop_if_possible(f, *args, **kwargs):
""" Simple decorator to provide optional uvloop usage""" |
try:
import uvloop
import asyncio
asyncio.set_event_loop_policy(uvloop.EventLoopPolicy())
print('uvloop will be used')
except ImportError:
print('uvloop unavailable')
return f(*args, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def initialize():
""" Initializes the global NST instance with the current NST and begins tracking """ |
NST.running = True
pg = Page("http://www.neopets.com/")
curtime = pg.find("td", {'id': 'nst'}).text
NST.curTime = datetime.datetime.strptime(curtime.replace(" NST", ""), "%I:%M:%S %p") + datetime.timedelta(0,2)
NST.inst = NST()
NST.daemon = True # Ensures the thread is properly destroyed when the master thread terminates
NST.inst.start() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _attach_to_model(self, model):
""" Check that the model can handle dynamic fields """ |
if not issubclass(model, ModelWithDynamicFieldMixin):
raise ImplementationError(
'The "%s" model does not inherit from ModelWithDynamicFieldMixin '
'so the "%s" DynamicField cannot be attached to it' % (
model.__name__, self.name))
super(DynamicFieldMixin, self)._attach_to_model(model)
if self.dynamic_version_of is not None:
return
if hasattr(model, self.name):
return
setattr(model, self.name, self) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def delete(self):
""" If a dynamic version, delete it the standard way and remove it from the inventory, else delete all dynamic versions. """ |
if self.dynamic_version_of is None:
self._delete_dynamic_versions()
else:
super(DynamicFieldMixin, self).delete()
self._inventory.srem(self.dynamic_part) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _delete_dynamic_versions(self):
""" Call the `delete` method of all dynamic versions of the current field found in the inventory then clean the inventory. """ |
if self.dynamic_version_of:
raise ImplementationError(u'"_delete_dynamic_versions" can only be '
u'executed on the base field')
inventory = self._inventory
for dynamic_part in inventory.smembers():
name = self.get_name_for(dynamic_part)
# create the field
new_field = self._create_dynamic_version()
new_field.name = name
new_field._dynamic_part = dynamic_part # avoid useless computation
new_field._attach_to_model(self._model)
new_field._attach_to_instance(self._instance)
# and delete its content
new_field.delete()
inventory.delete() |
<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_name_for(self, dynamic_part):
""" Compute the name of the variation of the current dynamic field based on the given dynamic part. Use the "format" attribute to create the final name. """ |
name = self.format % dynamic_part
if not self._accept_name(name):
raise ImplementationError('It seems that pattern and format do not '
'match for the field "%s"' % self.name)
return 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 get_for(self, dynamic_part):
""" Return a variation of the current dynamic field based on the given dynamic part. Use the "format" attribute to create the final name """ |
if not hasattr(self, '_instance'):
raise ImplementationError('"get_for" can be used only on a bound field')
name = self.get_name_for(dynamic_part)
return self._instance.get_field(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 threadsafe_generator(generator_func):
"""A decorator that takes a generator function and makes it thread-safe. """ |
def decoration(*args, **keyword_args):
"""A thread-safe decoration for a generator function."""
return ThreadSafeIter(generator_func(*args, **keyword_args))
return decoration |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def lazy_property(function):
"""Cache the first return value of a function for all subsequent calls. This decorator is usefull for argument-less functions that behave more like a global or static property that should be calculated once, but lazily (i.e. only if requested). """ |
cached_val = []
def _wrapper(*args):
try:
return cached_val[0]
except IndexError:
ret_val = function(*args)
cached_val.append(ret_val)
return ret_val
return _wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cat(self, numlines=None):
"""Return a list of lines output by this service.""" |
if len(self.titles) == 1:
lines = self.lines()
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("\n".join(lines))
else:
lines = [self._printtuple(line[0], line[1]) for line in self.lines()]
if numlines is not None:
lines = lines[len(lines)-numlines:]
log("".join(lines)) |
<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_service(self, line_with_color):
"""Return line if line matches this service's name, return None otherwise.""" |
line = re.compile("(\x1b\[\d+m)+").sub("", line_with_color) # Strip color codes
regexp = re.compile(r"^\[(.*?)\]\s(.*?)$")
if regexp.match(line):
title = regexp.match(line).group(1).strip()
if title in self.titles:
return (title, regexp.match(line).group(2))
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 json(self):
"""Return a list of JSON objects output by this service.""" |
lines = []
for line in self.lines():
try:
if len(line) == 1:
lines.append(json.loads(line, strict=False))
else:
lines.append(json.loads(line[1], strict=False))
except ValueError:
pass
return lines |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def restore_dict_kv(a_dict, key, copy_func=copy.deepcopy):
"""Backup an object in a with context and restore it when leaving the scope. :param a_dict: associative table :param: key key whose value has to be backed up :param copy_func: callbable object used to create an object copy. default is `copy.deepcopy` """ |
exists = False
if key in a_dict:
backup = copy_func(a_dict[key])
exists = True
try:
yield
finally:
if exists:
a_dict[key] = backup
else:
a_dict.pop(key, 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 popen(*args, **kwargs):
"""Run a process in background in a `with` context. Parameters given to this function are passed to `subprocess.Popen`. Process is kill when exiting the context. """ |
process = subprocess.Popen(*args, **kwargs)
try:
yield process.pid
finally:
os.kill(process.pid, signal.SIGTERM)
os.waitpid(process.pid, 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 coerce(self, value):
""" Takes one or two values in the domain and returns a LinearOrderedCell with the same domain """ |
if isinstance(value, LinearOrderedCell) and (self.domain == value.domain or \
list_diff(self.domain, value.domain) == []):
# is LinearOrderedCell with same domain
return value
elif value in self.domain:
return LinearOrderedCell(self.domain, value, value)
elif isinstance(value, (list, tuple)) and all(map(value in self.domain, value)):
if len(value) == 1:
return LinearOrderedCell(self.domain, value[0], value[0])
elif len(value) == 2:
return LinearOrderedCell(self.domain, *value)
else:
sorted_vals = sorted(value, key=lambda x: self.to_i(x))
return LinearOrderedCell(self.domain, sorted_vals[0], sorted_vals[-1])
else:
raise Exception("Cannot coerce %s into LinearOrderedCell" % (str(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 coerce(value):
""" Turns a value into a list """ |
if isinstance(value, ListCell):
return value
elif isinstance(value, (list)):
return ListCell(value)
else:
return ListCell([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 append(self, el):
""" Idiosynractic method for adding an element to a list """ |
if self.value is None:
self.value = [el]
else:
self.value.append(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 merge(self, other):
""" Merges two prefixes """ |
other = PrefixCell.coerce(other)
if self.is_equal(other):
# pick among dependencies
return self
elif other.is_entailed_by(self):
return self
elif self.is_entailed_by(other):
self.value = other.value
elif self.is_contradictory(other):
raise Contradiction("Cannot merge prefix '%s' with '%s'" % \
(self, other))
else:
if len(self.value) > len(other.value):
self.value = other.value[:]
# otherwise, return self
return self |
<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_template(self, context, **kwargs):
""" Returns the template to be used for the current context and arguments. """ |
if 'template' in kwargs['params']:
self.template = kwargs['params']['template']
return super(GoscaleTemplateInclusionTag, self).get_template(context, **kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def admin_keywords_submit(request):
""" Adds any new given keywords from the custom keywords field in the admin, and returns their IDs for use when saving a model with a keywords field. """ |
keyword_ids, titles = [], []
remove = punctuation.replace("-", "") # Strip punctuation, allow dashes.
for title in request.POST.get("text_keywords", "").split(","):
title = "".join([c for c in title if c not in remove]).strip()
if title:
kw, created = Keyword.objects.get_or_create_iexact(title=title)
keyword_id = str(kw.id)
if keyword_id not in keyword_ids:
keyword_ids.append(keyword_id)
titles.append(title)
return HttpResponse("%s|%s" % (",".join(keyword_ids), ", ".join(titles)),
content_type='text/plain') |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def comment(request, template="generic/comments.html", extra_context=None):
""" Handle a ``ThreadedCommentForm`` submission and redirect back to its related object. """ |
response = initial_validation(request, "comment")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
form_class = import_dotted_path(settings.COMMENT_FORM_CLASS)
form = form_class(request, obj, post_data)
if form.is_valid():
url = obj.get_absolute_url()
if is_spam(request, form, url):
return redirect(url)
comment = form.save(request)
response = redirect(add_cache_bypass(comment.get_absolute_url()))
# Store commenter's details in a cookie for 90 days.
for field in ThreadedCommentForm.cookie_fields:
cookie_name = ThreadedCommentForm.cookie_prefix + field
cookie_value = post_data.get(field, "")
set_cookie(response, cookie_name, cookie_value)
return response
elif request.is_ajax() and form.errors:
return HttpResponse(dumps({"errors": form.errors}))
# Show errors with stand-alone comment form.
context = {"obj": obj, "posted_comment_form": form}
context.update(extra_context or {})
return TemplateResponse(request, template, context) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def rating(request):
""" Handle a ``RatingForm`` submission and redirect back to its related object. """ |
response = initial_validation(request, "rating")
if isinstance(response, HttpResponse):
return response
obj, post_data = response
url = add_cache_bypass(obj.get_absolute_url().split("#")[0])
response = redirect(url + "#rating-%s" % obj.id)
rating_form = RatingForm(request, obj, post_data)
if rating_form.is_valid():
rating_form.save()
if request.is_ajax():
# Reload the object and return the rating fields as json.
obj = obj.__class__.objects.get(id=obj.id)
rating_name = obj.get_ratingfield_name()
json = {}
for f in ("average", "count", "sum"):
json["rating_" + f] = getattr(obj, "%s_%s" % (rating_name, f))
response = HttpResponse(dumps(json))
if rating_form.undoing:
ratings = set(rating_form.previous) ^ set([rating_form.current])
else:
ratings = rating_form.previous + [rating_form.current]
set_cookie(response, "yacms-rating", ",".join(ratings))
return response |
<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(self, obj, metadata=None, update=False):
""" Add an existing CDSTAR object to the catalog. :param obj: A pycdstar.resource.Object instance """ |
if (obj not in self) or update:
self[obj.id] = Object.fromdict(
obj.id,
dict(
metadata=obj.metadata.read() if metadata is None else metadata,
bitstreams=[bs._properties for bs in obj.bitstreams]))
time.sleep(0.1)
return self.objects[obj.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 delete(self, obj):
""" Delete an object in CDSTAR and remove it from the catalog. :param obj: An object ID or an Object instance. """ |
obj = self.api.get_object(getattr(obj, 'id', obj))
obj.delete()
self.remove(obj.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 create(self, path, metadata, filter_=filter_hidden, object_class=None):
""" Create objects in CDSTAR and register them in the catalog. Note that we guess the mimetype based on the filename extension, using `mimetypes.guess_type`. Thus, it is the caller's responsibility to add custom or otherwise uncommon types to the list of known types using `mimetypes.add_type`. :param path: :param metadata: :param filter_: :return: """ |
path = Path(path)
if path.is_file():
fnames = [path]
elif path.is_dir():
fnames = list(walk(path, mode='files'))
else:
raise ValueError('path must be a file or directory') # pragma: no cover
for fname in fnames:
if not filter_ or filter_(fname):
created, obj = self._create(fname, metadata, object_class=object_class)
yield fname, created, obj |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csep_close(ra, rb):
"""Return the closest separation vector between each point in one set, and every point in a second set. Parameters ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. `ra` is the set of points from which the closest separation vectors to points `rb` are calculated. Returns ------- csep_close: float array-like, shape (n, m, d) csep[i] is the closest separation vector from point ra[j] to any point rb[i]. Note the un-intuitive vector direction. """ |
seps = csep(ra, rb)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csep_periodic(ra, rb, L):
"""Return separation vectors between each pair of the two sets of points. Parameters ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. L: float array, shape (d,) System lengths. Returns ------- csep: float array-like, shape (n, m, d) csep[i, j] is the separation vector from point j to point i. Note the un-intuitive vector direction. """ |
seps = ra[:, np.newaxis, :] - rb[np.newaxis, :, :]
for i_dim in range(ra.shape[1]):
seps_dim = seps[:, :, i_dim]
seps_dim[seps_dim > L[i_dim] / 2.0] -= L[i_dim]
seps_dim[seps_dim < -L[i_dim] / 2.0] += L[i_dim]
return seps |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def csep_periodic_close(ra, rb, L):
"""Return the closest separation vector between each point in one set, and every point in a second set, in periodic space. Parameters ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. `ra` is the set of points from which the closest separation vectors to points `rb` are calculated. L: float array, shape (d,) System lengths. Returns ------- csep_close: float array-like, shape (n, m, d) csep[i] is the closest separation vector from point ra[j] to any point rb[i]. Note the un-intuitive vector direction. """ |
seps = csep_periodic(ra, rb, L)
seps_sq = np.sum(np.square(seps), axis=-1)
i_close = np.argmin(seps_sq, axis=-1)
i_all = list(range(len(seps)))
sep = seps[i_all, i_close]
sep_sq = seps_sq[i_all, i_close]
return sep, sep_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def cdist_sq_periodic(ra, rb, L):
"""Return the squared distance between each point in on set, and every point in a second set, in periodic space. Parameters ra, rb: float array-like, shape (n, d) and (m, d) in d dimensions. Two sets of points. L: float array, shape (d,) System lengths. Returns ------- cdist_sq: float array-like, shape (n, m, d) cdist_sq[i, j] is the squared distance between point j and point i. """ |
return np.sum(np.square(csep_periodic(ra, rb, L)), axis=-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 pdist_sq_periodic(r, L):
"""Return the squared distance between all combinations of a set of points, in periodic space. Parameters r: shape (n, d) for n points in d dimensions. Set of points L: float array, shape (d,) System lengths. Returns ------- d_sq: float array, shape (n, n, d) Squared distances """ |
d = csep_periodic(r, r, L)
d[np.identity(len(r), dtype=np.bool)] = np.inf
d_sq = np.sum(np.square(d), axis=-1)
return d_sq |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def angular_distance(n1, n2):
"""Return the angular separation between two 3 dimensional vectors. Parameters n1, n2: array-like, shape (3,) Coordinates of two vectors. Their magnitude does not matter. Returns ------- d_sigma: float Angle between n1 and n2 in radians. """ |
return np.arctan2(vector.vector_mag(np.cross(n1, n2)), np.dot(n1, n2)) |
<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_namedtuple(cls, field_mappings, name="Record"):
"""Gets a namedtuple class that matches the destination_names in the list of field_mappings.""" |
return namedtuple(name, [fm.destination_name for fm in field_mappings]) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def transfer(cls, field_mappings, source, destination_factory):
"""Convert a record to a dictionary via field_mappings, and pass that to destination_factory.""" |
data = dict()
for index, field_mapping in enumerate(field_mappings):
try:
data[field_mapping.destination_name] = field_mapping.get_value(source)
except Exception as ex:
raise Exception(
"Error with mapping #{0} '{1}'->'{2}': {3}".format(
index,
field_mapping.source_name,
field_mapping.destination_name, ex)) from ex
return destination_factory(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 transfer_all(cls, field_mappings, sources, destination_factory=None):
"""Calls cls.transfer on all records in sources.""" |
for index, source in enumerate(sources):
try:
yield cls.transfer(field_mappings, source, destination_factory or (lambda x: x))
except Exception as ex:
raise Exception("Error with source #{0}: {1}".format(index, ex)) from ex |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def merge_dict(lhs, rhs):
""" Merge content of a dict in another :param: dict: lhs dict where is merged the second one :param: dict: rhs dict whose content is merged """ |
assert isinstance(lhs, dict)
assert isinstance(rhs, dict)
for k, v in rhs.iteritems():
if k not in lhs:
lhs[k] = v
else:
lhs[k] = merge_dict(lhs[k], v)
return lhs |
<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_yaml(*streams):
""" Build voluptuous.Schema function parameters from a streams of YAMLs """ |
return from_dict(merge_dicts(*map(
lambda f: yaml.load(f, Loader=Loader),
list(streams)
))) |
<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_config(raise_=True):
""" Verifies that all configuration values have a valid setting """ |
ELIBConfig.check()
known_paths = set()
duplicate_values = set()
missing_values = set()
for config_value in ConfigValue.config_values:
if config_value.path not in known_paths:
known_paths.add(config_value.path)
else:
duplicate_values.add(config_value.name)
try:
config_value()
except MissingValueError:
missing_values.add(config_value.name)
if raise_ and duplicate_values:
raise DuplicateConfigValueError(str(duplicate_values))
if raise_ and missing_values:
raise MissingValueError(str(missing_values), 'missing config value(s)')
return duplicate_values, missing_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 groupby(iterable, key=None):
""" Group items from iterable by key and return a dictionary where values are the lists of items from the iterable having the same key. :param key: function to apply to each element of the iterable. If not specified or is None key defaults to identity function and returns the element unchanged. :Example: {True: [0, 2], False: [1, 3]} """ |
groups = {}
for item in iterable:
if key is None:
key_value = item
else:
key_value = key(item)
groups.setdefault(key_value, []).append(item)
return groups |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def enter(clsQname):
""" Delegate a rule to another class which instantiates a Klein app This also memoizes the resource instance on the handler function itself """ |
def wrapper(routeHandler):
@functools.wraps(routeHandler)
def inner(self, request, *a, **kw):
if getattr(inner, '_subKlein', None) is None:
cls = namedAny(clsQname)
inner._subKlein = cls().app.resource()
return routeHandler(self, request, inner._subKlein, *a, **kw)
inner._subKleinQname = clsQname
return inner
return wrapper |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def openAPIDoc(**kwargs):
""" Update a function's docstring to include the OpenAPI Yaml generated by running the openAPIGraph object """ |
s = yaml.dump(kwargs, default_flow_style=False)
def deco(routeHandler):
# Wrap routeHandler, retaining name and __doc__, then edit __doc__.
# The only reason we need to do this is so we can be certain
# that __doc__ will be modifiable. partial() objects have
# a modifiable __doc__, but native function objects do not.
ret = functools.wraps(routeHandler)(routeHandler)
if not ret.__doc__:
ret.__doc__ = ''
ret.__doc__ = cleandoc(ret.__doc__) + '\n---\n' + s
return ret
return deco |
<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_app(application):
""" Associates the error handler """ |
for code in werkzeug.exceptions.default_exceptions:
application.register_error_handler(code, handle_http_exception) |
<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_palettes(stream):
''' Need to configure palettes manually, since we are checking stderr. '''
chosen = choose_palette(stream=stream)
palettes = get_available_palettes(chosen)
fg = ForegroundPalette(palettes=palettes)
fx = EffectsPalette(palettes=palettes)
return fg, fx, chosen |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def configure(self, **kwargs):
''' Convenience function to set a number of parameters on this logger
and associated handlers and formatters.
'''
for kwarg in kwargs:
value = kwargs[kwarg]
if kwarg == 'level':
self.set_level(value)
elif kwarg == 'default_level':
self.default_level = level_map.get(value, value)
elif kwarg == 'datefmt':
self.handlers[0].formatter.datefmt = value
elif kwarg == 'msgfmt':
self.handlers[0].formatter._style._fmt = value
elif kwarg == 'stream':
global fg, fx, _CHOSEN_PALETTE
self.handlers[0].stream = value
fg, fx, _CHOSEN_PALETTE = _find_palettes(value)
elif kwarg == 'theme':
if type(value) is str:
theme = _themes[value]
if value == 'plain':
fmtr = logging.Formatter(style='{', **theme)
elif value == 'json':
fmtr = _JSONFormatter(**theme)
else:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
elif type(value) is dict:
if 'style' in value or 'icons' in value:
fmtr = _ColorFormatter(tty=_is_a_tty, **theme)
else:
fmtr = logging.Formatter(style='{', **theme)
self.handlers[0].setFormatter(fmtr)
elif kwarg == 'icons':
if type(value) is str:
value = _icons[value]
self.handlers[0].formatter._theme_icons = value
elif kwarg == 'style':
if type(value) is str:
value = _styles[value]
self.handlers[0].formatter._theme_style = value
elif kwarg == 'lexer':
try:
self.handlers[0].formatter.set_lexer(value)
except AttributeError as err:
self.error('lexer: ColorFormatter not available.')
else:
raise NameError('unknown keyword argument: %s' % kwarg) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
| def log_config(self):
''' Log the current logging configuration. '''
level = self.level
debug = self.debug
debug('Logging config:')
debug('/ name: {}, id: {}', self.name, id(self))
debug(' .level: %s (%s)', level_map_int[level], level)
debug(' .default_level: %s (%s)',
level_map_int[self.default_level], self.default_level)
for i, handler in enumerate(self.handlers):
fmtr = handler.formatter
debug(' + Handler: %s %r', i, handler)
debug(' + Formatter: %r', fmtr)
debug(' .datefmt: %r', fmtr.datefmt)
debug(' .msgfmt: %r', fmtr._fmt)
debug(' fmt_style: %r', fmtr._style)
try:
debug(' theme styles: %r', fmtr._theme_style)
debug(' theme icons:\n%r', fmtr._theme_icons)
debug(' lexer: %r\n', fmtr._lexer)
except AttributeError:
pass |
<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_timestamp(date, unit='millis'):
""" Checks that a number that represents a date as milliseconds is correct. """ |
assert isinstance(date, int), "Input is not instance of int"
if unit is 'millis':
return is_positive(date) and len(str(date)) == 13
elif unit is 'seconds':
return is_positive(date) and len(str(date)) == 10
else:
raise ValueError('Unknown unit "%s"' % unit) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def debug(self, msg=None, *args, **kwargs):
"""Write log at DEBUG level. Same arguments as Python's built-in Logger. """ |
return self._log(logging.DEBUG, msg, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def info(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at INFO level.""" |
return self._log(logging.INFO, msg, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def exception(self, msg=None, *args, **kwargs):
"""Similar to DEBUG but at ERROR level with exc_info set. https://github.com/python/cpython/blob/2.7/Lib/logging/__init__.py#L1472 """ |
kwargs['exc_info'] = 1
return self._log(logging.ERROR, msg, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def log(self, level, msg=None, *args, **kwargs):
"""Writes log out at any arbitray level.""" |
return self._log(level, msg, args, kwargs) |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def _log(self, level, msg, args, kwargs):
"""Throttled log output.""" |
with self._tb_lock:
if self._tb is None:
throttled = 0
should_log = True
else:
throttled = self._tb.throttle_count
should_log = self._tb.check_and_consume()
if should_log:
if throttled > 0:
self._logger.log(level, "")
self._logger.log(
level,
"(... throttled %d messages ...)",
throttled,
)
self._logger.log(level, "")
if msg is not None:
self._logger.log(level, msg, *args, **kwargs)
return FancyLogContext(self._logger,
level,
self._verbosity,
self._structured_detail,
self._with_prefix)
else:
return NoopLogContext() |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp_to_local_time(timestamp, timezone_name):
"""Convert epoch timestamp to a localized Delorean datetime object. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. Returns ------- delorean.Delorean A localized Delorean datetime object. """ |
# first convert timestamp to UTC
utc_time = datetime.utcfromtimestamp(float(timestamp))
delo = Delorean(utc_time, timezone='UTC')
# shift d according to input timezone
localized_d = delo.shift(timezone_name)
return localized_d |
<SYSTEM_TASK:>
Solve the following problem using Python, implementing the functions described below, one line at a time
<END_TASK>
<USER_TASK:>
Description:
def timestamp_to_local_time_str( timestamp, timezone_name, fmt="yyyy-MM-dd HH:mm:ss"):
"""Convert epoch timestamp to a localized datetime string. Arguments --------- timestamp : int The timestamp to convert. timezone_name : datetime.timezone The timezone of the desired local time. fmt : str The format of the output string. Returns ------- str The localized datetime string. """ |
localized_d = timestamp_to_local_time(timestamp, timezone_name)
localized_datetime_str = localized_d.format_datetime(fmt)
return localized_datetime_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_timestamp(timezone_name, year, month, day, hour=0, minute=0):
"""Epoch timestamp from timezone, year, month, day, hour and minute.""" |
tz = pytz.timezone(timezone_name)
tz_datetime = tz.localize(datetime(year, month, day, hour, minute))
timestamp = calendar.timegm(tz_datetime.utctimetuple())
return timestamp |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.