_id stringlengths 2 7 | title stringlengths 1 88 | partition stringclasses 3
values | text stringlengths 75 19.8k | language stringclasses 1
value | meta_information dict |
|---|---|---|---|---|---|
q275400 | reorder_resolved_levels | test | def reorder_resolved_levels(storage, debug):
"""L1 and L2 rules"""
# Applies L1.
should_reset = True
chars = storage['chars']
for _ch in chars[::-1]:
# L1. On each line, reset the embedding level of the following
# characters to the paragraph embedding level:
if _ch['orig'... | python | {
"resource": ""
} |
q275401 | CollectMayaCurrentFile.process | test | def process(self, context):
import os
from maya import cmds
"""Inject the current working file"""
current_file = cmds.file(sceneName=True, query=True)
# Maya returns forward-slashes by default
normalised = os.path.normpath(current_file)
context.set_data('curren... | python | {
"resource": ""
} |
q275402 | convert | test | def convert(lines):
"""Convert compiled .ui file from PySide2 to Qt.py
Arguments:
lines (list): Each line of of .ui file
Usage:
>> with open("myui.py") as f:
.. lines = convert(f.readlines())
"""
def parse(line):
line = line.replace("from PySide2 import", "from ... | python | {
"resource": ""
} |
q275403 | _add | test | def _add(object, name, value):
"""Append to self, accessible via Qt.QtCompat"""
self.__added__.append(name)
setattr(object, name, value) | python | {
"resource": ""
} |
q275404 | cli | test | def cli(args):
"""Qt.py command-line interface"""
import argparse
parser = argparse.ArgumentParser()
parser.add_argument("--convert",
help="Path to compiled Python module, e.g. my_ui.py")
parser.add_argument("--compile",
help="Accept raw .ui file and ... | python | {
"resource": ""
} |
q275405 | _maintain_backwards_compatibility | test | def _maintain_backwards_compatibility(binding):
"""Add members found in prior versions up till the next major release
These members are to be considered deprecated. When a new major
release is made, these members are removed.
"""
for member in ("__binding__",
"__binding_version... | python | {
"resource": ""
} |
q275406 | show | test | def show():
"""Try showing the most desirable GUI
This function cycles through the currently registered
graphical user interfaces, if any, and presents it to
the user.
"""
parent = next(
o for o in QtWidgets.QApplication.instance().topLevelWidgets()
if o.objectName() == "MayaW... | python | {
"resource": ""
} |
q275407 | _discover_gui | test | def _discover_gui():
"""Return the most desirable of the currently registered GUIs"""
# Prefer last registered
guis = reversed(pyblish.api.registered_guis())
for gui in guis:
try:
gui = __import__(gui).show
except (ImportError, AttributeError):
continue
... | python | {
"resource": ""
} |
q275408 | deregister_host | test | def deregister_host():
"""Register supported hosts"""
pyblish.api.deregister_host("mayabatch")
pyblish.api.deregister_host("mayapy")
pyblish.api.deregister_host("maya") | python | {
"resource": ""
} |
q275409 | add_to_filemenu | test | def add_to_filemenu():
"""Add Pyblish to file-menu
.. note:: We're going a bit hacky here, probably due to my lack
of understanding for `evalDeferred` or `executeDeferred`,
so if you can think of a better solution, feel free to edit.
"""
if hasattr(cmds, 'about') and not cmds.about(ba... | python | {
"resource": ""
} |
q275410 | maintained_selection | test | def maintained_selection():
"""Maintain selection during context
Example:
>>> with maintained_selection():
... # Modify selection
... cmds.select('node', replace=True)
>>> # Selection restored
"""
previous_selection = cmds.ls(selection=True)
try:
yi... | python | {
"resource": ""
} |
q275411 | maintained_time | test | def maintained_time():
"""Maintain current time during context
Example:
>>> with maintained_time():
... cmds.playblast()
>>> # Time restored
"""
ct = cmds.currentTime(query=True)
try:
yield
finally:
cmds.currentTime(ct, edit=True) | python | {
"resource": ""
} |
q275412 | _show_no_gui | test | def _show_no_gui():
"""Popup with information about how to register a new GUI
In the event of no GUI being registered or available,
this information dialog will appear to guide the user
through how to get set up with one.
"""
messagebox = QtWidgets.QMessageBox()
messagebox.setIcon(message... | python | {
"resource": ""
} |
q275413 | Field.setup_types | test | def setup_types(self):
"""
The Message object has a circular reference on itself, thus we have to allow
Type referencing by name. Here we lookup any Types referenced by name and
replace with the real class.
"""
def load(t):
from TelegramBotAPI.types.type impor... | python | {
"resource": ""
} |
q275414 | Line.get_cumulative_data | test | def get_cumulative_data(self):
"""Get the data as it will be charted. The first set will be
the actual first data set. The second will be the sum of the
first and the second, etc."""
sets = map(itemgetter('data'), self.data)
if not sets:
return
sum = sets.pop(0)
yield sum
while sets:
sum = map(a... | python | {
"resource": ""
} |
q275415 | Plot.get_single_axis_values | test | def get_single_axis_values(self, axis, dataset):
"""
Return all the values for a single axis of the data.
"""
data_index = getattr(self, '%s_data_index' % axis)
return [p[data_index] for p in dataset['data']] | python | {
"resource": ""
} |
q275416 | Plot.__draw_constant_line | test | def __draw_constant_line(self, value_label_style):
"Draw a constant line on the y-axis with the label"
value, label, style = value_label_style
start = self.transform_output_coordinates((0, value))[1]
stop = self.graph_width
path = etree.SubElement(self.graph, 'path', {
'd': 'M 0 %(start)s h%(stop)s' % loca... | python | {
"resource": ""
} |
q275417 | Plot.load_transform_parameters | test | def load_transform_parameters(self):
"Cache the parameters necessary to transform x & y coordinates"
x_min, x_max, x_div = self.x_range()
y_min, y_max, y_div = self.y_range()
x_step = (float(self.graph_width) - self.font_size * 2) / \
(x_max - x_min)
y_step = (float(self.graph_height) - self.font_size * 2)... | python | {
"resource": ""
} |
q275418 | reverse_mapping | test | def reverse_mapping(mapping):
"""
For every key, value pair, return the mapping for the
equivalent value, key pair
>>> reverse_mapping({'a': 'b'}) == {'b': 'a'}
True
"""
keys, values = zip(*mapping.items())
return dict(zip(values, keys)) | python | {
"resource": ""
} |
q275419 | float_range | test | def float_range(start=0, stop=None, step=1):
"""
Much like the built-in function range, but accepts floats
>>> tuple(float_range(0, 9, 1.5))
(0.0, 1.5, 3.0, 4.5, 6.0, 7.5)
"""
start = float(start)
while start < stop:
yield start
start += step | python | {
"resource": ""
} |
q275420 | Pie.add_data | test | def add_data(self, data_descriptor):
"""
Add a data set to the graph
>>> graph.add_data({data:[1,2,3,4]}) # doctest: +SKIP
Note that a 'title' key is ignored.
Multiple calls to add_data will sum the elements, and the pie will
display the aggregated data. e.g.
>>> graph.add_data({data:[1,2,3,4]}) # do... | python | {
"resource": ""
} |
q275421 | Pie.add_defs | test | def add_defs(self, defs):
"Add svg definitions"
etree.SubElement(
defs,
'filter',
id='dropshadow',
width='1.2',
height='1.2',
)
etree.SubElement(
defs,
'feGaussianBlur',
stdDeviation='4',
result='blur',
) | python | {
"resource": ""
} |
q275422 | Graph.add_data | test | def add_data(self, conf):
"""
Add data to the graph object. May be called several times to add
additional data sets.
conf should be a dictionary including 'data' and 'title' keys
"""
self.validate_data(conf)
self.process_data(conf)
self.data.append(conf) | python | {
"resource": ""
} |
q275423 | Graph.burn | test | def burn(self):
"""
Process the template with the data and
config which has been set and return the resulting SVG.
Raises ValueError when no data set has
been added to the graph object.
"""
if not self.data:
raise ValueError("No data available")
if hasattr(self, 'calculations'):
self.calculation... | python | {
"resource": ""
} |
q275424 | Graph.calculate_left_margin | test | def calculate_left_margin(self):
"""
Calculates the margin to the left of the plot area, setting
border_left.
"""
bl = 7
# Check for Y labels
if self.rotate_y_labels:
max_y_label_height_px = self.y_label_font_size
else:
label_lengths = map(len, self.get_y_labels())
max_y_label_len = max(label_l... | python | {
"resource": ""
} |
q275425 | Graph.calculate_right_margin | test | def calculate_right_margin(self):
"""
Calculate the margin in pixels to the right of the plot area,
setting border_right.
"""
br = 7
if self.key and self.key_position == 'right':
max_key_len = max(map(len, self.keys()))
br += max_key_len * self.key_font_size * 0.6
br += self.KEY_BOX_SIZE
br += 1... | python | {
"resource": ""
} |
q275426 | Graph.calculate_top_margin | test | def calculate_top_margin(self):
"""
Calculate the margin in pixels above the plot area, setting
border_top.
"""
self.border_top = 5
if self.show_graph_title:
self.border_top += self.title_font_size
self.border_top += 5
if self.show_graph_subtitle:
self.border_top += self.subtitle_font_size | python | {
"resource": ""
} |
q275427 | Graph.add_popup | test | def add_popup(self, x, y, label):
"""
Add pop-up information to a point on the graph.
"""
txt_width = len(label) * self.font_size * 0.6 + 10
tx = x + [5, -5][int(x + txt_width > self.width)]
anchor = ['start', 'end'][x + txt_width > self.width]
style = 'fill: #000; text-anchor: %s;' % anchor
id = 'label... | python | {
"resource": ""
} |
q275428 | Graph.calculate_bottom_margin | test | def calculate_bottom_margin(self):
"""
Calculate the margin in pixels below the plot area, setting
border_bottom.
"""
bb = 7
if self.key and self.key_position == 'bottom':
bb += len(self.data) * (self.font_size + 5)
bb += 10
if self.show_x_labels:
max_x_label_height_px = self.x_label_font_size
... | python | {
"resource": ""
} |
q275429 | Graph.draw_graph | test | def draw_graph(self):
"""
The central logic for drawing the graph.
Sets self.graph (the 'g' element in the SVG root)
"""
transform = 'translate (%s %s)' % (self.border_left, self.border_top)
self.graph = etree.SubElement(self.root, 'g', transform=transform)
etree.SubElement(self.graph, 'rect', {
'x':... | python | {
"resource": ""
} |
q275430 | Graph.make_datapoint_text | test | def make_datapoint_text(self, x, y, value, style=None):
"""
Add text for a datapoint
"""
if not self.show_data_values:
# do nothing
return
# first lay down the text in a wide white stroke to
# differentiate it from the background
e = etree.SubElement(self.foreground, 'text', {
'x': str(x),
'y... | python | {
"resource": ""
} |
q275431 | Graph.draw_x_labels | test | def draw_x_labels(self):
"Draw the X axis labels"
if self.show_x_labels:
labels = self.get_x_labels()
count = len(labels)
labels = enumerate(iter(labels))
start = int(not self.step_include_first_x_label)
labels = itertools.islice(labels, start, None, self.step_x_labels)
list(map(self.draw_x_label... | python | {
"resource": ""
} |
q275432 | Graph.draw_y_labels | test | def draw_y_labels(self):
"Draw the Y axis labels"
if not self.show_y_labels:
# do nothing
return
labels = self.get_y_labels()
count = len(labels)
labels = enumerate(iter(labels))
start = int(not self.step_include_first_y_label)
labels = itertools.islice(labels, start, None, self.step_y_labels)
l... | python | {
"resource": ""
} |
q275433 | Graph.draw_x_guidelines | test | def draw_x_guidelines(self, label_height, count):
"Draw the X-axis guidelines"
if not self.show_x_guidelines:
return
# skip the first one
for count in range(1, count):
move = 'M {start} 0 v{stop}'.format(
start=label_height * count,
stop=self.graph_height,
)
path = {'d': move, 'class': 'guid... | python | {
"resource": ""
} |
q275434 | Graph.draw_y_guidelines | test | def draw_y_guidelines(self, label_height, count):
"Draw the Y-axis guidelines"
if not self.show_y_guidelines:
return
for count in range(1, count):
move = 'M 0 {start} h{stop}'.format(
start=self.graph_height - label_height * count,
stop=self.graph_width,
)
path = {'d': move, 'class': 'guideLin... | python | {
"resource": ""
} |
q275435 | Graph.draw_titles | test | def draw_titles(self):
"Draws the graph title and subtitle"
if self.show_graph_title:
self.draw_graph_title()
if self.show_graph_subtitle:
self.draw_graph_subtitle()
if self.show_x_title:
self.draw_x_title()
if self.show_y_title:
self.draw_y_title() | python | {
"resource": ""
} |
q275436 | Graph.render_inline_styles | test | def render_inline_styles(self):
"Hard-code the styles into the SVG XML if style sheets are not used."
if not self.css_inline:
# do nothing
return
styles = self.parse_css()
for node in self.root.xpath('//*[@class]'):
cl = '.' + node.attrib['class']
if cl not in styles:
continue
style = styles... | python | {
"resource": ""
} |
q275437 | Graph.start_svg | test | def start_svg(self):
"Base SVG Document Creation"
SVG_NAMESPACE = 'http://www.w3.org/2000/svg'
SVG = '{%s}' % SVG_NAMESPACE
NSMAP = {
None: SVG_NAMESPACE,
'xlink': 'http://www.w3.org/1999/xlink',
'a3': 'http://ns.adobe.com/AdobeSVGViewerExtensions/3.0/',
}
root_attrs = self._get_root_attributes()
... | python | {
"resource": ""
} |
q275438 | Graph.get_stylesheet_resources | test | def get_stylesheet_resources(self):
"Get the stylesheets for this instance"
# allow css to include class variables
class_vars = class_dict(self)
loader = functools.partial(
self.load_resource_stylesheet,
subs=class_vars)
sheets = list(map(loader, self.stylesheet_names))
return sheets | python | {
"resource": ""
} |
q275439 | run_bot | test | def run_bot(bot_class, host, port, nick, channels=None, ssl=None):
"""\
Convenience function to start a bot on the given network, optionally joining
some channels
"""
conn = IRCConnection(host, port, nick, ssl)
bot_instance = bot_class(conn)
while 1:
if not conn.connect():
... | python | {
"resource": ""
} |
q275440 | IRCConnection.send | test | def send(self, data, force=False):
"""\
Send raw data over the wire if connection is registered. Otherewise,
save the data to an output buffer for transmission later on.
If the force flag is true, always send data, regardless of
registration status.
"""
if self._r... | python | {
"resource": ""
} |
q275441 | IRCConnection.connect | test | def connect(self):
"""\
Connect to the IRC server using the nickname
"""
self._sock = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
if self.use_ssl:
self._sock = ssl.wrap_socket(self._sock)
try:
self._sock.connect((self.server, self.port))
... | python | {
"resource": ""
} |
q275442 | IRCConnection.respond | test | def respond(self, message, channel=None, nick=None):
"""\
Multipurpose method for sending responses to channel or via message to
a single user
"""
if channel:
if not channel.startswith('#'):
channel = '#%s' % channel
self.send('PRIVMSG %s :... | python | {
"resource": ""
} |
q275443 | IRCConnection.dispatch_patterns | test | def dispatch_patterns(self):
"""\
Low-level dispatching of socket data based on regex matching, in general
handles
* In event a nickname is taken, registers under a different one
* Responds to periodic PING messages from server
* Dispatches to registered callbacks when
... | python | {
"resource": ""
} |
q275444 | IRCConnection.new_nick | test | def new_nick(self):
"""\
Generates a new nickname based on original nickname followed by a
random number
"""
old = self.nick
self.nick = '%s_%s' % (self.base_nick, random.randint(1, 1000))
self.logger.warn('Nick %s already taken, trying %s' % (old, self.nick))
... | python | {
"resource": ""
} |
q275445 | IRCConnection.handle_ping | test | def handle_ping(self, payload):
"""\
Respond to periodic PING messages from server
"""
self.logger.info('server ping: %s' % payload)
self.send('PONG %s' % payload, True) | python | {
"resource": ""
} |
q275446 | IRCConnection.handle_registered | test | def handle_registered(self, server):
"""\
When the connection to the server is registered, send all pending
data.
"""
if not self._registered:
self.logger.info('Registered')
self._registered = True
for data in self._out_buffer:
... | python | {
"resource": ""
} |
q275447 | IRCConnection.enter_event_loop | test | def enter_event_loop(self):
"""\
Main loop of the IRCConnection - reads from the socket and dispatches
based on regex matching
"""
patterns = self.dispatch_patterns()
self.logger.debug('entering receive loop')
while 1:
try:
data = self... | python | {
"resource": ""
} |
q275448 | BaseWorkerBot.register_with_boss | test | def register_with_boss(self):
"""\
Register the worker with the boss
"""
gevent.sleep(10) # wait for things to connect, etc
while not self.registered.is_set():
self.respond('!register {%s}' % platform.node(), nick=self.boss)
gevent.sleep(30) | python | {
"resource": ""
} |
q275449 | BaseWorkerBot.task_runner | test | def task_runner(self):
"""\
Run tasks in a greenlet, pulling from the workers' task queue and
reporting results to the command channel
"""
while 1:
(task_id, command) = self.task_queue.get()
for pattern, callback in self.task_patterns:
... | python | {
"resource": ""
} |
q275450 | BaseWorkerBot.require_boss | test | def require_boss(self, callback):
"""\
Decorator to ensure that commands only can come from the boss
"""
def inner(nick, message, channel, *args, **kwargs):
if nick != self.boss:
return
return callback(nick, message, channel, *args, **... | python | {
"resource": ""
} |
q275451 | BaseWorkerBot.command_patterns | test | def command_patterns(self):
"""\
Actual messages listened for by the worker bot - note that worker-execute
actually dispatches again by adding the command to the task queue,
from which it is pulled then matched against self.task_patterns
"""
return (
('!regist... | python | {
"resource": ""
} |
q275452 | BaseWorkerBot.register_success | test | def register_success(self, nick, message, channel, cmd_channel):
"""\
Received registration acknowledgement from the BotnetBot, as well as the
name of the command channel, so join up and indicate that registration
succeeded
"""
# the boss will tell what channel to join
... | python | {
"resource": ""
} |
q275453 | BaseWorkerBot.worker_execute | test | def worker_execute(self, nick, message, channel, task_id, command, workers=None):
"""\
Work on a task from the BotnetBot
"""
if workers:
nicks = workers.split(',')
do_task = self.conn.nick in nicks
else:
do_task = True
if do_ta... | python | {
"resource": ""
} |
q275454 | Task.add | test | def add(self, nick):
"""\
Indicate that the worker with given nick is performing this task
"""
self.data[nick] = ''
self.workers.add(nick) | python | {
"resource": ""
} |
q275455 | EmailVerifyUserMethodsMixin.send_validation_email | test | def send_validation_email(self):
"""Send a validation email to the user's email address."""
if self.email_verified:
raise ValueError(_('Cannot validate already active user.'))
site = Site.objects.get_current()
self.validation_notification(user=self, site=site).notify() | python | {
"resource": ""
} |
q275456 | EmailVerifyUserMethodsMixin.send_password_reset | test | def send_password_reset(self):
"""Send a password reset to the user's email address."""
site = Site.objects.get_current()
self.password_reset_notification(user=self, site=site).notify() | python | {
"resource": ""
} |
q275457 | validate_password_strength | test | def validate_password_strength(value):
"""
Passwords should be tough.
That means they should use:
- mixed case letters,
- numbers,
- (optionally) ascii symbols and spaces.
The (contrversial?) decision to limit the passwords to ASCII only
is for the sake of:
- simplicity (no need to... | python | {
"resource": ""
} |
q275458 | VerifyAccountViewMixin.verify_token | test | def verify_token(self, request, *args, **kwargs):
"""
Use `token` to allow one-time access to a view.
Set the user as a class attribute or raise an `InvalidExpiredToken`.
Token expiry can be set in `settings` with `VERIFY_ACCOUNT_EXPIRY` and is
set in seconds.
"""
... | python | {
"resource": ""
} |
q275459 | ProfileAvatar.delete | test | def delete(self, request, *args, **kwargs):
"""
Delete the user's avatar.
We set `user.avatar = None` instead of calling `user.avatar.delete()`
to avoid test errors with `django.inmemorystorage`.
"""
user = self.get_object()
user.avatar = None
user.save()... | python | {
"resource": ""
} |
q275460 | PostRequestThrottleMixin.allow_request | test | def allow_request(self, request, view):
"""
Throttle POST requests only.
"""
if request.method != 'POST':
return True
return super(PostRequestThrottleMixin, self).allow_request(request, view) | python | {
"resource": ""
} |
q275461 | SwarmSpawner.executor | test | def executor(self, max_workers=1):
"""single global executor"""
cls = self.__class__
if cls._executor is None:
cls._executor = ThreadPoolExecutor(max_workers)
return cls._executor | python | {
"resource": ""
} |
q275462 | SwarmSpawner.client | test | def client(self):
"""single global client instance"""
cls = self.__class__
if cls._client is None:
kwargs = {}
if self.tls_config:
kwargs['tls'] = docker.tls.TLSConfig(**self.tls_config)
kwargs.update(kwargs_from_env())
client = do... | python | {
"resource": ""
} |
q275463 | SwarmSpawner.tls_client | test | def tls_client(self):
"""A tuple consisting of the TLS client certificate and key if they
have been provided, otherwise None.
"""
if self.tls_cert and self.tls_key:
return (self.tls_cert, self.tls_key)
return None | python | {
"resource": ""
} |
q275464 | SwarmSpawner.service_name | test | def service_name(self):
"""
Service name inside the Docker Swarm
service_suffix should be a numerical value unique for user
{service_prefix}-{service_owner}-{service_suffix}
"""
if hasattr(self, "server_name") and self.server_name:
server_name = self.server_n... | python | {
"resource": ""
} |
q275465 | SwarmSpawner._docker | test | def _docker(self, method, *args, **kwargs):
"""wrapper for calling docker methods
to be passed to ThreadPoolExecutor
"""
m = getattr(self.client, method)
return m(*args, **kwargs) | python | {
"resource": ""
} |
q275466 | SwarmSpawner.docker | test | def docker(self, method, *args, **kwargs):
"""Call a docker method in a background thread
returns a Future
"""
return self.executor.submit(self._docker, method, *args, **kwargs) | python | {
"resource": ""
} |
q275467 | SwarmSpawner.poll | test | def poll(self):
"""Check for a task state like `docker service ps id`"""
service = yield self.get_service()
if not service:
self.log.warn("Docker service not found")
return 0
task_filter = {'service': service['Spec']['Name']}
tasks = yield self.docker(
... | python | {
"resource": ""
} |
q275468 | SwarmSpawner.stop | test | def stop(self, now=False):
"""Stop and remove the service
Consider using stop/start when Docker adds support
"""
self.log.info(
"Stopping and removing Docker service %s (id: %s)",
self.service_name, self.service_id[:7])
yield self.docker('remove_service',... | python | {
"resource": ""
} |
q275469 | UniqueEmailValidator.filter_queryset | test | def filter_queryset(self, value, queryset):
"""Check lower-cased email is unique."""
return super(UniqueEmailValidator, self).filter_queryset(
value.lower(),
queryset,
) | python | {
"resource": ""
} |
q275470 | PasswordChangeSerializer.update | test | def update(self, instance, validated_data):
"""Check the old password is valid and set the new password."""
if not instance.check_password(validated_data['old_password']):
msg = _('Invalid password.')
raise serializers.ValidationError({'old_password': msg})
instance.set_... | python | {
"resource": ""
} |
q275471 | PasswordResetSerializer.update | test | def update(self, instance, validated_data):
"""Set the new password for the user."""
instance.set_password(validated_data['new_password'])
instance.save()
return instance | python | {
"resource": ""
} |
q275472 | ResendConfirmationEmailSerializer.validate_email | test | def validate_email(self, email):
"""
Validate if email exists and requires a verification.
`validate_email` will set a `user` attribute on the instance allowing
the view to send an email confirmation.
"""
try:
self.user = User.objects.get_by_natural_key(email... | python | {
"resource": ""
} |
q275473 | GetAuthToken.post | test | def post(self, request):
"""Create auth token. Differs from DRF that it always creates new token
but not re-using them."""
serializer = self.serializer_class(data=request.data)
if serializer.is_valid():
user = serializer.validated_data['user']
signals.user_logged_... | python | {
"resource": ""
} |
q275474 | GetAuthToken.delete | test | def delete(self, request, *args, **kwargs):
"""Delete auth token when `delete` request was issued."""
# Logic repeated from DRF because one cannot easily reuse it
auth = get_authorization_header(request).split()
if not auth or auth[0].lower() != b'token':
return response.Res... | python | {
"resource": ""
} |
q275475 | ResendConfirmationEmail.initial | test | def initial(self, request, *args, **kwargs):
"""Disallow users other than the user whose email is being reset."""
email = request.data.get('email')
if request.user.is_authenticated() and email != request.user.email:
raise PermissionDenied()
return super(ResendConfirmationEma... | python | {
"resource": ""
} |
q275476 | ResendConfirmationEmail.post | test | def post(self, request, *args, **kwargs):
"""Validate `email` and send a request to confirm it."""
serializer = self.serializer_class(data=request.data)
if not serializer.is_valid():
return response.Response(
serializer.errors,
status=status.HTTP_400_... | python | {
"resource": ""
} |
q275477 | AuthToken.update_expiry | test | def update_expiry(self, commit=True):
"""Update token's expiration datetime on every auth action."""
self.expires = update_expiry(self.created)
if commit:
self.save() | python | {
"resource": ""
} |
q275478 | password_reset_email_context | test | def password_reset_email_context(notification):
"""Email context to reset a user password."""
return {
'protocol': 'https',
'uid': notification.user.generate_uid(),
'token': notification.user.generate_token(),
'site': notification.site,
} | python | {
"resource": ""
} |
q275479 | email_handler | test | def email_handler(notification, email_context):
"""Send a notification by email."""
incuna_mail.send(
to=notification.user.email,
subject=notification.email_subject,
template_name=notification.text_email_template,
html_template_name=notification.html_email_template,
conte... | python | {
"resource": ""
} |
q275480 | password_reset_email_handler | test | def password_reset_email_handler(notification):
"""Password reset email handler."""
base_subject = _('{domain} password reset').format(domain=notification.site.domain)
subject = getattr(settings, 'DUM_PASSWORD_RESET_SUBJECT', base_subject)
notification.email_subject = subject
email_handler(notificat... | python | {
"resource": ""
} |
q275481 | validation_email_handler | test | def validation_email_handler(notification):
"""Validation email handler."""
base_subject = _('{domain} account validate').format(domain=notification.site.domain)
subject = getattr(settings, 'DUM_VALIDATE_EMAIL_SUBJECT', base_subject)
notification.email_subject = subject
email_handler(notification, v... | python | {
"resource": ""
} |
q275482 | FormTokenAuthentication.authenticate | test | def authenticate(self, request):
"""
Authenticate a user from a token form field
Errors thrown here will be swallowed by django-rest-framework, and it
expects us to return None if authentication fails.
"""
try:
key = request.data['token']
except KeyEr... | python | {
"resource": ""
} |
q275483 | TokenAuthentication.authenticate_credentials | test | def authenticate_credentials(self, key):
"""Custom authentication to check if auth token has expired."""
user, token = super(TokenAuthentication, self).authenticate_credentials(key)
if token.expires < timezone.now():
msg = _('Token has expired.')
raise exceptions.Authent... | python | {
"resource": ""
} |
q275484 | notebook_show | test | def notebook_show(obj, doc, comm):
"""
Displays bokeh output inside a notebook.
"""
target = obj.ref['id']
load_mime = 'application/vnd.holoviews_load.v0+json'
exec_mime = 'application/vnd.holoviews_exec.v0+json'
# Publish plot HTML
bokeh_script, bokeh_div, _ = bokeh.embed.notebook.note... | python | {
"resource": ""
} |
q275485 | process_hv_plots | test | def process_hv_plots(widgets, plots):
"""
Temporary fix to patch HoloViews plot comms
"""
bokeh_plots = []
for plot in plots:
if hasattr(plot, '_update_callbacks'):
for subplot in plot.traverse(lambda x: x):
subplot.comm = widgets.server_comm
for c... | python | {
"resource": ""
} |
q275486 | Widgets._get_customjs | test | def _get_customjs(self, change, p_name):
"""
Returns a CustomJS callback that can be attached to send the
widget state across the notebook comms.
"""
data_template = "data = {{p_name: '{p_name}', value: cb_obj['{change}']}};"
fetch_data = data_template.format(change=chang... | python | {
"resource": ""
} |
q275487 | Widgets.widget | test | def widget(self, param_name):
"""Get widget for param_name"""
if param_name not in self._widgets:
self._widgets[param_name] = self._make_widget(param_name)
return self._widgets[param_name] | python | {
"resource": ""
} |
q275488 | render_function | test | def render_function(obj, view):
"""
The default Renderer function which handles HoloViews objects.
"""
try:
import holoviews as hv
except:
hv = None
if hv and isinstance(obj, hv.core.Dimensioned):
renderer = hv.renderer('bokeh')
if not view._notebook:
... | python | {
"resource": ""
} |
q275489 | TextWidget | test | def TextWidget(*args, **kw):
"""Forces a parameter value to be text"""
kw['value'] = str(kw['value'])
kw.pop('options', None)
return TextInput(*args,**kw) | python | {
"resource": ""
} |
q275490 | named_objs | test | def named_objs(objlist):
"""
Given a list of objects, returns a dictionary mapping from
string name for the object to the object itself.
"""
objs = []
for k, obj in objlist:
if hasattr(k, '__name__'):
k = k.__name__
else:
k = as_unicode(k)
objs.app... | python | {
"resource": ""
} |
q275491 | get_method_owner | test | def get_method_owner(meth):
"""
Returns the instance owning the supplied instancemethod or
the class owning the supplied classmethod.
"""
if inspect.ismethod(meth):
if sys.version_info < (3,0):
return meth.im_class if meth.im_self is None else meth.im_self
else:
... | python | {
"resource": ""
} |
q275492 | AsyncHttpConnection._assign_auth_values | test | def _assign_auth_values(self, http_auth):
"""Take the http_auth value and split it into the attributes that
carry the http auth username and password
:param str|tuple http_auth: The http auth value
"""
if not http_auth:
pass
elif isinstance(http_auth, (tuple... | python | {
"resource": ""
} |
q275493 | AsyncElasticsearch.ping | test | def ping(self, params=None):
""" Returns True if the cluster is up, False otherwise. """
try:
self.transport.perform_request('HEAD', '/', params=params)
except TransportError:
raise gen.Return(False)
raise gen.Return(True) | python | {
"resource": ""
} |
q275494 | AsyncElasticsearch.info | test | def info(self, params=None):
"""Get the basic info from the current cluster.
:rtype: dict
"""
_, data = yield self.transport.perform_request('GET', '/',
params=params)
raise gen.Return(data) | python | {
"resource": ""
} |
q275495 | AsyncElasticsearch.health | test | def health(self, params=None):
"""Coroutine. Queries cluster Health API.
Returns a 2-tuple, where first element is request status, and second
element is a dictionary with response data.
:param params: dictionary of query parameters, will be handed over to
the underlying :cl... | python | {
"resource": ""
} |
q275496 | SynoFormatHelper.bytes_to_readable | test | def bytes_to_readable(num):
"""Converts bytes to a human readable format"""
if num < 512:
return "0 Kb"
elif num < 1024:
return "1 Kb"
for unit in ['', 'Kb', 'Mb', 'Gb', 'Tb', 'Pb', 'Eb', 'Zb']:
if abs(num) < 1024.0:
return "%... | python | {
"resource": ""
} |
q275497 | SynoUtilization.cpu_total_load | test | def cpu_total_load(self):
"""Total CPU load for Synology DSM"""
system_load = self.cpu_system_load
user_load = self.cpu_user_load
other_load = self.cpu_other_load
if system_load is not None and \
user_load is not None and \
other_load is not None:
... | python | {
"resource": ""
} |
q275498 | SynoUtilization.memory_size | test | def memory_size(self, human_readable=True):
"""Total Memory Size of Synology DSM"""
if self._data is not None:
# Memory is actually returned in KB's so multiply before converting
return_data = int(self._data["memory"]["memory_size"]) * 1024
if human_readable:
... | python | {
"resource": ""
} |
q275499 | SynoUtilization.network_up | test | def network_up(self, human_readable=True):
"""Total upload speed being used"""
network = self._get_network("total")
if network is not None:
return_data = int(network["tx"])
if human_readable:
return SynoFormatHelper.bytes_to_readable(
... | python | {
"resource": ""
} |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.