Search is not available for this dataset
text stringlengths 75 104k |
|---|
def get_queryset(self):
"""Optionally restricts the returned articles by filtering against a `topic`
query parameter in the URL."""
# Get base queryset from DispatchPublishableMixin
queryset = self.get_publishable_queryset()
# Optimize queries by prefetching related data
... |
def get_queryset(self):
"""Only display unpublished content to authenticated users, filter by
query parameter if present."""
# Get base queryset from DispatchPublishableMixin
queryset = self.get_publishable_queryset()
queryset = queryset.order_by('-updated_at')
# Optio... |
def get_attribute(self, instance):
"""Overrides the default get_attribute method to convert None values to False."""
attr = super(NullBooleanField, self).get_attribute(instance)
return True if attr else False |
def validate_widget(widget):
"""Checks that the given widget contains the required fields"""
if not has_valid_id(widget):
raise InvalidWidget("%s must contain a valid 'id' attribute" % widget.__name__)
if not has_valid_name(widget):
raise InvalidWidget("%s must contain a valid 'name' attri... |
def validate_zone(zone):
"""Checks that the given zone contains the required fields"""
if not has_valid_id(zone):
raise InvalidZone("%s must contain a valid 'id' attribute" % zone.__name__)
if not has_valid_name(zone):
raise InvalidZone("%s must contain a valid 'name' attribute" % zone.__n... |
def is_valid_uuid(id):
"""Return True if id is a valid UUID, False otherwise."""
if not isinstance(id, basestring):
return False
try:
val = UUID(id, version=4)
except ValueError:
return False
return True |
def get_permissions(self):
"""Returns the user's permissions."""
permissions = ''
if self.groups.filter(name='Admin').exists() or self.is_superuser:
permissions = 'admin'
return permissions |
def modify_permissions(self, permissions):
"""Modify the user's permissions."""
group = Group.objects.get(name='Admin')
if permissions == 'admin':
self.groups.add(group)
else:
self.groups.remove(group) |
def AuthorValidator(data):
"""Raise a ValidationError if data does not match the author format."""
if not isinstance(data, list):
# Convert single instance to a list
data = [data]
for author in data:
if 'person' not in author:
raise ValidationError('An author must contai... |
def save(self, validated_data):
"""Save widget data for this zone."""
(zone, created) = ZoneModel.objects.get_or_create(zone_id=self.id)
zone.widget_id = validated_data['widget']
zone.data = validated_data['data']
# Call widget before-save hook on nested widgets
for ke... |
def get_data(self):
"""Returns data from each field."""
result = {}
for field in self.fields:
result[field.name] = self.data.get(field.name)
return result |
def prepare_data(self):
"""Prepare widget data for template."""
result = {}
for field in self.fields:
data = self.data.get(field.name)
result[field.name] = field.prepare_data(data)
return result |
def render(self, data=None, add_context=None):
"""Renders the widget as HTML."""
template = loader.get_template(self.template)
if not data:
data = self.context(self.prepare_data())
if add_context is not None:
for key, value in add_context.iteritems():
... |
def content_to_html(content, article_id):
"""Returns artilce/page content as HTML"""
def render_node(html, node, index):
"""Renders node as HTML"""
if node['type'] == 'paragraph':
return html + '<p>%s</p>' % node['data']
else:
if node['type'] == 'ad':
... |
def content_to_json(content):
"""Returns article/page content as JSON"""
def render_node(node):
"""Renders node as JSON"""
if node['type'] == 'paragraph':
return node
else:
return {
'type': node['type'],
'data': embeds.to_json(nod... |
def get_settings(cls, show_hidden=False):
"""
Retrieves the settings for this integration as a dictionary.
Removes all hidden fields if show_hidden=False
"""
settings = Integration.objects.get_settings(cls.ID)
if not show_hidden:
for field in cls.HIDDEN_FIEL... |
def callback(cls, user, query):
"""Receive OAuth callback request from Facebook."""
# Get settings for this integration
settings = cls.get_settings(show_hidden=True)
fb = Facebook()
payload = {
'client_id': settings['client_id'],
'client_secret': settin... |
def get_settings(self, integration_id):
"""Return settings for given integration as a dictionary."""
try:
integration = self.get(integration_id=integration_id)
return json.loads(integration.settings)
except (self.model.DoesNotExist, ValueError):
return {} |
def update_settings(self, integration_id, settings):
"""Updates settings for given integration."""
(integration, created) = self.get_or_create(integration_id=integration_id)
try:
current_settings = json.loads(integration.settings)
except ValueError:
current_sett... |
def signup(request, uuid=None):
"""Handles requests to the user signup page."""
invite = get_object_or_404(Invite.objects.all(), id=uuid)
if invite.expiration_date < timezone.now():
invite.delete()
raise Http404('This page does not exist.')
if request.method == 'POST':
form = ... |
def maptag(tagname, contents):
"""Returns the HTML produced from enclosing each item in
`contents` in a tag of type `tagname`"""
return u''.join(tag(tagname, item) for item in contents) |
def zone(zone_id, **kwargs):
"""Renders the contents of the zone with given zone_id."""
try:
zone = ThemeManager.Zones.get(zone_id)
except ZoneNotFound:
return ''
try:
return zone.widget.render(add_context=kwargs)
except (WidgetNotFound, AttributeError):
pass
r... |
def save(self, revision=True, *args, **kwargs):
"""
Handles the saving/updating of a Publishable instance.
Arguments:
revision - if True, a new version of this Publishable will be created.
"""
if revision:
# If this is a revision, set it to be the head of th... |
def save_featured_image(self, data):
"""
Handles saving the featured image.
If data is None, the featured image will be removed.
`data` should be dictionary with the following format:
{
'image_id': int,
'caption': str,
'credit': str
... |
def save_subsection(self, subsection_id):
""" Save the subsection to the parent article """
Article.objects.filter(parent_id=self.parent.id).update(subsection_id=subsection_id) |
def get_extension(self):
"""Returns the file extension."""
ext = os.path.splitext(self.img.name)[1]
if ext:
# Remove period from extension
return ext[1:]
return ext |
def get_medium_url(self):
"""Returns the medium size image URL."""
if self.is_gif():
return self.get_absolute_url()
return '%s%s-%s.jpg' % (settings.MEDIA_URL, self.get_name(), 'medium') |
def save(self, **kwargs):
"""Custom save method to process thumbnails and save image dimensions."""
is_new = self.pk is None
if is_new:
# Make filenames lowercase
self.img.name = self.img.name.lower()
# Call super method
super(Image, self).save(*... |
def save_thumbnail(self, image, size, name, label, file_type):
"""Processes and saves a resized thumbnail version of the image."""
width, height = size
(imw, imh) = image.size
# If image is larger than thumbnail size, resize image
if (imw > width) or (imh > height):
... |
def init_app(self, app):
"""Initialize the `app` for use with this
:class:`~flask_mysqldb.MySQL` class.
This is called automatically if `app` is passed to
:meth:`~MySQL.__init__`.
:param flask.Flask app: the application to configure for use with
this :class:`~flask_m... |
def connection(self):
"""Attempts to connect to the MySQL server.
:return: Bound MySQL connection object if successful or ``None`` if
unsuccessful.
"""
ctx = _app_ctx_stack.top
if ctx is not None:
if not hasattr(ctx, 'mysql_db'):
ctx.mysq... |
def get_bandwith_limited_stream(self, fileobj, transfer_coordinator,
enabled=True):
"""Wraps a fileobj in a bandwidth limited stream wrapper
:type fileobj: file-like obj
:param fileobj: The file-like obj to wrap
:type transfer_coordinator: s3transfer... |
def read(self, amount):
"""Read a specified amount
Reads will only be throttled if bandwidth limiting is enabled.
"""
if not self._bandwidth_limiting_enabled:
return self._fileobj.read(amount)
# We do not want to be calling consume on every read as the read
... |
def consume(self, amt, request_token):
"""Consume an a requested amount
:type amt: int
:param amt: The amount of bytes to request to consume
:type request_token: RequestToken
:param request_token: The token associated to the consumption
request that is used to ident... |
def schedule_consumption(self, amt, token, time_to_consume):
"""Schedules a wait time to be able to consume an amount
:type amt: int
:param amt: The amount of bytes scheduled to be consumed
:type token: RequestToken
:param token: The token associated to the consumption
... |
def process_scheduled_consumption(self, token):
"""Processes a scheduled consumption request that has completed
:type token: RequestToken
:param token: The token associated to the consumption
request that is used to identify the request.
"""
scheduled_retry = self._t... |
def get_projected_rate(self, amt, time_at_consumption):
"""Get the projected rate using a provided amount and time
:type amt: int
:param amt: The proposed amount to consume
:type time_at_consumption: float
:param time_at_consumption: The proposed time to consume at
:rt... |
def record_consumption_rate(self, amt, time_at_consumption):
"""Record the consumption rate based off amount and time point
:type amt: int
:param amt: The amount that got consumed
:type time_at_consumption: float
:param time_at_consumption: The time at which the amount was cons... |
def download_file(self, bucket, key, filename, extra_args=None,
expected_size=None):
"""Downloads the object's contents to a file
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to dow... |
def poll_for_result(self, transfer_id):
"""Poll for the result of a transfer
:param transfer_id: Unique identifier for the transfer
:return: If the transfer succeeded, it will return the result. If the
transfer failed, it will raise the exception associated to the
failur... |
def calculate_range_parameter(part_size, part_index, num_parts,
total_size=None):
"""Calculate the range parameter for multipart downloads/copies
:type part_size: int
:param part_size: The size of the part
:type part_index: int
:param part_index: The index for which t... |
def get_callbacks(transfer_future, callback_type):
"""Retrieves callbacks from a subscriber
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future the subscriber is associated
to.
:type callback_type: str
:param callback_type: The type of callb... |
def get_filtered_dict(original_dict, whitelisted_keys):
"""Gets a dictionary filtered by whitelisted keys
:param original_dict: The original dictionary of arguments to source keys
and values.
:param whitelisted_key: A list of keys to include in the filtered
dictionary.
:returns: A dict... |
def decrement(self):
"""Decrement the count by one"""
with self._lock:
if self._count == 0:
raise RuntimeError(
'Counter is at zero. It cannot dip below zero')
self._count -= 1
if self._is_finalized and self._count == 0:
... |
def finalize(self):
"""Finalize the counter
Once finalized, the counter never be incremented and the callback
can be invoked once the count reaches zero
"""
with self._lock:
self._is_finalized = True
if self._count == 0:
self._callback() |
def is_special_file(cls, filename):
"""Checks to see if a file is a special UNIX file.
It checks if the file is a character special device, block special
device, FIFO, or socket.
:param filename: Name of the file
:returns: True if the file is a special file. False, if is not.
... |
def from_filename(cls, filename, start_byte, chunk_size, callbacks=None,
enable_callbacks=True):
"""Convenience factory function to create from a filename.
:type start_byte: int
:param start_byte: The first byte from which to start reading.
:type chunk_size: int
... |
def acquire(self, tag, blocking=True):
"""Acquire the semaphore
:param tag: A tag identifying what is acquiring the semaphore. Note
that this is not really needed to directly use this class but is
needed for API compatibility with the SlidingWindowSemaphore
implement... |
def release(self, tag, acquire_token):
"""Release the semaphore
:param tag: A tag identifying what is releasing the semaphore
:param acquire_token: The token returned from when the semaphore was
acquired. Note that this is not really needed to directly use this
class bu... |
def adjust_chunksize(self, current_chunksize, file_size=None):
"""Get a chunksize close to current that fits within all S3 limits.
:type current_chunksize: int
:param current_chunksize: The currently configured chunksize.
:type file_size: int or None
:param file_size: The size ... |
def queue_file_io_task(self, fileobj, data, offset):
"""Queue IO write for submission to the IO executor.
This method accepts an IO executor and information about the
downloaded data, and handles submitting this to the IO executor.
This method may defer submission to the IO executor if... |
def get_io_write_task(self, fileobj, data, offset):
"""Get an IO write task for the requested set of data
This task can be ran immediately or be submitted to the IO executor
for it to run.
:type fileobj: file-like object
:param fileobj: The file-like object to write to
... |
def _get_download_output_manager_cls(self, transfer_future, osutil):
"""Retrieves a class for managing output for a download
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:type osutil: s3transfer.utils.OSUtils
... |
def _submit(self, client, config, osutil, request_executor, io_executor,
transfer_future, bandwidth_limiter=None):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associ... |
def _main(self, client, bucket, key, fileobj, extra_args, callbacks,
max_attempts, download_output_manager, io_chunksize,
start_index=0, bandwidth_limiter=None):
"""Downloads an object and places content into io queue
:param client: The client to use when calling GetObject
... |
def _main(self, fileobj, data, offset):
"""Pulls off an io queue to write contents to a file
:param fileobj: The file handle to write content to
:param data: The data to write
:param offset: The offset to write the data to.
"""
fileobj.seek(offset)
fileobj.write(... |
def request_writes(self, offset, data):
"""Request any available writes given new incoming data.
You call this method by providing new data along with the
offset associated with the data. If that new data unlocks
any contiguous writes that can now be submitted, this
method will... |
def seekable(fileobj):
"""Backwards compat function to determine if a fileobj is seekable
:param fileobj: The file-like object to determine if seekable
:returns: True, if seekable. False, otherwise.
"""
# If the fileobj has a seekable attr, try calling the seekable()
# method on it.
if has... |
def upload(self, fileobj, bucket, key, extra_args=None, subscribers=None):
"""Uploads a file to S3
:type fileobj: str or seekable file-like object
:param fileobj: The name of a file to upload or a seekable file-like
object to upload. It is recommended to use a filename because
... |
def download(self, bucket, key, fileobj, extra_args=None,
subscribers=None):
"""Downloads a file from S3
:type bucket: str
:param bucket: The name of the bucket to download from
:type key: str
:param key: The name of the key to download from
:type file... |
def copy(self, copy_source, bucket, key, extra_args=None,
subscribers=None, source_client=None):
"""Copies a file in S3
:type copy_source: dict
:param copy_source: The name of the source bucket, key name of the
source object, and optional version ID of the source object... |
def delete(self, bucket, key, extra_args=None, subscribers=None):
"""Delete an S3 object.
:type bucket: str
:param bucket: The name of the bucket.
:type key: str
:param key: The name of the S3 object to delete.
:type extra_args: dict
:param extra_args: Extra ar... |
def shutdown(self, cancel=False, cancel_msg=''):
"""Shutdown the TransferManager
It will wait till all transfers complete before it completely shuts
down.
:type cancel: boolean
:param cancel: If True, calls TransferFuture.cancel() for
all in-progress in transfers. T... |
def cancel(self, msg='', exc_type=CancelledError):
"""Cancels all inprogress transfers
This cancels the inprogress transfers by calling cancel() on all
tracked transfer coordinators.
:param msg: The message to pass on to each transfer coordinator that
gets cancelled.
... |
def wait(self):
"""Wait until there are no more inprogress transfers
This will not stop when failures are encountered and not propogate any
of these errors from failed transfers, but it can be interrupted with
a KeyboardInterrupt.
"""
try:
transfer_coordinato... |
def _read(self, fileobj, amount, truncate=True):
"""
Reads a specific amount of data from a stream and returns it. If there
is any data in initial_data, that will be popped out first.
:type fileobj: A file-like object that implements read
:param fileobj: The stream to read from.... |
def _wrap_data(self, data, callbacks, close_callbacks):
"""
Wraps data with the interrupt reader and the file chunk reader.
:type data: bytes
:param data: The data to wrap.
:type callbacks: list
:param callbacks: The callbacks associated with the transfer future.
... |
def _get_upload_input_manager_cls(self, transfer_future):
"""Retrieves a class for managing input for an upload based on file type
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future for the request
:rtype: class of UploadInputManager
... |
def _submit(self, client, config, osutil, request_executor,
transfer_future, bandwidth_limiter=None):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associated with the... |
def _main(self, client, fileobj, bucket, key, extra_args):
"""
:param client: The client to use when calling PutObject
:param fileobj: The file to upload.
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param extra_args: A ... |
def _main(self, client, fileobj, bucket, key, upload_id, part_number,
extra_args):
"""
:param client: The client to use when calling PutObject
:param fileobj: The file to upload.
:param bucket: The name of the bucket to upload to
:param key: The name of the key to u... |
def set_exception(self, exception):
"""Sets the exception on the future."""
if not self.done():
raise TransferNotDoneError(
'set_exception can only be called once the transfer is '
'complete.')
self._coordinator.set_exception(exception, override=True) |
def set_result(self, result):
"""Set a result for the TransferFuture
Implies that the TransferFuture succeeded. This will always set a
result because it is invoked on the final task where there is only
ever one final task and it is ran at the very end of a transfer
process. So i... |
def set_exception(self, exception, override=False):
"""Set an exception for the TransferFuture
Implies the TransferFuture failed.
:param exception: The exception that cause the transfer to fail.
:param override: If True, override any existing state.
"""
with self._lock:... |
def result(self):
"""Waits until TransferFuture is done and returns the result
If the TransferFuture succeeded, it will return the result. If the
TransferFuture failed, it will raise the exception associated to the
failure.
"""
# Doing a wait() with no timeout cannot be ... |
def cancel(self, msg='', exc_type=CancelledError):
"""Cancels the TransferFuture
:param msg: The message to attach to the cancellation
:param exc_type: The type of exception to set for the cancellation
"""
with self._lock:
if not self.done():
should_a... |
def submit(self, executor, task, tag=None):
"""Submits a task to a provided executor
:type executor: s3transfer.futures.BoundedExecutor
:param executor: The executor to submit the callable to
:type task: s3transfer.tasks.Task
:param task: The task to submit to the executor
... |
def add_done_callback(self, function, *args, **kwargs):
"""Add a done callback to be invoked when transfer is done"""
with self._done_callbacks_lock:
self._done_callbacks.append(
FunctionContainer(function, *args, **kwargs)
) |
def add_failure_cleanup(self, function, *args, **kwargs):
"""Adds a callback to call upon failure"""
with self._failure_cleanups_lock:
self._failure_cleanups.append(
FunctionContainer(function, *args, **kwargs)) |
def announce_done(self):
"""Announce that future is done running and run associated callbacks
This will run any failure cleanups if the transfer failed if not
they have not been run, allows the result() to be unblocked, and will
run any done callbacks associated to the TransferFuture if... |
def submit(self, task, tag=None, block=True):
"""Submit a task to complete
:type task: s3transfer.tasks.Task
:param task: The task to run __call__ on
:type tag: s3transfer.futures.TaskTag
:param tag: An optional tag to associate to the task. This
is used to overrid... |
def add_done_callback(self, fn):
"""Adds a callback to be completed once future is done
:parm fn: A callable that takes no arguments. Note that is different
than concurrent.futures.Future.add_done_callback that requires
a single argument for the future.
"""
# The... |
def _submit(self, client, request_executor, transfer_future, **kwargs):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associated with the transfer
manager
:type o... |
def _submit(self, client, config, osutil, request_executor,
transfer_future):
"""
:param client: The client associated with the transfer manager
:type config: s3transfer.manager.TransferConfig
:param config: The transfer config associated with the transfer
ma... |
def _main(self, client, copy_source, bucket, key, extra_args, callbacks,
size):
"""
:param client: The client to use when calling PutObject
:param copy_source: The CopySource parameter to use
:param bucket: The name of the bucket to copy to
:param key: The name of t... |
def _main(self, client, copy_source, bucket, key, upload_id, part_number,
extra_args, callbacks, size):
"""
:param client: The client to use when calling PutObject
:param copy_source: The CopySource parameter to use
:param bucket: The name of the bucket to upload to
... |
def from_filename(cls, filename, start_byte, chunk_size, callback=None,
enable_callback=True):
"""Convenience factory function to create from a filename.
:type start_byte: int
:param start_byte: The first byte from which to start reading.
:type chunk_size: int
... |
def upload_file(self, filename, bucket, key,
callback=None, extra_args=None):
"""Upload a file to an S3 object.
Variants have also been injected into S3 client, Bucket and Object.
You don't have to use S3Transfer.upload_file() directly.
"""
if extra_args is N... |
def download_file(self, bucket, key, filename, extra_args=None,
callback=None):
"""Download an S3 object to a file.
Variants have also been injected into S3 client, Bucket and Object.
You don't have to use S3Transfer.download_file() directly.
"""
# This met... |
def _main(self, transfer_future, **kwargs):
"""
:type transfer_future: s3transfer.futures.TransferFuture
:param transfer_future: The transfer future associated with the
transfer request that tasks are being submitted for
:param kwargs: Any additional kwargs that you may want... |
def _main(self, client, bucket, key, extra_args):
"""
:param client: The client to use when calling CreateMultipartUpload
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param extra_args: A dictionary of any extra arguments that ma... |
def _main(self, client, bucket, key, upload_id, parts, extra_args):
"""
:param client: The client to use when calling CompleteMultipartUpload
:param bucket: The name of the bucket to upload to
:param key: The name of the key to upload to
:param upload_id: The id of the upload
... |
def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
# Parso reads files in bi... |
def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file"""
func_defs = [func for func in self.py_tree.iter_funcdefs()] + [func for cls in self.py_tree.iter_classdefs() for func in cls.iter_funcdefs()]
for func in func_defs:
for decorator in func.get... |
def _step_decorator_args(self, decorator):
"""
Get the arguments passed to step decorators
converted to python objects.
"""
args = decorator.children[3:-2]
step = None
if len(args) == 1:
try:
step = ast.literal_eval(args[0].get_code())
... |
def iter_steps(self):
"""Iterate over steps in the parsed file."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
if step:
span = self._span_from_pos(decorator.start_pos, func.end_pos)
yield st... |
def _find_step_node(self, step_text):
"""Find the ast node which contains the text."""
for func, decorator in self._iter_step_func_decorators():
step = self._step_decorator_args(decorator)
arg_node = decorator.children[3]
if step == step_text:
return a... |
def refactor_step(self, old_text, new_text, move_param_from_idx):
"""
Find the step with old_text and change it to new_text.The step function
parameters are also changed according to move_param_from_idx.
Each entry in this list should specify parameter position from old.
"""
... |
def parse(file_path, content=None):
"""
Create a PythonFile object with specified file_path and content.
If content is None then, it is loaded from the file_path method.
Otherwise, file_path is only used for reporting errors.
"""
try:
if content is None:
... |
def _iter_step_func_decorators(self):
"""Find functions with step decorator in parsed file."""
for node in self.py_tree.find_all('def'):
for decorator in node.decorators:
if decorator.name.value == 'step':
yield node, decorator
break |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.