INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Remove all licenses matching both key and value.
def remove_license(self, name=None, url=None): """Remove all licenses matching both key and value. :param str name: Name of the license. :param str url: URL of the license. """ for k, v in self.licenses[:]: if (name is None or name == k) and (url is None or url == v)...
Remove all linked files that match all the criteria criterias that are None are ignored.
def remove_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, ex_from=None): """Remove all linked files that match all the criteria, criterias that are ``None`` are ignored. :param str file_path: Path of the file. :param str rel...
Remove all properties matching both key and value.
def remove_property(self, key=None, value=None): """Remove all properties matching both key and value. :param str key: Key of the property. :param str value: Value of the property. """ for k, v in self.properties[:]: if (key is None or key == k) and (value is None or...
Remove a reference annotation.
def remove_ref_annotation(self, id_tier, time): """Remove a reference annotation. :param str id_tier: Name of tier. :param int time: Time of the referenced annotation :raises KeyError: If the tier is non existent. :returns: Number of removed annotations. """ remo...
Remove all secondary linked files that match all the criteria criterias that are None are ignored.
def remove_secondary_linked_files(self, file_path=None, relpath=None, mimetype=None, time_origin=None, assoc_with=None): """Remove all secondary linked files that match all the criteria, criterias that are ``None`` are ignored. ...
Remove a tier.
def remove_tier(self, id_tier, clean=True): """Remove a tier. :param str id_tier: Name of the tier. :param bool clean: Flag to also clean the timeslots. :raises KeyError: If tier is non existent. """ del(self.tiers[id_tier]) if clean: self.clean_time_...
Remove multiple tiers note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots.
def remove_tiers(self, tiers): """Remove multiple tiers, note that this is a lot faster then removing them individually because of the delayed cleaning of timeslots. :param list tiers: Names of the tier to remove. :raises KeyError: If a tier is non existent. """ for a in...
Rename a tier. Note that this renames also the child tiers that have the tier as a parent.
def rename_tier(self, id_from, id_to): """Rename a tier. Note that this renames also the child tiers that have the tier as a parent. :param str id_from: Original name of the tier. :param str id_to: Target name of the tier. :throws KeyError: If the tier doesnt' exist. """...
Shift all annotations in time. Annotations that are in the beginning and a left shift is applied can be squashed or discarded.
def shift_annotations(self, time): """Shift all annotations in time. Annotations that are in the beginning and a left shift is applied can be squashed or discarded. :param int time: Time shift width, negative numbers make a left shift. :returns: Tuple of a list of squashed annotations a...
Convert the object to a: class: pympi. Praat. TextGrid object.
def to_textgrid(self, filtin=[], filtex=[], regex=False): """Convert the object to a :class:`pympi.Praat.TextGrid` object. :param list filtin: Include only tiers in this list, if empty all tiers are included. :param list filtex: Exclude all tiers in this list. :param bool re...
Will be used to create the console script
def main(): """Will be used to create the console script""" import optparse import sys import codecs import locale import six from .algorithm import get_display parser = optparse.OptionParser() parser.add_option('-e', '--encoding', dest='encoding', ...
Display debug information for the storage
def debug_storage(storage, base_info=False, chars=True, runs=False): "Display debug information for the storage" import codecs import locale import sys if six.PY2: stderr = codecs.getwriter(locale.getpreferredencoding())(sys.stderr) else: stderr = sys.stderr caller = inspe...
Get the paragraph base embedding level. Returns 0 for LTR 1 for RTL.
def get_base_level(text, upper_is_rtl=False): """Get the paragraph base embedding level. Returns 0 for LTR, 1 for RTL. `text` a unicode object. Set `upper_is_rtl` to True to treat upper case chars as strong 'R' for debugging (default: False). """ base_level = None prev_surrogate = F...
Get the paragraph base embedding level and direction set the storage to the array of chars
def get_embedding_levels(text, storage, upper_is_rtl=False, debug=False): """Get the paragraph base embedding level and direction, set the storage to the array of chars""" prev_surrogate = False base_level = storage['base_level'] # preset the storage's chars for _ch in text: if _IS_UCS...
Apply X1 to X9 rules of the unicode algorithm.
def explicit_embed_and_overrides(storage, debug=False): """Apply X1 to X9 rules of the unicode algorithm. See http://unicode.org/reports/tr9/#Explicit_Levels_and_Directions """ overflow_counter = almost_overflow_counter = 0 directional_override = 'N' levels = deque() # X1 embedding_le...
Split the storage to run of char types at the same level.
def calc_level_runs(storage): """Split the storage to run of char types at the same level. Applies X10. See http://unicode.org/reports/tr9/#X10 """ # run level depends on the higher of the two levels on either side of # the boundary If the higher level is odd, the type is R; otherwise, # it is ...
Reslove weak type rules W1 - W3.
def resolve_weak_types(storage, debug=False): """Reslove weak type rules W1 - W3. See: http://unicode.org/reports/tr9/#Resolving_Weak_Types """ for run in storage['runs']: prev_strong = prev_type = run['sor'] start, length = run['start'], run['length'] chars = storage['chars']...
Resolving neutral types. Implements N1 and N2
def resolve_neutral_types(storage, debug): """Resolving neutral types. Implements N1 and N2 See: http://unicode.org/reports/tr9/#Resolving_Neutral_Types """ for run in storage['runs']: start, length = run['start'], run['length'] # use sor and eor chars = [{'type': run['sor']}]...
Resolving implicit levels ( I1 I2 )
def resolve_implicit_levels(storage, debug): """Resolving implicit levels (I1, I2) See: http://unicode.org/reports/tr9/#Resolving_Implicit_Levels """ for run in storage['runs']: start, length = run['start'], run['length'] chars = storage['chars'][start:start+length] for _ch in...
L2. From the highest level found in the text to the lowest odd level on each line including intermediate levels not actually present in the text reverse any contiguous sequence of characters that are at that level or higher.
def reverse_contiguous_sequence(chars, line_start, line_end, highest_level, lowest_odd_level): """L2. From the highest level found in the text to the lowest odd level on each line, including intermediate levels not actually present in the text, reverse any contiguous sequence...
L1 and L2 rules
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'...
Applies L4: mirroring
def apply_mirroring(storage, debug): """Applies L4: mirroring See: http://unicode.org/reports/tr9/#L4 """ # L4. A character is depicted by a mirrored glyph if and only if (a) the # resolved directionality of that character is R, and (b) the # Bidi_Mirrored property value of that character is t...
Accepts unicode or string. In case it s a string encoding is needed as it works on unicode ones ( default: utf - 8 ).
def get_display(unicode_or_str, encoding='utf-8', upper_is_rtl=False, base_dir=None, debug=False): """Accepts unicode or string. In case it's a string, `encoding` is needed as it works on unicode ones (default:"utf-8"). Set `upper_is_rtl` to True to treat upper case chars as strong 'R' ...
Inject the current working file
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...
Convert compiled. ui file from PySide2 to Qt. py
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 ...
Append to self accessible via Qt. QtCompat
def _add(object, name, value): """Append to self, accessible via Qt.QtCompat""" self.__added__.append(name) setattr(object, name, value)
Qt. py command - line interface
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 ...
Add members found in prior versions up till the next major release
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...
Setup integration
def setup(menu=True): """Setup integration Registers Pyblish for Maya plug-ins and appends an item to the File-menu Attributes: console (bool): Display console with GUI port (int, optional): Port from which to start looking for an available port to connect with Pyblish QML, def...
Try showing the most desirable GUI
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...
Return the most desirable of the currently registered GUIs
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 ...
Remove integration
def teardown(): """Remove integration""" if not self._has_been_setup: return deregister_plugins() deregister_host() if self._has_menu: remove_from_filemenu() self._has_menu = False self._has_been_setup = False print("pyblish: Integration torn down successfully")
Register supported hosts
def deregister_host(): """Register supported hosts""" pyblish.api.deregister_host("mayabatch") pyblish.api.deregister_host("mayapy") pyblish.api.deregister_host("maya")
Add Pyblish to file - menu
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...
Helper function for the above: func: add_to_filemenu ()
def _add_to_filemenu(): """Helper function for the above :func:add_to_filemenu() This function is serialised into a string and passed on to evalDeferred above. """ import os import pyblish from maya import cmds # This must be duplicated here, due to this function # not being avai...
Maintain selection during context
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...
Maintain current time during context
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)
Popup with information about how to register a new GUI
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...
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 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...
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.
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...
Return all the values for a single axis of the data.
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']]
Draw a constant line on the y - axis with the label
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...
Cache the parameters necessary to transform x & y coordinates
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)...
For every key value pair return the mapping for the equivalent value key pair
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))
For every key that has an __iter__ method assign the values to a key for each.
def flatten_mapping(mapping): """ For every key that has an __iter__ method, assign the values to a key for each. >>> flatten_mapping({'ab': 3, ('c','d'): 4}) == {'ab': 3, 'c': 4, 'd': 4} True """ return { key: value for keys, value in mapping.items() for key in always_iterable(keys) }
Much like the built - in function range but accepts floats
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
Add a data set to the graph
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...
Add svg definitions
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', )
Add data to the graph object. May be called several times to add additional data sets.
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)
Process the template with the data and config which has been set and return the resulting SVG.
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...
Calculates the margin to the left of the plot area setting border_left.
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...
Calculate the margin in pixels to the right of the plot area setting border_right.
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...
Calculate the margin in pixels above the plot area setting border_top.
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
Add pop - up information to a point on the graph.
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...
Calculate the margin in pixels below the plot area setting border_bottom.
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 ...
The central logic for drawing the graph.
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':...
Add text for a datapoint
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...
Draw the X axis labels
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...
Draw the Y axis labels
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...
Draw the X - axis guidelines
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...
Draw the Y - axis guidelines
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...
Draws the graph title and subtitle
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()
Hard - code the styles into the SVG XML if style sheets are not used.
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...
Take a. css file ( classes only please ) and parse it into a dictionary of class/ style pairs.
def parse_css(self): """ Take a .css file (classes only please) and parse it into a dictionary of class/style pairs. """ # todo: save the prefs for use later # orig_prefs = cssutils.ser.prefs cssutils.ser.prefs.useMinified() pairs = ( (r.selectorText, r.style.cssText) for r in self.get_stylesheet(...
Base SVG Document Creation
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() ...
Get the stylesheets for this instance
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
\ Convenience function to start a bot on the given network optionally joining some channels
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(): ...
\ 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.
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...
\ Connect to the IRC server using the nickname
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)) ...
\ Multipurpose method for sending responses to channel or via message to a single user
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 :...
\ Low - level dispatching of socket data based on regex matching in general handles
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 ...
\ Generates a new nickname based on original nickname followed by a random number
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)) ...
\ Respond to periodic PING messages from server
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)
\ When the connection to the server is registered send all pending data.
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: ...
\ Main loop of the IRCConnection - reads from the socket and dispatches based on regex matching
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...
\ Hook for registering callbacks with connection -- handled by __init__ ()
def register_callbacks(self): """\ Hook for registering callbacks with connection -- handled by __init__() """ self.conn.register_callbacks(( (re.compile(pattern), callback) \ for pattern, callback in self.command_patterns() ))
\ Wraps the connection object s respond () method
def respond(self, message, channel=None, nick=None): """\ Wraps the connection object's respond() method """ self.conn.respond(message, channel, nick)
\ Register the worker with the boss
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)
\ Run tasks in a greenlet pulling from the workers task queue and reporting results to the command channel
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: ...
\ Decorator to ensure that commands only can come from the boss
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, **...
\ 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
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...
\ Received registration acknowledgement from the BotnetBot as well as the name of the command channel so join up and indicate that registration succeeded
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 ...
\ Work on a task from the BotnetBot
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...
\ Indicate that the worker with given nick is performing this task
def add(self, nick): """\ Indicate that the worker with given nick is performing this task """ self.data[nick] = '' self.workers.add(nick)
Send a validation email to the user s email address.
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()
Send a password reset to the user s email address.
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()
Passwords should be tough.
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...
Use token to allow one - time access to a view.
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. """ ...
Delete the user s avatar.
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()...
Throttle POST requests only.
def allow_request(self, request, view): """ Throttle POST requests only. """ if request.method != 'POST': return True return super(PostRequestThrottleMixin, self).allow_request(request, view)
single global executor
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
single global client instance
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...
A tuple consisting of the TLS client certificate and key if they have been provided otherwise None.
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
Service name inside the Docker Swarm
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...
wrapper for calling docker methods
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)
Call a docker method in a background thread
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)
Check for a task state like docker service ps id
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( ...
Start the single - user server in a docker service. You can specify the params for the service through jupyterhub_config. py or using the user_options
def start(self): """Start the single-user server in a docker service. You can specify the params for the service through jupyterhub_config.py or using the user_options """ # https://github.com/jupyterhub/jupyterhub/blob/master/jupyterhub/user.py#L202 # By default jupyter...
Stop and remove the service
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',...
Check lower - cased email is unique.
def filter_queryset(self, value, queryset): """Check lower-cased email is unique.""" return super(UniqueEmailValidator, self).filter_queryset( value.lower(), queryset, )