text stringlengths 81 112k |
|---|
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}'
... |
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... |
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.
:... |
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... |
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
... |
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... |
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... |
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.
def is_connection_dropped(conn): # Plat... |
Convert a Morsel object into a Cookie containing the one k/v pair.
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... |
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.
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-val... |
feed a character with known length
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 >=... |
return confidence based on existing data
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:
... |
Helper for quickly adding a StreamHandler to the logger. Useful for
debugging.
Returns the handler after adding it.
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.
"""
#... |
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.
def assert_fingerprint(cert, fingerprint):
"""
Checks if given fingerprint matches the supplied... |
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... |
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... |
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... |
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... |
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... |
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 ... |
Return a fresh :class:`httplib.HTTPSConnection`.
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.C... |
Called right before a request is made, after the socket is created.
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 th... |
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
def description_of(lines, name='stdin'):
"""
Return a string descri... |
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
def main(argv=None):
'''
Handles command line arguments and gets things started.
:param ... |
Returns the current size of the terminal as tuple in the form
``(width, height)`` in columns and rows.
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) us... |
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... |
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... |
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`
def merge_setting(request_setting, session_setting, dict_class=OrderedDict):
"""
De... |
Receives a Response. Returns a generator of Responses.
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
... |
Send a given PreparedRequest.
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.s... |
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... |
Prepares the given HTTP method.
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 headers.
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() |
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 ... |
Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
def json(self, **kwargs):
"""Returns the json-encoded content of a response, if any.
:param \*\*kwargs: Optional arguments that ``json.loads`` takes.
"""
i... |
Raises stored :class:`HTTPError`, if one occurred.
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 ... |
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.
def _new_pool(self, scheme, host, port):
... |
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``.
def connection_from_host(self, host, port=None, scheme='http'):
"""
Get a :class:`ConnectionPool` based on... |
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... |
A decorator to register a subcommand with the global `Subcommands` instance.
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 |
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 ... |
Overridden process_response would "pipe" response.body through BeautifulSoup.
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))) |
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`
def genty(target_cls):
"""
This ... |
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 : ... |
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... |
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... |
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... |
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>"
... |
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... |
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 ... |
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.
... |
Close any open window.
Note that this only works with non-blocking methods.
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)
... |
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.
... |
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... |
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.
def error(self, message, rofi_args=Non... |
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... |
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... |
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
... |
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... |
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... |
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... |
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. ... |
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... |
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... |
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... |
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.
def exit_with_error(self, error, **kwargs):
"""Report an error and exit.
This raises a Sys... |
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.
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 st... |
:param value:
Some value in a dataset.
:type value:
varies
:return:
unicode representation of that value
:rtype:
`unicode`
def format_arg(value):
"""
:param value:
Some value in a dataset.
:type value:
varies
:return:
unicode represent... |
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The encoded string
:rtype:
str
def encode_non_ascii_string(string):
"""
:param string:
The string to be encoded
:type string:
unicode or str
:return:
The enc... |
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 ... |
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(
... |
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... |
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
def _add_arg_datasets(datasets, args):
"""Add data sets of the given args.
:p... |
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
def _add_kwarg_datasets(datasets, kwargs):
"""Add data sets of ... |
Removes the hanging dedent from all the first line of a string.
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)
... |
The top-level documentation string for the program.
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) |
A decorator to add subcommands.
def command(self, name=None):
"""A decorator to add subcommands.
"""
def decorator(f):
self.add_command(f, name)
return f
return decorator |
Add a subcommand `name` which invokes `handler`.
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[na... |
Create variations of the word based on letter combinations like oo,
sh, etc.
def variations(word):
"""Create variations of the word based on letter combinations like oo,
sh, etc."""
if len(word) == 1:
return [[word[0]]]
elif word == 'aa':
return [['A']]
elif word == 'ee':
retur... |
Convert a single word from Finglish to Persian.
max_word_size: Maximum size of the words to consider. Words larger
than this will be kept unchanged.
cutoff: The cut-off point. For each word, there could be many
possibilities. By default 3 of these possibilities are considered
for each word. This n... |
Convert a phrase from Finglish to Persian.
phrase: The phrase to convert.
max_word_size: Maximum size of the words to consider. Words larger
than this will be kept unchanged.
cutoff: The cut-off point. For each word, there could be many
possibilities. By default 3 of these possibilities are consi... |
Convert a Finglish phrase to the most probable Persian phrase.
def f2p(phrase, max_word_size=15, cutoff=3):
"""Convert a Finglish phrase to the most probable Persian phrase.
"""
results = f2p_list(phrase, max_word_size, cutoff)
return ' '.join(i[0][0] for i in results) |
try to get the version of the named distribution,
returs None on failure
def distribution_version(name):
"""try to get the version of the named distribution,
returs None on failure"""
from pkg_resources import get_distribution, DistributionNotFound
try:
dist = get_distribution(name)
exc... |
initialize given package from the export definitions.
def initpkg(pkgname, exportdefs, attr=None, eager=False):
""" initialize given package from the export definitions. """
attr = attr or {}
oldmod = sys.modules.get(pkgname)
d = {}
f = getattr(oldmod, '__file__', None)
if f:
f = _py_ab... |
imports a module, then resolves the attrname on it
def importobj(modpath, attrname):
"""imports a module, then resolves the attrname on it"""
module = __import__(modpath, None, None, ['__doc__'])
if not attrname:
return module
retval = module
names = attrname.split(".")
for x in names:... |
lazily compute value for name or raise AttributeError if unknown.
def __makeattr(self, name):
"""lazily compute value for name or raise AttributeError if unknown."""
# print "makeattr", self.__name__, name
target = None
if '__onfirstaccess__' in self.__map__:
target = self._... |
Does actual HTTP request using requests library.
def _request(self, http_method, relative_url='', **kwargs):
"""Does actual HTTP request using requests library."""
# It could be possible to call api.resource.get('/index')
# but it would be non-intuitive that the path would resolve
# to ... |
Create new Url which points to new url.
def _new_url(self, relative_url):
"""Create new Url which points to new url."""
return Url(
urljoin(self._base_url, relative_url),
**self._default_kwargs
) |
gets user groups
def roles(self):
"""gets user groups"""
result = AuthGroup.objects(creator=self.client).only('role')
return json.loads(result.to_json()) |
gets permissions of role
def get_permissions(self, role):
"""gets permissions of role"""
target_role = AuthGroup.objects(role=role, creator=self.client).first()
if not target_role:
return '[]'
targets = AuthPermission.objects(groups=target_role, creator=self.client).only('na... |
get permissions of a user
def get_user_permissions(self, user):
"""get permissions of a user"""
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
tar... |
get permissions of a user
def get_user_roles(self, user):
"""get permissions of a user"""
memberShipRecords = AuthMembership.objects(creator=self.client, user=user).only('groups')
results = []
for each in memberShipRecords:
for group in each.groups:
results.a... |
get permissions of a user
def get_role_members(self, role):
"""get permissions of a user"""
targetRoleDb = AuthGroup.objects(creator=self.client, role=role)
members = AuthMembership.objects(groups__in=targetRoleDb).only('user')
return json.loads(members.to_json()) |
Which role can SendMail?
def which_roles_can(self, name):
"""Which role can SendMail? """
targetPermissionRecords = AuthPermission.objects(creator=self.client, name=name).first()
return [{'role': group.role} for group in targetPermissionRecords.groups] |
Which role can SendMail?
def which_users_can(self, name):
"""Which role can SendMail? """
_roles = self.which_roles_can(name)
result = [self.get_role_members(i.get('role')) for i in _roles]
return result |
Returns a role object
def get_role(self, role):
"""Returns a role object
"""
role = AuthGroup.objects(role=role, creator=self.client).first()
return role |
Creates a new group
def add_role(self, role, description=None):
""" Creates a new group """
new_group = AuthGroup(role=role, creator=self.client)
try:
new_group.save()
return True
except NotUniqueError:
return False |
deletes a group
def del_role(self, role):
""" deletes a group """
target = AuthGroup.objects(role=role, creator=self.client).first()
if target:
target.delete()
return True
else:
return False |
make user a member of a group
def add_membership(self, user, role):
""" make user a member of a group """
targetGroup = AuthGroup.objects(role=role, creator=self.client).first()
if not targetGroup:
return False
target = AuthMembership.objects(user=user, creator=self.client)... |
dismember user from a group
def del_membership(self, user, role):
""" dismember user from a group """
if not self.has_membership(user, role):
return True
targetRecord = AuthMembership.objects(creator=self.client, user=user).first()
if not targetRecord:
return Tr... |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.