INSTRUCTION
stringlengths
1
8.43k
RESPONSE
stringlengths
75
104k
Runs Godot.
def main(): """ Runs Godot. """ application = GodotApplication( id="godot", plugins=[CorePlugin(), PuddlePlugin(), WorkbenchPlugin(), ResourcePlugin(), GodotPlugin()] ) application.run()
Gets the object s children.
def get_children ( self, object ): """ Gets the object's children. """ children = [] children.extend( object.subgraphs ) children.extend( object.clusters ) children.extend( object.nodes ) children.extend( object.edges ) return children
Appends a child to the object s children.
def append_child ( self, object, child ): """ Appends a child to the object's children. """ if isinstance( child, Subgraph ): object.subgraphs.append( child ) elif isinstance( child, Cluster ): object.clusters.append( child ) elif isinstance( child, Node...
Inserts a child into the object s children.
def insert_child ( self, object, index, child ): """ Inserts a child into the object's children. """ if isinstance( child, Subgraph ): object.subgraphs.insert( index, child ) elif isinstance( child, Cluster ): object.clusters.insert( index, child ) elif ...
Deletes a child at a specified index from the object s children.
def delete_child ( self, object, index ): """ Deletes a child at a specified index from the object's children. """ if isinstance( child, Subgraph ): object.subgraphs.pop(index) elif isinstance( child, Cluster ): object.clusters.pop( index ) elif isinstan...
Sets up or removes a listener for children being replaced on a specified object.
def when_children_replaced ( self, object, listener, remove ): """ Sets up or removes a listener for children being replaced on a specified object. """ object.on_trait_change( listener, "subgraphs", remove = remove, dispatch = "fast_ui" ) objec...
Sets up or removes a listener for children being changed on a specified object.
def when_children_changed ( self, object, listener, remove ): """ Sets up or removes a listener for children being changed on a specified object. """ object.on_trait_change( listener, "subgraphs_items", remove = remove, dispatch = "fast_ui" ) o...
Gets the label to display for a specified object.
def get_label ( self, object ): """ Gets the label to display for a specified object. """ label = self.label if label[:1] == '=': return label[1:] label = xgetattr( object, label, '' ) if self.formatter is None: return label return self....
Sets the label for a specified object.
def set_label ( self, object, label ): """ Sets the label for a specified object. """ label_name = self.label if label_name[:1] != '=': xsetattr( object, label_name, label )
Sets up or removes a listener for the label being changed on a specified object.
def when_label_changed ( self, object, listener, remove ): """ Sets up or removes a listener for the label being changed on a specified object. """ label = self.label if label[:1] != '=': object.on_trait_change( listener, label, remove = remove, ...
Finishes initialising the editor by creating the underlying toolkit widget.
def init ( self, parent ): """ Finishes initialising the editor by creating the underlying toolkit widget. """ self._graph = graph = Graph() ui = graph.edit_traits(parent=parent, kind="panel") self.control = ui.control
Updates the editor when the object trait changes externally to the editor.
def update_editor ( self ): """ Updates the editor when the object trait changes externally to the editor. """ object = self.value # Graph the new object... canvas = self.factory.canvas if canvas is not None: for nodes_name in canvas.node_children:...
Adds the event listeners for a specified object.
def _add_listeners ( self ): """ Adds the event listeners for a specified object. """ object = self.value canvas = self.factory.canvas if canvas is not None: for name in canvas.node_children: object.on_trait_change(self._nodes_replaced, name) ...
Handles a list of nodes being set.
def _nodes_replaced(self, object, name, old, new): """ Handles a list of nodes being set. """ self._delete_nodes(old) self._add_nodes(new)
Handles addition and removal of nodes.
def _nodes_changed(self, object, name, undefined, event): """ Handles addition and removal of nodes. """ self._delete_nodes(event.removed) self._add_nodes(event.added)
Adds a node to the graph for each item in features using the GraphNodes from the editor factory.
def _add_nodes(self, features): """ Adds a node to the graph for each item in 'features' using the GraphNodes from the editor factory. """ graph = self._graph if graph is not None: for feature in features: for graph_node in self.factory.nodes: ...
Removes the node corresponding to each item in features.
def _delete_nodes(self, features): """ Removes the node corresponding to each item in 'features'. """ graph = self._graph if graph is not None: for feature in features: graph.delete_node( id(feature) ) graph.arrange_all()
Handles a list of edges being set.
def _edges_replaced(self, object, name, old, new): """ Handles a list of edges being set. """ self._delete_edges(old) self._add_edges(new)
Handles addition and removal of edges.
def _edges_changed(self, object, name, undefined, event): """ Handles addition and removal of edges. """ self._delete_edges(event.removed) self._add_edges(event.added)
Adds an edge to the graph for each item in features using the GraphEdges from the editor factory.
def _add_edges(self, features): """ Adds an edge to the graph for each item in 'features' using the GraphEdges from the editor factory. """ graph = self._graph if graph is not None: for feature in features: for graph_edge in self.factory.edges: ...
Removes the node corresponding to each item in features.
def _delete_edges(self, features): """ Removes the node corresponding to each item in 'features'. """ graph = self._graph if graph is not None: for feature in features: for graph_edge in self.factory.edges: if feature.__class__ in graph_ed...
Property getter.
def _get_name(self): """ Property getter. """ if (self.tail_node is not None) and (self.head_node is not None): return "%s %s %s" % (self.tail_node.ID, self.conn, self.head_node.ID) else: return "Edge"
Arrange the components of the node using Graphviz.
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...
Handles parsing Xdot drawing directives.
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] ) ...
Handles the containers of drawing components being set.
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...
Give new nodes a unique ID.
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...
Give new edges a unique ID.
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...
Initialize the database connection.
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...
Attach this connection s default database to the context using our alias.
def prepare(self, context): """Attach this connection's default database to the context using our alias.""" context.db[self.alias] = MongoEngineProxy(self.connection)
Trait initialiser.
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 ...
Trait initialiser.
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
Arrange the components of the node using Graphviz.
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...
Parses the drawing directive updating the node components.
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] ) ...
Parses the label drawing directive updating the label components.
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...
Handles the container of drawing components changing.
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...
Handles the poition of the component changing.
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) ])
Handles the Graphviz position attribute changing.
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()
Handles the right mouse button being clicked when the tool is in the normal state.
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...
Outputs the CSS which can be customized for highlighted code
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}" ...
Draws a closed polygon
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_) ...
Test if a point is within this polygonal region
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...
Draws the Bezier component
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...
Initialize the database connection.
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...
Broadcast an event to the database connections registered.
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)
Method that gets run when the Worker thread is started.
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 =...
Get the full external URL for this page optinally with the passed in URL scheme
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 ...
Render the rel = prev and rel = next links to a Markup object for injection into a template
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)) ...
Render the rel = canonical rel = prev and rel = next links to a Markup object for injection into a template
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) ...
: 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
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: ...
Is candidate an exact match or sub - type of pattern ?
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...
Selects the best content type.
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...
Create a new URL from input_url with modifications applied.
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...
Removes the user & password and returns them along with a new url.
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`. ...
Generate the user + password portion of a URL.
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) ...
Normalize a host for a URL.
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 ...
: X: numpy ndarray
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
: data: original data as numpy matrix: noise: noise matrix as numpy matrix
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) ])
将被装饰函数封装为一个: class: click. core. Command 类, 此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 mohand 子命令的功能
def general(*dargs, **dkwargs): """ 将被装饰函数封装为一个 :class:`click.core.Command` 类, 此装饰器并不提供额外的复杂功能,仅提供将被装饰方法注册为一个 ``mohand`` 子命令的功能 该装饰器作为一个一般装饰器使用(如: ``@hand.general`` ) .. note:: 该装饰器会在插件系统加载外部插件前辈注册到 :data:`.hands.hand` 中。 此处的 ``general`` 装饰器同时兼容有参和无参调用方式 :param int log_level...
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.
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...
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.
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...
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.
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...
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.
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...
Attempts to list all of the classes within a given module namespace. This method unlike list_classes will recurse into discovered submodules.
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...
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
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,...
: param html_colour: Colour string like FF0088: param alpha: Alpha value ( opacity ): return: RGBA semitransparent version of colour for use in css
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...
: param html_colour: Colour string like FF552B or #334455: param alpha: Alpha value: return: Html colour alpha blended onto white
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...
: X: list of dict: y: labels
def fit(self, X, y): ''' :X: list of dict :y: labels ''' self._avgs = average_by_label(X, y, self.reference_label) return self
: X: list of dict
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)
Formats prices rounding ( i. e. to the nearest whole number of pounds ) with commas
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(...
Turns a string like a \ nb \ nc into a<br > b<br > c and marks as Markup
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('...
Ensure that a needed directory exists creating it if it doesn t
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
: 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
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) ...
Converts a number to base 62: param n: The number to convert: return: Base 62 representation of number ( string )
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...
Convert a base62 String back into a number: param s: The base62 encoded String: return: The number encoded in the String ( integer )
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 ...
Return list containing URIs with base URI.
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...
Return list of overlay names.
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...
Store the given key: value pair for the item associated with handle.
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 """ ...
Store the given text contents so that they are later retrievable by the given key.
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 )
Return absolute path at which item content can be accessed.
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...
Return iterator over item handles.
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'] == '...
Return dictionary containing all metadata associated with handle.
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 ...
: param filename: The filename of the file to process: returns: The MD5 hash of the file
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...
checks to make sure that the card passes a luhn mod - 10 checksum
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 *...
Return the git hash as a string.
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...
加载hand扩展插件
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): _...
: 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
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...
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.
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_...
Adds a path to search through when attempting to look up a 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)
Searches the paths for the required module.
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 ...
: param tag: Beautiful soup tag: return: Flattened text
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) ...
This is designed to work with prettified output from Beautiful Soup which indents with a single space.
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...
Pretty print HTML splitting it into lines of a reasonable length ( if possible ).
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...
: X: list of dict: y: labels
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...
: x: dict which contains feature names and values: return: pairs of values which shows number of feature makes filter function true or false
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...
: param kwargs: Pass in the arguments to the function and they will be printed too!
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))
Call this on an lxml. etree document to remove all namespaces
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...
Checks that the versions are consistent
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 ...
Returns ------- bool or None: None if we can t tell
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...
Creates a new instance of a rule in relation to the config file.
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. """ ...
Merges a dictionary into the Rule object.
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)