Search is not available for this dataset
text
stringlengths
75
104k
def arrange_all(self): """ Arrange the components of the node using Graphviz. """ # FIXME: Circular reference avoidance. import godot.dot_data_parser import godot.graph graph = godot.graph.Graph( ID="g", directed=True ) self.conn = "->" graph.edges.append...
def _parse_xdot_directive(self, name, new): """ Handles parsing Xdot drawing directives. """ parser = XdotAttrParser() components = parser.parse_xdot_data(new) # The absolute coordinate of the drawing container wrt graph origin. x1 = min( [c.x for c in components] ) ...
def _on_drawing(self, object, name, old, new): """ Handles the containers of drawing components being set. """ attrs = [ "drawing", "arrowhead_drawing" ] others = [getattr(self, a) for a in attrs \ if (a != name) and (getattr(self, a) is not None)] x, y = self.compo...
def node_factory(**row_factory_kw): """ Give new nodes a unique ID. """ if "__table_editor__" in row_factory_kw: graph = row_factory_kw["__table_editor__"].object ID = make_unique_name("n", [node.ID for node in graph.nodes]) del row_factory_kw["__table_editor__"] return godot.no...
def edge_factory(**row_factory_kw): """ Give new edges a unique ID. """ if "__table_editor__" in row_factory_kw: table_editor = row_factory_kw["__table_editor__"] graph = table_editor.object ID = make_unique_name("node", [node.ID for node in graph.nodes]) n_nodes = len(graph.no...
def start(self, context): """Initialize the database connection.""" self.config['alias'] = self.alias safe_config = dict(self.config) del safe_config['host'] log.info("Connecting MongoEngine database layer.", extra=dict( uri = redact_uri(self.config['host']), config = self.config, )) sel...
def prepare(self, context): """Attach this connection's default database to the context using our alias.""" context.db[self.alias] = MongoEngineProxy(self.connection)
def _component_default(self): """ Trait initialiser. """ component = Container(fit_window=False, auto_size=True, bgcolor="green")#, position=list(self.pos) ) component.tools.append( MoveTool(component) ) # component.tools.append( TraitsTool(component) ) return ...
def _vp_default(self): """ Trait initialiser. """ vp = Viewport(component=self.component) vp.enable_zoom=True # vp.view_position = [-10, -10] vp.tools.append(ViewportPanTool(vp)) return vp
def arrange_all(self): """ Arrange the components of the node using Graphviz. """ # FIXME: Circular reference avoidance. import godot.dot_data_parser import godot.graph graph = godot.graph.Graph(ID="g") graph.add_node(self) print "GRAPH DOT:\n", str(grap...
def parse_xdot_drawing_directive(self, new): """ Parses the drawing directive, updating the node components. """ components = XdotAttrParser().parse_xdot_data(new) max_x = max( [c.bounds[0] for c in components] + [1] ) max_y = max( [c.bounds[1] for c in components] + [1] ) ...
def parse_xdot_label_directive(self, new): """ Parses the label drawing directive, updating the label components. """ components = XdotAttrParser().parse_xdot_data(new) pos_x = min( [c.x for c in components] ) pos_y = min( [c.y for c in components] ) move_to...
def _drawing_changed(self, old, new): """ Handles the container of drawing components changing. """ if old is not None: self.component.remove( old ) if new is not None: # new.bgcolor="pink" self.component.add( new ) w, h = self.component.bounds...
def _on_position_change(self, new): """ Handles the poition of the component changing. """ w, h = self.component.bounds self.pos = tuple([ new[0] + (w/2), new[1] + (h/2) ])
def _pos_changed(self, new): """ Handles the Graphviz position attribute changing. """ w, h = self.component.bounds self.component.position = [ new[0] - (w/2), new[1] - (h/2) ] # self.component.position = list( new ) self.component.request_redraw()
def normal_right_down(self, event): """ Handles the right mouse button being clicked when the tool is in the 'normal' state. If the event occurred on this tool's component (or any contained component of that component), the method opens a context menu with menu items from any to...
def highlight_info(ctx, style): """Outputs the CSS which can be customized for highlighted code""" click.secho("The following styles are available to choose from:", fg="green") click.echo(list(pygments.styles.get_all_styles())) click.echo() click.secho( f'The following CSS for the "{style}" ...
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws a closed polygon """ gc.save_state() try: # self._draw_bounds(gc) if len(self.points) >= 2: # Set the drawing parameters. gc.set_fill_color(self.pen.fill_color_) ...
def is_in(self, point_x, point_y): """ Test if a point is within this polygonal region """ point_array = array(((point_x, point_y),)) vertices = array(self.points) winding = self.inside_rule == "winding" result = points_in_polygon(point_array, vertices, winding) return r...
def _draw_mainlayer(self, gc, view_bounds=None, mode="default"): """ Draws the Bezier component """ if not self.points: return gc.save_state() try: gc.set_fill_color(self.pen.fill_color_) gc.set_line_width(self.pen.line_width) gc.set_stroke_color(sel...
def _connect(self, context): """Initialize the database connection.""" if __debug__: log.info("Connecting " + self.engine.partition(':')[0] + " database layer.", extra=dict( uri = redact_uri(self.uri, self.protect), config = self.config, alias = self.alias, )) self.connection = context...
def _handle_event(self, event, *args, **kw): """Broadcast an event to the database connections registered.""" for engine in self.engines.values(): if hasattr(engine, event): getattr(engine, event)(*args, **kw)
def run(self): """ Method that gets run when the Worker thread is started. When there's an item in in_queue, it takes it out, passes it to func as an argument, and puts the result in out_queue. """ while not self.stopper.is_set(): try: item =...
def get_full_page_url(self, page_number, scheme=None): """Get the full, external URL for this page, optinally with the passed in URL scheme""" args = dict( request.view_args, _external=True, ) if scheme is not None: args['_scheme'] = scheme ...
def render_prev_next_links(self, scheme=None): """Render the rel=prev and rel=next links to a Markup object for injection into a template""" output = '' if self.has_prev: output += '<link rel="prev" href="{}" />\n'.format(self.get_full_page_url(self.prev, scheme=scheme)) ...
def render_seo_links(self, scheme=None): """Render the rel=canonical, rel=prev and rel=next links to a Markup object for injection into a template""" out = self.render_prev_next_links(scheme=scheme) if self.total_pages == 1: out += self.render_canonical_link(scheme=scheme) ...
def last_item_number(self): """ :return: The last "item number", used when displaying messages to the user like "Displaying items 1 to 10 of 123" - in this example 10 would be returned """ n = self.first_item_number + self.page_size - 1 if n > self.total_items: ...
def _content_type_matches(candidate, pattern): """Is ``candidate`` an exact match or sub-type of ``pattern``?""" def _wildcard_compare(type_spec, type_pattern): return type_pattern == '*' or type_spec == type_pattern return ( _wildcard_compare(candidate.content_type, pattern.content_type) a...
def select_content_type(requested, available): """Selects the best content type. :param requested: a sequence of :class:`.ContentType` instances :param available: a sequence of :class:`.ContentType` instances that the server is capable of producing :returns: the selected content type (from ``a...
def rewrite_url(input_url, **kwargs): """ Create a new URL from `input_url` with modifications applied. :param str input_url: the URL to modify :keyword str fragment: if specified, this keyword sets the fragment portion of the URL. A value of :data:`None` will remove the fragment port...
def remove_url_auth(url): """ Removes the user & password and returns them along with a new url. :param str url: the URL to sanitize :return: a :class:`tuple` containing the authorization portion and the sanitized URL. The authorization is a simple user & password :class:`tuple`. ...
def _create_url_identifier(user, password): """ Generate the user+password portion of a URL. :param str user: the user name or :data:`None` :param str password: the password or :data:`None` """ if user is not None: user = parse.quote(user.encode('utf-8'), safe=USERINFO_SAFE_CHARS) ...
def _normalize_host(host, enable_long_host=False, encode_with_idna=None, scheme=None): """ Normalize a host for a URL. :param str host: the host name to normalize :keyword bool enable_long_host: if this keyword is specified and it is :data:`True`, then the host name length ...
def transform(self, X): ''' :X: numpy ndarray ''' noise = self._noise_func(*self._args, size=X.shape) results = X + noise self.relative_noise_size_ = self.relative_noise_size(X, results) return results
def relative_noise_size(self, data, noise): ''' :data: original data as numpy matrix :noise: noise matrix as numpy matrix ''' return np.mean([ sci_dist.cosine(u / la.norm(u), v / la.norm(v)) for u, v in zip(noise, data) ])
def general(*dargs, **dkwargs): """ 将被装饰函数封装为一个 :class:`click.core.Command` 类, 此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 ``mohand`` 子命令的功能 该装饰器作为一个一般装饰器使用(如: ``@hand.general`` ) .. note:: 该装饰器会在插件系统加载外部插件前辈注册到 :data:`.hands.hand` 中。 此处的 ``general`` 装饰器同时兼容有参和无参调用方式 :param int log_level...
def discover_modules(directory): """ Attempts to list all of the modules and submodules found within a given directory tree. This function searches the top-level of the directory tree for potential python modules and returns a list of candidate names. **Note:** This function returns a list of strin...
def rdiscover_modules(directory): """ Attempts to list all of the modules and submodules found within a given directory tree. This function recursively searches the directory tree for potential python modules and returns a list of candidate names. **Note:** This function returns a list of strings r...
def rlist_modules(mname): """ Attempts to the submodules under a module recursively. This function works for modules located in the default path as well as extended paths via the sys.meta_path hooks. This function carries the expectation that the hidden module variable '__path__' has been set c...
def list_classes(mname, cls_filter=None): """ Attempts to list all of the classes within a specified module. This function works for modules located in the default path as well as extended paths via the sys.meta_path hooks. If a class filter is set, it will be called with each class as its para...
def rlist_classes(module, cls_filter=None): """ Attempts to list all of the classes within a given module namespace. This method, unlike list_classes, will recurse into discovered submodules. If a type filter is set, it will be called with each class as its parameter. This filter's return value...
def rgb_to_hsl(r, g, b): """ Converts an RGB color value to HSL. :param r: The red color value :param g: The green color value :param b: The blue color value :return: The HSL representation """ r = float(r) / 255.0 g = float(g) / 255.0 b = float(b) / 255.0 max_value = max(r,...
def html_color_to_rgba(html_colour, alpha): """ :param html_colour: Colour string like FF0088 :param alpha: Alpha value (opacity) :return: RGBA semitransparent version of colour for use in css """ html_colour = html_colour.upper() if html_colour[0] == '#': html_colour = html_colour[1...
def blend_html_colour_to_white(html_colour, alpha): """ :param html_colour: Colour string like FF552B or #334455 :param alpha: Alpha value :return: Html colour alpha blended onto white """ html_colour = html_colour.upper() has_hash = False if html_colour[0] == '#': has_hash = Tru...
def fit(self, X, y): ''' :X: list of dict :y: labels ''' self._avgs = average_by_label(X, y, self.reference_label) return self
def transform(self, X, y=None): ''' :X: list of dict ''' return map_dict_list( X, key_func=lambda k, v: self.names[k.lower()], if_func=lambda k, v: k.lower() in self.names)
def format_price_commas(price): """ Formats prices, rounding (i.e. to the nearest whole number of pounds) with commas """ if price is None: return None if price >= 0: return jinja2.Markup('&pound;{:,.2f}'.format(price)) else: return jinja2.Markup('-&pound;{:,.2f}'.format(...
def format_multiline_html(text): """ Turns a string like 'a\nb\nc' into 'a<br>b<br>c' and marks as Markup Note: Will remove all \r characters from output (if present) """ if text is None: return None if '\n' not in text: return text.replace('\r', '') parts = text.replace('...
def ensure_dir(path): """Ensure that a needed directory exists, creating it if it doesn't""" try: log.info('Ensuring directory exists: %s' % path) os.makedirs(path) except OSError: if not os.path.isdir(path): raise
def make_csv_response(csv_data, filename): """ :param csv_data: A string with the contents of a csv file in it :param filename: The filename that the file will be saved as when it is downloaded by the user :return: The response to return to the web connection """ resp = make_response(csv_data) ...
def to_base62(n): """ Converts a number to base 62 :param n: The number to convert :return: Base 62 representation of number (string) """ remainder = n % 62 result = BASE62_MAP[remainder] num = n // 62 while num > 0: remainder = num % 62 result = '%s%s' % (BASE62_MAP...
def from_base62(s): """ Convert a base62 String back into a number :param s: The base62 encoded String :return: The number encoded in the String (integer) """ result = 0 for c in s: if c not in BASE62_MAP: raise Exception('Invalid base64 string: %s' % s) result ...
def list_dataset_uris(cls, base_uri, config_path): """Return list containing URIs with base URI.""" storage_account_name = generous_parse_uri(base_uri).netloc blobservice = get_blob_service(storage_account_name, config_path) containers = blobservice.list_containers(include_metadata=True...
def list_overlay_names(self): """Return list of overlay names.""" overlay_names = [] for blob in self._blobservice.list_blobs( self.uuid, prefix=self.overlays_key_prefix ): overlay_file = blob.name.rsplit('/', 1)[-1] overlay_name, ext = ov...
def add_item_metadata(self, handle, key, value): """Store the given key:value pair for the item associated with handle. :param handle: handle for accessing an item before the dataset is frozen :param key: metadata key :param value: metadata value """ ...
def put_text(self, key, contents): """Store the given text contents so that they are later retrievable by the given key.""" self._blobservice.create_blob_from_text( self.uuid, key, contents )
def get_item_abspath(self, identifier): """Return absolute path at which item content can be accessed. :param identifier: item identifier :returns: absolute path from which the item content can be accessed """ admin_metadata = self.get_admin_metadata() uuid = admin_metad...
def iter_item_handles(self): """Return iterator over item handles.""" blob_generator = self._blobservice.list_blobs( self.uuid, include='metadata' ) for blob in blob_generator: if 'type' in blob.metadata: if blob.metadata['type'] == '...
def get_item_metadata(self, handle): """Return dictionary containing all metadata associated with handle. In other words all the metadata added using the ``add_item_metadata`` method. :param handle: handle for accessing an item before the dataset is frozen ...
def file_md5sum(filename): """ :param filename: The filename of the file to process :returns: The MD5 hash of the file """ hash_md5 = hashlib.md5() with open(filename, 'rb') as f: for chunk in iter(lambda: f.read(1024 * 4), b''): hash_md5.update(chunk) return hash_md5.hex...
def luhn_check(card_number): """ checks to make sure that the card passes a luhn mod-10 checksum """ sum = 0 num_digits = len(card_number) oddeven = num_digits & 1 for count in range(0, num_digits): digit = int(card_number[count]) if not ((count & 1) ^ oddeven): digit *...
def get_git_version(): """ Return the git hash as a string. Apparently someone got this from numpy's setup.py. It has since been modified a few times. """ # Return the git revision as a string # copied from numpy setup.py def _minimal_ext_cmd(cmd): # construct minimal environmen...
def load_hands(): """ 加载hand扩展插件 :return: 返回hand注册字典(单例) :rtype: HandDict """ # 优先进行自带 hand 的注册加载 import mohand.decorator # noqa # 注册hand插件 mgr = stevedore.ExtensionManager( namespace=env.plugin_namespace, invoke_on_load=True) def register_hand(ext): _...
def partial_fit(self, X, y): """ :X: {array-like, sparse matrix}, shape [n_samples, n_features] The data used to compute the mean and standard deviation used for later scaling along the features axis. :y: Healthy 'h' or 'sick_name' """ X, y = filter_by_lab...
def load_module(self, module_name): """ Loads a module's code and sets the module's expected hidden variables. For more information on these variables and what they are for, please see PEP302. :param module_name: the full name of the module to load """ if module_...
def add_path(self, path): """ Adds a path to search through when attempting to look up a module. :param path: the path the add to the list of searchable paths """ if path not in self.paths: self.paths.append(path)
def find_module(self, module_name, path=None): """ Searches the paths for the required module. :param module_name: the full name of the module to find :param path: set to None when the module in being searched for is a top-level module - otherwise this is set to ...
def tag_to_text(tag): """ :param tag: Beautiful soup tag :return: Flattened text """ out = [] for item in tag.contents: # If it has a name, it is a tag if item.name: out.append(tag_to_text(item)) else: # Just text! out.append(item) ...
def split_line(line, min_line_length=30, max_line_length=100): """ This is designed to work with prettified output from Beautiful Soup which indents with a single space. :param line: The line to split :param min_line_length: The minimum desired line length :param max_line_length: The maximum desire...
def pretty_print(html, max_line_length=110, tab_width=4): """ Pretty print HTML, splitting it into lines of a reasonable length (if possible). This probably needs a whole lot more testing! :param html: The HTML to format :param max_line_length: The desired maximum line length. Will not be strictly...
def transform(self, X, y=None): ''' :X: list of dict :y: labels ''' return [{ new_feature: self._fisher_pval(x, old_features) for new_feature, old_features in self.feature_groups.items() if len(set(x.keys()) & set(old_features)) } for x...
def _filtered_values(self, x: dict, feature_set: list=None): ''' :x: dict which contains feature names and values :return: pairs of values which shows number of feature makes filter function true or false ''' feature_set = feature_set or x n = sum(self.filter_func(x[i]) f...
def print_location(**kwargs): """ :param kwargs: Pass in the arguments to the function and they will be printed too! """ stack = inspect.stack()[1] debug_print('{}:{} {}()'.format(stack[1], stack[2], stack[3])) for k, v in kwargs.items(): lesser_debug_print('{} = {}'.format(k, v))
def remove_namespaces(root): """Call this on an lxml.etree document to remove all namespaces""" for elem in root.getiterator(): if not hasattr(elem.tag, 'find'): continue i = elem.tag.find('}') if i >= 0: elem.tag = elem.tag[i + 1:] objectify.deannotate(root...
def consistency(self, desired_version=None, include_package=False, strictness=None): """Checks that the versions are consistent Parameters ---------- desired_version: str optional; the version that all of these should match include_package: bool ...
def setup_is_release(setup, expected=True): """ Returns ------- bool or None : None if we can't tell """ try: is_release = setup.IS_RELEASE except AttributeError: return None else: if is_release and expected: return "" elif not is_relea...
def from_yaml(cls, **kwargs): """Creates a new instance of a rule in relation to the config file. This updates the dictionary of the class with the added details, which allows for flexibility in the configuation file. Only called when parsing the default configuation file. """ ...
def merge(self, new_dict): """Merges a dictionary into the Rule object.""" actions = new_dict.pop("actions") for action in actions: self.add_action(action) self.__dict__.update(new_dict)
def execute_actions(self, cwd): """Iterates over the actions and executes them in order.""" self._execute_globals(cwd) for action in self.actions: logger.info("executing {}".format(action)) p = subprocess.Popen(action, shell=True, cwd=cwd) p.wait()
def from_yaml(cls, defaults, **kwargs): """Creates a new instance of a rule by merging two dictionaries. This allows for independant configuration files to be merged into the defaults.""" # TODO: I hate myself for this. Fix it later mmkay? if "token" not in defaults: ...
def parse_address(formatted_address): """ :param formatted_address: A string like "email@address.com" or "My Email <email@address.com>" :return: Tuple: (address, name) """ if email_regex.match(formatted_address): # Just a raw address return (formatted_address, None) mat...
def send_mail(recipient_list, subject, body, html=False, from_address=None): """ :param recipient_list: List of recipients i.e. ['testing@fig14.com', 'Stephen Brown <steve@fig14.com>'] :param subject: The subject :param body: The email body :param html: Is this a html email? Defaults to False :p...
def add_details(self, message): """ Add extra details to the message. Separate so that it can be overridden """ msg = message # Try to append Flask request details try: from flask import request url = request.url method = request.metho...
def emit(self, record): """ Emit a record. Format the record and send it to the specified addressees. """ try: # First, remove all records from the rate limiter list that are over a minute old now = timetool.unix_time() one_minute_ago = now - ...
def get_context(self, value): """Ensure `image_rendition` is added to the global context.""" context = super(RenditionAwareStructBlock, self).get_context(value) context['image_rendition'] = self.rendition.\ image_rendition or 'original' return context
def log_attempt(self, key): """ Log an attempt against key, incrementing the number of attempts for that key and potentially adding a lock to the lock table """ with self.lock: if key not in self.attempts: self.attempts[key] = 1 else: ...
def service(self): """ Decrease the countdowns, and remove any expired locks. Should be called once every <decrease_every> seconds. """ with self.lock: # Decrement / remove all attempts for key in list(self.attempts.keys()): log.debug('Decrementin...
def add_to_queue(self, url): """ Adds an URL to the download queue. :param str url: URL to the music service track """ if self.connection_handler.current_music is None: log.error('Music service is not initialized. URL was not added to queue.') elif self.conn...
def use_music_service(self, service_name, api_key=None): """ Sets the current music service to service_name. :param str service_name: Name of the music service :param str api_key: Optional API key if necessary """ self.connection_handler.use_music_service(servic...
def use_storage_service(self, service_name, custom_path=None): """ Sets the current storage service to service_name and attempts to connect to it. :param str service_name: Name of the storage service :param str custom_path: Custom path where to download tracks for local storage ...
def start_workers(self, workers_per_task=1): """ Creates and starts the workers, as well as attaching a handler to terminate them gracefully when a SIGINT signal is received. :param int workers_per_task: Number of workers to create for each task in the pipeline """ if not self....
def set(self, k, v): """Add or update a key, value pair to the database""" k = k.lstrip('/') url = '{}/{}'.format(self.endpoint, k) r = requests.put(url, data=str(v)) if r.status_code != 200 or r.json() is not True: raise KVStoreError('PUT returned {}'.format(r.status...
def get(self, k, wait=False, wait_index=False, timeout='5m'): """Get the value of a given key""" k = k.lstrip('/') url = '{}/{}'.format(self.endpoint, k) params = {} if wait: params['index'] = wait_index params['wait'] = timeout r = requests.get(ur...
def recurse(self, k, wait=False, wait_index=None, timeout='5m'): """Recursively get the tree below the given key""" k = k.lstrip('/') url = '{}/{}'.format(self.endpoint, k) params = {} params['recurse'] = 'true' if wait: params['wait'] = timeout if...
def index(self, k, recursive=False): """Get the current index of the key or the subtree. This is needed for later creating long polling requests """ k = k.lstrip('/') url = '{}/{}'.format(self.endpoint, k) params = {} if recursive: params['recurse'] = ...
def delete(self, k, recursive=False): """Delete a given key or recursively delete the tree below it""" k = k.lstrip('/') url = '{}/{}'.format(self.endpoint, k) params = {} if recursive: params['recurse'] = '' r = requests.delete(url, params=params) if ...
def internal_error(exception, template_path, is_admin, db=None): """ Render an "internal error" page. The following variables will be populated when rendering the template: title: The page title message: The body of the error message to display to the user preformat: Boolean stating whethe...
def plot_heatmap(X, y, top_n=10, metric='correlation', method='complete'): ''' Plot heatmap which shows features with classes. :param X: list of dict :param y: labels :param top_n: most important n feature :param metric: metric which will be used for clustering :param method: method which w...
def get_setup_version(): """ 获取打包使用的版本号,符合 PYPI 官方推荐的版本号方案 :return: PYPI 打包版本号 :rtype: str """ ver = '.'.join(map(str, VERSION[:3])) # 若后缀描述字串为 None ,则直接返回主版本号 if not VERSION[3]: return ver # 否则,追加版本号后缀 hyphen = '' suffix = hyphen.join(map(str, VERSION[-2:])) i...
def get_cli_version(): """ 获取终端命令版本号,若存在VERSION文件则使用其中的版本号, 否则使用 :meth:`.get_setup_version` :return: 终端命令版本号 :rtype: str """ directory = os.path.dirname(os.path.abspath(__file__)) version_path = os.path.join(directory, 'VERSION') if os.path.exists(version_path): with open(ve...