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 has_conversion(self, plugin): """Return True if the plugin supports this block."""
plugin = kurt.plugin.Kurt.get_plugin(plugin) return plugin.name in self._plugins
<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_command(self, command): """Returns True if any of the plugins have the given command."""
for pbt in self._plugins.values(): if pbt.command == command: return True return False
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def copy(self): """Return a new Block instance with the same attributes."""
args = [] for arg in self.args: if isinstance(arg, Block): arg = arg.copy() elif isinstance(arg, list): arg = [b.copy() for b in arg] args.append(arg) return Block(self.type, *args)
<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, path): """Load costume from image file. Uses :attr:`Image.load`, but will set the Costume's name based on the image filename. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Costume(name, Image.load(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 format(self): """The format of the image file. An uppercase string corresponding to the :attr:`PIL.ImageFile.ImageFile.format` attribute. Valid values includ...
if self._format: return self._format elif self.pil_image: return self.pil_image.format
<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(cls, path): """Load image from file."""
assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) image = Image(None) image._path = path image._format = Image.image_format(extension) return image
<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(self, *formats): """Return an Image instance with the first matching format. For each format in ``*args``: If the image's :attr:`format` attribute is...
for format in formats: format = Image.image_format(format) if self.format == format: return self else: return self._convert(format)
<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(self, format): """Return a new Image instance with the given format. Returns self if the format is already the same. """
if self.format == format: return self else: image = Image(self.pil_image) image._format = format return image
<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, path): """Save image to file path. The image format is guessed from the extension. If path has no extension, the image's :attr:`format` is used. :...
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" if extension: format = Image.image_format(extension) else: format = self.format 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 new(self, size, fill): """Return a new Image instance filled with a color."""
return Image(PIL.Image.new("RGB", size, fill))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def resize(self, size): """Return a new Image instance with the given size."""
return Image(self.pil_image.resize(size, PIL.Image.ANTIALIAS))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def paste(self, other): """Return a new Image with the given image pasted on top. This image will show through transparent areas of the given image. """
r, g, b, alpha = other.pil_image.split() pil_image = self.pil_image.copy() pil_image.paste(other.pil_image, mask=alpha) return kurt.Image(pil_image)
<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, path): """Load sound from wave file. Uses :attr:`Waveform.load`, but will set the Waveform's name based on the sound filename. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) return Sound(name, Waveform.load(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 save(self, path): """Save the sound to a wave file at the given path. Uses :attr:`Waveform.save`, but if the path ends in a folder instead of a file, the fil...
(folder, filename) = os.path.split(path) if not filename: filename = _clean_filename(self.name) path = os.path.join(folder, filename) return self.waveform.save(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 _wave(self): """Return a wave.Wave_read instance from the ``wave`` module."""
try: return wave.open(StringIO(self.contents)) except wave.Error, err: err.message += "\nInvalid wave file: %s" % self err.args = (err.message,) raise
<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(cls, path): """Load Waveform from file."""
assert os.path.exists(path), "No such file: %r" % path (folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) wave = Waveform(None) wave._path = path return wave
<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, path): """Save waveform to file path as a WAV file. :returns: Path to the saved file. """
(folder, filename) = os.path.split(path) (name, extension) = os.path.splitext(filename) if not name: raise ValueError, "name is required" path = os.path.join(folder, name + self.extension) f = open(path, "wb") f.write(self.contents) f.close() ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def open_channel(self): """ Open a new channel on this connection. This method is a :ref:`coroutine <coroutine>`. :return: The new :class:`Channel` object. """
if self._closing: raise ConnectionClosed("Closed by application") if self.closed.done(): raise self.closed.exception() channel = yield from self.channel_factory.open() return channel
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close the connection by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """
if not self.is_closed(): self._closing = True # Let the ConnectionActor do the actual close operations. # It will do the work on CloseOK self.sender.send_Close( 0, 'Connection closed by application', 0, 0) try: yield fr...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_PoisonPillFrame(self, frame): """ Is sent in case protocol lost connection to server."""
# Will be delivered after Close or CloseOK handlers. It's for channels, # so ignore it. if self.connection.closed.done(): return # If connection was not closed already - we lost connection. # Protocol should already be closed self._close_all(frame.exception)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def publish(self, message, routing_key, *, mandatory=True): """ Publish a message on the exchange, to be asynchronously delivered to queues. :param asynqp.Messag...
self.sender.send_BasicPublish(self.name, routing_key, mandatory, message)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, *, if_unused=True): """ Delete the exchange. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the exchange will ...
self.sender.send_ExchangeDelete(self.name, if_unused) yield from self.synchroniser.wait(spec.ExchangeDeleteOK) self.reader.ready()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reject(self, *, requeue=True): """ Reject the message. :keyword bool requeue: if true, the broker will attempt to requeue the message and deliver it to an al...
self.sender.send_BasicReject(self.delivery_tag, requeue)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def declare_queue(self, name='', *, durable=True, exclusive=False, auto_delete=False, passive=False, nowait=False, arguments=None): """ Declare a queue on the br...
q = yield from self.queue_factory.declare( name, durable, exclusive, auto_delete, passive, nowait, arguments if arguments is not None else {}) return q
<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_qos(self, prefetch_size=0, prefetch_count=0, apply_globally=False): """ Specify quality of service by requesting that messages be pre-fetched from the se...
self.sender.send_BasicQos(prefetch_size, prefetch_count, apply_globally) yield from self.synchroniser.wait(spec.BasicQosOK) self.reader.ready()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def close(self): """ Close the channel by handshaking with the server. This method is a :ref:`coroutine <coroutine>`. """
# If we aren't already closed ask for server to close if not self.is_closed(): self._closing = True # Let the ChannelActor do the actual close operations. # It will do the work on CloseOK self.sender.send_Close( 0, 'Channel closed by appli...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def handle_ChannelCloseOK(self, frame): """ AMQP server closed channel as per our request """
assert self.channel._closing, "received a not expected CloseOk" # Release the `close` method's future self.synchroniser.notify(spec.ChannelCloseOK) exc = ChannelClosed() self._close_all(exc)
<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, exchange, routing_key, *, arguments=None): """ Bind a queue to an exchange, with the supplied routing key. This action 'subscribes' the queue to t...
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) if not exchange: raise InvalidExchangeName("Can't bind queue {} to the default exchange".format(self.name)) self.sender.send_QueueBind(self.name, exchange.name, routing_key, arguments or {}) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def consume(self, callback, *, no_local=False, no_ack=False, exclusive=False, arguments=None): """ Start a consumer on the queue. Messages will be delivered asyn...
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicConsume(self.name, no_local, no_ack, exclusive, arguments or {}) tag = yield from self.synchroniser.wait(spec.BasicConsumeOK) consumer = Consumer( tag, callback, 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(self, *, no_ack=False): """ Synchronously get a message from the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool no_ack: if true, the...
if self.deleted: raise Deleted("Queue {} was deleted".format(self.name)) self.sender.send_BasicGet(self.name, no_ack) tag_msg = yield from self.synchroniser.wait(spec.BasicGetOK, spec.BasicGetEmpty) if tag_msg is not None: consumer_tag, msg = tag_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 purge(self): """ Purge all undelivered messages from the queue. This method is a :ref:`coroutine <coroutine>`. """
self.sender.send_QueuePurge(self.name) yield from self.synchroniser.wait(spec.QueuePurgeOK) self.reader.ready()
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def delete(self, *, if_unused=True, if_empty=True): """ Delete the queue. This method is a :ref:`coroutine <coroutine>`. :keyword bool if_unused: If true, the qu...
if self.deleted: raise Deleted("Queue {} was already deleted".format(self.name)) self.sender.send_QueueDelete(self.name, if_unused, if_empty) yield from self.synchroniser.wait(spec.QueueDeleteOK) self.deleted = True self.reader.ready()
<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(self, arguments=None): """ Unbind the queue from the exchange. This method is a :ref:`coroutine <coroutine>`. """
if self.deleted: raise Deleted("Queue {} was already unbound from exchange {}".format(self.queue.name, self.exchange.name)) self.sender.send_QueueUnbind(self.queue.name, self.exchange.name, self.routing_key, arguments or {}) yield from self.synchroniser.wait(spec.QueueUnbindOK) ...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def cancel(self): """ Cancel the consumer and stop recieving messages. This method is a :ref:`coroutine <coroutine>`. """
self.sender.send_BasicCancel(self.tag) try: yield from self.synchroniser.wait(spec.BasicCancelOK) except AMQPError: pass else: # No need to call ready if channel closed. self.reader.ready() self.cancelled = True self.cancel...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hello_world(): """ Sends a 'hello world' message and then reads it from the queue. """
# connect to the RabbitMQ broker connection = yield from asynqp.connect('localhost', 5672, username='guest', password='guest') # Open a communications channel channel = yield from connection.open_channel() # Create a queue and an exchange on the broker exchange = yield from channel.declare_ex...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def connect(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, sock=None, **kwargs): """ ...
from .protocol import AMQP from .routing import Dispatcher from .connection import open_connection loop = asyncio.get_event_loop() if loop is None else loop if sock is None: kwargs['host'] = host kwargs['port'] = port else: kwargs['sock'] = sock dispatcher = Dispa...
<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_timeout(self): """ Called by heartbeat_monitor on timeout """
assert not self._closed, "Did we not stop heartbeat_monitor on close?" log.error("Heartbeat time out") poison_exc = ConnectionLostError('Heartbeat timed out') poison_frame = frames.PoisonPillFrame(poison_exc) self.dispatcher.dispatch_all(poison_frame) # Spec says to just...
<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_general(value): """Take a python object and convert it to the format Imgur expects."""
if isinstance(value, bool): return "true" if value else "false" elif isinstance(value, list): value = [convert_general(item) for item in value] value = convert_to_imgur_list(value) elif isinstance(value, Integral): return str(value) elif 'pyimgur' in str(type(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 to_imgur_format(params): """Convert the parameters to the format Imgur expects."""
if params is None: return None return dict((k, convert_general(val)) for (k, val) in params.items())
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def render(self, name, value, attrs=None, *args, **kwargs): """Handle a few expected values for rendering the current choice. Extracts the state name from StateW...
if isinstance(value, base.StateWrapper): state_name = value.state.name elif isinstance(value, base.State): state_name = value.name else: state_name = str(value) return super(StateSelect, self).render(name, state_name, attrs, *args, **kwargs)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def contribute_to_class(self, cls, name): """Contribute the state to a Model. Attaches a StateFieldProperty to wrap the attribute. """
super(StateField, self).contribute_to_class(cls, name) parent_property = getattr(cls, self.name, None) setattr(cls, self.name, StateFieldProperty(self, parent_property))
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def to_python(self, value): """Converts the DB-stored value into a Python value."""
if isinstance(value, base.StateWrapper): res = value else: if isinstance(value, base.State): state = value elif value is None: state = self.workflow.initial_state else: try: state = 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_db_prep_value(self, value, connection, prepared=False): """Convert a value to DB storage. Returns the state name. """
if not prepared: value = self.get_prep_value(value) return value.state.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 value_to_string(self, obj): """Convert a field value to a string. Returns the state name. """
statefield = self.to_python(self.value_from_object(obj)) return statefield.state.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 validate(self, value, model_instance): """Validate that a given value is a valid option for a given model instance. Args: value (xworkflows.base.StateWrapper...
if not isinstance(value, base.StateWrapper): raise exceptions.ValidationError(self.error_messages['wrong_type'] % value) elif not value.workflow == self.workflow: raise exceptions.ValidationError(self.error_messages['wrong_workflow'] % value.workflow) elif value.state no...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django ...
name, path, args, kwargs = super(StateField, self).deconstruct() # We want to display the proper class name, which isn't available # at the same point for _SerializedWorkflow and Workflow. if isinstance(self.workflow, _SerializedWorkflow): workflow_class_name = self.workflo...
<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_log_model_class(self): """Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled import...
if self.log_model_class is not None: return self.log_model_class app_label, model_label = self.log_model.rsplit('.', 1) self.log_model_class = apps.get_model(app_label, model_label) return self.log_model_class
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def db_log(self, transition, from_state, instance, *args, **kwargs): """Logs the transition into the database."""
if self.log_model: model_class = self._get_log_model_class() extras = {} for db_field, transition_arg, default in model_class.EXTRA_LOG_ATTRIBUTES: extras[db_field] = kwargs.get(transition_arg, default) return model_class.log_transition( ...
<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_transition(self, transition, from_state, instance, *args, **kwargs): """Generic transition logging."""
save = kwargs.pop('save', True) log = kwargs.pop('log', True) super(Workflow, self).log_transition( transition, from_state, instance, *args, **kwargs) if save: instance.save() if log: self.db_log(transition, from_state, instance, *args, **kwar...
<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_readme(fname): """Cleanup README.rst for proper PyPI formatting."""
with codecs.open(fname, 'r', 'utf-8') as f: return ''.join( re.sub(r':\w+:`([^`]+?)( <[^<>]+>)?`', r'``\1``', line) for line in f if not (line.startswith('.. currentmodule') or line.startswith('.. toctree')) )
<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(self): """ Refresh this objects attributes to the newest values. Attributes that weren't added to the object before, due to lazy loading, will be add...
resp = self._imgur._send_request(self._INFO_URL) self._populate(resp) self._has_fetched = 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 add_images(self, images): """ Add images to the album. :param images: A list of the images we want to add to the album. Can be Image objects, ids or a combin...
url = self._imgur._base_url + "/3/album/{0}/add".format(self.id) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
<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_images(self, images): """ Remove images from the album. :param images: A list of the images we want to remove from the album. Can be Image objects, id...
url = (self._imgur._base_url + "/3/album/{0}/" "remove_images".format(self._delete_or_id_hash)) # NOTE: Returns True and everything seem to be as it should in testing. # Seems most likely to be upstream bug. params = {'ids': images} return self._imgur._send_reques...
<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_images(self, images): """ Set the images in this album. :param images: A list of the images we want the album to contain. Can be Image objects, ids or a ...
url = (self._imgur._base_url + "/3/album/" "{0}/".format(self._delete_or_id_hash)) params = {'ids': images} return self._imgur._send_request(url, needs_auth=True, params=params, method="POST")
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def submit_to_gallery(self, title, bypass_terms=False): """ Add this to the gallery. Require that the authenticated user has accepted gallery terms and verified ...
url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) payload = {'title': title, 'terms': '1' if bypass_terms else '0'} self._imgur._send_request(url, needs_auth=True, params=payload, method='POST') item = self._imgur.get_gallery_album(self.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 update(self, title=None, description=None, images=None, cover=None, layout=None, privacy=None): """ Update the album's information. Arguments with the value ...
url = (self._imgur._base_url + "/3/album/" "{0}".format(self._delete_or_id_hash)) is_updated = self._imgur._send_request(url, params=locals(), method='POST') if is_updated: self.title = title or self.title 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 get_replies(self): """Get the replies to this comment."""
url = self._imgur._base_url + "/3/comment/{0}/replies".format(self.id) json = self._imgur._send_request(url) child_comments = json['children'] return [Comment(com, self._imgur) for com in child_comments]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def comment(self, text): """ Make a top-level comment to this. :param text: The comment text. """
url = self._imgur._base_url + "/3/comment" payload = {'image_id': self.id, 'comment': text} resp = self._imgur._send_request(url, params=payload, needs_auth=True, method='POST') return Comment(resp, imgur=self._imgur, has_fetched=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 downvote(self): """ Dislike this. A downvote will replace a neutral vote or an upvote. Downvoting something the authenticated user has already downvoted will...
url = self._imgur._base_url + "/3/gallery/{0}/vote/down".format(self.id) return self._imgur._send_request(url, needs_auth=True, method='POST')
<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_comments(self): """Get a list of the top-level comments."""
url = self._imgur._base_url + "/3/gallery/{0}/comments".format(self.id) resp = self._imgur._send_request(url) return [Comment(com, self._imgur) for com in resp]
<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_from_gallery(self): """Remove this image from the gallery."""
url = self._imgur._base_url + "/3/gallery/{0}".format(self.id) self._imgur._send_request(url, needs_auth=True, method='DELETE') if isinstance(self, Image): item = self._imgur.get_image(self.id) else: item = self._imgur.get_album(self.id) _change_object(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 download(self, path='', name=None, overwrite=False, size=None): """ Download the image. :param path: The image will be downloaded to the folder specified at ...
def save_as(filename): local_path = os.path.join(path, filename) if os.path.exists(local_path) and not overwrite: raise Exception("Trying to save as {0}, but file " "already exists.".format(local_path)) with open(local_path, '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 _send_request(self, url, needs_auth=False, **kwargs): """ Handles top level functionality for sending requests to Imgur. This mean - Raising client-side erro...
# TODO: Add automatic test for timed_out access_tokens and # automatically refresh it before carrying out the request. if self.access_token is None and needs_auth: # TODO: Use inspect to insert name of method in error msg. raise Exception("Authentication as a user is req...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorization_url(self, response, state=""): """ Return the authorization url that's needed to authorize as a user. :param response: Can be either code or pi...
return AUTHORIZE_URL.format(self._base_url, self.client_id, response, state)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def change_authentication(self, client_id=None, client_secret=None, access_token=None, refresh_token=None): """Change the current authentication."""
# TODO: Add error checking so you cannot change client_id and retain # access_token. Because that doesn't make sense. self.client_id = client_id or self.client_id self.client_secret = client_secret or self.client_secret self.access_token = access_token or self.access_token ...
<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_album(self, title=None, description=None, images=None, cover=None): """ Create a new Album. :param title: The title of the album. :param description: ...
url = self._base_url + "/3/album/" payload = {'ids': images, 'title': title, 'description': description, 'cover': cover} resp = self._send_request(url, params=payload, method='POST') return Album(resp, self, has_fetched=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 exchange_code(self, code): """Exchange one-use code for an access_token and request_token."""
params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'authorization_code', 'code': code} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method=...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def exchange_pin(self, pin): """Exchange one-use pin for an access_token and request_token."""
params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'pin', 'pin': pin} result = self._send_request(EXCHANGE_URL.format(self._base_url), params=params, method='POST', ...
<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_album(self, id): """Return information about this album."""
url = self._base_url + "/3/album/{0}".format(id) json = self._send_request(url) return Album(json, 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_at_url(self, url): """ Return a object representing the content at url. Returns None if no object could be matched with the id. Works for Album, Comment,...
class NullDevice(): def write(self, string): pass def get_gallery_item(id): """ Special helper method to get gallery items. The problem is that it's impossible to distinguish albums and images from each other based on the url...
<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_comment(self, id): """Return information about this comment."""
url = self._base_url + "/3/comment/{0}".format(id) json = self._send_request(url) return Comment(json, 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_gallery(self, section='hot', sort='viral', window='day', show_viral=True, limit=None): """ Return a list of gallery albums and gallery images. :param sec...
url = (self._base_url + "/3/gallery/{}/{}/{}/{}?showViral=" "{}".format(section, sort, window, '{}', show_viral)) resp = self._send_request(url, limit=limit) return [_get_album_or_image(thing, self) for thing in resp]
<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_gallery_album(self, id): """ Return the gallery album matching the id. Note that an album's id is different from it's id as a gallery album. This makes i...
url = self._base_url + "/3/gallery/album/{0}".format(id) resp = self._send_request(url) return Gallery_album(resp, 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_gallery_image(self, id): """ Return the gallery image matching the id. Note that an image's id is different from it's id as a gallery image. This makes i...
url = self._base_url + "/3/gallery/image/{0}".format(id) resp = self._send_request(url) return Gallery_image(resp, 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_image(self, id): """Return a Image object representing the image with the given id."""
url = self._base_url + "/3/image/{0}".format(id) resp = self._send_request(url) return Image(resp, 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_message(self, id): """ Return a Message object for given id. :param id: The id of the message object to return. """
url = self._base_url + "/3/message/{0}".format(id) resp = self._send_request(url) return Message(resp, 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_notification(self, id): """ Return a Notification object. :param id: The id of the notification object to return. """
url = self._base_url + "/3/notification/{0}".format(id) resp = self._send_request(url) return Notification(resp, 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_subreddit_image(self, subreddit, id): """ Return the Gallery_image with the id submitted to subreddit gallery :param subreddit: The subreddit the image h...
url = self._base_url + "/3/gallery/r/{0}/{1}".format(subreddit, id) resp = self._send_request(url) return Gallery_image(resp, 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_user(self, username): """ Return a User object for this username. :param username: The name of the user we want more information about. """
url = self._base_url + "/3/account/{0}".format(username) json = self._send_request(url) return User(json, 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 refresh_access_token(self): """ Refresh the access_token. The self.access_token attribute will be updated with the value of the new access_token which will a...
if self.client_secret is None: raise Exception("client_secret must be set to execute " "refresh_access_token.") if self.refresh_token is None: raise Exception("refresh_token must be set to execute " "refresh_access_token.")...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def search_gallery(self, q): """Search the gallery with the given query string."""
url = self._base_url + "/3/gallery/search?q={0}".format(q) resp = self._send_request(url) return [_get_album_or_image(thing, self) for thing in resp]
<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_image(self, path=None, url=None, title=None, description=None, album=None): """ Upload the image at either path or url. :param path: The path to the i...
if bool(path) == bool(url): raise LookupError("Either path or url must be given.") if path: with open(path, 'rb') as image_file: binary_data = image_file.read() image = b64encode(binary_data) else: image = url payload ...
<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): """Delete the message."""
url = self._imgur._base_url + "/3/message/{0}".format(self.id) return self._imgur._send_request(url, method='DELETE')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_thread(self): """Return the message thread this Message is in."""
url = (self._imgur._base_url + "/3/message/{0}/thread".format( self.first_message.id)) resp = self._imgur._send_request(url) return [Message(msg, self._imgur) for msg in resp]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def reply(self, body): """ Reply to this message. This is a convenience method calling User.send_message. See it for more information on usage. Note that both re...
return self.author.send_message(body=body, reply_to=self.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 change_settings(self, bio=None, public_images=None, messaging_enabled=None, album_privacy=None, accepted_gallery_terms=None): """ Update the settings for the...
# NOTE: album_privacy should maybe be renamed to default_privacy # NOTE: public_images is a boolean, despite the documentation saying it # is a string. url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) resp = self._imgur._send_request(url, needs_auth=True...
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_albums(self, limit=None): """ Return a list of the user's albums. Secret and hidden albums are only returned if this is the logged-in user. """
url = (self._imgur._base_url + "/3/account/{0}/albums/{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [Album(alb, self._imgur, False) for alb in resp]
<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_favorites(self): """Return the users favorited images."""
url = self._imgur._base_url + "/3/account/{0}/favorites".format(self.name) resp = self._imgur._send_request(url, needs_auth=True) return [_get_album_or_image(thing, self._imgur) for thing in resp]
<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_gallery_favorites(self): """Get a list of the images in the gallery this user has favorited."""
url = (self._imgur._base_url + "/3/account/{0}/gallery_favorites".format( self.name)) resp = self._imgur._send_request(url) return [Image(img, self._imgur) for img in resp]
<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_gallery_profile(self): """Return the users gallery profile."""
url = (self._imgur._base_url + "/3/account/{0}/" "gallery_profile".format(self.name)) return self._imgur._send_request(url)
<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_verified_email(self): """ Has the user verified that the email he has given is legit? Verified e-mail is required to the gallery. Confirmation happens by...
url = (self._imgur._base_url + "/3/account/{0}/" "verifyemail".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_images(self, limit=None): """Return all of the images associated with the user."""
url = (self._imgur._base_url + "/3/account/{0}/" "images/{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [Image(img, self._imgur) for img in resp]
<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_messages(self, new=True): """ Return all messages sent to this user, formatted as a notification. :param new: False for all notifications, True for only ...
url = (self._imgur._base_url + "/3/account/{0}/notifications/" "messages".format(self.name)) result = self._imgur._send_request(url, params=locals(), needs_auth=True) return [Notification(msg_dict, self._imgur, has_fetched=True) for ...
<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_notifications(self, new=True): """Return all the notifications for this user."""
url = (self._imgur._base_url + "/3/account/{0}/" "notifications".format(self.name)) resp = self._imgur._send_request(url, params=locals(), needs_auth=True) msgs = [Message(msg_dict, self._imgur, has_fetched=True) for msg_dict in resp['messages']] replies =...
<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_replies(self, new=True): """ Return all reply notifications for this user. :param new: False for all notifications, True for only non-viewed notification...
url = (self._imgur._base_url + "/3/account/{0}/" "notifications/replies".format(self.name)) return self._imgur._send_request(url, needs_auth=True)
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def get_settings(self): """ Returns current settings. Only accessible if authenticated as the user. """
url = self._imgur._base_url + "/3/account/{0}/settings".format(self.name) return self._imgur._send_request(url)
<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_submissions(self, limit=None): """Return a list of the images a user has submitted to the gallery."""
url = (self._imgur._base_url + "/3/account/{0}/submissions/" "{1}".format(self.name, '{}')) resp = self._imgur._send_request(url, limit=limit) return [_get_album_or_image(thing, self._imgur) for thing in resp]
<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_message(self, body, subject=None, reply_to=None): """ Send a message to this user from the logged in user. :param body: The body of the message. :param ...
url = self._imgur._base_url + "/3/message" parent_id = reply_to.id if isinstance(reply_to, Message) else reply_to payload = {'recipient': self.name, 'body': body, 'subject': subject, 'parent_id': parent_id} self._imgur._send_request(url, params=payload, needs_auth=Tru...
<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_verification_email(self): """ Send verification email to this users email address. Remember that the verification email may end up in the users spam fol...
url = (self._imgur._base_url + "/3/account/{0}" "/verifyemail".format(self.name)) self._imgur._send_request(url, needs_auth=True, method='POST')
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def hook(reverse=False, align=False, strip_path=False, enable_on_envvar_only=False, on_tty=False, conservative=False, styles=None, tb=None, tpe=None, value=None):...
if enable_on_envvar_only and 'ENABLE_BACKTRACE' not in os.environ: return isatty = getattr(sys.stderr, 'isatty', lambda: False) if on_tty and not isatty(): return if conservative: styles = CONVERVATIVE_STYLES align = align or False elif styles: for k in STY...