_id
stringlengths 2
7
| title
stringlengths 1
88
| partition
stringclasses 3
values | text
stringlengths 31
13.1k
| 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'] in ('B', 'S'):
# 1. Segment separators,
# 2. Paragraph separators,
_ch['level'] = storage['base_level']
should_reset = True
elif should_reset and _ch['orig'] in ('BN', 'WS'):
# 3. Any sequence of whitespace characters preceding a segment
# separator or paragraph separator
# 4. Any sequence of white space characters at the end of the
# line.
_ch['level'] = storage['base_level']
else:
should_reset = False
max_len = len(chars)
# L2 should be per line
# Calculates highest level and loweset odd level on the fly.
line_start = line_end = 0
highest_level = 0
lowest_odd_level = EXPLICIT_LEVEL_LIMIT
for idx in range(max_len):
_ch = chars[idx]
# calc the levels
char_level = _ch['level']
|
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)
|
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 Qt import")
line =
|
python
|
{
"resource": ""
}
|
q275403
|
_add
|
test
|
def _add(object, name, value):
"""Append to self, accessible via Qt.QtCompat"""
|
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 compile with native "
"PySide2 compiler.")
parser.add_argument("--stdout",
help="Write to stdout instead of file",
action="store_true")
parser.add_argument("--stdin",
help="Read from stdin instead of file",
action="store_true")
args = parser.parse_args(args)
if args.stdout:
raise NotImplementedError("--stdout")
if args.stdin:
raise NotImplementedError("--stdin")
if args.compile:
raise NotImplementedError("--compile")
if args.convert:
sys.stdout.write("#\n"
"# WARNING: --convert is an ALPHA feature.\n#\n"
"# See https://github.com/mottosso/Qt.py/pull/132\n"
|
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()
|
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())
|
python
|
{
"resource": ""
}
|
q275408
|
deregister_host
|
test
|
def deregister_host():
"""Register supported hosts"""
pyblish.api.deregister_host("mayabatch")
|
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(batch=True):
# As Maya builds its menus dynamically upon being accessed,
# we force its build here prior to adding our entry using it's
# native mel function call.
mel.eval("evalDeferred buildFileMenu")
# Serialise function into string
script =
|
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:
yield
finally:
|
python
|
{
"resource": ""
}
|
q275411
|
maintained_time
|
test
|
def maintained_time():
"""Maintain current time during context
Example:
>>> with maintained_time():
|
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(messagebox.Warning)
messagebox.setWindowIcon(QtGui.QIcon(os.path.join(
os.path.dirname(pyblish.__file__),
"icons",
"logo-32x32.svg"))
)
spacer = QtWidgets.QWidget()
spacer.setMinimumSize(400, 0)
spacer.setSizePolicy(QtWidgets.QSizePolicy.Minimum,
QtWidgets.QSizePolicy.Expanding)
layout = messagebox.layout()
layout.addWidget(spacer, layout.rowCount(), 0, 1, layout.columnCount())
messagebox.setWindowTitle("Uh oh")
text = "No registered GUI found.\n\n"
if not pyblish.api.registered_guis():
text += (
"In order to show you a GUI, one must first be registered. "
"\n"
"Pyblish supports one or more graphical user interfaces "
"to be registered at once, the next acting as a fallback to "
"the previous."
"\n"
"\n"
"For example, to use Pyblish Lite, first install it:"
"\n"
"\n"
"$ pip install pyblish-lite"
"\n"
"\n"
"Then register it, like so:"
"\n"
"\n"
">>> import pyblish.api\n"
|
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):
|
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)
|
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.
"""
|
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
|
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)
|
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'}) ==
|
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
|
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]}) # doctest: +SKIP
>>> graph.add_data({data:[2,3,5,7]}) # doctest: +SKIP
is the same as:
>>> graph.add_data({data:[3,5,8,11]}) # doctest: +SKIP
If data is added of with differing lengths, the corresponding
values will be assumed to be zero.
>>> graph.add_data({data:[1,2,3,4]})
|
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',
|
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
|
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.calculations()
self.start_svg()
|
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_lengths)
max_y_label_height_px = 0.6 * max_y_label_len *
|
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 *
|
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:
|
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-%s' % self._w3c_name(label)
attrs = {
'x': str(tx),
'y': str(y - self.font_size),
'visibility': 'hidden',
'style': style,
'text': label,
'id': id,
}
etree.SubElement(self.foreground, 'text', attrs)
|
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
if self.rotate_x_labels:
label_lengths = map(len, self.get_x_labels())
|
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': '0',
'y': '0',
'width': str(self.graph_width),
'height': str(self.graph_height),
'class': 'graphBackground'
})
# Axis
|
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': str(y),
'class': 'dataPointLabel',
'style': '%(style)s stroke: #fff; stroke-width: 2;' % vars(),
})
e.text = str(value)
|
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)
|
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)
|
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
|
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,
|
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()
|
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
|
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()
self.root = etree.Element(SVG + "svg", attrib=root_attrs, nsmap=NSMAP)
if hasattr(self, 'style_sheet_href'):
pi = etree.ProcessingInstruction(
'xml-stylesheet',
'href="%s" type="text/css"' % self.style_sheet_href
)
self.root.addprevious(pi)
comment_strings = (
' Created with SVG.Graph ',
' SVG.Graph by Jason R. Coombs ',
' Based on SVG::Graph by Sean E. Russel ',
' Based on Perl SVG:TT:Graph by Leo Lapworth & Stephan Morgan ',
' ' + '/' * 66,
)
list(map(self.root.append, map(etree.Comment, comment_strings)))
defs = etree.SubElement(self.root, 'defs')
self.add_defs(defs)
if not
|
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(
|
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.
|
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))
except socket.error:
self.logger.error('Unable to connect to
|
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
|
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
- any user leaves or enters a room currently connected to
- a channel message is observed
- a private message is received
"""
return (
(self.nick_re, self.new_nick),
|
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))
|
python
|
{
"resource": ""
}
|
q275445
|
IRCConnection.handle_ping
|
test
|
def handle_ping(self, payload):
"""\
Respond to periodic PING messages from server
"""
|
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')
|
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._sock_file.readline()
except socket.error:
data = None
if not data:
|
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():
|
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:
match = re.match(pattern, command)
if match:
# execute the callback
ret = callback(**match.groupdict()) or ''
# clear the stop flag in the event it was set
self.stop_flag.clear()
|
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:
|
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 (
('!register-success (?P<cmd_channel>.+)', self.require_boss(self.register_success)),
|
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
|
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
|
python
|
{
"resource": ""
}
|
q275454
|
Task.add
|
test
|
def add(self, nick):
"""\
Indicate that the worker with given nick is performing this task
"""
|
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.'))
|
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()
|
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 normalise UTF-8 input)
- security (some character sets are visible as typed into password fields)
TODO: In future, it may be worth considering:
- rejecting common passwords. (Where can we get a list?)
- rejecting passwords with too many repeated characters.
It should be noted that no restriction has been placed on the length of the
password here, as that can easily be achieved with use of the min_length
attribute of a form/serializer field.
|
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.
"""
User = get_user_model()
try:
max_age = settings.VERIFY_ACCOUNT_EXPIRY
except AttributeError:
max_age = self.DEFAULT_VERIFY_ACCOUNT_EXPIRY
try:
email_data = signing.loads(kwargs['token'], max_age=max_age)
except signing.BadSignature:
|
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()`
|
python
|
{
"resource": ""
}
|
q275460
|
PostRequestThrottleMixin.allow_request
|
test
|
def allow_request(self, request, view):
"""
Throttle POST requests only.
"""
|
python
|
{
"resource": ""
}
|
q275461
|
SwarmSpawner.executor
|
test
|
def executor(self, max_workers=1):
"""single global executor"""
cls = self.__class__
if cls._executor is None:
|
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:
|
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.
"""
|
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_name
else:
|
python
|
{
"resource": ""
}
|
q275465
|
SwarmSpawner._docker
|
test
|
def _docker(self, method, *args, **kwargs):
"""wrapper for calling docker methods
|
python
|
{
"resource": ""
}
|
q275466
|
SwarmSpawner.docker
|
test
|
def docker(self, method, *args, **kwargs):
"""Call a docker method in a background thread
returns a Future
|
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(
'tasks', task_filter
)
running_task = None
for task in tasks:
task_state = task['Status']['State']
self.log.debug(
"Task %s of Docker service %s
|
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
|
python
|
{
"resource": ""
}
|
q275469
|
UniqueEmailValidator.filter_queryset
|
test
|
def filter_queryset(self, value, queryset):
"""Check lower-cased email is unique."""
return
|
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.')
|
python
|
{
"resource": ""
}
|
q275471
|
PasswordResetSerializer.update
|
test
|
def update(self, instance, validated_data):
"""Set the new password for the user."""
|
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)
except User.DoesNotExist:
|
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_in.send(type(self), user=user, request=request)
token = self.model.objects.create(user=user)
|
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.Response(status=status.HTTP_400_BAD_REQUEST)
if len(auth) == 1:
msg = 'Invalid token header. No credentials provided.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
elif len(auth) > 2:
msg = 'Invalid token header. Token string should not contain spaces.'
return response.Response(msg, status=status.HTTP_400_BAD_REQUEST)
|
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()
|
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():
|
python
|
{
"resource": ""
}
|
q275477
|
AuthToken.update_expiry
|
test
|
def update_expiry(self, commit=True):
"""Update token's expiration datetime on every auth action."""
|
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(),
|
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,
|
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)
|
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)
|
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.
|
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.')
|
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.notebook_content(obj, comm.id)
publish_display_data(data={'text/html': encode_utf8(bokeh_div)})
# Publish comm manager
JS = '\n'.join([PYVIZ_PROXY, JupyterCommManager.js_manager])
publish_display_data(data={load_mime: JS, 'application/javascript': JS})
# Publish bokeh plot JS
msg_handler = bokeh_msg_handler.format(plot_id=target)
|
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):
|
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=change, p_name=p_name)
self_callback = JS_CALLBACK.format(comm_id=self.comm.id,
timeout=self.timeout,
|
python
|
{
"resource": ""
}
|
q275487
|
Widgets.widget
|
test
|
def widget(self, param_name):
"""Get widget for param_name"""
if param_name not
|
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:
renderer =
|
python
|
{
"resource": ""
}
|
q275489
|
TextWidget
|
test
|
def TextWidget(*args, **kw):
"""Forces a parameter value to be text"""
kw['value'] = str(kw['value'])
|
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__'):
|
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
|
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:
|
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)
|
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', '/',
|
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 :class:`~torando_elasticsearch.AsyncHTTPConnection`
|
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']:
|
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 \
|
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:
|
python
|
{
"resource": ""
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.