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 unpack(self, message): """Called to extract a STOMP message into this instance. message: This is a text string representing a valid STOMP (v1.0) message. inf...
if not message: raise FrameError("Unpack error! The given message isn't valid '%s'!" % message) msg = unpack_frame(message) self.cmd = msg['cmd'] self.headers = msg['headers'] # Assign directly as the message will have the null # character in the message a...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def react(self, msg): """Called to provide a response to a message if needed. msg: or it can be a straight STOMP message. This function will attempt to determine...
returned = "" # If its not a string assume its a dict. mtype = type(msg) if mtype in stringTypes: msg = unpack_frame(msg) elif mtype == dict: pass else: raise FrameError("Unknown message type '%s', I don't know what to do with this!" ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def error(self, msg): """Called to handle an error message received from the server. This method just logs the error message returned: NO_RESPONSE_NEEDED """
body = msg['body'].replace(NULL, '') brief_msg = "" if 'message' in msg['headers']: brief_msg = msg['headers']['message'] self.log.error("Received server error - message%s\n\n%s" % (brief_msg, body)) returned = NO_RESPONSE_NEEDED if self.testing: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def receipt(self, msg): """Called to handle a receipt message received from the server. This method just logs the receipt message returned: NO_RESPONSE_NEEDED ""...
body = msg['body'].replace(NULL, '') brief_msg = "" if 'receipt-id' in msg['headers']: brief_msg = msg['headers']['receipt-id'] self.log.info("Received server receipt message - receipt-id:%s\n\n%s" % (brief_msg, body)) returned = NO_RESPONSE_NEEDED if 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 log_init(level): """Set up a logger that catches all channels and logs it to stdout. This is used to set up logging when testing. """
log = logging.getLogger() hdlr = logging.StreamHandler() formatter = logging.Formatter('%(asctime)s %(name)s %(levelname)s %(message)s') hdlr.setFormatter(formatter) log.addHandler(hdlr) log.setLevel(level)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ack(self, msg): """Override this and do some customer message handler. """
print("Got a message:\n%s\n" % msg['body']) # do something with the message... # Generate the ack or not if you subscribed with ack='auto' return super(Pong, self).ack(msg)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def transaction_atomic_with_retry(num_retries=5, backoff=0.1): """ This is a decorator that will wrap the decorated method in an atomic transaction and retry the...
# Create the decorator @wrapt.decorator def wrapper(wrapped, instance, args, kwargs): # Keep track of how many times we have tried num_tries = 0 exception = None # Call the main sync entities method and catch any exceptions while num_tries <= num_retries: ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def defer_entity_syncing(wrapped, instance, args, kwargs): """ A decorator that can be used to defer the syncing of entities until after the method has been run ...
# Defer entity syncing while we run our method sync_entities.defer = True # Run the method try: return wrapped(*args, **kwargs) # After we run the method disable the deferred syncing # and sync all the entities that have been buffered to be synced finally: # Enable entity...
<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_super_entities_by_ctype(model_objs_by_ctype, model_ids_to_sync, sync_all): """ Given model objects organized by content type and a dictionary of all mod...
super_entities_by_ctype = defaultdict(lambda: defaultdict(list)) # pragma: no cover for ctype, model_objs_for_ctype in model_objs_by_ctype.items(): entity_config = entity_registry.entity_registry.get(ctype.model_class()) super_entities = entity_config.get_super_entities(model_objs_for_ctype, 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 _get_model_objs_to_sync(model_ids_to_sync, model_objs_map, sync_all): """ Given the model IDs to sync, fetch all model objects to sync """
model_objs_to_sync = {} for ctype, model_ids_to_sync_for_ctype in model_ids_to_sync.items(): model_qset = entity_registry.entity_registry.get(ctype.model_class()).queryset if not sync_all: model_objs_to_sync[ctype] = model_qset.filter(id__in=model_ids_to_sync_for_ctype) els...
<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_entities_watching(instance): """ Syncs entities watching changes of a model instance. """
for entity_model, entity_model_getter in entity_registry.entity_watching[instance.__class__]: model_objs = list(entity_model_getter(instance)) if model_objs: sync_entities(*model_objs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def upsert_entity_kinds(self, entity_kinds): """ Given a list of entity kinds ensure they are synced properly to the database. This will ensure that only unchang...
# Filter out unchanged entity kinds unchanged_entity_kinds = {} if entity_kinds: unchanged_entity_kinds = { (entity_kind.name, entity_kind.display_name): entity_kind for entity_kind in EntityKind.all_objects.extra( where=['(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_entity_kind(self, model_obj): """ Returns a tuple for a kind name and kind display name of an entity. By default, uses the app_label and model of the mod...
model_obj_ctype = ContentType.objects.get_for_model(self.queryset.model) return (u'{0}.{1}'.format(model_obj_ctype.app_label, model_obj_ctype.model), u'{0}'.format(model_obj_ctype))
<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_entity(self, entity_config): """ Registers an entity config """
if not issubclass(entity_config, EntityConfig): raise ValueError('Must register entity config class of subclass EntityConfig') if entity_config.queryset is None: raise ValueError('Entity config must define queryset') model = entity_config.queryset.model 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 start(host='localhost', port=61613, username='', password=''): """
StompClientFactory.username = username StompClientFactory.password = password reactor.connectTCP(host, port, StompClientFactory()) reactor.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 send(self): """Send out a hello message periodically. """
self.log.info("Saying hello (%d)." % self.counter) f = stomper.Frame() f.unpack(stomper.send(DESTINATION, 'hello there (%d)' % self.counter)) self.counter += 1 # ActiveMQ specific headers: # #f.headers['persistent'] = 'true' self.transport.wri...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectionMade(self): """Register with stomp server. """
cmd = stomper.connect(self.username, self.password) self.transport.write(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataReceived(self, data): """Use stompbuffer to determine when a complete message has been received. """
self.stompBuffer.appendData(data) while True: msg = self.stompBuffer.getOneMessage() if msg is None: break returned = self.react(msg) if returned: self.transport.write(returned)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ack(self, msg): """Process the message and determine what to do with it. """
self.log.info("receiverId <%s> Received: <%s> " % (self.receiverId, msg['body'])) #return super(MyStomp, self).ack(msg) return stomper.NO_REPONSE_NEEDED
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connectionMade(self): """Register with the stomp server. """
cmd = self.sm.connect() self.transport.write(cmd)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def dataReceived(self, data): """Data received, react to it and respond if needed. """
# print "receiver dataReceived: <%s>" % data msg = stomper.unpack_frame(data) returned = self.sm.react(msg) # print "receiver returned <%s>" % returned if returned: self.transport.write(returned)
<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_id_in_folder(self, name, parent_folder_id=0): """Find a folder or a file ID from its name, inside a given folder. Args: name (str): Name of the folder ...
if name is None or len(name) == 0: return parent_folder_id offset = 0 resp = self.get_folder_items(parent_folder_id, limit=1000, offset=offset, fields_list=['name']) total = int(resp['total_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 create_folder(self, name, parent_folder_id=0): """Create a folder If the folder exists, a BoxError will be raised. Args: folder_id (int): Name of the folder...
return self.__request("POST", "folders", data={ "name": name, "parent": {"id": unicode(parent_folder_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_folder(self, folder_id, recursive=True): """Delete an existing folder Args: folder_id (int): ID of the folder to delete. recursive (bool): Delete al...
return self.__request("DELETE", "folders/%s" % (folder_id, ), querystring={'recursive': unicode(recursive).lower()})
<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_folder_items(self, folder_id, limit=100, offset=0, fields_list=None): """Get files and folders inside a given folder Args: folder_id (int): Where to get...
qs = { "limit": limit, "offset": offset } if fields_list: qs['fields'] = ','.join(fields_list) return self.__request("GET", "folders/%s/items" % (folder_id, ), querystring=qs)
<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_file(self, name, folder_id, file_path): """Upload a file into a folder. Use function for small file otherwise there is the chunk_upload_file() functio...
try: return self.__do_upload_file(name, folder_id, file_path) except BoxError, ex: if ex.status != 401: raise #tokens had been refreshed, so we start again the upload return self.__do_upload_file(name, folder_id, file_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 upload_new_file_version(self, name, folder_id, file_id, file_path): """Upload a new version of a file into a folder. Use function for small file otherwise th...
try: return self.__do_upload_file(name, folder_id, file_path, file_id) except BoxError, ex: if ex.status != 401: raise #tokens had been refreshed, so we start again the upload return self.__do_upload_file(name, folder_id, file_path, file_i...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chunk_upload_file(self, name, folder_id, file_path, progress_callback=None, chunk_size=1024*1024*1): """Upload a file chunk by chunk. The whole file is never...
try: return self.__do_chunk_upload_file(name, folder_id, file_path, progress_callback, chunk_size) except BoxError, ex: if ex.status != 401: raise #tokens had been refreshed, so ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy_file(self, file_id, dest_folder_id): """Copy file to new destination Args: file_id (int): ID of the folder. dest_folder_id (int): ID of parent folder ...
return self.__request("POST", "/files/" + unicode(file_id) + "/copy", data={ "parent": {"id": unicode(dest_folder_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 ack(self, msg): """Processes the received message. I don't need to generate an ack message. """
self.log.info("senderID:%s Received: %s " % (self.senderID, msg['body'])) return stomper.NO_REPONSE_NEEDED
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _clear(self, pipe=None): """Helper for clear operations. :param pipe: Redis pipe in case update is performed as a part of transaction. :type pipe: :class:`re...
redis = self.redis if pipe is None else pipe redis.delete(self.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 _normalize_index(self, index, pipe=None): """Convert negative indexes into their positive equivalents."""
pipe = self.redis if pipe is None else pipe len_self = self.__len__(pipe) positive_index = index if index >= 0 else len_self + index return len_self, positive_index
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def _transaction(self, fn, *extra_keys): """Helper simplifying code within watched transaction. Takes *fn*, function treated as a transaction. Returns whatever *...
results = [] def trans(pipe): results.append(fn(pipe)) self.redis.transaction(trans, self.key, *extra_keys) return results[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 recursive_path(pack, path): """Find paths recursively"""
matches = [] for root, _, filenames in os.walk(os.path.join(pack, path)): for filename in filenames: matches.append(os.path.join(root, filename)[len(pack) + 1:]) return matches
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def nack(messageid, subscriptionid, transactionid=None): """STOMP negative acknowledge command. NACK is the opposite of ACK. It is used to tell the server that t...
header = 'subscription:%s\nmessage-id:%s' % (subscriptionid, messageid) if transactionid: header += '\ntransaction:%s' % transactionid return "NACK\n%s\n\n\x00\n" % header
<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(username, password, host, heartbeats=(0,0)): """STOMP connect command. username, password: These are the needed auth details to connect to the messag...
if len(heartbeats) != 2: raise ValueError('Invalid heartbeat %r' % heartbeats) cx, cy = heartbeats return "CONNECT\naccept-version:1.1\nhost:%s\nheart-beat:%i,%i\nlogin:%s\npasscode:%s\n\n\x00\n" % (host, cx, cy, username, password)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def ack(self, msg): """Called when a MESSAGE has been received. Override this method to handle received messages. This function will generate an acknowledge mess...
message_id = msg['headers']['message-id'] subscription = msg['headers']['subscription'] transaction_id = None if 'transaction-id' in msg['headers']: transaction_id = msg['headers']['transaction-id'] # print "acknowledging message id <%s>." % message_id retu...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def getOneMessage ( self ): """ I pull one complete message off the buffer and return it decoded as a dict. If there is no complete message in the buffer, I retu...
( mbytes, hbytes ) = self._findMessageBytes ( self.buffer ) if not mbytes: return None msgdata = self.buffer[:mbytes] self.buffer = self.buffer[mbytes:] hdata = msgdata[:hbytes] elems = hdata.split ( '\n' ) cmd = elems.pop ( 0 ) 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 delete_entity_signal_handler(sender, instance, **kwargs): """ Defines a signal handler for syncing an individual entity. Called when an entity is saved or de...
if instance.__class__ in entity_registry.entity_registry: Entity.all_objects.delete_for_obj(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def save_entity_signal_handler(sender, instance, **kwargs): """ Defines a signal handler for saving an entity. Syncs the entity to the entity mirror table. """
if instance.__class__ in entity_registry.entity_registry: sync_entities(instance) if instance.__class__ in entity_registry.entity_watching: sync_entities_watching(instance)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def turn_on_syncing(for_post_save=True, for_post_delete=True, for_m2m_changed=True, for_post_bulk_operation=False): """ Enables all of the signals for syncing en...
if for_post_save: post_save.connect(save_entity_signal_handler, dispatch_uid='save_entity_signal_handler') if for_post_delete: post_delete.connect(delete_entity_signal_handler, dispatch_uid='delete_entity_signal_handler') if for_m2m_changed: m2m_changed.connect(m2m_changed_entity_si...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def scan_elements(self): """ Yield each of the elements from the collection, without pulling them all into memory. .. warning:: This method is not available on t...
for x in self.redis.sscan_iter(self.key): yield self._unpickle(x)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def places_within_radius( self, place=None, latitude=None, longitude=None, radius=0, **kwargs ): """ Return descriptions of the places stored in the collection t...
kwargs['withdist'] = True kwargs['withcoord'] = True kwargs['withhash'] = False kwargs.setdefault('sort', 'ASC') unit = kwargs.setdefault('unit', 'km') # Make the query if place is not None: response = self.redis.georadiusbymember( 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 rotate(self, n=1): """ Rotate the deque n steps to the right. If n is negative, rotate to the left. """
# No work to do for a 0-step rotate if n == 0: return def rotate_trans(pipe): # Synchronize the cache before rotating if self.writeback: self._sync_helper(pipe) # Rotating len(self) times has no effect. len_self = sel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def is_sub_to_all(self, *super_entities): """ Given a list of super entities, return the entities that have those as a subset of their super entities. """
if super_entities: if len(super_entities) == 1: # Optimize for the case of just one super entity since this is a much less intensive query has_subset = EntityRelationship.objects.filter( super_entity=super_entities[0]).values_list('sub_entity', fl...
<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_sub_to_any(self, *super_entities): """ Given a list of super entities, return the entities that have super entities that interset with those provided. """
if super_entities: return self.filter(id__in=EntityRelationship.objects.filter( super_entity__in=super_entities).values_list('sub_entity', flat=True)) else: 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 is_sub_to_any_kind(self, *super_entity_kinds): """ Find all entities that have super_entities of any of the specified kinds """
if super_entity_kinds: # get the pks of the desired subs from the relationships table if len(super_entity_kinds) == 1: entity_pks = EntityRelationship.objects.filter( super_entity__entity_kind=super_entity_kinds[0] ).select_related('en...
<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_obj(self, entity_model_obj): """ Given a saved entity model object, return the associated entity. """
return self.get(entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_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_for_obj(self, entity_model_obj): """ Delete the entities associated with a model object. """
return self.filter( entity_type=ContentType.objects.get_for_model( entity_model_obj, for_concrete_model=False), entity_id=entity_model_obj.id).delete( force=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def all_entities(self, is_active=True): """ Return all the entities in the group. Because groups can contain both individual entities, as well as whole groups of...
return self.get_all_entities(return_models=True, is_active=is_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 add_entity(self, entity, sub_entity_kind=None): """ Add an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The entity to...
membership = EntityGroupMembership.objects.create( entity_group=self, entity=entity, sub_entity_kind=sub_entity_kind, ) return membership
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def bulk_add_entities(self, entities_and_kinds): """ Add many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity, Enti...
memberships = [EntityGroupMembership( entity_group=self, entity=entity, sub_entity_kind=sub_entity_kind, ) for entity, sub_entity_kind in entities_and_kinds] created = EntityGroupMembership.objects.bulk_create(memberships) return created
<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_entity(self, entity, sub_entity_kind=None): """ Remove an entity, or sub-entity group to this EntityGroup. :type entity: Entity :param entity: The ent...
EntityGroupMembership.objects.get( entity_group=self, entity=entity, sub_entity_kind=sub_entity_kind, ).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 bulk_remove_entities(self, entities_and_kinds): """ Remove many entities and sub-entity groups to this EntityGroup. :type entities_and_kinds: List of (Entity...
criteria = [ Q(entity=entity, sub_entity_kind=entity_kind) for entity, entity_kind in entities_and_kinds ] criteria = reduce(lambda q1, q2: q1 | q2, criteria, Q()) EntityGroupMembership.objects.filter( criteria, entity_group=self).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 bulk_overwrite(self, entities_and_kinds): """ Update the group to the given entities and sub-entity groups. After this operation, the only members of this En...
EntityGroupMembership.objects.filter(entity_group=self).delete() return self.bulk_add_entities(entities_and_kinds)
<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_slug(apps, schema_editor, class_name): """ Create a slug for each Work already in the DB. """
Cls = apps.get_model('spectator_events', class_name) for obj in Cls.objects.all(): obj.slug = generate_slug(obj.pk) obj.save(update_fields=['slug'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_descriptor_and_rows(self, descriptor, rows): """Convert descriptor and rows to Pandas """
# Prepare primary_key = None schema = tableschema.Schema(descriptor) if len(schema.primary_key) == 1: primary_key = schema.primary_key[0] elif len(schema.primary_key) > 1: message = 'Multi-column primary keys are not supported' raise tablesch...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def convert_type(self, type): """Convert type to Pandas """
# Mapping mapping = { 'any': np.dtype('O'), 'array': np.dtype(list), 'boolean': np.dtype(bool), 'date': np.dtype('O'), 'datetime': np.dtype('datetime64[ns]'), 'duration': np.dtype('O'), 'geojson': np.dtype('O'), ...
<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_descriptor(self, dataframe): """Restore descriptor from Pandas """
# Prepare fields = [] primary_key = None # Primary key if dataframe.index.name: field_type = self.restore_type(dataframe.index.dtype) field = { 'name': dataframe.index.name, 'type': field_type, 'constraint...
<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_row(self, row, schema, pk): """Restore row from Pandas """
result = [] for field in schema.fields: if schema.primary_key and schema.primary_key[0] == field.name: if field.type == 'number' and np.isnan(pk): pk = None if pk and field.type == 'integer': pk = int(pk) ...
<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_type(self, dtype, sample=None): """Restore type from Pandas """
# Pandas types if pdc.is_bool_dtype(dtype): return 'boolean' elif pdc.is_datetime64_any_dtype(dtype): return 'datetime' elif pdc.is_integer_dtype(dtype): return 'integer' elif pdc.is_numeric_dtype(dtype): return '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 domain_urlize(value): """ Returns an HTML link to the supplied URL, but only using the domain as the text. Strips 'www.' from the start of the domain, if pre...
parsed_uri = urlparse(value) domain = '{uri.netloc}'.format(uri=parsed_uri) if domain.startswith('www.'): domain = domain[4:] return format_html('<a href="{}" rel="nofollow">{}</a>', value, domain )
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def current_url_name(context): """ Returns the name of the current URL, namespaced, or False. Example usage: {% current_url_name as url_name %} <a href="#"{% if ...
url_name = False if context.request.resolver_match: url_name = "{}:{}".format( context.request.resolver_match.namespace, context.request.resolver_match.url_name ) return url_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 most_read_creators_card(num=10): """ Displays a card showing the Creators who have the most Readings associated with their Publications. In spectator_core ta...
if spectator_apps.is_enabled('reading'): object_list = most_read_creators(num=num) object_list = chartify(object_list, 'num_readings', cutoff=1) return { 'card_title': 'Most read authors', 'score_attr': 'num_readings', 'object_list': object_list, ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_visited_venues_card(num=10): """ Displays a card showing the Venues that have the most Events. In spectator_core tags, rather than spectator_events so i...
if spectator_apps.is_enabled('events'): object_list = most_visited_venues(num=num) object_list = chartify(object_list, 'num_visits', cutoff=1) return { 'card_title': 'Most visited venues', 'score_attr': 'num_visits', 'object_list': object_list, ...
<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_urls(self): "Handy for templates." if self.isbn_uk or self.isbn_us or self.official_url or self.notes_url: return True else: 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 get_queryset(self): "Reduce the number of queries and speed things up." qs = super().get_queryset() qs = qs.select_related('publication__series') \ .prefetch_related('publication__roles__creator') return qs
<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_slug(apps, schema_editor): """ Create a slug for each Creator already in the DB. """
Creator = apps.get_model('spectator_core', 'Creator') for c in Creator.objects.all(): c.slug = generate_slug(c.pk) c.save(update_fields=['slug'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Copy the ClassicalWork and DancePiece data to use the new through models. """
Event = apps.get_model('spectator_events', 'Event') ClassicalWorkSelection = apps.get_model( 'spectator_events', 'ClassicalWorkSelection') DancePieceSelection = apps.get_model( 'spectator_events', 'DancePieceSelection') for event in Event...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Set the venue_name field of all Events that have a Venue. """
Event = apps.get_model('spectator_events', 'Event') for event in Event.objects.all(): if event.venue is not None: event.venue_name = event.venue.name event.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Migrate all 'exhibition' Events to the new 'museum' Event kind. """
Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='exhibition'): ev.kind = 'museum' ev.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def chartify(qs, score_field, cutoff=0, ensure_chartiness=True): """ Given a QuerySet it will go through and add a `chart_position` property to each object retur...
chart = [] position = 0 prev_obj = None for counter, obj in enumerate(qs): score = getattr(obj, score_field) if score != getattr(prev_obj, score_field, None): position = counter + 1 if cutoff is None or score > cutoff: obj.chart_position = position ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_visits(self, event_kind=None): """ Gets Venues in order of how many Events have been held there. Adds a `num_visits` field to each one. event_kind filters...
qs = self.get_queryset() if event_kind is not None: qs = qs.filter(event__kind=event_kind) qs = qs.annotate(num_visits=Count('event')) \ .order_by('-num_visits', 'name_sort') return qs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_views(self, kind=None): """ Gets Works in order of how many times they've been attached to Events. kind is the kind of Work, e.g. 'play', 'movie', etc. ""...
qs = self.get_queryset() if kind is not None: qs = qs.filter(kind=kind) qs = qs.annotate(num_views=Count('event')) \ .order_by('-num_views', 'title_sort') return qs
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def naturalize_person(self, string): """ Attempt to make a version of the string that has the surname, if any, at the start. 'John, Brown' to 'Brown, John' 'Sir ...
suffixes = [ 'Jr', 'Jr.', 'Sr', 'Sr.', 'I', 'II', 'III', 'IV', 'V', ] # Add lowercase versions: suffixes = suffixes + [s.lower() for s in suffixes] # If a name has a capitalised particle in we use that to sort. # So '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 forward(apps, schema_editor): """ Copying data from the old `Event.movie` and `Event.play` ForeignKey fields into the new `Event.movies` and `Event.plays` Ma...
Event = apps.get_model('spectator_events', 'Event') MovieSelection = apps.get_model('spectator_events', 'MovieSelection') PlaySelection = apps.get_model('spectator_events', 'PlaySelection') for event in Event.objects.all(): if event.movie is not None: selection = MovieSelection(ev...
<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_slug(apps, schema_editor): """ Create a slug for each Event already in the DB. """
Event = apps.get_model('spectator_events', 'Event') for e in Event.objects.all(): e.slug = generate_slug(e.pk) e.save(update_fields=['slug'])
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def page(self, number, *args, **kwargs): """Return a standard ``Page`` instance with custom, digg-specific page ranges attached. """
page = super().page(number, *args, **kwargs) number = int(number) # we know this will work # easier access num_pages, body, tail, padding, margin = \ self.num_pages, self.body, self.tail, self.padding, self.margin # put active page in middle of main range ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def version(): """Get the version number without importing the mrcfile package."""
namespace = {} with open(os.path.join('mrcfile', 'version.py')) as f: exec(f.read(), namespace) return namespace['__version__']
<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_event_kind(self): """ Unless we're on the front page we'll have a kind_slug like 'movies'. We need to translate that into an event `kind` like 'movie'. "...
slug = self.kwargs.get('kind_slug', None) if slug is None: return None # Front page; showing all Event kinds. else: slugs_to_kinds = {v:k for k,v in Event.KIND_SLUGS.items()} return slugs_to_kinds.get(slug, 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 get_queryset(self): "Restrict to a single kind of event, if any, and include Venue data." qs = super().get_queryset() kind = self.get_event_kind() if kind is not None: qs = qs.filter(kind=kind) qs = qs.select_related('venue') return qs
<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_work_kind(self): """ We'll have a kind_slug like 'movies'. We need to translate that into a work `kind` like 'movie'. """
slugs_to_kinds = {v:k for k,v in Work.KIND_SLUGS.items()} return slugs_to_kinds.get(self.kind_slug, 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 get_countries(self): """ Returns a list of dicts, one per country that has at least one Venue in it. Each dict has 'code' and 'name' elements. The list is so...
qs = Venue.objects.values('country') \ .exclude(country='') \ .distinct() \ .order_by('country') countries = [] for c in qs: countries.append({ 'code': c['co...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Re-save all the Works because something earlier didn't create their slugs. """
Work = apps.get_model('spectator_events', 'Work') for work in Work.objects.all(): if not work.slug: work.slug = generate_slug(work.pk) work.save()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def annual_event_counts_card(kind='all', current_year=None): """ Displays years and the number of events per year. kind is an Event kind (like 'cinema', 'gig', e...
if kind == 'all': card_title = 'Events per year' else: card_title = '{} per year'.format(Event.get_kind_name_plural(kind)) return { 'card_title': card_title, 'kind': kind, 'years': annual_event_counts(kind=kind), 'current_year': current_year ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def event_list_tabs(counts, current_kind, page_number=1): """ Displays the tabs to different event_list pages. `counts` is a dict of number of events for each ki...
return { 'counts': counts, 'current_kind': current_kind, 'page_number': page_number, # A list of all the kinds we might show tabs for, like # ['gig', 'movie', 'play', ...] 'event_kinds': Event.get_kinds(), # A dict of data about ea...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def day_events_card(date): """ Displays Events that happened on the supplied date. `date` is a date object. """
d = date.strftime(app_settings.DATE_FORMAT) card_title = 'Events on {}'.format(d) return { 'card_title': card_title, 'event_list': day_events(date=date), }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_seen_creators_card(event_kind=None, num=10): """ Displays a card showing the Creators that are associated with the most Events. """
object_list = most_seen_creators(event_kind=event_kind, num=num) object_list = chartify(object_list, 'num_events', cutoff=1) return { 'card_title': 'Most seen people/groups', 'score_attr': 'num_events', 'object_list': object_list, }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_seen_creators_by_works(work_kind=None, role_name=None, num=10): """ Returns a QuerySet of the Creators that are associated with the most Works. """
return Creator.objects.by_works(kind=work_kind, role_name=role_name)[:num]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_seen_creators_by_works_card(work_kind=None, role_name=None, num=10): """ Displays a card showing the Creators that are associated with the most Works. e...
object_list = most_seen_creators_by_works( work_kind=work_kind, role_name=role_name, num=num) object_list = chartify(object_list, 'num_works', cutoff=1) # Attempt to create a sensible card title... if role_name: # Yes, this pluralization is going to break at some ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def most_seen_works_card(kind=None, num=10): """ Displays a card showing the Works that are associated with the most Events. """
object_list = most_seen_works(kind=kind, num=num) object_list = chartify(object_list, 'num_views', cutoff=1) if kind: card_title = 'Most seen {}'.format( Work.get_kind_name_plural(kind).lower()) else: card_title = 'Most seen works' return { ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Change all Movie objects into Work objects, and their associated data into WorkRole and WorkSelection models, then delete ...
Movie = apps.get_model('spectator_events', 'Movie') Work = apps.get_model('spectator_events', 'Work') WorkRole = apps.get_model('spectator_events', 'WorkRole') WorkSelection = apps.get_model('spectator_events', 'WorkSelection') for m in Movie.objects.all(): work = Work.objects.create( ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paginate_queryset(self, queryset, page_size): """ Paginate the queryset, if needed. This is EXACTLY the same as the standard ListView.paginate_queryset() exc...
paginator = self.get_paginator( queryset, page_size, orphans = self.get_paginate_orphans(), allow_empty_first_page = self.get_allow_empty(), body = self.paginator_body, margin = self.paginator_margin, padding = self.paginat...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def day_publications(date): """ Returns a QuerySet of Publications that were being read on `date`. `date` is a date tobject. """
readings = Reading.objects \ .filter(start_date__lte=date) \ .filter( Q(end_date__gte=date) | Q(end_date__isnull=True) ) if readings: return Public...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def day_publications_card(date): """ Displays Publications that were being read on `date`. `date` is a date tobject. """
d = date.strftime(app_settings.DATE_FORMAT) card_title = 'Reading on {}'.format(d) return { 'card_title': card_title, 'publication_list': day_publications(date=date), }
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def forwards(apps, schema_editor): """ Change Events with kind 'movie' to 'cinema' and Events with kind 'play' to 'theatre'. Purely for more consistency. """
Event = apps.get_model('spectator_events', 'Event') for ev in Event.objects.filter(kind='movie'): ev.kind = 'cinema' ev.save() for ev in Event.objects.filter(kind='play'): ev.kind = 'theatre' ev.save()
<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_env_variable(var_name, default=None): """Get the environment variable or return exception."""
try: return os.environ[var_name] except KeyError: if default is None: error_msg = "Set the %s environment variable" % var_name raise ImproperlyConfigured(error_msg) else: return 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 forwards(apps, schema_editor): """ Having added the new 'exhibition' Work type, we're going to assume that every Event of type 'museum' should actually have ...
Event = apps.get_model('spectator_events', 'Event') Work = apps.get_model('spectator_events', 'Work') WorkRole = apps.get_model('spectator_events', 'WorkRole') WorkSelection = apps.get_model('spectator_events', 'WorkSelection') for event in Event.objects.filter(kind='museum'): # Create a ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_readings(self, role_names=['', 'Author']): """ The Creators who have been most-read, ordered by number of readings. By default it will only include Creato...
if not spectator_apps.is_enabled('reading'): raise ImproperlyConfigured("To use the CreatorManager.by_readings() method, 'spectator.reading' must by in INSTALLED_APPS.") qs = self.get_queryset() qs = qs.filter(publication_roles__role_name__in=role_names) \ .exclude...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def by_events(self, kind=None): """ Get the Creators involved in the most Events. This only counts Creators directly involved in an Event. i.e. if a Creator is t...
if not spectator_apps.is_enabled('events'): raise ImproperlyConfigured("To use the CreatorManager.by_events() method, 'spectator.events' must by in INSTALLED_APPS.") qs = self.get_queryset() if kind is not None: qs = qs.filter(events__kind=kind) qs = qs.annota...