Search is not available for this dataset
text
stringlengths
75
104k
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' ...
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...
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 ...
def _add(object, name, value): """Append to self, accessible via Qt.QtCompat""" self.__added__.append(name) setattr(object, name, value)
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 ...
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...
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...
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...
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 ...
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")
def deregister_host(): """Register supported hosts""" pyblish.api.deregister_host("mayabatch") pyblish.api.deregister_host("mayapy") pyblish.api.deregister_host("maya")
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...
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...
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...
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)
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...
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...
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...
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']]
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...
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)...
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))
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) }
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
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...
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', )
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)
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...
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...
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...
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
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...
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 ...
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':...
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...
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...
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...
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...
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...
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()
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...
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(...
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() ...
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
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(): ...
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...
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)) ...
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 :...
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 ...
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)) ...
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)
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: ...
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...
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() ))
def respond(self, message, channel=None, nick=None): """\ Wraps the connection object's respond() method """ self.conn.respond(message, channel, nick)
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)
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: ...
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, **...
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...
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 ...
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...
def add(self, nick): """\ Indicate that the worker with given nick is performing this task """ self.data[nick] = '' self.workers.add(nick)
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()
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()
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...
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. """ ...
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()...
def allow_request(self, request, view): """ Throttle POST requests only. """ if request.method != 'POST': return True return super(PostRequestThrottleMixin, self).allow_request(request, view)
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
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...
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
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...
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)
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)
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( ...
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...
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',...
def filter_queryset(self, value, queryset): """Check lower-cased email is unique.""" return super(UniqueEmailValidator, self).filter_queryset( value.lower(), queryset, )
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_...
def update(self, instance, validated_data): """Set the new password for the user.""" instance.set_password(validated_data['new_password']) instance.save() return instance
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...
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_...
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...
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...
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_...
def clean_email(self): """ Since User.email is unique, this check is redundant, but it sets a nicer error message than the ORM. See #13147. """ email = self.cleaned_data['email'] try: User._default_manager.get(email__iexact=email) except User.DoesNotEx...
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()
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, }
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...
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...
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...
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...
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...
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...
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...
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...
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]
def widgets(self): """Return name,widget boxes for all parameters (i.e., a property sheet)""" params = self.parameterized.params().items() key_fn = lambda x: x[1].precedence if x[1].precedence is not None else self.p.default_precedence sorted_precedence = sorted(params, key=key_fn) ...
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: ...
def TextWidget(*args, **kw): """Forces a parameter value to be text""" kw['value'] = str(kw['value']) kw.pop('options', None) return TextInput(*args,**kw)