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 include ``"JPEG"`` and ``"PNG"``. """
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 the same as the format, return self, otherwise try the next format. If none of the formats match, return a new Image instance with the last format. """
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. :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" if extension: format = Image.image_format(extension) else: format = self.format filename = name + self.extension path = os.path.join(folder, filename) image = self.convert(format) if image._contents: f = open(path, "wb") f.write(image._contents) f.close() else: image.pil_image.save(path, format) return 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 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 filename is based on the project's :attr:`name`. :returns: Path to the saved file. """
(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() return 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 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 from self.synchroniser.wait(spec.ConnectionCloseOK) except AMQPConnectionError: # For example if both sides want to close or the connection # is closed. pass else: if self._closing: log.warn("Called `close` on already closing connection...") # finish all pending tasks yield from self.protocol.heartbeat_monitor.wait_closed()
<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.Message message: the message to send :param str routing_key: the routing key with which to publish the message :param bool mandatory: if True (the default) undeliverable messages result in an error (see also :meth:`Channel.set_return_handler`) """
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 only be deleted if it has no queues bound to it. """
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 alternate consumer. """
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 broker. If the queue does not exist, it will be created. This method is a :ref:`coroutine <coroutine>`. :param str name: the name of the queue. Supplying a name of '' will create a queue with a unique name of the server's choosing. :keyword bool durable: If true, the queue will be re-created when the server restarts. :keyword bool exclusive: If true, the queue can only be accessed by the current connection, and will be deleted when the connection is closed. :keyword bool auto_delete: If true, the queue will be deleted when the last consumer is cancelled. If there were never any conusmers, the queue won't be deleted. :keyword bool passive: If true and queue with such a name does not exist it will raise a :class:`exceptions.NotFound` instead of creating it. Arguments ``durable``, ``auto_delete`` and ``exclusive`` are ignored if ``passive=True``. :keyword bool nowait: If true, will not wait for a declare-ok to arrive. :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The new :class:`Queue` object. """
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 server. Pre-fetching means that the server will deliver messages to the client while the client is still processing unacknowledged messages. This method is a :ref:`coroutine <coroutine>`. :param int prefetch_size: Specifies a prefetch window in bytes. Messages smaller than this will be sent from the server in advance. This value may be set to 0, which means "no specific limit". :param int prefetch_count: Specifies a prefetch window in terms of whole messages. :param bool apply_globally: If true, apply these QoS settings on a global level. The meaning of this is implementation-dependent. From the `RabbitMQ documentation <https://www.rabbitmq.com/amqp-0-9-1-reference.html#basic.qos.global>`_: RabbitMQ has reinterpreted this field. The original specification said: "By default the QoS settings apply to the current channel only. If this field is set, they are applied to the entire connection." Instead, RabbitMQ takes global=false to mean that the QoS settings should apply per-consumer (for new consumers on the channel; existing ones being unaffected) and global=true to mean that the QoS settings should apply per-channel. """
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 application', 0, 0) try: yield from self.synchroniser.wait(spec.ChannelCloseOK) except AMQPError: # For example if both sides want to close or the connection # is closed. pass else: if self._closing: log.warn("Called `close` on already closing 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 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 the routing key; the precise meaning of this varies with the exchange type. This method is a :ref:`coroutine <coroutine>`. :param asynqp.Exchange exchange: the :class:`Exchange` to bind to :param str routing_key: the routing key under which to bind :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The new :class:`QueueBinding` object """
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 {}) yield from self.synchroniser.wait(spec.QueueBindOK) b = QueueBinding(self.reader, self.sender, self.synchroniser, self, exchange, routing_key) self.reader.ready() return b
<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 asynchronously to the consumer. The callback function will be called whenever a new message arrives on the queue. Advanced usage: the callback object must be callable (it must be a function or define a ``__call__`` method), but may also define some further methods: * ``callback.on_cancel()``: called with no parameters when the consumer is successfully cancelled. * ``callback.on_error(exc)``: called when the channel is closed due to an error. The argument passed is the exception which caused the error. This method is a :ref:`coroutine <coroutine>`. :param callable callback: a callback to be called when a message is delivered. The callback must accept a single argument (an instance of :class:`~asynqp.message.IncomingMessage`). :keyword bool no_local: If true, the server will not deliver messages that were published by this connection. :keyword bool no_ack: If true, messages delivered to the consumer don't require acknowledgement. :keyword bool exclusive: If true, only this consumer can access the queue. :keyword dict arguments: Table of optional parameters for extensions to the AMQP protocol. See :ref:`extensions`. :return: The newly created :class:`Consumer` object. """
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.sender, self.synchroniser, self.reader, loop=self._loop) self.consumers.add_consumer(consumer) self.reader.ready() return consumer
<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 broker does not require acknowledgement of receipt of the message. :return: an :class:`~asynqp.message.IncomingMessage`, or ``None`` if there were no messages on the queue. """
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 assert consumer_tag is None else: msg = None self.reader.ready() return 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 queue will only be deleted if it has no consumers. :keyword bool if_empty: If true, the queue will only be deleted if it has no unacknowledged messages. """
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) 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 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.cancelled_future.set_result(self) if hasattr(self.callback, 'on_cancel'): self.callback.on_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_exchange('test.exchange', 'direct') queue = yield from channel.declare_queue('test.queue') # Bind the queue to the exchange, so the queue will get messages published to the exchange yield from queue.bind(exchange, 'routing.key') # If you pass in a dict it will be automatically converted to JSON msg = asynqp.Message({'hello': 'world'}) exchange.publish(msg, 'routing.key') # Synchronously get a message from the queue received_message = yield from queue.get() print(received_message.json()) # get JSON from incoming messages easily # Acknowledge a delivered message received_message.ack() yield from channel.close() yield from connection.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 connect(host='localhost', port=5672, username='guest', password='guest', virtual_host='/', on_connection_close=None, *, loop=None, sock=None, **kwargs): """ Connect to an AMQP server on the given host and port. Log in to the given virtual host using the supplied credentials. This function is a :ref:`coroutine <coroutine>`. :param str host: the host server to connect to. :param int port: the port which the AMQP server is listening on. :param str username: the username to authenticate with. :param str password: the password to authenticate with. :param str virtual_host: the AMQP virtual host to connect to. :param func on_connection_close: function called after connection lost. :keyword BaseEventLoop loop: An instance of :class:`~asyncio.BaseEventLoop` to use. (Defaults to :func:`asyncio.get_event_loop()`) :keyword socket sock: A :func:`~socket.socket` instance to use for the connection. This is passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`. If ``sock`` is supplied then ``host`` and ``port`` will be ignored. Further keyword arguments are passed on to :meth:`loop.create_connection() <asyncio.BaseEventLoop.create_connection>`. This function will set TCP_NODELAY on TCP and TCP6 sockets either on supplied ``sock`` or created one. :return: the :class:`Connection` object. """
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 = Dispatcher() def protocol_factory(): return AMQP(dispatcher, loop, close_callback=on_connection_close) transport, protocol = yield from loop.create_connection(protocol_factory, **kwargs) # RPC-like applications require TCP_NODELAY in order to acheive # minimal response time. Actually, this library send data in one # big chunk and so this will not affect TCP-performance. sk = transport.get_extra_info('socket') # 1. Unfortunatelly we cannot check socket type (sk.type == socket.SOCK_STREAM). https://bugs.python.org/issue21327 # 2. Proto remains zero, if not specified at creation of socket if (sk.family in (socket.AF_INET, socket.AF_INET6)) and (sk.proto in (0, socket.IPPROTO_TCP)): sk.setsockopt(socket.IPPROTO_TCP, socket.TCP_NODELAY, 1) connection_info = { 'username': username, 'password': password, 'virtual_host': virtual_host } connection = yield from open_connection( loop, transport, protocol, dispatcher, connection_info) return connection
<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 close socket without ConnectionClose handshake. self.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 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)): return str(getattr(value, 'id', value)) return value
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 StateWrapper and State object. """
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.workflow.states[value] except KeyError: raise exceptions.ValidationError(self.error_messages['invalid']) res = base.StateWrapper(state, self.workflow) if res.state not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid']) return res
<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): The base.StateWrapper returned by to_python. model_instance: A WorkflowEnabled instance """
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 not in self.workflow.states: raise exceptions.ValidationError(self.error_messages['invalid_state'] % value.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 deconstruct(self): """Deconstruction for migrations. Return a simpler object (_SerializedWorkflow), since our Workflows are rather hard to serialize: Django doesn't like deconstructing metaclass-built classes. """
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.workflow._name else: workflow_class_name = self.workflow.__class__.__name__ kwargs['workflow'] = _SerializedWorkflow( name=workflow_class_name, initial_state=str(self.workflow.initial_state.name), states=[str(st.name) for st in self.workflow.states], ) del kwargs['choices'] del kwargs['default'] return name, path, 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 _get_log_model_class(self): """Cache for fetching the actual log model object once django is loaded. Otherwise, import conflict occur: WorkflowEnabled imports <log_model> which tries to import all models to retrieve the proper model class. """
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( modified_object=instance, transition=transition.name, from_state=from_state.name, to_state=transition.target.name, **extras)
<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, **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 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 added by calling refresh. """
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 combination of the two. Images that you cannot add (non-existing or not owned by you) will not cause exceptions, but fail silently. """
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, ids or a combination of the two. Images that you cannot remove (non-existing, not owned by you or not part of album) will not cause exceptions, but fail silently. """
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_request(url, params=params, 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 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 combination of the two. Images that images that you cannot set (non-existing or not owned by you) will not cause exceptions, but fail silently. """
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 their email. :param title: The title of the new gallery item. :param bypass_terms: If the user has not accepted Imgur's terms yet, this method will return an error. Set this to True to by-pass the terms. """
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) _change_object(self, item) 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 update(self, title=None, description=None, images=None, cover=None, layout=None, privacy=None): """ Update the album's information. Arguments with the value None will retain their old values. :param title: The title of the album. :param description: A description of the album. :param images: A list of the images we want the album to contain. Can be Image objects, ids or a combination of the two. Images that images that you cannot set (non-existing or not owned by you) will not cause exceptions, but fail silently. :param privacy: The albums privacy level, can be public, hidden or secret. :param cover: The id of the cover image. :param layout: The way the album is displayed, can be blog, grid, horizontal or vertical. """
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 self.description = description or self.description self.layout = layout or self.layout self.privacy = privacy or self.privacy if cover is not None: self.cover = (cover if isinstance(cover, Image) else Image({'id': cover}, self._imgur, has_fetched=False)) if images: self.images = [img if isinstance(img, Image) else Image({'id': img}, self._imgur, False) for img in images] return is_updated
<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 set the vote to neutral. """
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(self, item) 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 download(self, path='', name=None, overwrite=False, size=None): """ Download the image. :param path: The image will be downloaded to the folder specified at path, if path is None (default) then the current working directory will be used. :param name: The name the image will be stored as (not including file extension). If name is None, then the title of the image will be used. If the image doesn't have a title, it's id will be used. Note that if the name given by name or title is an invalid filename, then the hash will be used as the name instead. :param overwrite: If True overwrite already existing file with the same name as what we want to save the file as. :param size: Instead of downloading the image in it's original size, we can choose to instead download a thumbnail of it. Options are 'small_square', 'big_square', 'small_thumbnail', 'medium_thumbnail', 'large_thumbnail' or 'huge_thumbnail'. :returns: Name of the new file. """
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, 'wb') as out_file: out_file.write(resp.content) return local_path valid_sizes = {'small_square': 's', 'big_square': 'b', 'small_thumbnail': 't', 'medium_thumbnail': 'm', 'large_thumbnail': 'l', 'huge_thumbnail': 'h'} if size is not None: size = size.lower().replace(' ', '_') if size not in valid_sizes: raise LookupError('Invalid size. Valid options are: {0}'.format( ", " .join(valid_sizes.keys()))) suffix = valid_sizes.get(size, '') base, sep, ext = self.link.rpartition('.') resp = requests.get(base + suffix + sep + ext) if name or self.title: try: return save_as((name or self.title) + suffix + sep + ext) except IOError: pass # Invalid filename return save_as(self.id + suffix + sep + ext)
<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 error if insufficient authentication. - Adding authentication information to the request. - Split the request into multiple request for pagination. - Retry calls for certain server-side errors. - Refresh access token automatically if expired. - Updating ratelimit info :param needs_auth: Is authentication as a user needed for the execution of this method? """
# 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 required to use this " "method.") if self.access_token is None: # Not authenticated as a user. Use anonymous access. auth = {'Authorization': 'Client-ID {0}'.format(self.client_id)} else: auth = {'Authorization': 'Bearer {0}'.format(self.access_token)} if self.mashape_key: auth.update({'X-Mashape-Key': self.mashape_key}) content = [] is_paginated = False if 'limit' in kwargs: is_paginated = True limit = kwargs['limit'] or self.DEFAULT_LIMIT del kwargs['limit'] page = 0 base_url = url url.format(page) kwargs['authentication'] = auth while True: result = request.send_request(url, verify=self.verify, **kwargs) new_content, ratelimit_info = result if is_paginated and new_content and limit > len(new_content): content += new_content page += 1 url = base_url.format(page) else: if is_paginated: content = (content + new_content)[:limit] else: content = new_content break # Note: When the cache is implemented, it's important that the # ratelimit info doesn't get updated with the ratelimit info in the # cache since that's likely incorrect. for key, value in ratelimit_info.items(): setattr(self, key[2:].replace('-', '_'), value) return content
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def authorization_url(self, response, state=""): """ Return the authorization url that's needed to authorize as a user. :param response: Can be either code or pin. If it's code the user will be redirected to your redirect url with the code as a get parameter after authorizing your application. If it's pin then after authorizing your application, the user will instead be shown a pin on Imgurs website. Both code and pin are used to get an access_token and refresh token with the exchange_code and exchange_pin functions respectively. :param state: This optional parameter indicates any state which may be useful to your application upon receipt of the response. Imgur round-trips this parameter, so your application receives the same value it sent. Possible uses include redirecting the user to the correct resource in your site, nonces, and cross-site-request-forgery mitigations. """
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 self.refresh_token = refresh_token or self.refresh_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: The albums description. :param images: A list of the images that will be added to the album after it's created. Can be Image objects, ids or a combination of the two. Images that you cannot add (non-existing or not owned by you) will not cause exceptions, but fail silently. :param cover: The id of the image you want as the albums cover image. :returns: The newly created album. """
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='POST', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_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 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', data_field=None) self.access_token = result['access_token'] self.refresh_token = result['refresh_token'] return self.access_token, self.refresh_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 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, Gallery_album, Gallery_image, Image and User. NOTE: Imgur's documentation does not cover what urls are available. Some urls, such as imgur.com/<ID> can be for several different types of object. Using a wrong, but similair call, such as get_subreddit_image on a meme image will not cause an error. But instead return a subset of information, with either the remaining pieces missing or the value set to None. This makes it hard to create a method such as this that attempts to deduce the object from the url. Due to these factors, this method should be considered experimental and used carefully. :param url: The url where the content is located at """
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. And there isn't a common url endpoints that return either a Gallery_album or a Gallery_image depending on what the id represents. So the only option is to assume it's a Gallery_image and if we get an exception then try Gallery_album. Gallery_image is attempted first because there is the most of them. """ try: # HACK: Problem is that send_request prints the error message # from Imgur when it encounters an error. This is nice because # this error message is more descriptive than just the status # code that Requests give. But since we first assume the id # belong to an image, it means we will get an error whenever # the id belongs to an album. The following code temporarily # disables stdout to avoid give a cryptic and incorrect error. # Code for disabling stdout is from # http://coreygoldberg.blogspot.dk/2009/05/ # python-redirect-or-turn-off-stdout-and.html original_stdout = sys.stdout # keep a reference to STDOUT sys.stdout = NullDevice() # redirect the real STDOUT return self.get_gallery_image(id) # TODO: Add better error codes so I don't have to do a catch-all except Exception: return self.get_gallery_album(id) finally: sys.stdout = original_stdout # turn STDOUT back on if not self.is_imgur_url(url): return None objects = {'album': {'regex': "a/(?P<id>[\w.]*?)$", 'method': self.get_album}, 'comment': {'regex': "gallery/\w*/comment/(?P<id>[\w.]*?)$", 'method': self.get_comment}, 'gallery': {'regex': "(gallery|r/\w*?)/(?P<id>[\w.]*?)$", 'method': get_gallery_item}, # Valid image extensions: http://imgur.com/faq#types # All are between 3 and 4 chars long. 'image': {'regex': "(?P<id>[\w.]*?)(\\.\w{3,4})?$", 'method': self.get_image}, 'user': {'regex': "user/(?P<id>[\w.]*?)$", 'method': self.get_user} } parsed_url = urlparse(url) for obj_type, values in objects.items(): regex_result = re.match('/' + values['regex'], parsed_url.path) if regex_result is not None: obj_id = regex_result.group('id') initial_object = values['method'](obj_id) if obj_type == 'image': try: # A better version might be to ping the url where the # gallery_image should be with a requests.head call. If # we get a 200 returned, then that means it exists and # this becomes less hacky. original_stdout = sys.stdout sys.stdout = NullDevice() if getattr(initial_object, 'section', None): sub = initial_object.section return self.get_subreddit_image(sub, obj_id) return self.get_gallery_image(obj_id) except Exception: pass finally: sys.stdout = original_stdout return initial_object
<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 section: hot | top | user - defaults to hot. :param sort: viral | time - defaults to viral. :param window: Change the date range of the request if the section is "top", day | week | month | year | all, defaults to day. :param show_viral: true | false - Show or hide viral images from the 'user' section. Defaults to true. :param limit: The number of items to return. """
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 it possible to remove an album from the gallery and setting it's privacy setting as secret, without compromising it's secrecy. """
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 it possible to remove an image from the gallery and setting it's privacy setting as secret, without compromising it's secrecy. """
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 has been submitted to. :param id: The id of the image we want. """
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 also be returned. """
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.") params = {'client_id': self.client_id, 'client_secret': self.client_secret, 'grant_type': 'refresh_token', 'refresh_token': self.refresh_token} result = self._send_request(REFRESH_URL.format(self._base_url), params=params, method='POST', data_field=None) self.access_token = result['access_token'] return 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 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 image you want to upload. :param url: The url to the image you want to upload. :param title: The title the image will have when uploaded. :param description: The description the image will have when uploaded. :param album: The album the image will be added to when uploaded. Can be either a Album object or it's id. Leave at None to upload without adding to an Album, adding it later is possible. Authentication as album owner is necessary to upload to an album with this function. :returns: An Image object representing the uploaded image. """
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 = {'album_id': album, 'image': image, 'title': title, 'description': description} resp = self._send_request(self._base_url + "/3/image", params=payload, method='POST') # TEMPORARY HACK: # On 5-08-2013 I noticed Imgur now returned enough information from # this call to fully populate the Image object. However those variables # that matched arguments were always None, even if they had been given. # See https://groups.google.com/forum/#!topic/imgur/F3uVb55TMGo resp['title'] = title resp['description'] = description if album is not None: resp['album'] = (Album({'id': album}, self, False) if not isinstance(album, Album) else album) 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 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 recipient and reply_to are given by using this convenience method. :param body: The body of the message. """
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 user. :param bio: A basic description filled out by the user, is displayed in the gallery profile page. :param public_images: Set the default privacy setting of the users images. If True images are public, if False private. :param messaging_enabled: Set to True to enable messaging. :param album_privacy: The default privacy level of albums created by the user. Can be public, hidden or secret. :param accepted_gallery_terms: The user agreement to Imgur Gallery terms. Necessary before the user can submit to the gallery. """
# 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, params=locals(), method='POST') return 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_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 sending an email to the user and the owner of the email user verifying that he is the same as the Imgur user. """
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 non-viewed notifications. """
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 msg_dict in result]
<SYSTEM_TASK:> Solve the following problem using Python, implementing the functions described below, one line at a time <END_TASK> <USER_TASK:> Description: def 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 = [Comment(com_dict, self._imgur, has_fetched=True) for com_dict in resp['replies']] return {'messages': msgs, 'replies': 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 notifications. """
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 subject: The subject of the message. Note that if the this message is a reply, then the subject of the first message will be used instead. :param reply_to: Messages can either be replies to other messages or start a new message thread. If this is None it will start a new message thread. If it's a Message object or message_id, then the new message will be sent as a reply to the reply_to message. """
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=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 send_verification_email(self): """ Send verification email to this users email address. Remember that the verification email may end up in the users spam folder. """
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): """Hook the current excepthook to the backtrace. If `align` is True, all parts (line numbers, file names, etc..) will be aligned to the left according to the longest entry. If `strip_path` is True, only the file name will be shown, not its full path. If `enable_on_envvar_only` is True, only if the environment variable `ENABLE_BACKTRACE` is set, backtrace will be activated. If `on_tty` is True, backtrace will be activated only if you're running in a readl terminal (i.e. not piped, redirected, etc..). If `convervative` is True, the traceback will have more seemingly original style (There will be no alignment by default, 'File', 'line' and 'in' prefixes and will ignore any styling provided by the user.) See https://github.com/nir0s/backtrace/blob/master/README.md for information on `styles`. """
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 STYLES.keys(): styles[k] = styles.get(k, STYLES[k]) else: styles = STYLES # For Windows colorama.init() def backtrace_excepthook(tpe, value, tb=None): # Don't know if we're getting traceback or traceback entries. # We'll try to parse a traceback object. try: traceback_entries = traceback.extract_tb(tb) except AttributeError: traceback_entries = tb parser = _Hook(traceback_entries, align, strip_path, conservative) tpe = tpe if isinstance(tpe, str) else tpe.__name__ tb_message = styles['backtrace'].format('Traceback ({0}):'.format( 'Most recent call ' + ('first' if reverse else 'last'))) + \ Style.RESET_ALL err_message = styles['error'].format(tpe + ': ' + str(value)) + \ Style.RESET_ALL if reverse: parser.reverse() _flush(tb_message) backtrace = parser.generate_backtrace(styles) backtrace.insert(0 if reverse else len(backtrace), err_message) for entry in backtrace: _flush(entry) if tb: backtrace_excepthook(tpe=tpe, value=value, tb=tb) else: sys.excepthook = backtrace_excepthook