sentence1
stringlengths
52
3.87M
sentence2
stringlengths
1
47.2k
label
stringclasses
1 value
def request_encode_url(self, method, url, fields=None, **urlopen_kw): """ Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc. """ if fields: url += '?' + urlencode(fields) ...
Make a request using :meth:`urlopen` with the ``fields`` encoded in the url. This is useful for request methods like GET, HEAD, DELETE, etc.
entailment
def make_str(value): """Converts a value into a valid string.""" if isinstance(value, bytes): try: return value.decode(sys.getfilesystemencoding()) except UnicodeError: return value.decode('utf-8', 'replace') return text_type(value)
Converts a value into a valid string.
entailment
def echo(message=None, file=None, nl=True, err=False, color=None): """Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the s...
Prints a message plus a newline to the given file or stdout. On first sight, this looks like the print function, but it has improved support for handling Unicode and binary data that does not fail no matter how badly configured the system is. Primarily it means that you can print binary data as well a...
entailment
def parent(): """Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.e...
Determine subshell matching the currently running shell The shell is determined by either a pre-defined BE_SHELL environment variable, or, if none is found, via psutil which looks at the parent process directly through system-level calls. For example, is `be` is run from cmd.exe, then the full ...
entailment
def platform(): """Return platform for the current shell, e.g. windows or unix""" executable = parent() basename = os.path.basename(executable) basename, _ = os.path.splitext(basename) if basename in ("bash", "sh"): return "unix" if basename in ("cmd", "powershell"): return "win...
Return platform for the current shell, e.g. windows or unix
entailment
def cmd(parent): """Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable """ shell_name = os.path.basename(parent).rsplit(".", 1)[0] dirname = os.path.dirname(__file__) # Support for Bash if shell_name in ("bash", "sh")...
Determine subshell command for subprocess.call Arguments: parent (str): Absolute path to parent shell executable
entailment
def context(root, project=""): """Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below. """ environment = os.environ.copy() environment.update({ "BE_PROJECT":...
Produce the be environment The environment is an exact replica of the active environment of the current process, with a few additional variables, all of which are listed below.
entailment
def random_name(): """Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus """ adj = _data.adjectives[random.randint(0, len(_data.adjectives) - 1)] noun = _data.nouns[random.randint(0, len(_data.nouns) - 1)] return "%s_%s" ...
Return a random name Example: >> random_name() dizzy_badge >> random_name() evasive_cactus
entailment
def isproject(path): """Return whether or not `path` is a project Arguments: path (str): Absolute path """ try: if os.path.basename(path)[0] in (".", "_"): return False if not os.path.isdir(path): return False if not any(fname in os.listdir(path...
Return whether or not `path` is a project Arguments: path (str): Absolute path
entailment
def echo(text, silent=False, newline=True): """Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline. """ if silent: return ...
Print to the console Arguments: text (str): Text to print to the console silen (bool, optional): Whether or not to produce any output newline (bool, optional): Whether or not to append a newline.
entailment
def list_projects(root, backend=os.listdir): """List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. """ projects = list() for project in sorted(backend(root)): abspath = os.path.join(root, pro...
List projects at `root` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory.
entailment
def list_inventory(inventory): """List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml """ inv...
List a projects inventory Given a project, simply list the contents of `inventory.yaml` Arguments: root (str): Absolute path to the `be` root directory, typically the current working directory. inventory (dict): inventory.yaml
entailment
def list_template(root, topics, templates, inventory, be, absolute=False): """List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list...
List contents for resolved template Resolve a template as far as possible via the given `topics`. For example, if a template supports 5 arguments, but only 3 are given, resolve the template until its 4th argument and list the contents thereafter. In some cases, an additional path is present follow...
entailment
def invert_inventory(inventory): """Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory """ inverted = dict() for binding, items in inventory.iteritems(): for...
Return {item: binding} from {binding: item} Protect against items with additional metadata and items whose type is a number Returns: Dictionary of inverted inventory
entailment
def pos_development_directory(templates, inventory, context, topics, user, item): """Return absolute path to development directory Arguments: templates (...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user item (str): Item from template-bin...
entailment
def fixed_development_directory(templates, inventory, topics, user): """Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` ...
Return absolute path to development directory Arguments: templates (dict): templates.yaml inventory (dict): inventory.yaml context (dict): The be context, from context() topics (list): Arguments to `in` user (str): Current `be` user
entailment
def replacement_fields_from_context(context): """Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context """ return dict((k[3:].lower(), context[k]) for k in context if k.startswith("BE_"))
Convert context replacement fields Example: BE_KEY=value -> {"key": "value} Arguments: context (dict): The current context
entailment
def item_from_topics(key, topics): """Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for t...
Get binding from `topics` via `key` Example: {0} == hello --> be in hello world {1} == world --> be in hello world Returns: Single topic matching the key Raises: IndexError (int): With number of required arguments for the key
entailment
def pattern_from_template(templates, name): """Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name """ if name not in templates: echo("No template named \"%s\"" % name) sys.exit(1) return templates[name]
Return pattern for name Arguments: templates (dict): Current templates name (str): Name of name
entailment
def binding_from_item(inventory, item): """Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item """ if item in self.bindings: return self.bindings[item] bindin...
Return binding for `item` Example: asset: - myasset The binding is "asset" Arguments: project: Name of project item (str): Name of item
entailment
def parse_environment(fields, context, topics): """Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1} """ def _resolve_environ...
Resolve the be.yaml environment key Features: - Lists, e.g. ["/path1", "/path2"] - Environment variable references, via $ - Replacement field references, e.g. {key} - Topic references, e.g. {1}
entailment
def parse_redirect(redirect, topics, context): """Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample """...
Resolve the be.yaml redirect key Arguments: redirect (dict): Source/destination pairs, e.g. {BE_ACTIVE: ACTIVE} topics (tuple): Topics from which to sample, e.g. (project, item, task) context (dict): Context from which to sample
entailment
def slice(index, template): """Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template to slice Example: >>> slice(0, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}' >>> slice(1, "{cwd}/{0}/assets/{1}/{2...
Slice a template based on it's positional argument Arguments: index (int): Position at which to slice template (str): Template to slice Example: >>> slice(0, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}' >>> slice(1, "{cwd}/{0}/assets/{1}/{2}") '{cwd}/{0}/assets/{1}'
entailment
def proxy_manager_for(self, proxy, **proxy_kwargs): """Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The prox...
Return urllib3 ProxyManager for the given proxy. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param proxy: The proxy to return a urllib3 ProxyManager for. :param proxy_kw...
entailment
def cert_verify(self, conn, url, verify, cert): """Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with...
Verify a SSL certificate. This method should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param conn: The urllib3 connection object associated with the cert. :param url: The requested URL. :...
entailment
def get_connection(self, url, proxies=None): """Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :pa...
Returns a urllib3 connection for the given URL. This should not be called from user code, and is only exposed for use when subclassing the :class:`HTTPAdapter <requests.adapters.HTTPAdapter>`. :param url: The URL to connect to. :param proxies: (optional) A Requests-style dictionary of p...
entailment
def request_url(self, request, proxies): """Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is o...
Obtain the url to use when making the final request. If the message is being sent through a HTTP proxy, the full URL has to be used. Otherwise, we should only use the path portion of the URL. This should not be called from user code, and is only exposed for use when subclassing the ...
entailment
def proxy_headers(self, proxy): """Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be c...
Returns a dictionary of the headers to add to any request sent through a proxy. This works with urllib3 magic to ensure that they are correctly sent to the proxy, rather than in a tunnelled request if CONNECT is being used. This should not be called from user code, and is only exposed f...
entailment
def request(method, url, **kwargs): """Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`...
Constructs and sends a :class:`Request <Request>`. :param method: method for the new :class:`Request` object. :param url: URL for the new :class:`Request` object. :param params: (optional) Dictionary or bytes to be sent in the query string for the :class:`Request`. :param data: (optional) Dictionary, b...
entailment
def is_connection_dropped(conn): # Platform-specific """ Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycli...
Returns True if the connection is dropped and should be closed. :param conn: :class:`httplib.HTTPConnection` object. Note: For platforms like AppEngine, this will always return ``False`` to let the platform handle connection recycling transparently for us.
entailment
def morsel_to_cookie(morsel): """Convert a Morsel object into a Cookie containing the one k/v pair.""" expires = None if morsel['max-age']: expires = time.time() + morsel['max-age'] elif morsel['expires']: time_template = '%a, %d-%b-%Y %H:%M:%S GMT' expires = time.mktime( ...
Convert a Morsel object into a Cookie containing the one k/v pair.
entailment
def get_dict(self, domain=None, path=None): """Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements.""" dictionary = {} for cookie in iter(self): if (domain is None or cookie.dom...
Takes as an argument an optional domain and path and returns a plain old Python dict of name-value pairs of cookies that meet the requirements.
entailment
def feed(self, aBuf, aCharLen): """feed a character with known length""" if aCharLen == 2: # we only care about 2-bytes character in our distribution analysis order = self.get_order(aBuf) else: order = -1 if order >= 0: self._mTotalChars +=...
feed a character with known length
entailment
def get_confidence(self): """return confidence based on existing data""" # if we didn't receive any character in our consideration range, # return negative answer if self._mTotalChars <= 0 or self._mFreqChars <= MINIMUM_DATA_THRESHOLD: return SURE_NO if self._mTotalC...
return confidence based on existing data
entailment
def add_stderr_logger(level=logging.DEBUG): """ Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it. """ # This method needs to be in this __init__.py to get the __name__ correct # even if urllib3 is vendored within another pack...
Helper for quickly adding a StreamHandler to the logger. Useful for debugging. Returns the handler after adding it.
entailment
def assert_fingerprint(cert, fingerprint): """ Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons. """ # Maps the length of a digest to a p...
Checks if given fingerprint matches the supplied certificate. :param cert: Certificate as bytes object. :param fingerprint: Fingerprint as string of hexdigits, can be interspersed by colons.
entailment
def create_urllib3_context(ssl_version=None, cert_reqs=ssl.CERT_REQUIRED, options=None, ciphers=None): """All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It:...
All arguments have the same meaning as ``ssl_wrap_socket``. By default, this function does a lot of the same work that ``ssl.create_default_context`` does on Python 3.4+. It: - Disables SSLv2, SSLv3, and compression - Sets a restricted set of server ciphers If you wish to enable SSLv3, you can do...
entailment
def ssl_wrap_socket(sock, keyfile=None, certfile=None, cert_reqs=None, ca_certs=None, server_hostname=None, ssl_version=None, ciphers=None, ssl_context=None): """ All arguments except for server_hostname and ssl_context have the same meaning as they do when using :fun...
All arguments except for server_hostname and ssl_context have the same meaning as they do when using :func:`ssl.wrap_socket`. :param server_hostname: When SNI is supported, the expected hostname of the certificate :param ssl_context: A pre-made :class:`SSLContext` object. If none is provide...
entailment
def connection_from_url(url, **kw): """ Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must...
Given a url, return an :class:`.ConnectionPool` instance of its host. This is a shortcut for not having to parse out the scheme, host, and port of the url before creating an :class:`.ConnectionPool` instance. :param url: Absolute URL string that must include the scheme. Port is optional. :par...
entailment
def _put_conn(self, conn): """ Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded ...
Put a connection back into the pool. :param conn: Connection object for the current host and port as returned by :meth:`._new_conn` or :meth:`._get_conn`. If the pool is already full, the connection is closed and discarded because we exceeded maxsize. If connections are...
entailment
def _make_request(self, conn, method, url, timeout=_Default, **httplib_request_kw): """ Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: ...
Perform a request on a given urllib connection object taken from our pool. :param conn: a connection from one of our connection pools :param timeout: Socket timeout in seconds for the request. This can be a float or integer, which will set the same timeout v...
entailment
def urlopen(self, method, url, body=None, headers=None, retries=None, redirect=True, assert_same_host=True, timeout=_Default, pool_timeout=None, release_conn=None, **response_kw): """ Get a connection from the pool and perform an HTTP request. This is the lowest l...
Get a connection from the pool and perform an HTTP request. This is the lowest level call for making a request, so you'll need to specify all the raw details. .. note:: More commonly, it's appropriate to use a convenience method provided by :class:`.RequestMethods`, such ...
entailment
def _new_conn(self): """ Return a fresh :class:`httplib.HTTPSConnection`. """ self.num_connections += 1 log.info("Starting new HTTPS connection (%d): %s" % (self.num_connections, self.host)) if not self.ConnectionCls or self.ConnectionCls is DummyConnect...
Return a fresh :class:`httplib.HTTPSConnection`.
entailment
def _validate_conn(self, conn): """ Called right before a request is made, after the socket is created. """ super(HTTPSConnectionPool, self)._validate_conn(conn) # Force connect early to allow us to validate the connection. if not getattr(conn, 'sock', None): # AppEngin...
Called right before a request is made, after the socket is created.
entailment
def description_of(lines, name='stdin'): """ Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str """ u = Univers...
Return a string describing the probable encoding of a file or list of strings. :param lines: The lines to get the encoding of. :type lines: Iterable of bytes :param name: Name of file or collection of lines :type name: str
entailment
def main(argv=None): ''' Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str ''' # Get command line arguments parser = argparse.Argume...
Handles command line arguments and gets things started. :param argv: List of arguments, as if specified on the command-line. If None, ``sys.argv[1:]`` is used instead. :type argv: list of str
entailment
def get_terminal_size(): """Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows. """ # If shutil has get_terminal_size() (Python 3.3 and later) use that if sys.version_info >= (3, 3): import shutil shutil_get_terminal_size = getattr(s...
Returns the current size of the terminal as tuple in the form ``(width, height)`` in columns and rows.
entailment
def style(text, fg=None, bg=None, bold=None, dim=None, underline=None, blink=None, reverse=None, reset=True): """Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be preve...
Styles a text with ANSI styles and returns the new string. By default the styling is self contained which means that at the end of the string a reset code is issued. This can be prevented by passing ``reset=False``. Examples:: click.echo(click.style('Hello World!', fg='green')) click...
entailment
def secho(text, file=None, nl=True, err=False, color=None, **styles): """This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyw...
This function combines :func:`echo` and :func:`style` into one call. As such the following two calls are the same:: click.secho('Hello World!', fg='green') click.echo(click.style('Hello World!', fg='green')) All keyword arguments are forwarded to the underlying functions depending on whic...
entailment
def merge_setting(request_setting, session_setting, dict_class=OrderedDict): """ Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class` ...
Determines appropriate setting for a given request, taking into account the explicit setting on that request, and the setting in the session. If a setting is a dictionary, they will be merged together using `dict_class`
entailment
def resolve_redirects(self, resp, req, stream=False, timeout=None, verify=True, cert=None, proxies=None): """Receives a Response. Returns a generator of Responses.""" i = 0 hist = [] # keep track of history while resp.is_redirect: prepared_request ...
Receives a Response. Returns a generator of Responses.
entailment
def send(self, request, **kwargs): """Send a given PreparedRequest.""" # Set defaults that the hooks can utilize to ensure they always have # the correct parameters to reproduce the previous request. kwargs.setdefault('stream', self.stream) kwargs.setdefault('verify', self.verify...
Send a given PreparedRequest.
entailment
def stream(self, amt=2**16, decode_content=None): """ A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator wil...
A generator wrapper for the read() method. A call will block until ``amt`` bytes have been read from the connection or until the connection is closed. :param amt: How much of the content to read. The generator will return up to much data per iteration, but may return les...
entailment
def prepare_method(self, method): """Prepares the given HTTP method.""" self.method = method if self.method is not None: self.method = self.method.upper()
Prepares the given HTTP method.
entailment
def prepare_headers(self, headers): """Prepares the given HTTP headers.""" if headers: self.headers = CaseInsensitiveDict((to_native_string(name), value) for name, value in headers.items()) else: self.headers = CaseInsensitiveDict()
Prepares the given HTTP headers.
entailment
def iter_content(self, chunk_size=1, decode_unicode=False): """Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is no...
Iterates over the response data. When stream=True is set on the request, this avoids reading the content at once into memory for large responses. The chunk size is the number of bytes it should read into memory. This is not necessarily the length of each item returned as decoding can ...
entailment
def json(self, **kwargs): """Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes. """ if not self.encoding and len(self.content) > 3: # No encoding set. JSON RFC 4627 section 3 states we should expect ...
Returns the json-encoded content of a response, if any. :param \*\*kwargs: Optional arguments that ``json.loads`` takes.
entailment
def raise_for_status(self): """Raises stored :class:`HTTPError`, if one occurred.""" http_error_msg = '' if 400 <= self.status_code < 500: http_error_msg = '%s Client Error: %s' % (self.status_code, self.reason) elif 500 <= self.status_code < 600: http_error_ms...
Raises stored :class:`HTTPError`, if one occurred.
entailment
def _new_pool(self, scheme, host, port): """ Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for cust...
Create a new :class:`ConnectionPool` based on host, port and scheme. This method is used to actually create the connection pools handed out by :meth:`connection_from_url` and companion methods. It is intended to be overridden for customization.
entailment
def connection_from_host(self, host, port=None, scheme='http'): """ Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``. """ if not host: ...
Get a :class:`ConnectionPool` based on the host, port, and scheme. If ``port`` isn't given, it will be derived from the ``scheme`` using ``urllib3.connectionpool.port_by_scheme``.
entailment
def genty_repeat(count): """ To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @g...
To use in conjunction with a TestClass wrapped with @genty. Runs the wrapped test 'count' times: @genty_repeat(count) def test_some_function(self) ... Can also wrap a test already decorated with @genty_dataset @genty_repeat(3) @genty_dataset(True, False) def...
entailment
def command(name=None): """A decorator to register a subcommand with the global `Subcommands` instance. """ def decorator(f): _commands.append((name, f)) return f return decorator
A decorator to register a subcommand with the global `Subcommands` instance.
entailment
def main(program=None, version=None, doc_template=None, commands=None, argv=None, exit_at_end=True): """Top-level driver for creating subcommand-based programs. Args: program: The name of your program. version: The version string for your program. ...
Top-level driver for creating subcommand-based programs. Args: program: The name of your program. version: The version string for your program. doc_template: The top-level docstring template for your program. If `None`, a standard default version is applied. commands: A ...
entailment
def process_response(self, request, response, spider): """Overridden process_response would "pipe" response.body through BeautifulSoup.""" return response.replace(body=str(BeautifulSoup(response.body, self.parser)))
Overridden process_response would "pipe" response.body through BeautifulSoup.
entailment
def genty(target_cls): """ This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class` ""...
This decorator takes the information provided by @genty_dataset, @genty_dataprovider, and @genty_repeat and generates the corresponding test methods. :param target_cls: Test class whose test methods have been decorated. :type target_cls: `class`
entailment
def _expand_datasets(test_functions): """ Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator...
Generator producing test_methods, with an optional dataset. :param test_functions: Iterator over tuples of test name and test unbound function. :type test_functions: `iterator` of `tuple` of (`unicode`, `function`) :return: Generator yielding a tuple of - method_name : ...
entailment
def _expand_repeats(test_functions): """ Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset ...
Generator producing test_methods, with any repeat count unrolled. :param test_functions: Sequence of tuples of - method_name : Name of the test method - unbound function : Unbound function that will be the test method. - dataset name : String representation of the given dat...
entailment
def _is_referenced_in_argv(method_name): """ Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: ...
Various test runners allow one to run a specific test like so: python -m unittest -v <test_module>.<test_name> Return True is the given method name is so referenced. :param method_name: Base name of the method to add. :type method_name: `unicode` :return: Is the given m...
entailment
def _build_repeat_suffix(iteration, count): """ Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param c...
Return the suffix string to identify iteration X out of Y. For example, with a count of 100, this will build strings like "iteration_053" or "iteration_008". :param iteration: Current iteration. :type iteration: `int` :param count: Total number of iterations. :type coun...
entailment
def _build_final_method_name( method_name, dataset_name, dataprovider_name, repeat_suffix, ): """ Return a nice human friendly name, that almost looks like code. Example: a test called 'test_something' with a dataset of (5, 'hello') Return: "test_something(5, 'hell...
Return a nice human friendly name, that almost looks like code. Example: a test called 'test_something' with a dataset of (5, 'hello') Return: "test_something(5, 'hello')" Example: a test called 'test_other_stuff' with dataset of (9) and repeats Return: "test_other_stuff(9) iteration_<X>" ...
entailment
def _build_dataset_method(method, dataset): """ Return a fabricated method that marshals the dataset into parameters for given 'method' :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of t...
Return a fabricated method that marshals the dataset into parameters for given 'method' :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance containing the args of the dataset. :type dataset: `tuple` or :class...
entailment
def _build_dataprovider_method(method, dataset, dataprovider): """ Return a fabricated method that calls the dataprovider with the given dataset, and marshals the return value from that into params to the underlying test 'method'. :param method: The underlying test method. :type method: ...
Return a fabricated method that calls the dataprovider with the given dataset, and marshals the return value from that into params to the underlying test 'method'. :param method: The underlying test method. :type method: `callable` :param dataset: Tuple or GentyArgs instance ...
entailment
def _add_method_to_class( target_cls, method_name, func, dataset_name, dataset, dataprovider, repeat_suffix, ): """ Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: ...
Add the described method to the given class. :param target_cls: Test class to which to add a method. :type target_cls: `class` :param method_name: Base name of the method to add. :type method_name: `unicode` :param func: The underlying test function to call. ...
entailment
def close(self): """Close any open window. Note that this only works with non-blocking methods. """ if self._process: # Be nice first. self._process.send_signal(signal.SIGINT) # If it doesn't close itself promptly, be brutal. # Python 3....
Close any open window. Note that this only works with non-blocking methods.
entailment
def _run_blocking(self, args, input=None): """Internal API: run a blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string ...
Internal API: run a blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process. ...
entailment
def _run_nonblocking(self, args, input=None): """Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: str...
Internal API: run a non-blocking command with subprocess. This closes any open non-blocking dialog before running the command. Parameters ---------- args: Popen constructor arguments Command to run. input: string Value to feed to the stdin of the process...
entailment
def error(self, message, rofi_args=None, **kwargs): """Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported for error windows, and if specified will be ignored. Parameters ---------- message: string ...
Show an error window. This method blocks until the user presses a key. Fullscreen mode is not supported for error windows, and if specified will be ignored. Parameters ---------- message: string Error message to show.
entailment
def status(self, message, rofi_args=None, **kwargs): """Show a status message. This method is non-blocking, and intended to give a status update to the user while something is happening in the background. To close the window, either call the close() method or use any of the dis...
Show a status message. This method is non-blocking, and intended to give a status update to the user while something is happening in the background. To close the window, either call the close() method or use any of the display methods to replace it with a different window. Ful...
entailment
def select(self, prompt, options, rofi_args=None, message="", select=None, **kwargs): """Show a list of options and return user selection. This method blocks until the user makes their choice. Parameters ---------- prompt: string The prompt telling the user what the...
Show a list of options and return user selection. This method blocks until the user makes their choice. Parameters ---------- prompt: string The prompt telling the user what they are selecting. options: list of strings The options they can choose from. A...
entailment
def generic_entry(self, prompt, validator=None, message=None, rofi_args=None, **kwargs): """A generic entry box. Parameters ---------- prompt: string Text prompt for the entry. validator: function, optional A function to validate and convert the value ent...
A generic entry box. Parameters ---------- prompt: string Text prompt for the entry. validator: function, optional A function to validate and convert the value entered by the user. It should take one parameter, the string that the user entered, and ...
entailment
def text_entry(self, prompt, message=None, allow_blank=False, strip=True, rofi_args=None, **kwargs): """Prompt the user to enter a piece of text. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Mes...
Prompt the user to enter a piece of text. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. allow_blank: Boolean Whether to allow blank entries. strip...
entailment
def integer_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter an integer. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the...
Prompt the user to enter an integer. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: integer, optional Minimum and maximum values to allow. If Non...
entailment
def float_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a floating point number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to displa...
Prompt the user to enter a floating point number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: float, optional Minimum and maximum values to al...
entailment
def decimal_entry(self, prompt, message=None, min=None, max=None, rofi_args=None, **kwargs): """Prompt the user to enter a decimal number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display und...
Prompt the user to enter a decimal number. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. min, max: Decimal, optional Minimum and maximum values to allow. ...
entailment
def date_entry(self, prompt, message=None, formats=['%x', '%d/%m/%Y'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional ...
Prompt the user to enter a date. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter date...
entailment
def time_entry(self, prompt, message=None, formats=['%X', '%H:%M', '%I:%M', '%H.%M', '%I.%M'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: stri...
Prompt the user to enter a time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can enter time...
entailment
def datetime_entry(self, prompt, message=None, formats=['%x %X'], show_example=False, rofi_args=None, **kwargs): """Prompt the user to enter a date and time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional ...
Prompt the user to enter a date and time. Parameters ---------- prompt: string Prompt to display to the user. message: string, optional Message to display under the entry line. formats: list of strings, optional The formats that the user can e...
entailment
def exit_with_error(self, error, **kwargs): """Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters ---------- error: string The error to report before quitting. """ self.error(error, **kwargs) ...
Report an error and exit. This raises a SystemExit exception to ask the interpreter to quit. Parameters ---------- error: string The error to report before quitting.
entailment
def format_kwarg(key, value): """ Return a string of form: "key=<value>" If 'value' is a string, we want it quoted. The goal is to make the string a named parameter in a method call. """ translator = repr if isinstance(value, six.string_types) else six.text_type arg_value = translator(valu...
Return a string of form: "key=<value>" If 'value' is a string, we want it quoted. The goal is to make the string a named parameter in a method call.
entailment
def format_arg(value): """ :param value: Some value in a dataset. :type value: varies :return: unicode representation of that value :rtype: `unicode` """ translator = repr if isinstance(value, six.string_types) else six.text_type return translator(value)
:param value: Some value in a dataset. :type value: varies :return: unicode representation of that value :rtype: `unicode`
entailment
def encode_non_ascii_string(string): """ :param string: The string to be encoded :type string: unicode or str :return: The encoded string :rtype: str """ encoded_string = string.encode('utf-8', 'replace') if six.PY3: encoded_string = encoded_string...
:param string: The string to be encoded :type string: unicode or str :return: The encoded string :rtype: str
entailment
def genty_dataprovider(builder_function): """Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable that returns parameters that will be passed to the method decorated by this decorator. If the builder_function returns a...
Decorator defining that this test gets parameters from the given build_function. :param builder_function: A callable that returns parameters that will be passed to the method decorated by this decorator. If the builder_function returns a tuple or list, then that will be passed ...
entailment
def genty_dataset(*args, **kwargs): """Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-in-PHPUnit-3.2.html The canonical way to call @genty_dataset, with each argument each representing a data set to be injected in the test m...
Decorator defining data sets to provide to a test. Inspired by http://sebastian-bergmann.de/archives/ 702-Data-Providers-in-PHPUnit-3.2.html The canonical way to call @genty_dataset, with each argument each representing a data set to be injected in the test method call: @genty_dataset( ...
entailment
def _build_datasets(*args, **kwargs): """Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets...
Build the datasets into a dict, where the keys are the name of the data set and the values are the data sets themselves. :param args: Tuple of unnamed data sets. :type args: `tuple` of varies :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicod...
entailment
def _add_arg_datasets(datasets, args): """Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies """ for dataset in args: ...
Add data sets of the given args. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param args: Tuple of unnamed data sets. :type args: `tuple` of varies
entailment
def _add_kwarg_datasets(datasets, kwargs): """Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies """ for te...
Add data sets of the given kwargs. :param datasets: The dict where to accumulate data sets. :type datasets: `dict` :param kwargs: Dict of pre-named data sets. :type kwargs: `dict` of `unicode` to varies
entailment
def dedent(s): """Removes the hanging dedent from all the first line of a string.""" head, _, tail = s.partition('\n') dedented_tail = textwrap.dedent(tail) result = "{head}\n{tail}".format( head=head, tail=dedented_tail) return result
Removes the hanging dedent from all the first line of a string.
entailment
def top_level_doc(self): """The top-level documentation string for the program. """ return self._doc_template.format( available_commands='\n '.join(sorted(self._commands)), program=self.program)
The top-level documentation string for the program.
entailment
def command(self, name=None): """A decorator to add subcommands. """ def decorator(f): self.add_command(f, name) return f return decorator
A decorator to add subcommands.
entailment
def add_command(self, handler, name=None): """Add a subcommand `name` which invokes `handler`. """ if name is None: name = docstring_to_subcommand(handler.__doc__) # TODO: Prevent overwriting 'help'? self._commands[name] = handler
Add a subcommand `name` which invokes `handler`.
entailment