_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q5500 | press_check | train | def press_check(df):
"""
Remove pressure reversals from the index.
"""
new_df = df.copy()
press = new_df.copy().index.values
ref = press[0]
inversions = np.diff(np.r_[press, press[-1]]) < 0
mask = np.zeros_like(inversions)
for k, p in enumerate(inversions):
if p:
... | python | {
"resource": ""
} |
q5501 | Client.put | train | def put(self,
body: Body,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY,
ttr: int = DEFAULT_TTR) -> int:
"""Inserts a job into the currently used tube and returns the job ID.
:param body: The data representing the job.
:param priori... | python | {
"resource": ""
} |
q5502 | Client.use | train | def use(self, tube: str) -> None:
"""Changes the currently used tube.
:param tube: The tube to use.
"""
self._send_cmd(b'use %b' % tube.encode('ascii'), b'USING') | python | {
"resource": ""
} |
q5503 | Client.reserve | train | def reserve(self, timeout: Optional[int] = None) -> Job:
"""Reserves a job from a tube on the watch list, giving this client
exclusive access to it for the TTR. Returns the reserved job.
This blocks until a job is reserved unless a ``timeout`` is given,
which will raise a :class:`TimedO... | python | {
"resource": ""
} |
q5504 | Client.release | train | def release(self,
job: Job,
priority: int = DEFAULT_PRIORITY,
delay: int = DEFAULT_DELAY) -> None:
"""Releases a reserved job.
:param job: The job to release.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
... | python | {
"resource": ""
} |
q5505 | Client.bury | train | def bury(self, job: Job, priority: int = DEFAULT_PRIORITY) -> None:
"""Buries a reserved job.
:param job: The job to bury.
:param priority: An integer between 0 and 4,294,967,295 where 0 is the
most urgent.
"""
self._send_cmd(b'bury %d %d' % (job.id, pri... | python | {
"resource": ""
} |
q5506 | Client.touch | train | def touch(self, job: Job) -> None:
"""Refreshes the TTR of a reserved job.
:param job: The job to touch.
"""
self._send_cmd(b'touch %d' % job.id, b'TOUCHED') | python | {
"resource": ""
} |
q5507 | Client.watch | train | def watch(self, tube: str) -> int:
"""Adds a tube to the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to watch.
"""
return self._int_cmd(b'watch %b' % tube.encode('ascii'), b'WATCHING') | python | {
"resource": ""
} |
q5508 | Client.ignore | train | def ignore(self, tube: str) -> int:
"""Removes a tube from the watch list. Returns the number of tubes this
client is watching.
:param tube: The tube to ignore.
"""
return self._int_cmd(b'ignore %b' % tube.encode('ascii'), b'WATCHING') | python | {
"resource": ""
} |
q5509 | Client.kick | train | def kick(self, bound: int) -> int:
"""Moves delayed and buried jobs into the ready queue and returns the
number of jobs effected.
Only jobs from the currently used tube are moved.
A kick will only move jobs in a single state. If there are any buried
jobs, only those will be mov... | python | {
"resource": ""
} |
q5510 | Client.kick_job | train | def kick_job(self, job: JobOrID) -> None:
"""Moves a delayed or buried job into the ready queue.
:param job: The job or job ID to kick.
"""
self._send_cmd(b'kick-job %d' % _to_id(job), b'KICKED') | python | {
"resource": ""
} |
q5511 | Client.stats_job | train | def stats_job(self, job: JobOrID) -> Stats:
"""Returns job statistics.
:param job: The job or job ID to return statistics for.
"""
return self._stats_cmd(b'stats-job %d' % _to_id(job)) | python | {
"resource": ""
} |
q5512 | Client.stats_tube | train | def stats_tube(self, tube: str) -> Stats:
"""Returns tube statistics.
:param tube: The tube to return statistics for.
"""
return self._stats_cmd(b'stats-tube %b' % tube.encode('ascii')) | python | {
"resource": ""
} |
q5513 | Client.pause_tube | train | def pause_tube(self, tube: str, delay: int) -> None:
"""Prevents jobs from being reserved from a tube for a period of time.
:param tube: The tube to pause.
:param delay: The number of seconds to pause the tube for.
"""
self._send_cmd(b'pause-tube %b %d' % (tube.encode('ascii'), ... | python | {
"resource": ""
} |
q5514 | cli | train | def cli(conf):
"""The fedora-messaging command line interface."""
if conf:
if not os.path.isfile(conf):
raise click.exceptions.BadParameter("{} is not a file".format(conf))
try:
config.conf.load_config(config_path=conf)
except exceptions.ConfigurationException as ... | python | {
"resource": ""
} |
q5515 | consume | train | def consume(exchange, queue_name, routing_key, callback, app_name):
"""Consume messages from an AMQP queue using a Python callback."""
# The configuration validates these are not null and contain all required keys
# when it is loaded.
bindings = config.conf["bindings"]
queues = config.conf["queues"... | python | {
"resource": ""
} |
q5516 | _consume_errback | train | def _consume_errback(failure):
"""Handle any errors that occur during consumer registration."""
global _exit_code
if failure.check(exceptions.BadDeclaration):
_log.error(
"Unable to declare the %s object on the AMQP broker. The "
"broker responded with %s. Check permissions f... | python | {
"resource": ""
} |
q5517 | _consume_callback | train | def _consume_callback(consumers):
"""
Callback when consumers are successfully registered.
This simply registers callbacks for consumer.result deferred object which
fires when the consumer stops.
Args
consumers (list of fedora_messaging.api.Consumer):
The list of consumers that... | python | {
"resource": ""
} |
q5518 | _add_timeout | train | def _add_timeout(deferred, timeout):
"""
Add a timeout to the given deferred. This is designed to work with both old
Twisted and versions of Twisted with the addTimeout API. This is
exclusively to support EL7.
The deferred will errback with a :class:`defer.CancelledError` if the
version of Twis... | python | {
"resource": ""
} |
q5519 | FedoraMessagingProtocolV2._allocate_channel | train | def _allocate_channel(self):
"""
Allocate a new AMQP channel.
Raises:
NoFreeChannels: If this connection has reached its maximum number of channels.
"""
try:
channel = yield self.channel()
except pika.exceptions.NoFreeChannels:
raise N... | python | {
"resource": ""
} |
q5520 | FedoraMessagingProtocolV2.declare_exchanges | train | def declare_exchanges(self, exchanges):
"""
Declare a number of exchanges at once.
This simply wraps the :meth:`pika.channel.Channel.exchange_declare`
method and deals with error handling and channel allocation.
Args:
exchanges (list of dict): A list of dictionaries... | python | {
"resource": ""
} |
q5521 | FedoraMessagingProtocolV2.declare_queues | train | def declare_queues(self, queues):
"""
Declare a list of queues.
Args:
queues (list of dict): A list of dictionaries, where each dictionary
represents an exchange. Each dictionary can have the following keys:
* queue (str): The name of the queue
... | python | {
"resource": ""
} |
q5522 | FedoraMessagingProtocolV2.bind_queues | train | def bind_queues(self, bindings):
"""
Declare a set of bindings between queues and exchanges.
Args:
bindings (list of dict): A list of binding definitions. Each dictionary
must contain the "queue" key whose value is the name of the queue
to create the ... | python | {
"resource": ""
} |
q5523 | FedoraMessagingProtocolV2.halt | train | def halt(self):
"""
Signal to consumers they should stop after finishing any messages
currently being processed, then close the connection.
Returns:
defer.Deferred: fired when all consumers have successfully stopped
and the connection is closed.
"""
... | python | {
"resource": ""
} |
q5524 | FedoraMessagingProtocol.resumeProducing | train | def resumeProducing(self):
"""
Starts or resumes the retrieval of messages from the server queue.
This method starts receiving messages from the server, they will be
passed to the consumer callback.
.. note:: This is called automatically when :meth:`.consume` is called,
... | python | {
"resource": ""
} |
q5525 | FedoraMessagingProtocol.pauseProducing | train | def pauseProducing(self):
"""
Pause the reception of messages by canceling all existing consumers.
This does not disconnect from the server.
Message reception can be resumed with :meth:`resumeProducing`.
Returns:
Deferred: fired when the production is paused.
... | python | {
"resource": ""
} |
q5526 | get_class | train | def get_class(schema_name):
"""
Retrieve the message class associated with the schema name.
If no match is found, the default schema is returned and a warning is logged.
Args:
schema_name (six.text_type): The name of the :class:`Message` sub-class;
this is typically the Python path... | python | {
"resource": ""
} |
q5527 | get_name | train | def get_name(cls):
"""
Retrieve the schema name associated with a message class.
Returns:
str: The schema name.
Raises:
TypeError: If the message class isn't registered. Check your entry point
for correctness.
"""
global _registry_loaded
if not _registry_loaded:... | python | {
"resource": ""
} |
q5528 | load_message_classes | train | def load_message_classes():
"""Load the 'fedora.messages' entry points and register the message classes."""
for message in pkg_resources.iter_entry_points("fedora.messages"):
cls = message.load()
_log.info(
"Registering the '%s' key as the '%r' class in the Message "
"cla... | python | {
"resource": ""
} |
q5529 | get_message | train | def get_message(routing_key, properties, body):
"""
Construct a Message instance given the routing key, the properties and the
body received from the AMQP broker.
Args:
routing_key (str): The AMQP routing key (will become the message topic)
properties (pika.BasicProperties): the AMQP pr... | python | {
"resource": ""
} |
q5530 | dumps | train | def dumps(messages):
"""
Serialize messages to a JSON formatted str
Args:
messages (list): The list of messages to serialize. Each message in
the messages is subclass of Messge.
Returns:
str: Serialized messages.
Raises:
TypeError: If at least one message is no... | python | {
"resource": ""
} |
q5531 | loads | train | def loads(serialized_messages):
"""
Deserialize messages from a JSON formatted str
Args:
serialized_messages (JSON str):
Returns:
list: Deserialized message objects.
Raises:
ValidationError: If deserialized message validation failed.
KeyError: If serialized_message... | python | {
"resource": ""
} |
q5532 | Message._filter_headers | train | def _filter_headers(self):
"""
Add headers designed for filtering messages based on objects.
Returns:
dict: Filter-related headers to be combined with the existing headers
"""
headers = {}
for user in self.usernames:
headers["fedora_messaging_user... | python | {
"resource": ""
} |
q5533 | Message._encoded_routing_key | train | def _encoded_routing_key(self):
"""The encoded routing key used to publish the message on the broker."""
topic = self.topic
if config.conf["topic_prefix"]:
topic = ".".join((config.conf["topic_prefix"].rstrip("."), topic))
return topic.encode("utf-8") | python | {
"resource": ""
} |
q5534 | Message.validate | train | def validate(self):
"""
Validate the headers and body with the message schema, if any.
In addition to the user-provided schema, all messages are checked against
the base schema which requires certain message headers and the that body
be a JSON object.
.. warning:: This ... | python | {
"resource": ""
} |
q5535 | Message._dump | train | def _dump(self):
"""
Dump message attributes.
Returns:
dict: A dictionary of message attributes.
"""
return {
"topic": self.topic,
"headers": self._headers,
"id": self.id,
"body": self.body,
"queue": self.qu... | python | {
"resource": ""
} |
q5536 | _check_callback | train | def _check_callback(callback):
"""
Turns a callback that is potentially a class into a callable object.
Args:
callback (object): An object that might be a class, method, or function.
if the object is a class, this creates an instance of it.
Raises:
ValueError: If an instance ca... | python | {
"resource": ""
} |
q5537 | consume | train | def consume(callback, bindings=None, queues=None):
"""
Start a message consumer that executes the provided callback when messages are
received.
This API is blocking and will not return until the process receives a signal
from the operating system.
.. warning:: This API is runs the callback in ... | python | {
"resource": ""
} |
q5538 | FedoraMessagingFactory._on_client_ready | train | def _on_client_ready(self):
"""Called when the client is ready to send and receive messages."""
_legacy_twisted_log.msg("Successfully connected to the AMQP broker.")
yield self.client.resumeProducing()
yield self.client.declare_exchanges(self.exchanges)
yield self.client.declare... | python | {
"resource": ""
} |
q5539 | FedoraMessagingFactory.clientConnectionLost | train | def clientConnectionLost(self, connector, reason):
"""Called when the connection to the broker has been lost.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
if not isinstance(reason.value, error.ConnectionDone):
_legac... | python | {
"resource": ""
} |
q5540 | FedoraMessagingFactory.clientConnectionFailed | train | def clientConnectionFailed(self, connector, reason):
"""Called when the client has failed to connect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
_legacy_twisted_log.msg(
"Connection to the AMQP broker... | python | {
"resource": ""
} |
q5541 | FedoraMessagingFactory.stopTrying | train | def stopTrying(self):
"""Stop trying to reconnect to the broker.
See the documentation of
`twisted.internet.protocol.ReconnectingClientFactory` for details.
"""
protocol.ReconnectingClientFactory.stopTrying(self)
if not self._client_ready.called:
self._client... | python | {
"resource": ""
} |
q5542 | FedoraMessagingFactory.consume | train | def consume(self, callback, queue):
"""
Register a new consumer.
This consumer will be configured for every protocol this factory
produces so it will be reconfigured on network failures. If a connection
is already active, the consumer will be added to it.
Args:
... | python | {
"resource": ""
} |
q5543 | FedoraMessagingFactoryV2.when_connected | train | def when_connected(self):
"""
Retrieve the currently-connected Protocol, or the next one to connect.
Returns:
defer.Deferred: A Deferred that fires with a connected
:class:`FedoraMessagingProtocolV2` instance. This is similar to
the whenConnected meth... | python | {
"resource": ""
} |
q5544 | FedoraMessagingFactoryV2.consume | train | def consume(self, callback, bindings, queues):
"""
Start a consumer that lasts across individual connections.
Args:
callback (callable): A callable object that accepts one positional argument,
a :class:`Message` or a class object that implements the ``__call__``
... | python | {
"resource": ""
} |
q5545 | FedoraMessagingFactoryV2.cancel | train | def cancel(self, consumers):
"""
Cancel a consumer that was previously started with consume.
Args:
consumer (list of fedora_messaging.api.Consumer): The consumers to cancel.
"""
for consumer in consumers:
del self._consumers[consumer.queue]
pr... | python | {
"resource": ""
} |
q5546 | Consumer.cancel | train | def cancel(self):
"""
Cancel the consumer and clean up resources associated with it.
Consumers that are canceled are allowed to finish processing any
messages before halting.
Returns:
defer.Deferred: A deferred that fires when the consumer has finished
pr... | python | {
"resource": ""
} |
q5547 | validate_bindings | train | def validate_bindings(bindings):
"""
Validate the bindings configuration.
Raises:
exceptions.ConfigurationException: If the configuration provided is of an
invalid format.
"""
if not isinstance(bindings, (list, tuple)):
raise exceptions.ConfigurationException(
... | python | {
"resource": ""
} |
q5548 | validate_queues | train | def validate_queues(queues):
"""
Validate the queues configuration.
Raises:
exceptions.ConfigurationException: If the configuration provided is of an
invalid format.
"""
if not isinstance(queues, dict):
raise exceptions.ConfigurationException(
"'queues' must ... | python | {
"resource": ""
} |
q5549 | validate_client_properties | train | def validate_client_properties(props):
"""
Validate the client properties setting.
This will add the "version", "information", and "product" keys if they are
missing. All other keys are application-specific.
Raises:
exceptions.ConfigurationException: If any of the basic keys are overridden... | python | {
"resource": ""
} |
q5550 | LazyConfig._validate | train | def _validate(self):
"""
Perform checks on the configuration to assert its validity
Raises:
ConfigurationException: If the configuration is invalid.
"""
for key in self:
if key not in DEFAULTS:
raise exceptions.ConfigurationException(
... | python | {
"resource": ""
} |
q5551 | LazyConfig.load_config | train | def load_config(self, config_path=None):
"""
Load application configuration from a file and merge it with the default
configuration.
If the ``FEDORA_MESSAGING_CONF`` environment variable is set to a
filesystem path, the configuration will be loaded from that location.
Ot... | python | {
"resource": ""
} |
q5552 | _ssl_context_factory | train | def _ssl_context_factory(parameters):
"""
Produce a Twisted SSL context object from a pika connection parameter object.
This is necessary as Twisted manages the connection, not Pika.
Args:
parameters (pika.ConnectionParameters): The connection parameters built
from the fedora_messag... | python | {
"resource": ""
} |
q5553 | FedoraMessagingServiceV2.stopService | train | def stopService(self):
"""
Gracefully stop the service.
Returns:
defer.Deferred: a Deferred which is triggered when the service has
finished shutting down.
"""
self._service.factory.stopTrying()
yield self._service.factory.stopFactory()
... | python | {
"resource": ""
} |
q5554 | _configure_tls_parameters | train | def _configure_tls_parameters(parameters):
"""
Configure the pika connection parameters for TLS based on the configuration.
This modifies the object provided to it. This accounts for whether or not
the new API based on the standard library's SSLContext is available for
pika.
Args:
para... | python | {
"resource": ""
} |
q5555 | ConsumerSession._shutdown | train | def _shutdown(self):
"""Gracefully shut down the consumer and exit."""
if self._channel:
_log.info("Halting %r consumer sessions", self._channel.consumer_tags)
self._running = False
if self._connection and self._connection.is_open:
self._connection.close()
... | python | {
"resource": ""
} |
q5556 | ConsumerSession._on_cancelok | train | def _on_cancelok(self, cancel_frame):
"""
Called when the server acknowledges a cancel request.
Args:
cancel_frame (pika.spec.Basic.CancelOk): The cancelok frame from
the server.
"""
_log.info("Consumer canceled; returning all unprocessed messages to ... | python | {
"resource": ""
} |
q5557 | ConsumerSession._on_channel_open | train | def _on_channel_open(self, channel):
"""
Callback used when a channel is opened.
This registers all the channel callbacks.
Args:
channel (pika.channel.Channel): The channel that successfully opened.
"""
channel.add_on_close_callback(self._on_channel_close)
... | python | {
"resource": ""
} |
q5558 | ConsumerSession._on_qosok | train | def _on_qosok(self, qosok_frame):
"""
Callback invoked when the server acknowledges the QoS settings.
Asserts or creates the exchanges and queues exist.
Args:
qosok_frame (pika.spec.Basic.Qos): The frame send from the server.
"""
for name, args in self._exch... | python | {
"resource": ""
} |
q5559 | ConsumerSession._on_channel_close | train | def _on_channel_close(self, channel, reply_code_or_reason, reply_text=None):
"""
Callback invoked when the channel is closed.
Args:
channel (pika.channel.Channel): The channel that got closed.
reply_code_or_reason (int|Exception): The reason why the channel
... | python | {
"resource": ""
} |
q5560 | ConsumerSession._on_connection_open | train | def _on_connection_open(self, connection):
"""
Callback invoked when the connection is successfully established.
Args:
connection (pika.connection.SelectConnection): The newly-estabilished
connection.
"""
_log.info("Successfully opened connection to %... | python | {
"resource": ""
} |
q5561 | ConsumerSession._on_connection_close | train | def _on_connection_close(self, connection, reply_code_or_reason, reply_text=None):
"""
Callback invoked when a previously-opened connection is closed.
Args:
connection (pika.connection.SelectConnection): The connection that
was just closed.
reply_code_or_... | python | {
"resource": ""
} |
q5562 | ConsumerSession._on_connection_error | train | def _on_connection_error(self, connection, error_message):
"""
Callback invoked when the connection failed to be established.
Args:
connection (pika.connection.SelectConnection): The connection that
failed to open.
error_message (str): The reason the conn... | python | {
"resource": ""
} |
q5563 | ConsumerSession._on_queue_declareok | train | def _on_queue_declareok(self, frame):
"""
Callback invoked when a queue is successfully declared.
Args:
frame (pika.frame.Method): The message sent from the server.
"""
_log.info("Successfully declared the %s queue", frame.method.queue)
for binding in self._b... | python | {
"resource": ""
} |
q5564 | ConsumerSession.call_later | train | def call_later(self, delay, callback):
"""Schedule a one-shot timeout given delay seconds.
This method is only useful for compatibility with older versions of pika.
Args:
delay (float): Non-negative number of seconds from now until
expiration
callback (m... | python | {
"resource": ""
} |
q5565 | ConsumerSession.reconnect | train | def reconnect(self):
"""Will be invoked by the IOLoop timer if the connection is
closed. See the _on_connection_close method.
"""
# This is the old connection instance, stop its ioloop.
self._connection.ioloop.stop()
if self._running:
# Create a new connection... | python | {
"resource": ""
} |
q5566 | ConsumerSession.consume | train | def consume(self, callback, bindings=None, queues=None, exchanges=None):
"""
Consume messages from a message queue.
Simply define a callable to be used as the callback when messages are
delivered and specify the queue bindings. This call blocks. The callback
signature should acc... | python | {
"resource": ""
} |
q5567 | get_avatar | train | def get_avatar(from_header, size=64, default="retro"):
"""Get the avatar URL from the email's From header.
Args:
from_header (str): The email's From header. May contain the sender's full name.
Returns:
str: The URL to that sender's avatar.
"""
params = OrderedDict([("s", size), ("d... | python | {
"resource": ""
} |
q5568 | BaseMessage.url | train | def url(self):
"""An URL to the email in HyperKitty
Returns:
str or None: A relevant URL.
"""
base_url = "https://lists.fedoraproject.org/archives"
archived_at = self._get_archived_at()
if archived_at and archived_at.startswith("<"):
archived_at =... | python | {
"resource": ""
} |
q5569 | user_avatar_url | train | def user_avatar_url(username, size=64, default="retro"):
"""Get the avatar URL of the provided Fedora username.
The URL is returned from the Libravatar service.
Args:
username (str): The username to get the avatar of.
size (int): Size of the avatar in pixels (it's a square).
defaul... | python | {
"resource": ""
} |
q5570 | libravatar_url | train | def libravatar_url(email=None, openid=None, size=64, default="retro"):
"""Get the URL to an avatar from libravatar.
Either the user's email or openid must be provided.
If you want to use Libravatar federation (through DNS), you should install
and use the ``libravatar`` library instead. Check out the
... | python | {
"resource": ""
} |
q5571 | get_all_fields | train | def get_all_fields(obj):
"""Returns a list of all field names on the instance."""
fields = []
for f in obj._meta.fields:
fname = f.name
get_choice = "get_" + fname + "_display"
if hasattr(obj, get_choice):
value = getattr(obj, get_choice)()
else:
try:... | python | {
"resource": ""
} |
q5572 | query_string | train | def query_string(context, **kwargs):
"""Add param to the given query string"""
params = context["request"].GET.copy()
for key, value in list(kwargs.items()):
params[key] = value
return "?" + params.urlencode() | python | {
"resource": ""
} |
q5573 | arctic_url | train | def arctic_url(context, link, *args, **kwargs):
"""
Resolves links into urls with optional
arguments set in self.urls. please check get_urls method in View.
We could tie this to check_url_access() to check for permissions,
including object-level.
"""
def reverse_mutable_url_args(url_args):... | python | {
"resource": ""
} |
q5574 | get_role_model | train | def get_role_model():
"""
Returns the Role model that is active in this project.
"""
app_model = getattr(settings, "ARCTIC_ROLE_MODEL", "arctic.Role")
try:
return django_apps.get_model(app_model)
except ValueError:
raise ImproperlyConfigured(
"ARCTIC_ROLE_MODEL must ... | python | {
"resource": ""
} |
q5575 | get_user_role_model | train | def get_user_role_model():
"""
Returns the UserRole model that is active in this project.
"""
app_model = getattr(settings, "ARCTIC_USER_ROLE_MODEL", "arctic.UserRole")
try:
return django_apps.get_model(app_model)
except ValueError:
raise ImproperlyConfigured(
"ARCTI... | python | {
"resource": ""
} |
q5576 | View.dispatch | train | def dispatch(self, request, *args, **kwargs):
"""
Most views in a CMS require a login, so this is the default setup.
If a login is not required then the requires_login property
can be set to False to disable this.
"""
if self.requires_login:
if settings.LOGIN... | python | {
"resource": ""
} |
q5577 | View.media | train | def media(self):
"""
Return all media required to render this view, including forms.
"""
media = self._get_common_media()
media += self._get_view_media()
media += self.get_media_assets()
return media | python | {
"resource": ""
} |
q5578 | View._get_view_media | train | def _get_view_media(self):
"""
Gather view-level media assets
"""
try:
css = self.Media.css
except AttributeError:
css = {}
try:
js = self.Media.js
except AttributeError:
js = []
return Media(css=css, js=js) | python | {
"resource": ""
} |
q5579 | DataListView.get_paginator | train | def get_paginator(
self,
dataset,
per_page,
orphans=0,
allow_empty_first_page=True,
**kwargs
):
"""Return an instance of the paginator for this view."""
return IndefinitePaginator(
dataset,
per_page,
orphans=orphans,... | python | {
"resource": ""
} |
q5580 | DeleteView.get | train | def get(self, request, *args, **kwargs):
"""
Catch protected relations and show to user.
"""
self.object = self.get_object()
can_delete = True
protected_objects = []
collector_message = None
collector = Collector(using="default")
try:
c... | python | {
"resource": ""
} |
q5581 | ModalMixin.get_modal_link | train | def get_modal_link(self, url, obj={}):
"""
Returns the metadata for a link that needs to be confirmed, if it
exists, it also parses the message and title of the url to include
row field data if needed.
"""
if not (url in self.modal_links.keys()):
return None
... | python | {
"resource": ""
} |
q5582 | FormMixin.get_success_url | train | def get_success_url(self):
"""Return the URL to redirect to after processing a valid form."""
if not self.success_url:
if self.request.GET.get("inmodal"):
return reverse("arctic:redirect_to_parent")
raise ImproperlyConfigured(
"No URL to redirect t... | python | {
"resource": ""
} |
q5583 | FormMixin._set_has_no_columns | train | def _set_has_no_columns(self, has_no_column, col_avg, col_last, fields):
"""
Regenerate has_no_column by adding the amount of columns at the end
"""
for index, field in has_no_column.items():
if index == len(has_no_column):
field_name = "{field}|{col_last}".fo... | python | {
"resource": ""
} |
q5584 | FormMixin._return_fieldset | train | def _return_fieldset(self, fieldset):
"""
This function became a bit messy, since it needs to deal with two
cases.
1) No fieldset, which is represented as an integer
2) A fieldset
"""
collapsible = None
description = None
try:
# Make s... | python | {
"resource": ""
} |
q5585 | ListMixin.ordering_url | train | def ordering_url(self, field_name):
"""
Creates a url link for sorting the given field.
The direction of sorting will be either ascending, if the field is not
yet sorted, or the opposite of the current sorting if sorted.
"""
path = self.request.path
direction = "... | python | {
"resource": ""
} |
q5586 | ListMixin.get_fields | train | def get_fields(self, strip_labels=False):
"""
Hook to dynamically change the fields that will be displayed
"""
if strip_labels:
return [
f[0] if type(f) in (tuple, list) else f for f in self.fields
]
return self.fields | python | {
"resource": ""
} |
q5587 | ListMixin.get_ordering_fields_lookups | train | def get_ordering_fields_lookups(self):
"""
Getting real model fields to order by
"""
ordering_field = []
for field_name in self.get_ordering_fields():
ordering_field.append(self._get_ordering_field_lookup(field_name))
return ordering_field | python | {
"resource": ""
} |
q5588 | ListMixin._get_ordering_field_lookup | train | def _get_ordering_field_lookup(self, field_name):
"""
get real model field to order by
"""
field = field_name
get_field = getattr(self, "get_%s_ordering_field" % field_name, None)
if get_field:
field = get_field()
return field | python | {
"resource": ""
} |
q5589 | ListMixin.get_advanced_search_form | train | def get_advanced_search_form(self, data):
"""
Hook to dynamically change the advanced search form
"""
if self.get_advanced_search_form_class():
self._advanced_search_form = self.get_advanced_search_form_class()(
data=data
)
return self.... | python | {
"resource": ""
} |
q5590 | RoleAuthentication.sync | train | def sync(cls):
"""
Save all the roles defined in the settings that are not yet in the db
this is needed to create a foreign key relation between a user and a
role. Roles that are no longer specified in settings are set as
inactive.
"""
try:
settings_ro... | python | {
"resource": ""
} |
q5591 | RoleAuthentication.get_permission_required | train | def get_permission_required(cls):
"""
Get permission required property.
Must return an iterable.
"""
if cls.permission_required is None:
raise ImproperlyConfigured(
"{0} is missing the permission_required attribute. "
"Define {0}.permis... | python | {
"resource": ""
} |
q5592 | RoleAuthentication.has_permission | train | def has_permission(cls, user):
"""
We override this method to customize the way permissions are checked.
Using our roles to check permissions.
"""
# no login is needed, so its always fine
if not cls.requires_login:
return True
# if user is somehow not... | python | {
"resource": ""
} |
q5593 | RoleAuthentication.check_permission | train | def check_permission(cls, role, permission):
"""
Check if role contains permission
"""
result = permission in settings.ARCTIC_ROLES[role]
# will try to call a method with the same name as the permission
# to enable an object level permission check.
if result:
... | python | {
"resource": ""
} |
q5594 | str_to_bool | train | def str_to_bool(val):
"""
Helper function to turn a string representation of "true" into
boolean True.
"""
if isinstance(val, str):
val = val.lower()
return val in ["true", "on", "yes", True] | python | {
"resource": ""
} |
q5595 | menu | train | def menu(menu_config=None, **kwargs):
"""
Tranforms a menu definition into a dictionary which is a frendlier format
to parse in a template.
"""
request = kwargs.pop("request", None)
user = kwargs.pop("user", None)
url_full_name = ":".join(
[request.resolver_match.namespace, request.r... | python | {
"resource": ""
} |
q5596 | view_from_url | train | def view_from_url(named_url): # noqa
"""
Finds and returns the view class from a named url
"""
# code below is `stolen` from django's reverse method.
resolver = get_resolver(get_urlconf())
if type(named_url) in (list, tuple):
named_url = named_url[0]
parts = named_url.split(":")
... | python | {
"resource": ""
} |
q5597 | find_field_meta | train | def find_field_meta(obj, value):
"""
In a model, finds the attribute meta connected to the last object when
a chain of connected objects is given in a string separated with double
underscores.
"""
if "__" in value:
value_list = value.split("__")
child_obj = obj._meta.get_field(v... | python | {
"resource": ""
} |
q5598 | get_field_class | train | def get_field_class(qs, field_name):
"""
Given a queryset and a field name, it will return the field's class
"""
try:
return qs.model._meta.get_field(field_name).__class__.__name__
# while annotating, it's possible that field does not exists.
except FieldDoesNotExist:
return None | python | {
"resource": ""
} |
q5599 | arctic_setting | train | def arctic_setting(setting_name, valid_options=None):
"""
Tries to get a setting from the django settings, if not available defaults
to the one defined in defaults.py
"""
try:
value = getattr(settings, setting_name)
if valid_options and value not in valid_options:
error_m... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.