Search is not available for this dataset
text
stringlengths
75
104k
def setZeroResettableKWH(self, password="00000000"): """ Serial call to zero resettable kWh registers. Args: password (str): Optional password. Returns: bool: True on completion and ACK. """ result = False self.setContext("setZeroResettableKWH") ...
def setLCD(self, password="00000000"): """ Serial call to set LCD using meter object bufer. Used with :func:`~ekmmeters.V4Meter.addLcdItem`. Args: password (str): Optional password Returns: bool: True on completion and ACK. """ result = False ...
def iterate_fields(fields, schema): """Recursively iterate over all DictField sub-fields. :param fields: Field instance (e.g. input) :type fields: dict :param schema: Schema instance (e.g. input_schema) :type schema: dict """ schema_dict = {val['name']: val for val in schema} for field...
def iterate_schema(fields, schema, path=None): """Recursively iterate over all schema sub-fields. :param fields: Field instance (e.g. input) :type fields: dict :param schema: Schema instance (e.g. input_schema) :type schema: dict :path schema: Field path :path schema: string """ fo...
def paragraphs(quantity=2, separator='\n\n', wrap_start='', wrap_end='', html=False, sentences_quantity=3, as_list=False): """Random paragraphs.""" if html: wrap_start = '<p>' wrap_end = '</p>' separator = '\n\n' result = [] for i in xrange(0, quantity): r...
def text(length=None, at_least=10, at_most=15, lowercase=True, uppercase=True, digits=True, spaces=True, punctuation=False): """ Random text. If `length` is present the text will be exactly this chars long. Else the text will be something between `at_least` and `at_most` chars long. """ ...
def add_arguments(cls, parser): """Add arguments to the parser for collection in app.args. Args: parser: `argparse.ArgumentParser`. Parser. Arguments added here are server on self.args. """ parser.add_argument( '-c...
def apply_tasks_to_issue(self, issue, tasks, issue_body=None): """Applies task numbers to an issue.""" issue_body = issue_body or issue.body task_numbers = transport.format_task_numbers_with_links(tasks) if task_numbers: new_body = transport.ASANA_SECTION_RE.sub('', issue_bod...
def sync_labels(self, repo): """Creates a local map of github labels/milestones to asana tags.""" logging.info("syncing new github.com labels to tags") # create label tag map ltm = self.app.data.get("label-tag-map", {}) # loop over labels, if they don't have tags, make them ...
def statistics(self, elapsed, result): """ Return output for the combined time and result summary statistics. """ return "\n".join((self.timing(elapsed), self.result_summary(result)))
def color(self, color, text): """ Color some text in the given ANSI color. """ return "{escape}{text}{reset}".format( escape=self.ANSI[color], text=text, reset=self.ANSI["reset"], )
def show(self, text): """ Write the text to the stream and flush immediately. """ self.stream.write(text) self.stream.flush()
def result_summary(self, result): """ Return a summary of the results. """ return "{} examples, {} errors, {} failures\n".format( result.testsRun, len(result.errors), len(result.failures), )
def parse(argv=None): """ Parse some arguments using the parser. """ if argv is None: argv = sys.argv[1:] # Evade http://bugs.python.org/issue9253 if not argv or argv[0] not in {"run", "transform"}: argv = ["run"] + argv arguments = _clean(_parser.parse_args(argv)) re...
def setup(config): """ Setup the environment for an example run. """ formatter = config.Formatter() if config.verbose: formatter = result.Verbose(formatter) if config.color: formatter = result.Colored(formatter) current_result = result.ExampleResult(formatter) ivoire...
def run(config): """ Time to run. """ setup(config) if config.exitfirst: ivoire.current_result.failfast = True ivoire.current_result.startTestRun() for spec in config.specs: try: load_by_name(spec) except Exception: ivoire.current_result.a...
def transform(config): """ Run in transform mode. """ if transform_possible: ExampleLoader.register() args, sys.argv[1:] = sys.argv[1:], config.args try: return runpy.run_path(config.runner, run_name="__main__") finally: sys.argv[1:] = args
def visit_With(self, node): """ with describe(thing) as it: ... | v class TestThing(TestCase): ... """ withitem, = node.items context = withitem.context_expr if context.func.id == "describe": descr...
def transform_describe(self, node, describes, context_variable): """ Transform a describe node into a ``TestCase``. ``node`` is the node object. ``describes`` is the name of the object being described. ``context_variable`` is the name bound in the context manager (usually ...
def transform_describe_body(self, body, group_var): """ Transform the body of an ``ExampleGroup``. ``body`` is the body. ``group_var`` is the name bound to the example group in the context manager (usually "it"). """ for node in body: withitem, = no...
def transform_example(self, node, name, context_variable, group_variable): """ Transform an example node into a test method. Returns the unchanged node if it wasn't an ``Example``. ``node`` is the node object. ``name`` is the name of the example being described. ``conte...
def transform_example_body(self, body, context_variable): """ Transform the body of an ``Example`` into the body of a method. Replaces instances of ``context_variable`` to refer to ``self``. ``body`` is the body. ``context_variable`` is the name bound in the surrounding context...
def takes_only_self(self): """ Return an argument list node that takes only ``self``. """ return ast.arguments( args=[ast.arg(arg="self")], defaults=[], kw_defaults=[], kwonlyargs=[], )
def register(cls): """ Register the path hook. """ cls._finder = FileFinder.path_hook((cls, [cls.suffix])) sys.path_hooks.append(cls._finder)
def source_to_code(self, source_bytes, source_path): """ Transform the source code, then return the code object. """ node = ast.parse(source_bytes) transformed = ExampleTransformer().transform(node) return compile(transformed, source_path, "exec", dont_inherit=True)
def apply_argument_parser(argumentsParser, options=None): """ Apply the argument parser. """ if options is not None: args = argumentsParser.parse_args(options) else: args = argumentsParser.parse_args() return args
def load_by_name(name): """ Load a spec from either a file path or a fully qualified name. """ if os.path.exists(name): load_from_path(name) else: __import__(name)
def load_from_path(path): """ Load a spec from a given path, discovering specs if a directory is given. """ if os.path.isdir(path): paths = discover(path) else: paths = [path] for path in paths: name = os.path.basename(os.path.splitext(path)[0]) imp.load_source...
def discover(path, filter_specs=filter_specs): """ Discover all of the specs recursively inside ``path``. Successively yields the (full) relative paths to each spec. """ for dirpath, _, filenames in os.walk(path): for spec in filter_specs(filenames): yield os.path.join(dirpath...
def checker(location, receiver): """Construct a function that checks a directory for process configuration The function checks for additions or removals of JSON process configuration files and calls the appropriate receiver methods. :param location: string, the directory to monitor :param rece...
def messages(location, receiver): """Construct a function that checks a directory for messages The function checks for new messages and calls the appropriate method on the receiver. Sent messages are deleted. :param location: string, the directory to monitor :param receiver: IEventReceiver ...
def add(places, name, cmd, args, env=None, uid=None, gid=None, extras=None, env_inherit=None): """Add a process. :param places: a Places instance :param name: string, the logical name of the process :param cmd: string, executable :param args: list of strings, command-line arguments :par...
def remove(places, name): """Remove a process :params places: a Places instance :params name: string, the logical name of the process :returns: None """ config = filepath.FilePath(places.config) fle = config.child(name) fle.remove()
def restart(places, name): """Restart a process :params places: a Places instance :params name: string, the logical name of the process :returns: None """ content = _dumps(dict(type='RESTART', name=name)) _addMessage(places, content)
def call(results): """Call results.func on the attributes of results :params result: dictionary-like object :returns: None """ results = vars(results) places = Places(config=results.pop('config'), messages=results.pop('messages')) func = results.pop('func') func(plac...
def get(config, messages, freq, pidDir=None, reactor=None): """Return a service which monitors processes based on directory contents Construct and return a service that, when started, will run processes based on the contents of the 'config' directory, restarting them if file contents change and stoppin...
def makeService(opt): """Return a service based on parsed command-line options :param opt: dict-like object. Relevant keys are config, messages, pid, frequency, threshold, killtime, minrestartdelay and maxrestartdelay :returns: service, {twisted.application.interfaces.IServi...
def refresh_session(self, node_id=None): """ Adds or refreshes a particular node in the nodelist, attributing the current time with the node_id. :param string node_id: optional, the connection id of the node whose session should be refreshed """ if not node_id: ...
def find_expired_nodes(self, node_ids=None): """ Detects connections that have held a reference for longer than its process_ttl without refreshing its session. This function does not actually removed them from the hash. (See remove_expired_nodes.) :param list node_ids: optional,...
def remove_expired_nodes(self, node_ids=None): """ Removes all expired nodes from the nodelist. If a set of node_ids is passed in, those ids are checked to ensure they haven't been refreshed prior to a lock being acquired. Should only be run with a lock. :param list no...
def remove_node(self, node_id=None): """ Removes a particular node from the nodelist. :param string node_id: optional, the process id of the node to remove """ if not node_id: node_id = self.conn.id self.conn.client.hdel(self.nodelist_key, node_id)
def get_last_updated(self, node_id=None): """ Returns the time a particular node has been last refreshed. :param string node_id: optional, the connection id of the node to retrieve :rtype: int :returns: Returns a unix timestamp if it exists, otherwise None """ i...
def get_all_nodes(self): """ Returns all nodes in the hash with the time they were last refreshed as a dictionary. :rtype: dict(string, int) :returns: A dictionary of strings and corresponding timestamps """ nodes = self.conn.client.hgetall(self.nodelist_key) ...
def refresh_session(self): """ Update the session for this node. Specifically; lock on the reflist, then update the time this node acquired the reference. This method should only be called while the reference is locked. """ expired_nodes = self.nodelist.find_expired_nod...
def increment_times_modified(self): """ Increments the number of times this resource has been modified by all processes. """ rc = self.conn.client.incr(self.times_modified_key) self.conn.client.pexpire(self.times_modified_key, phonon.s_to_...
def get_times_modified(self): """ :returns: The total number of times increment_times_modified has been called for this resource by all processes. :rtype: int """ times_modified = self.conn.client.get(self.times_modified_key) if times_modified is None: return ...
def count(self): """ :returns: The total number of elements in the reference list. :rtype: int """ references = self.conn.client.get(self.refcount_key) if references is None: return 0 return int(references)
def dereference(self, callback=None, args=None, kwargs=None): """ This method should only be called while the reference is locked. Decrements the reference count for the resource. If this process holds the only reference at the time we finish dereferencing it; True is returned. ...
def delimit(values, delimiter=', '): "Returns a list of tokens interleaved with the delimiter." toks = [] if not values: return toks if not isinstance(delimiter, (list, tuple)): delimiter = [delimiter] last = len(values) - 1 for i, value in enumerate(values): toks.app...
def check(path, start, now): """check which processes need to be restarted :params path: a twisted.python.filepath.FilePath with configurations :params start: when the checker started running :params now: current time :returns: list of strings """ return [child.basename() for child in path....
def parseConfig(opt): """Parse configuration :params opt: dict-like object with config and messages keys :returns: restarter, path """ places = ctllib.Places(config=opt['config'], messages=opt['messages']) restarter = functools.partial(ctllib.restart, places) path = filepath.FilePath(opt['c...
def makeService(opt): """Make a service :params opt: dictionary-like object with 'freq', 'config' and 'messages' :returns: twisted.application.internet.TimerService that at opt['freq'] checks for stale processes in opt['config'], and sends restart messages through opt['messages'...
def expected_error(self, expected: str) -> str: """Generate a basic error to include the current state. A parser can supply only a representation of what it is expecting to this method and the reader will provide the context, including the index to the error. Args: ...
def recursion_error(self, repeated_parser: str): """Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args...
def expected_error(self, expected: str) -> str: """Generate a basic error to include the current state. A parser can supply only a representation of what it is expecting to this method and the reader will provide the context, including the line and character positions. Args: ...
def recursion_error(self, repeated_parser: str): """Generate an error to indicate that infinite recursion was encountered. A parser can supply a representation of itself to this method and the reader will supply the context, including the location where the parser stalled. Args...
def merge(self, status: 'Status[Input, Output]') -> 'Status[Input, Output]': """Merge the failure message from another status into this one. Whichever status represents parsing that has gone the farthest is retained. If both statuses have gone the same distance, then the expected values...
def exists(value): "Query to test if a value exists." if not isinstance(value, Token): raise TypeError('value must be a token') if not hasattr(value, 'identifier'): raise TypeError('value must support an identifier') if not value.identifier: value = value.__class__(**value.__di...
def get(value): "Query to get the value." if not isinstance(value, Token): raise TypeError('value must be a token') if not hasattr(value, 'identifier'): raise TypeError('value must support an identifier') if not value.identifier: value = value.__class__(**value.__dict__) ...
def constant(x: A) -> Callable[..., A]: """Produce a function that always returns a supplied value. Args: x: Any object. Returns: A function that accepts any number of positional and keyword arguments, discards them, and returns ``x``. """ def constanted(*args, **kwargs): ...
def splat(f: Callable[..., A]) -> Callable[[Iterable], A]: """Convert a function taking multiple arguments into a function taking a single iterable argument. Args: f: Any function Returns: A function that accepts a single iterable argument. Each element of this iterable argument is passed ...
def unsplat(f: Callable[[Iterable], A]) -> Callable[..., A]: """Convert a function taking a single iterable argument into a function taking multiple arguments. Args: f: Any function taking a single iterable argument Returns: A function that accepts multiple arguments. Each argument of this...
def runProcess(args, timeout, grace, reactor): """Run a process, return a deferred that fires when it is done :params args: Process arguments :params timeout: Time before terminating process :params grace: Time before killing process after terminating it :params reactor: IReactorProcess and IReacto...
def makeService(opts): """Make scheduler service :params opts: dict-like object. keys: frequency, args, timeout, grace """ ser = tainternet.TimerService(opts['frequency'], runProcess, opts['args'], opts['timeout'], opts['grace'], tireactor) ret = service.Mul...
def completely_parse_reader(parser: Parser[Input, Output], reader: Reader[Input]) -> Result[Output]: """Consume reader and return Success only on complete consumption. This is a helper function for ``parse`` methods, which return ``Success`` when the input is completely consumed and ``Failure`` with an app...
def lit(literal: Sequence[Input], *literals: Sequence[Sequence[Input]]) -> Parser: """Match a literal sequence. In the `TextParsers`` context, this matches the literal string provided. In the ``GeneralParsers`` context, this matches a sequence of input. If multiple literals are provided, they are ...
def opt(parser: Union[Parser, Sequence[Input]]) -> OptionalParser: """Optionally match a parser. An ``OptionalParser`` attempts to match ``parser``. If it succeeds, it returns a list of length one with the value returned by the parser as the only element. If it fails, it returns an empty list. Arg...
def rep1(parser: Union[Parser, Sequence[Input]]) -> RepeatedOnceParser: """Match a parser one or more times repeatedly. This matches ``parser`` multiple times in a row. If it matches as least once, it returns a list of values from each time ``parser`` matched. If it does not match ``parser`` at all, it...
def rep(parser: Union[Parser, Sequence[Input]]) -> RepeatedParser: """Match a parser zero or more times repeatedly. This matches ``parser`` multiple times in a row. A list is returned containing the value from each match. If there are no matches, an empty list is returned. Args: parser: Pa...
def rep1sep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \ -> RepeatedOnceSeparatedParser: """Match a parser one or more times separated by another parser. This matches repeated sequences of ``parser`` separated by ``separator``. If there is at least one match,...
def repsep(parser: Union[Parser, Sequence[Input]], separator: Union[Parser, Sequence[Input]]) \ -> RepeatedSeparatedParser: """Match a parser zero or more times separated by another parser. This matches repeated sequences of ``parser`` separated by ``separator``. A list is returned containing the v...
def check(settings, states, location): """Check all processes""" children = {child.basename(): child for child in location.children()} last = set(states) current = set(children) gone = last - current added = current - last for name in gone: states[name].close() del states[nam...
def makeService(opt): """Make a service :params opt: dictionary-like object with 'freq', 'config' and 'messages' :returns: twisted.application.internet.TimerService that at opt['freq'] checks for stale processes in opt['config'], and sends restart messages through opt['messages'...
def close(self): """Discard data and cancel all calls. Instance cannot be reused after closing. """ if self.closed: raise ValueError("Cannot close a closed state") if self.call is not None: self.call.cancel() self.closed = True
def check(self): """Check the state of HTTP""" if self.closed: raise ValueError("Cannot check a closed state") self._maybeReset() if self.url is None: return False return self._maybeCheck()
def makeService(): """Make a service :returns: an IService """ configJSON = os.environ.get('NCOLONY_CONFIG') if configJSON is None: return None config = json.loads(configJSON) params = config.get('ncolony.beatcheck') if params is None: return None myFilePath = filepa...
def maybeAddHeart(master): """Add a heart to a service collection Add a heart to a service.IServiceCollector if the heart is not None. :params master: a service.IServiceCollector """ heartSer = makeService() if heartSer is None: return heartSer.setName('heart') heartSer.set...
def wrapHeart(service): """Wrap a service in a MultiService with a heart""" master = taservice.MultiService() service.setServiceParent(master) maybeAddHeart(master) return master
def freeze_from_checkpoint(input_checkpoint, output_file_path, output_node_names): """Freeze and shrink the graph based on a checkpoint and the output node names.""" check_input_checkpoint(input_checkpoint) output_node_names = output_node_names_string_as_list(output_node_names) with tf.Session() as se...
def freeze(sess, output_file_path, output_node_names): """Freeze and shrink the graph based on a session and the output node names.""" with TemporaryDirectory() as temp_dir_name: checkpoint_path = os.path.join(temp_dir_name, 'model.ckpt') tf.train.Saver().save(sess, checkpoint_path) fre...
def save_graph_only(sess, output_file_path, output_node_names, as_text=False): """Save a small version of the graph based on a session and the output node names.""" for node in sess.graph_def.node: node.device = '' graph_def = graph_util.extract_sub_graph(sess.graph_def, output_node_names) outpu...
def save_graph_only_from_checkpoint(input_checkpoint, output_file_path, output_node_names, as_text=False): """Save a small version of the graph based on a checkpoint and the output node names.""" check_input_checkpoint(input_checkpoint) output_node_names = output_node_names_string_as_list(output_node_names...
def save_weights(sess, output_path, conv_var_names=None, conv_transpose_var_names=None): """Save the weights of the trainable variables, each one in a different file in output_path.""" if not conv_var_names: conv_var_names = [] if not conv_transpose_var_names: conv_transpose_var_names = [] ...
def save_weights_from_checkpoint(input_checkpoint, output_path, conv_var_names=None, conv_transpose_var_names=None): """Save the weights of the trainable variables given a checkpoint, each one in a different file in output_path.""" check_input_checkpoint(input_checkpoint) with tf.Session() as sess: ...
def restore_from_checkpoint(sess, input_checkpoint): """Return a TensorFlow saver from a checkpoint containing the metagraph.""" saver = tf.train.import_meta_graph('{}.meta'.format(input_checkpoint)) saver.restore(sess, input_checkpoint) return saver
def parse(cls, parser, token): """ Parse the tag, instantiate the class. :type parser: django.template.base.Parser :type token: django.template.base.Token """ tag_name, args, kwargs = parse_token_kwargs( parser, token, allowed_kwargs=cls.allowed_k...
def render(self, context): """ The default Django render() method for the tag. This method resolves the filter expressions, and calls :func:`render_tag`. """ # Resolve token kwargs tag_args = [expr.resolve(context) for expr in self.args] if self.compile_args else self.ar...
def render_tag(self, context, *tag_args, **tag_kwargs): """ Render the tag, with all arguments resolved to their actual values. """ raise NotImplementedError("{0}.render_tag() is not implemented!".format(self.__class__.__name__))
def validate_args(cls, tag_name, *args, **kwargs): """ Validate the syntax of the template tag. """ if cls.min_args is not None and len(args) < cls.min_args: if cls.min_args == 1: raise TemplateSyntaxError("'{0}' tag requires at least {1} argument".format(tag_...
def get_context_data(self, parent_context, *tag_args, **tag_kwargs): """ Return the context data for the included template. """ raise NotImplementedError("{0}.get_context_data() is not implemented.".format(self.__class__.__name__))
def get_context(self, parent_context, data): """ Wrap the context data in a :class:`~django.template.Context` object. :param parent_context: The context of the parent template. :type parent_context: :class:`~django.template.Context` :param data: The result from :func:`get_contex...
def render_tag(self, context, *tag_args, **tag_kwargs): """ Rendering of the tag. It either assigns the value as variable, or renders it. """ if self.as_var: # Assign the value in the parent context context[self.as_var] = self.get_value(context, *tag_args, **tag_k...
def parse(cls, parser, token): """ Parse the "as var" syntax. """ bits, as_var = parse_as_var(parser, token) tag_name, args, kwargs = parse_token_kwargs(parser, bits, ('template',) + cls.allowed_kwargs, compile_args=cls.compile_args, compile_kwargs=cls.compile_kwargs) # ...
def render_tag(self, context, *tag_args, **tag_kwargs): """ Rendering of the tag. It either assigns the value as variable, or renders it. """ # Be very explicit about which base functionality is used: # Using super() for mixin support will not work nicely anyway here. if ...
def get_context_data(self, parent_context, *tag_args, **tag_kwargs): """ Return the context data for the inclusion tag. Returns ``{'value': self.get_value(parent_context, *tag_args, **tag_kwargs)}`` by default. """ if 'template' not in self.allowed_kwargs: # The over...
def caffe_to_tensorflow_session(caffe_def_path, caffemodel_path, inputs, graph_name='Graph', conversion_out_dir_path=None, use_padding_same=False): """Create a TensorFlow Session from a Caffe model.""" try: # noinspection PyUnresolvedReferences from caffeflow impo...
def freeze(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph', conversion_out_dir_path=None, checkpoint_out_path=None, use_padding_same=False): """Freeze and shrink the graph based on a Caffe model, the input tensors and the output node names.""" with caf...
def save_graph_only(caffe_def_path, caffemodel_path, inputs, output_file_path, output_node_names, graph_name='Graph', use_padding_same=False): """Save a small version of the graph based on a Caffe model, the input tensors and the output node names.""" with caffe_to_tensorflow_session(caffe_d...
def save_weights(caffe_def_path, caffemodel_path, inputs, output_path, graph_name='Graph', conv_var_names=None, conv_transpose_var_names=None, use_padding_same=False): """Save the weights of the trainable variables, each one in a different file in output_path.""" with caffe_to_tensorflow_sessio...
def make_rows(num_columns, seq): """ Make a sequence into rows of num_columns columns. >>> tuple(make_rows(2, [1, 2, 3, 4, 5])) ((1, 4), (2, 5), (3, None)) >>> tuple(make_rows(3, [1, 2, 3, 4, 5])) ((1, 3, 5), (2, 4, None)) """ # calculate the minimum number of rows necessary to fit the list in # num_columns C...