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 get_context_data(self, **kwargs): """ Adds `next` to the context. This makes sure that the `next` parameter doesn't get lost if the form was submitted invali...
ctx = super(UserMediaImageViewMixin, self).get_context_data(**kwargs) ctx.update({ 'action': self.action, 'next': self.next, }) return ctx
<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_success_url(self): """ Returns the success URL. This is either the given `next` URL parameter or the content object's `get_absolute_url` method's return ...
if self.next: return self.next if self.object and self.object.content_object: return self.object.content_object.get_absolute_url() raise Exception( 'No content object given. Please provide ``next`` in your POST' ' 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 dispatch(self, request, *args, **kwargs): """Adds useful objects to the class and performs security checks."""
self._add_next_and_user(request) self.content_object = None self.content_type = None self.object_id = kwargs.get('object_id', None) if kwargs.get('content_type'): # Check if the user forged the URL and posted a non existant # content type try...
<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_queryset(self): """ Making sure that a user can only delete his own images. Even when he forges the request URL. """
queryset = super(DeleteImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
<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_queryset(self): """ Making sure that a user can only edit his own images. Even when he forges the request URL. """
queryset = super(UpdateImageView, self).get_queryset() queryset = queryset.filter(user=self.user) return queryset
<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_images(self, instance): """Deletes all user media images of the given instance."""
UserMediaImage.objects.filter( content_type=ContentType.objects.get_for_model(instance), object_id=instance.pk, user=instance.user, ).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 clean_image(self): """ It seems like in Django 1.5 something has changed. When Django tries to validate the form, it checks if the generated filename fit int...
self.instance.user = self.user data = self.cleaned_data.get('image') return 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 get_image_file_path(instance, filename): """Returns a unique filename for images."""
ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return os.path.join( 'user_media', str(instance.user.pk), 'images', filename)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def image_post_delete_handler(sender, instance, **kwargs): """ Makes sure that a an image is also deleted from the media directory. This should prevent a load of...
for f in glob.glob('{}/{}*'.format(instance.image.storage.location, instance.image.name)): if not os.path.isdir(f): instance.image.storage.delete(f)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def box_coordinates(self): """Returns a thumbnail's coordinates."""
if ( self.thumb_x is not None and self.thumb_y is not None and self.thumb_x2 is not None and self.thumb_y2 is not None ): return ( int(self.thumb_x), int(self.thumb_y), int(self.thumb_x2), ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def large_size(self, as_string=True): """Returns a thumbnail's large size."""
size = getattr(settings, 'USER_MEDIA_THUMB_SIZE_LARGE', (150, 150)) if as_string: return u'{}x{}'.format(size[0], size[1]) return size
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def crop_box(im, box=False, **kwargs): """Uses box coordinates to crop an image without resizing it first."""
if box: im = im.crop(box) return im
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def load_germanet(host = None, port = None, database_name = 'germanet'): ''' Loads a GermaNet instance connected to the given MongoDB instance. Arguments: - `host`: the hostname of the MongoDB instance - `port`: the port number of the MongoDB instance - `database_name`: the name of the GermaNet...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def cache_size(self, new_value): ''' Set the cache size used to reduce the number of database access operations. ''' if type(new_value) == int and 0 < new_value: if self._lemma_cache is not None: self._lemma_cache = repoze.lru.LRUCache(new_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 all_lemmas(self): ''' A generator over all the lemmas in the GermaNet database. ''' for lemma_dict in self._mongo_db.lexunits.find(): yield Lemma(self, lemma_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def lemmas(self, lemma, pos = None): ''' Looks up lemmas in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' if pos is not None: if pos not in SHORT_POS_TO_LONG: return None pos = SHORT_POS_TO_LONG[pos] ...
<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_synsets(self): ''' A generator over all the synsets in the GermaNet database. ''' for synset_dict in self._mongo_db.synsets.find(): yield Synset(self, synset_dict)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def synsets(self, lemma, pos = None): ''' Looks up synsets in the GermaNet database. Arguments: - `lemma`: - `pos`: ''' return sorted(set(lemma_obj.synset for lemma_obj in self.lemmas(lemma, pos)))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def synset(self, synset_repr): ''' Looks up a synset in GermaNet using its string representation. Arguments: - `synset_repr`: a unicode string containing the lemma, part of speech, and sense number of the first lemma of the synset >>> gn.synset(u'funktionieren.v.2') ...
<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_synset_by_id(self, mongo_id): ''' Builds a Synset object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._synset_cache is not None: cache_hit = 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_lemma_by_id(self, mongo_id): ''' Builds a Lemma object from the database entry with the given ObjectId. Arguments: - `mongo_id`: a bson.objectid.ObjectId object ''' cache_hit = None if self._lemma_cache is not None: cache_hit = self._l...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def find_germanet_xml_files(xml_path): ''' Globs the XML files contained in the given directory and sorts them into sections for import into the MongoDB database. Arguments: - `xml_path`: the path to the directory containing the GermaNet XML files ''' xml_files = sorted(glob.glob(os.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 read_relation_file(filename): ''' Reads the GermaNet relation file ``gn_relations.xml`` which lists all the relations holding between lexical units and synsets. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) lex_rels = []...
<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_paraphrase_file(filename): ''' Reads in a GermaNet wiktionary paraphrase file and returns its contents as a list of dictionary structures. Arguments: - `filename`: ''' with open(filename, 'rb') as input_file: doc = etree.parse(input_file) assert doc.getroot().tag == 'w...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_lexical_information(germanet_db, lex_files): ''' Reads in the given lexical information files and inserts their contents into the given MongoDB database. Arguments: - `germanet_db`: a pymongo.database.Database object - `lex_files`: a list of paths to XML files containing lexial ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_lemmatisation_data(germanet_db): ''' Creates the lemmatiser collection in the given MongoDB instance using the data derived from the Projekt deutscher Wortschatz. Arguments: - `germanet_db`: a pymongo.database.Database object ''' # drop the database collection if it already exist...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description:
def insert_infocontent_data(germanet_db): ''' For every synset in GermaNet, inserts count information derived from SDEWAC. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) # use add one smoothing gn_counts = defa...
<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_max_min_depth(germanet_db): ''' For every part of speech in GermaNet, computes the maximum min_depth in that hierarchy. Arguments: - `germanet_db`: a pymongo.database.Database object ''' gnet = germanet.GermaNet(germanet_db) max_min_depths = defaultdict(lambda: -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 AssignVar(self, value): """Assign a value to this Value."""
self.value = value # Call OnAssignVar on options. [option.OnAssignVar() for option in self.options]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _CheckLine(self, line): """Passes the line through each rule until a match is made. Args: line: A string, the current input line. """
for rule in self._cur_state: matched = self._CheckRule(rule, line) if matched: for value in matched.groupdict(): self._AssignVar(matched, value) if self._Operations(rule): # Not a Continue so check for state transition. if rule.new_state: if ru...
<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_graphite_api_points_list(influxdb_data): """Make graphite-api data points dictionary from Influxdb ResultSet data"""
_data = {} for key in influxdb_data.keys(): _data[key[0]] = [(datetime.datetime.fromtimestamp(float(d['time'])), d['value']) for d in influxdb_data.get_points(key[0])] return _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 _setup_logger(self, level, log_file): """Setup log level and log file if set"""
if logger.handlers: return level = getattr(logging, level.upper()) logger.setLevel(level) formatter = logging.Formatter( '[%(levelname)s] %(asctime)s - %(module)s.%(funcName)s() - %(message)s') handler = logging.StreamHandler() logger.addHandler(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 walk_subclasses(root): """Does not yield the input class"""
classes = [root] visited = set() while classes: cls = classes.pop() if cls is type or cls in visited: continue classes.extend(cls.__subclasses__()) visited.add(cls) if cls is not root: yield 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 new_expiry(days=DEFAULT_PASTE_LIFETIME_DAYS): """Return an expiration `days` in the future"""
now = delorean.Delorean() return now + datetime.timedelta(days=days)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def sync(obj, engine): """Mark the object as having been persisted at least once. Store the latest snapshot of all marked values."""
snapshot = Condition() # Only expect values (or lack of a value) for columns that have been explicitly set for column in sorted(_obj_tracking[obj]["marked"], key=lambda col: col.dynamo_name): value = getattr(obj, column.name, None) value = engine._dump(column.typedef, value) conditi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def printable_name(column, path=None): """Provided for debug output when rendering conditions. User.name[3]["foo"][0]["bar"] -> name[3].foo[0].bar """
pieces = [column.name] path = path or path_of(column) for segment in path: if isinstance(segment, str): pieces.append(segment) else: pieces[-1] += "[{}]".format(segment) return ".".join(pieces)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_conditions(condition): """Yield all conditions within the given condition. If the root condition is and/or/not, it is not yielded (unless a cyclic refer...
conditions = list() visited = set() # Has to be split out, since we don't want to visit the root (for cyclic conditions) # but we don't want to yield it (if it's non-cyclic) because this only yields inner conditions if condition.operation in {"and", "or"}: conditions.extend(reversed(conditi...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def iter_columns(condition): """ Yield all columns in the condition or its inner conditions. Unwraps proxies when the condition's column (or any of its values) i...
# Like iter_conditions, this can't live in each condition without going possibly infinite on the # recursion, or passing the visited set through every call. That makes the signature ugly, so we # take care of it here. Luckily, it's pretty easy to leverage iter_conditions and just unpack the # actual ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _value_ref(self, column, value, *, dumped=False, inner=False): """inner=True uses column.typedef.inner_type instead of column.typedef"""
ref = ":v{}".format(self.next_index) # Need to dump this value if not dumped: typedef = column.typedef for segment in path_of(column): typedef = typedef[segment] if inner: typedef = typedef.inner_typedef value = 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 pop_refs(self, *refs): """Decrement the usage of each ref by 1. If this was the last use of a ref, remove it from attr_names or attr_values. """
for ref in refs: name = ref.name count = self.counts[name] # Not tracking this ref if count < 1: continue # Someone else is using this ref elif count > 1: self.counts[name] -= 1 # Last 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 render(self, obj=None, condition=None, atomic=False, update=False, filter=None, projection=None, key=None): """Main entry point for rendering multiple expres...
if (atomic or update) and not obj: raise InvalidCondition("An object is required to render atomic conditions or updates without an object.") if filter: self.render_filter_expression(filter) if projection: self.render_projection_expression(projection) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _unpack(self, record, key, expected): """Replaces the attr dict at the given key with an instance of a Model"""
attrs = record.get(key) if attrs is None: return obj = unpack_from_dynamodb( attrs=attrs, expected=expected, model=self.model, engine=self.engine ) object_loaded.send(self.engine, engine=self.engine, obj=obj) 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 reformat_record(record): """Repack a record into a cleaner structure for consumption."""
return { "key": record["dynamodb"].get("Keys", None), "new": record["dynamodb"].get("NewImage", None), "old": record["dynamodb"].get("OldImage", None), "meta": { "created_at": record["dynamodb"]["ApproximateCreationDateTime"], "event": { "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 token(self): """JSON-serializable representation of the current Shard state. The token is enough to rebuild the Shard as part of rebuilding a Stream. :return...
if self.iterator_type in RELATIVE_ITERATORS: logger.warning("creating shard token at non-exact location \"{}\"".format(self.iterator_type)) token = { "stream_arn": self.stream_arn, "shard_id": self.shard_id, "iterator_type": self.iterator_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 jump_to(self, *, iterator_type, sequence_number=None): """Move to a new position in the shard using the standard parameters to GetShardIterator. :param str i...
# Just a simple wrapper; let the caller handle RecordsExpired self.iterator_id = self.session.get_shard_iterator( stream_arn=self.stream_arn, shard_id=self.shard_id, iterator_type=iterator_type, sequence_number=sequence_number) self.iterator_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 load_children(self): """If the Shard doesn't have any children, tries to find some from DescribeStream. If the Shard is open this won't find any children, so...
# Child count is fixed the first time any of the following happen: # 0 :: stream closed or throughput decreased # 1 :: shard was open for ~4 hours # 2 :: throughput increased if self.children: return self.children # ParentShardId -> [Shard, ...] by_...
<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_records(self): """Get the next set of records in this shard. An empty list doesn't guarantee the shard is exhausted. :returns: A list of reformatted reco...
# Won't be able to find new records. if self.exhausted: return [] # Already caught up, just the one call please. if self.empty_responses >= CALLS_TO_REACH_HEAD: return self._apply_get_records_response(self.session.get_stream_records(self.iterator_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 bind(self, model, *, skip_table_setup=False): """Create backing tables for a model and its non-abstract subclasses. :param model: Base model to bind. Can be ...
# Make sure we're looking at models validate_is_model(model) concrete = set(filter(lambda m: not m.Meta.abstract, walk_subclasses(model))) if not model.Meta.abstract: concrete.add(model) logger.debug("binding non-abstract models {}".format( sorted(c.__na...
<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, *objs, condition=None, atomic=False): """Delete one or more objects. :param objs: objects to delete. :param condition: only perform each delete ...
objs = set(objs) validate_not_abstract(*objs) for obj in objs: self.session.delete_item({ "TableName": self._compute_table_name(obj.__class__), "Key": dump_key(self, obj), **render(self, obj=obj, atomic=atomic, condition=condition) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, *objs, consistent=False): """Populate objects from DynamoDB. :param objs: objects to delete. :param bool consistent: Use `strongly consistent read...
get_table_name = self._compute_table_name objs = set(objs) validate_not_abstract(*objs) table_index, object_index, request = {}, {}, {} for obj in objs: table_name = get_table_name(obj.__class__) key = dump_key(self, obj) index = index_for(k...
<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, *objs, condition=None, atomic=False): """Save one or more objects. :param objs: objects to save. :param condition: only perform each save if this ...
objs = set(objs) validate_not_abstract(*objs) for obj in objs: self.session.save_item({ "TableName": self._compute_table_name(obj.__class__), "Key": dump_key(self, obj), **render(self, obj=obj, atomic=atomic, condition=condition, updat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def backing_type_for(value): """Returns the DynamoDB backing type for a given python value's type :: 4 -> 'N' ['x', 3] -> 'L' {2, 4} -> 'SS' """
if isinstance(value, str): vtype = "S" elif isinstance(value, bytes): vtype = "B" # NOTE: numbers.Number check must come **AFTER** bool check since isinstance(True, numbers.Number) elif isinstance(value, bool): vtype = "BOOL" elif isinstance(v...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def stream_replicate(): """Monitor changes in approximately real-time and replicate them"""
stream = primary.stream(SomeDataBlob, "trim_horizon") next_heartbeat = pendulum.now() while True: now = pendulum.now() if now >= next_heartbeat: stream.heartbeat() next_heartbeat = now.add(minutes=10) record = next(stream) if record is 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 _move_stream_endpoint(coordinator, position): """Move to the "trim_horizon" or "latest" of the entire stream."""
# 0) Everything will be rebuilt from DescribeStream. stream_arn = coordinator.stream_arn coordinator.roots.clear() coordinator.active.clear() coordinator.buffer.clear() # 1) Build a Dict[str, Shard] of the current Stream from a DescribeStream call current_shards = coordinator.session.descr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _move_stream_token(coordinator, token): """Move to the Stream position described by the token. The following rules are applied when interpolation is required...
stream_arn = coordinator.stream_arn = token["stream_arn"] # 0) Everything will be rebuilt from the DescribeStream masked by the token. coordinator.roots.clear() coordinator.active.clear() coordinator.closed.clear() coordinator.buffer.clear() # Injecting the token gives us access to the sta...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def advance_shards(self): """Poll active shards for records and insert them into the buffer. Rotate exhausted shards. Returns immediately if the buffer isn't emp...
# Don't poll shards when there are pending records. if self.buffer: return # 0) Collect new records from all active shards. record_shard_pairs = [] for shard in self.active: records = next(shard) if records: record_shard_pairs...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def heartbeat(self): """Keep active shards with "trim_horizon", "latest" iterators alive by advancing their iterators."""
for shard in self.active: if shard.sequence_number is None: records = next(shard) # Success! This shard now has an ``at_sequence`` iterator if records: self.buffer.push_all((record, shard) for record in records) self.migra...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def token(self): """JSON-serializable representation of the current Stream state. Use :func:`Engine.stream(YourModel, token) <bloop.engine.Engine.stream>` to cre...
# 0) Trace roots and active shards active_ids = [] shard_tokens = [] for root in self.roots: for shard in root.walk_tree(): shard_tokens.append(shard.token) # dedupe, stream_arn will be in the root token shard_tokens[-1].pop("s...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def remove_shard(self, shard, drop_buffered_records=False): """Remove a Shard from the Coordinator. Drops all buffered records from the Shard. If the Shard is ac...
try: self.roots.remove(shard) except ValueError: # Wasn't a root Shard pass else: self.roots.extend(shard.children) try: self.active.remove(shard) except ValueError: # Wasn't an active Shard pas...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def move_to(self, position): """Set the Coordinator to a specific endpoint or time, or load state from a token. :param position: "trim_horizon", "latest", :class...
if isinstance(position, collections.abc.Mapping): move = _move_stream_token elif hasattr(position, "timestamp") and callable(position.timestamp): move = _move_stream_time elif isinstance(position, str) and position.lower() in ["latest", "trim_horizon"]: move ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def push(self, record, shard): """Push a new record into the buffer :param dict record: new record :param shard: Shard the record came from :type shard: :class:`...
heapq.heappush(self.heap, heap_item(self.clock, record, shard))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unpack_from_dynamodb(*, attrs, expected, model=None, obj=None, engine=None, context=None, **kwargs): """Push values by dynamo_name into an object"""
context = context or {"engine": engine} engine = engine or context.get("engine", None) if not engine: raise ValueError("You must provide engine or a context with an engine.") if model is None and obj is None: raise ValueError("You must provide a model or obj to unpack.") if model is...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def setdefault(obj, field, default): """Set an object's field to default if it doesn't have a value"""
setattr(obj, field, getattr(obj, field, 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 bind_column(model, name, column, force=False, recursive=False, copy=False) -> Column: """Bind a column to the model with the given name. This method is primar...
if not subclassof(model, BaseModel): raise InvalidModel(f"{model} is not a subclass of BaseModel") meta = model.Meta if copy: column = copyfn(column) # TODO elif column.model is not None: logger.warning(f"Trying to rebind column bound to {column.model}") column._name = name safe...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bind_index(model, name, index, force=False, recursive=True, copy=False) -> Index: """Bind an index to the model with the given name. This method is primarily ...
if not subclassof(model, BaseModel): raise InvalidModel(f"{model} is not a subclass of BaseModel") meta = model.Meta if copy: index = copyfn(index) # TODO elif index.model is not None: logger.warning(f"Trying to rebind index bound to {index.model}") index._name = name safe_repr ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def refresh_index(meta, index) -> None: """Recalculate the projection, hash_key, and range_key for the given index. :param meta: model.Meta to find columns by nam...
# All projections include model + index keys projection_keys = set.union(meta.keys, index.keys) proj = index.projection mode = proj["mode"] if mode == "keys": proj["included"] = projection_keys elif mode == "all": proj["included"] = meta.columns elif mode == "include": # ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def unbind(meta, name=None, dynamo_name=None) -> None: """Unconditionally remove any columns or indexes bound to the given name or dynamo_name. .. code-block:: py...
if name is not None: columns = {x for x in meta.columns if x.name == name} indexes = {x for x in meta.indexes if x.name == name} elif dynamo_name is not None: columns = {x for x in meta.columns if x.dynamo_name == dynamo_name} indexes = {x for x in meta.indexes if x.dynamo_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 _dump(cls, obj, *, context, **kwargs): """ obj -> dict """
if obj is None: return None dump = context["engine"]._dump filtered = filter( lambda item: item[1] is not None, (( column.dynamo_name, dump(column.typedef, getattr(obj, column.name, None), context=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 is_valid_superset(actual_projection, index): """Returns True if the actual index is a valid superset of the expected index"""
projection_type = actual_projection["ProjectionType"] if projection_type == "ALL": return True meta = index.model.Meta # all index types provide index keys and model keys provides = set.union(meta.keys, index.keys) if projection_type == "KEYS_ONLY": pass elif projection_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 save_item(self, item): """Save an object to DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.update_item`. :raises bloop.exceptio...
try: self.dynamodb_client.update_item(**item) except botocore.exceptions.ClientError as error: handle_constraint_violation(error)
<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_item(self, item): """Delete an object in DynamoDB. :param item: Unpacked into kwargs for :func:`boto3.DynamoDB.Client.delete_item`. :raises bloop.exce...
try: self.dynamodb_client.delete_item(**item) except botocore.exceptions.ClientError as error: handle_constraint_violation(error)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load_items(self, items): """Loads any number of items in chunks, handling continuation tokens. :param items: Unpacked in chunks into "RequestItems" for :func...
loaded_items = {} requests = collections.deque(create_batch_get_chunks(items)) while requests: request = requests.pop() try: response = self.dynamodb_client.batch_get_item(RequestItems=request) except botocore.exceptions.ClientError as error: ...
<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_table(self, table_name, model): """Create the model's table. Returns True if the table is being created, False otherwise. Does not wait for the table ...
table = create_table_request(table_name, model) try: self.dynamodb_client.create_table(**table) is_creating = True except botocore.exceptions.ClientError as error: handle_table_exists(error, model) is_creating = False return is_creating
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def describe_table(self, table_name): """ Polls until the table is ready, then returns the first result when the table was ready. The returned dict is standardiz...
if table_name in self._tables: return self._tables[table_name] status, description = None, {} calls = 0 while status is not ready: calls += 1 try: description = self.dynamodb_client.describe_table(TableName=table_name)["Table"] ...
<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_table(self, table_name, model): """Polls until a creating table is ready, then verifies the description against the model's requirements. The model ...
actual = self.describe_table(table_name) if not compare_tables(model, actual): raise TableMismatch("The expected and actual tables for {!r} do not match.".format(model.__name__)) # Fill in values that Meta doesn't know ahead of time (such as arns). # These won't be populate...
<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_hash_key(query_on, key): """Only allows == against query_on.hash_key"""
return ( isinstance(key, BaseCondition) and (key.operation == "==") and (key.column is query_on.hash_key) )
<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_range_key(query_on, key): """BeginsWith, Between, or any Comparison except '!=' against query_on.range_key"""
return ( isinstance(key, BaseCondition) and key.operation in ("begins_with", "between", "<", ">", "<=", ">=", "==") and key.column is query_on.range_key )
<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(self): """Number of items that have been loaded from DynamoDB so far, including buffered items."""
if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._count
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scanned(self): """Number of items that DynamoDB evaluated, before any filter was applied."""
if self.request["Select"] == "COUNT": while not self.exhausted: next(self, None) return self._scanned
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reset(self): """Reset to the initial state, clearing the buffer and zeroing count and scanned."""
self.buffer.clear() self._count = 0 self._scanned = 0 self._exhausted = False self.request.pop("ExclusiveStartKey", 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 prepare(self): """ Create a new PreparedTransaction that can be committed. This is called automatically when exiting the transaction as a context: .. code-bl...
tx = PreparedTransaction() tx.prepare( engine=self.engine, mode=self.mode, items=self._items, ) return tx
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def prepare(self, engine, mode, items) -> None: """ Create a unique transaction id and dumps the items into a cached request object. """
self.tx_id = str(uuid.uuid4()).replace("-", "") self.engine = engine self.mode = mode self.items = items self._prepare_request()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def commit(self) -> None: """ Commit the transaction with a fixed transaction id. A read transaction can call commit() any number of times, while a write transact...
now = datetime.now(timezone.utc) if self.first_commit_at is None: self.first_commit_at = now if self.mode == "r": response = self.engine.session.transaction_read(self._request) elif self.mode == "w": if now - self.first_commit_at > MAX_TOKEN_LIFETIME...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def load(self, *objs) -> "ReadTransaction": """ Add one or more objects to be loaded in this transaction. At most 10 items can be loaded in the same transaction. ...
self._extend([TxItem.new("get", obj) for obj in objs]) 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 check(self, obj, condition) -> "WriteTransaction": """ Add a condition which must be met for the transaction to commit. While the condition is checked against...
self._extend([TxItem.new("check", obj, condition)]) 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 save(self, *objs, condition=None, atomic=False) -> "WriteTransaction": """ Add one or more objects to be saved in this transaction. At most 10 items can be ch...
self._extend([TxItem.new("save", obj, condition, atomic) for obj in objs]) 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 encode(self, cube_dimensions): """ Produces a numpy array of integers which encode the supplied cube dimensions. """
return np.asarray([getattr(cube_dimensions[d], s) for d in self._dimensions for s in self._schema], dtype=np.int32)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def decode(self, descriptor): """ Produce a list of dictionaries for each dimension in this transcoder """
i = iter(descriptor) n = len(self._schema) # Add the name key to our schema schema = self._schema + ('name',) # For each dimensions, generator takes n items off iterator # wrapping the descriptor, making a tuple with the dimension # name appended tuple_g...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dl_cub(cub_url, cub_archive_name): """ Download cub archive from cub_url and store it in cub_archive_name """
with open(cub_archive_name, 'wb') as f: remote_file = urllib2.urlopen(cub_url) meta = remote_file.info() # The server may provide us with the size of the file. cl_header = meta.getheaders("Content-Length") remote_file_size = int(cl_header[0]) if len(cl_header) > 0 else 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 sha_hash_file(filename): """ Compute the SHA1 hash of filename """
hash_sha = hashlib.sha1() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024*1024), b""): hash_sha.update(chunk) return hash_sha.hexdigest()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def install_cub(mb_inc_path): """ Downloads and installs cub into mb_inc_path """
cub_url = 'https://github.com/NVlabs/cub/archive/1.6.4.zip' cub_sha_hash = '0d5659200132c2576be0b3959383fa756de6105d' cub_version_str = 'Current release: v1.6.4 (12/06/2016)' cub_zip_file = 'cub.zip' cub_zip_dir = 'cub-1.6.4' cub_unzipped_path = os.path.join(mb_inc_path, cub_zip_dir) cub_ne...
<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_tensorflow_extension(nvcc_settings, device_info): """ Create an extension that builds the custom tensorflow ops """
import tensorflow as tf import glob use_cuda = (bool(nvcc_settings['cuda_available']) and tf.test.is_built_with_cuda()) # Source and includes source_path = os.path.join('montblanc', 'impl', 'rime', 'tensorflow', 'rime_ops') sources = glob.glob(os.path.join(source_path, '*.cpp')) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def updated_dimensions(self): """ Inform montblanc about dimension sizes """
return [("ntime", args.ntime), # Timesteps ("nchan", args.nchan), # Channels ("na", args.na), # Antenna ("npsrc", len(lm_coords))]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def point_lm(self, context): """ Supply point source lm coordinates to montblanc """
# Shape (npsrc, 2) (ls, us), _ = context.array_extents(context.name) return np.asarray(lm_coords[ls:us], dtype=context.dtype)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def point_stokes(self, context): """ Supply point source stokes parameters to montblanc """
# Shape (npsrc, ntime, 4) (ls, us), (lt, ut), (l, u) = context.array_extents(context.name) data = np.empty(context.shape, context.dtype) data[ls:us,:,l:u] = np.asarray(lm_stokes)[ls:us,None,:] return 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 uvw(self, context): """ Supply UVW antenna coordinates to montblanc """
# Shape (ntime, na, 3) (lt, ut), (la, ua), (l, u) = context.array_extents(context.name) # Create empty UVW coordinates data = np.empty(context.shape, context.dtype) data[:,:,0] = np.arange(la+1, ua+1) # U = antenna index data[:,:,1] = 0 # V = ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nr_of_baselines(na, auto_correlations=False): """ Compute the number of baselines for the given number of antenna. Can specify whether auto-correlations shou...
m = (na-1) if auto_correlations is False else (na+1) return (na*m)//2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nr_of_antenna(nbl, auto_correlations=False): """ Compute the number of antenna for the given number of baselines. Can specify whether auto-correlations shoul...
t = 1 if auto_correlations is False else -1 return int(t + math.sqrt(1 + 8*nbl)) // 2
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def array_bytes(shape, dtype): """ Estimates the memory in bytes required for an array of the supplied shape and dtype """
return np.product(shape)*np.dtype(dtype).itemsize
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def random_like(ary=None, shape=None, dtype=None): """ Returns a random array of the same shape and type as the supplied array argument, or the supplied shape an...
if ary is not None: shape, dtype = ary.shape, ary.dtype elif shape is None or dtype is None: raise ValueError(( 'random_like(ary, shape, dtype) must be supplied ' 'with either an array argument, or the shape and dtype ' 'of the desired random array.')) i...