docstring stringlengths 52 499 | function stringlengths 67 35.2k | __index_level_0__ int64 52.6k 1.16M |
|---|---|---|
Move source file to destination.
Overwrites dest.
Args:
src: str or path-like. source file
dest: str or path-like. destination file
Returns:
None.
Raises:
FileNotFoundError: out path parent doesn't exist.
OSError: if any IO operations go wrong. | def move_file(src, dest):
try:
os.replace(src, dest)
except Exception as ex_replace:
logger.error(f"error moving file {src} to "
f"{dest}. {ex_replace}")
raise | 579,815 |
Move src to dest. Delete src if something goes wrong.
Overwrites dest.
Args:
src: str or path-like. source file
dest: str or path-like. destination file
Returns:
None.
Raises:
FileNotFoundError: out path parent doesn't exist.
OSError: if any IO operations go w... | def move_temp_file(src, dest):
try:
move_file(src, dest)
except Exception:
try:
os.remove(src)
except Exception as ex_clean:
# at this point, something's deeply wrong, so log error.
# raising the original error, though, not this error in the
... | 579,816 |
Initialize formatter and object representer.
Args:
formatter: Callable object/function that will format object loaded
from in file. Formatter signature:
iterable = formatter(iterable)
object_representer: An ObjectRepresenter instance. | def __init__(self, formatter, object_representer):
super().__init__(formatter)
self.object_representer = object_representer
logger.debug('obj loader set') | 579,818 |
Dump json oject to open file output.
Writes json with 2 spaces indentation.
Args:
file: Open file-like object. Must be open for writing.
payload: The Json object to write to file.
Returns:
None. | def dump(self, file, payload):
json.dump(payload, file, indent=2, ensure_ascii=False) | 579,821 |
Prepare context for pipeline run.
Args:
pipeline: dict. Dictionary representing the pipeline.
context_in_string: string. Argument string used to initialize context.
context: pypyr.context.Context. Merge any new context generated from
context_in_string into this context inst... | def prepare_context(pipeline, context_in_string, context):
logger.debug("starting")
parsed_context = get_parsed_context(
pipeline=pipeline,
context_in_string=context_in_string)
context.update(parsed_context)
logger.debug("done") | 579,829 |
Simple echo. Outputs context['echoMe'].
Args:
context: dictionary-like. context is mandatory.
context must contain key 'echoMe'
context['echoMe'] will echo the value to logger.
This logger could well be stdout.
When you execute the pipeline, it should... | def run_step(context):
logger.debug("started")
assert context, ("context must be set for echo. Did you set "
"'echoMe=text here'?")
context.assert_key_exists('echoMe', __name__)
if isinstance(context['echoMe'], str):
val = context.get_formatted('echoMe')
else:
... | 579,834 |
Return canonical error name as string.
For builtin errors like ValueError or Exception, will return the bare
name, like ValueError or Exception.
For all other exceptions, will return modulename.errorname, such as
arbpackage.mod.myerror
Args:
error: Exception object.
Returns:
... | def get_error_name(error):
error_type = type(error)
if error_type.__module__ in ['__main__', 'builtins']:
return error_type.__name__
else:
return f'{error_type.__module__}.{error_type.__name__}' | 579,835 |
Use importlib to get the module dynamically.
Get instance of the module specified by the module_abs_import.
This means that module_abs_import must be resolvable from this package.
Args:
module_abs_import: string. Absolute name of module to import.
Raises:
PyModuleNotFoundError: if mod... | def get_module(module_abs_import):
logger.debug("starting")
logger.debug(f"loading module {module_abs_import}")
try:
imported_module = importlib.import_module(module_abs_import)
logger.debug("done")
return imported_module
except ModuleNotFoundError as err:
msg = ("Th... | 579,836 |
Add working_directory to sys.paths.
This allows dynamic loading of arbitrary python modules in cwd.
Args:
working_directory: string. path to add to sys.paths | def set_working_directory(working_directory):
logger.debug("starting")
logger.debug(f"adding {working_directory} to sys.paths")
sys.path.append(working_directory)
logger.debug("done") | 579,837 |
Assert that context contains key that has child which has a value.
Args:
parent: parent key
child: validate this sub-key of parent exists AND isn't None.
caller: string. calling function name - this used to construct
error messages
Raises:
... | def assert_child_key_has_value(self, parent, child, caller):
assert parent, ("parent parameter must be specified.")
assert child, ("child parameter must be specified.")
self.assert_key_has_value(parent, caller)
try:
child_exists = child in self[parent]
excep... | 579,838 |
Assert that context contains key which also has a value.
Args:
key: validate this key exists in context AND has a value that isn't
None.
caller: string. calling function name - this used to construct
error messages
Raises:
KeyNot... | def assert_key_has_value(self, key, caller):
assert key, ("key parameter must be specified.")
self.assert_key_exists(key, caller)
if self[key] is None:
raise KeyInContextHasNoValueError(
f"context['{key}'] must have a value for {caller}.") | 579,839 |
Assert that context contains keys.
Args:
keys: validates that these keys exists in context
caller: string. calling function or module name - this used to
construct error messages
Raises:
KeyNotInContextError: When key doesn't exist in context. | def assert_keys_exist(self, caller, *keys):
assert keys, ("*keys parameter must be specified.")
for key in keys:
self.assert_key_exists(key, caller) | 579,841 |
Check that keys list are all in context and all have values.
Args:
*keys: Will check each of these keys in context
caller: string. Calling function name - just used for informational
messages
Raises:
KeyNotInContextError: Key doesn't exist
... | def assert_keys_have_values(self, caller, *keys):
for key in keys:
self.assert_key_has_value(key, caller) | 579,842 |
Return formatted value for input value, returns as out_type.
Caveat emptor: if out_type is bool and value a string,
return will be True if str is 'True'. It will be False for all other
cases.
Args:
value: the value to format
default: if value is None, set to thi... | def get_formatted_as_type(self, value, default=None, out_type=str):
if value is None:
value = default
if isinstance(value, SpecialTagDirective):
result = value.get_value(self)
return types.cast_to_type(result, out_type)
if isinstance(value, str):
... | 579,847 |
Do the file in to out rewrite.
Doesn't do anything more crazy than call files_in_to_out on the
rewriter.
Args:
rewriter: pypyr.filesystem.FileRewriter instance. | def run_step(self, rewriter):
assert rewriter, ("FileRewriter instance required to run "
"FileInRewriterStep.")
rewriter.files_in_to_out(in_path=self.path_in, out_path=self.path_out) | 579,853 |
Do the object in-out rewrite.
Args:
representer: A pypyr.filesystem.ObjectRepresenter instance. | def run_step(self, representer):
assert representer, ("ObjectRepresenter instance required to run "
"ObjectRewriterStep.")
rewriter = ObjectRewriter(self.context.get_formatted_iterable,
representer)
super().run_step(rewriter... | 579,854 |
Create a function that uses replacement pairs to process a string.
The returned function takes an iterator and yields on each processed
line.
Args:
replacements: Dict containing 'find_string': 'replace_string' pairs
Returns:
function with signature: iterator of... | def iter_replace_strings(replacements):
def function_iter_replace_strings(iterable_strings):
for string in iterable_strings:
yield reduce((lambda s, kv: s.replace(*kv)),
replacements.items(),
string)
... | 579,858 |
Cast obj to out_type if it's not out_type already.
If the obj happens to be out_type already, it just returns obj as is.
Args:
obj: input object
out_type: type.
Returns:
obj cast to out_type. Usual python conversion / casting rules apply. | def cast_to_type(obj, out_type):
in_type = type(obj)
if out_type is in_type:
# no need to cast.
return obj
else:
return out_type(obj) | 579,860 |
Return pipeline yaml from open file object.
Use specific custom representers to model the custom pypyr pipeline yaml
format, to load in special literal types like py and sic strings.
If looking to extend the pypyr pipeline syntax with special types, add
these to the tag_representers list.
Args:
... | def get_pipeline_yaml(file):
tag_representers = [PyString, SicString]
yaml_loader = get_yaml_parser_safe()
for representer in tag_representers:
yaml_loader.register_class(representer)
pipeline_definition = yaml_loader.load(file)
return pipeline_definition | 579,861 |
Convert frame-based duration to milliseconds.
Arguments:
frames: Number of frames (should be int).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of milliseconds (rounded to int).
Raises:
ValueError: fps was negative or zero. | def frames_to_ms(frames, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round(frames * (1000 / fps))) | 580,049 |
Convert milliseconds to number of frames.
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
fps: Framerate (must be a positive number, eg. 23.976).
Returns:
Number of frames (int).
Raises:
ValueError: fps was negative or zero... | def ms_to_frames(ms, fps):
if fps <= 0:
raise ValueError("Framerate must be positive number (%f)." % fps)
return int(round((ms / 1000) * fps)) | 580,050 |
Convert milliseconds to normalized tuple (h, m, s, ms).
Arguments:
ms: Number of milliseconds (may be int, float or other numeric class).
Should be non-negative.
Returns:
Named tuple (h, m, s, ms) of ints.
Invariants: ``ms in range(1000) and s in range(60) and m in ... | def ms_to_times(ms):
ms = int(round(ms))
h, ms = divmod(ms, 3600000)
m, ms = divmod(ms, 60000)
s, ms = divmod(ms, 1000)
return Times(h, m, s, ms) | 580,051 |
Prettyprint milliseconds to [-]H:MM:SS[.mmm]
Handles huge and/or negative times. Non-negative times with ``fractions=True``
are matched by :data:`pysubs2.time.TIMESTAMP`.
Arguments:
ms: Number of milliseconds (int, float or other numeric class).
fractions: Whether to print up to mi... | def ms_to_str(ms, fractions=False):
sgn = "-" if ms < 0 else ""
h, m, s, ms = ms_to_times(abs(ms))
if fractions:
return sgn + "{:01d}:{:02d}:{:02d}.{:03d}".format(h, m, s, ms)
else:
return sgn + "{:01d}:{:02d}:{:02d}".format(h, m, s) | 580,052 |
Load subtitle file from string.
See :meth:`SSAFile.load()` for full description.
Arguments:
string (str): Subtitle file in a string. Note that the string
must be Unicode (in Python 2).
Returns:
SSAFile
Example:
>>> text = '''
... | def from_string(cls, string, format_=None, fps=None, **kwargs):
fp = io.StringIO(string)
return cls.from_file(fp, format_, fps=fps, **kwargs) | 580,081 |
Read subtitle file from file object.
See :meth:`SSAFile.load()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.load()`
or :meth:`SSAFile.from_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :c... | def from_file(cls, fp, format_=None, fps=None, **kwargs):
if format_ is None:
# Autodetect subtitle format, then read again using correct parser.
# The file might be a pipe and we need to read it twice,
# so just buffer everything.
text = fp.read()
... | 580,082 |
Write subtitle file to file object.
See :meth:`SSAFile.save()` for full description.
Note:
This is a low-level method. Usually, one of :meth:`SSAFile.save()`
or :meth:`SSAFile.to_string()` is preferable.
Arguments:
fp (file object): A file object, ie. :clas... | def to_file(self, fp, format_, fps=None, **kwargs):
impl = get_format_class(format_)
impl.to_file(self, fp, format_, fps=fps, **kwargs) | 580,085 |
Rescale all timestamps by ratio of in_fps/out_fps.
Can be used to fix files converted from frame-based to time-based
with wrongly assumed framerate.
Arguments:
in_fps (float)
out_fps (float)
Raises:
ValueError: Non-positive framerate given. | def transform_framerate(self, in_fps, out_fps):
if in_fps <= 0 or out_fps <= 0:
raise ValueError("Framerates must be positive, cannot transform %f -> %f" % (in_fps, out_fps))
ratio = in_fps / out_fps
for line in self:
line.start = int(round(line.start * ratio))
... | 580,086 |
Rename a style, including references to it.
Arguments:
old_name (str): Style to be renamed.
new_name (str): New name for the style (must be unused).
Raises:
KeyError: No style named old_name.
ValueError: new_name is not a legal name (cannot use commas)
... | def rename_style(self, old_name, new_name):
if old_name not in self.styles:
raise KeyError("Style %r not found" % old_name)
if new_name in self.styles:
raise ValueError("There is already a style called %r" % new_name)
if not is_valid_field_content(new_name):
... | 580,087 |
Merge in styles from other SSAFile.
Arguments:
subs (SSAFile): Subtitle file imported from.
overwrite (bool): On name conflict, use style from the other file
(default: True). | def import_styles(self, subs, overwrite=True):
if not isinstance(subs, SSAFile):
raise TypeError("Must supply an SSAFile.")
for name, style in subs.styles.items():
if name not in self.styles or overwrite:
self.styles[name] = style | 580,088 |
Send HTTP request and parse it as a DOM tree.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | def fetch(url: str, **kwargs) -> Selector:
kwargs.setdefault('headers', DEFAULT_HEADERS)
try:
res = requests.get(url, **kwargs)
res.raise_for_status()
except requests.RequestException as e:
print(e)
else:
html = res.text
tree = Selector(text=html)
ret... | 580,360 |
Do the fetch in an async style.
Args:
url (str): The url of the site.
Returns:
Selector: allows you to select parts of HTML text using CSS or XPath expressions. | async def async_fetch(url: str, **kwargs) -> Selector:
kwargs.setdefault('headers', DEFAULT_HEADERS)
async with aiohttp.ClientSession(**kwargs) as ses:
async with ses.get(url, **kwargs) as res:
html = await res.text()
tree = Selector(text=html)
return tree | 580,361 |
View the page whether rendered properly. (ensure the <base> tag to make external links work)
Args:
url (str): The url of the site. | def view(url: str, **kwargs) -> bool:
kwargs.setdefault('headers', DEFAULT_HEADERS)
html = requests.get(url, **kwargs).content
if b'<base' not in html:
repl = f'<head><base href="{url}">'
html = html.replace(b'<head>', repl.encode('utf-8'))
fd, fname = tempfile.mkstemp('.html')
... | 580,362 |
Get the links of the page.
Args:
res (requests.models.Response): The response of the page.
search (str, optional): Defaults to None. Search the links you want.
pattern (str, optional): Defaults to None. Search the links use a regex pattern.
Returns:
list: All the links of the p... | def links(res: requests.models.Response,
search: str = None,
pattern: str = None) -> list:
hrefs = [link.to_text() for link in find_all_links(res.text)]
if search:
hrefs = [href for href in hrefs if search in href]
if pattern:
hrefs = [href for href in hrefs if re.fi... | 580,363 |
Save what you crawled as a json file.
Args:
total (list): Total of data you crawled.
name (str, optional): Defaults to 'data.json'. The name of the file.
sort_by (str, optional): Defaults to None. Sort items by a specific key.
no_duplicate (bool, optional): Defaults to False. If Tru... | def save_as_json(total: list,
name='data.json',
sort_by: str = None,
no_duplicate=False,
order='asc'):
if sort_by:
reverse = order == 'desc'
total = sorted(total, key=itemgetter(sort_by), reverse=reverse)
if no_duplicate:
... | 580,364 |
Creates a client for the Amazon SES API.
Args:
fail_silently: Flag that determines whether Amazon SES
client errors should throw an exception. | def __init__(self, fail_silently=False, aws_access_key_id=None,
aws_secret_access_key=None, **kwargs):
super(EmailBackend, self).__init__(fail_silently=fail_silently)
# Get configuration from AWS prefixed settings in settings.py
access_key_id = getattr(settings, 'AWS_A... | 580,809 |
Sends one or more EmailMessage objects and returns the
number of email messages sent.
Args:
email_messages: A list of Django EmailMessage objects.
Returns:
An integer count of the messages sent.
Raises:
ClientError: An interaction with the Amazon SES ... | def send_messages(self, email_messages):
if not email_messages:
return
sent_message_count = 0
for email_message in email_messages:
if self._send(email_message):
sent_message_count += 1
return sent_message_count | 580,810 |
Sends an individual message via the Amazon SES HTTP API.
Args:
email_message: A single Django EmailMessage object.
Returns:
True if the EmailMessage was sent successfully, otherwise False.
Raises:
ClientError: An interaction with the Amazon SES HTTP API
... | def _send(self, email_message):
pre_send.send(self.__class__, message=email_message)
if not email_message.recipients():
return False
from_email = sanitize_address(email_message.from_email,
email_message.encoding)
recipients = [... | 580,811 |
Returns a numpy array (snapshot representation) from thedataframe contact list
Parameters:
df : pandas df
pandas df with columns, i,j,t.
netshape : tuple
network shape, format: (node, time)
nettype : str
'wu', 'wd', 'bu', 'bd'
Returns:
--------
... | def df_to_array(df, netshape, nettype):
if len(df) > 0:
idx = np.array(list(map(list, df.values)))
G = np.zeros([netshape[0], netshape[0], netshape[1]])
if idx.shape[1] == 3:
if nettype[-1] == 'u':
idx = np.vstack([idx, idx[:, [1, 0, 2]]])
idx = i... | 581,175 |
Loads the Duckling corpus.
Languages can be specified, defaults to all.
Args:
languages: Optional parameter to specify languages,
e.g. [Duckling.ENGLISH, Duckling.FRENCH] or supported ISO 639-1 Codes (e.g. ["en", "fr"]) | def load(self, languages=[]):
duckling_load = self.clojure.var("duckling.core", "load!")
clojure_hashmap = self.clojure.var("clojure.core", "hash-map")
clojure_list = self.clojure.var("clojure.core", "list")
if languages:
# Duckling's load function expects ISO 639-1... | 581,633 |
Shortcut function for ``unittest.TestCase.assertEqual()``.
Arguments:
x (mixed)
y (mixed)
Raises:
AssertionError: in case of assertion error.
Returns:
bool | def equal(x, y):
if PY_3:
return test_case().assertEqual(x, y) or True
assert x == y | 582,995 |
Tries to match a regular expression value ``x`` against ``y``.
Aliast``unittest.TestCase.assertEqual()``
Arguments:
x (regex|str): regular expression to test.
y (str): value to match.
regex_expr (bool): enables regex string based expression matching.
Raises:
AssertionError:... | def matches(x, y, regex_expr=False):
# Parse regex expression, if needed
x = strip_regex(x) if regex_expr and isregex_expr(x) else x
# Run regex assertion
if PY_3:
# Retrieve original regex pattern
x = x.pattern if isregex(x) else x
# Assert regular expression via unittest ... | 582,996 |
Compares to values based on regular expression matching or
strict equality comparison.
Arguments:
x (regex|str): string or regular expression to test.
y (str): value to match.
regex_expr (bool): enables regex string based expression matching.
Raises:
AssertionError: in case... | def test(x, y, regex_expr=False):
return matches(x, y, regex_expr=regex_expr) if isregex(x) else equal(x, y) | 582,997 |
Returns ``True`` is the given expression value is a regular expression
like string with prefix ``re/`` and suffix ``/``, otherwise ``False``.
Arguments:
expr (mixed): expression value to test.
Returns:
bool | def isregex_expr(expr):
if not isinstance(expr, str):
return False
return all([
len(expr) > 3,
expr.startswith('re/'),
expr.endswith('/')
]) | 583,001 |
Returns ``True`` if the input argument object is a native
regular expression object, otherwise ``False``.
Arguments:
value (mixed): input value to test.
Returns:
bool | def isregex(value):
if not value:
return False
return any((isregex_expr(value), isinstance(value, retype))) | 583,002 |
Compares two values with regular expression matching support.
Arguments:
value (mixed): value to compare.
expectation (mixed): value to match.
regex_expr (bool, optional): enables string based regex matching.
Returns:
bool | def compare(self, value, expectation, regex_expr=False):
return compare(value, expectation, regex_expr=regex_expr) | 583,004 |
Simple function decorator allowing easy method chaining.
Arguments:
fn (function): target function to decorate. | def fluent(fn):
@functools.wraps(fn)
def wrapper(self, *args, **kw):
# Trigger method proxy
result = fn(self, *args, **kw)
# Return self instance or method result
return self if result is None else result
return wrapper | 583,006 |
Compares an string or regular expression againast a given value.
Arguments:
expr (str|regex): string or regular expression value to compare.
value (str): value to compare against to.
regex_expr (bool, optional): enables string based regex matching.
Raises:
AssertionError: in ca... | def compare(expr, value, regex_expr=False):
# Strict equality comparison
if expr == value:
return True
# Infer negate expression to match, if needed
negate = False
if isinstance(expr, str):
negate = expr.startswith(NEGATE)
expr = strip_negate(expr) if negate else expr
... | 583,008 |
Triggers specific class methods using a simple reflection
mechanism based on the given input dictionary params.
Arguments:
instance (object): target instance to dynamically trigger methods.
args (iterable): input arguments to trigger objects to
Returns:
None | def trigger_methods(instance, args):
# Start the magic
for name in sorted(args):
value = args[name]
target = instance
# If response attibutes
if name.startswith('response_') or name.startswith('reply_'):
name = name.replace('response_', '').replace('reply_', '')... | 583,011 |
Match the given HTTP request instance against the registered
matcher functions in the current engine.
Arguments:
request (pook.Request): outgoing request to match.
Returns:
tuple(bool, list[Exception]): ``True`` if all matcher tests
passes, otherwise ``F... | def match(self, request):
errors = []
def match(matcher):
try:
return matcher.match(request)
except Exception as err:
err = '{}: {}'.format(type(matcher).__name__, err)
errors.append(err)
return False
... | 583,023 |
Returns a matcher instance by class or alias name.
Arguments:
name (str): matcher class name or alias.
Returns:
matcher: found matcher instance, otherwise ``None``. | def get(name):
for matcher in matchers:
if matcher.__name__ == name or getattr(matcher, 'name', None) == name:
return matcher | 583,035 |
Initializes a matcher instance passing variadic arguments to
its constructor. Acts as a delegator proxy.
Arguments:
name (str): matcher class name or alias to execute.
*args (mixed): variadic argument
Returns:
matcher: matcher instance.
Raises:
ValueError: if matcher w... | def init(name, *args):
matcher = get(name)
if not matcher:
raise ValueError('Cannot find matcher: {}'.format(name))
return matcher(*args) | 583,036 |
Defines a new response header.
Alias to ``Response.header()``.
Arguments:
header (str): header name.
value (str): header value.
Returns:
self: ``pook.Response`` current instance. | def header(self, key, value):
if type(key) is tuple:
key, value = str(key[0]), key[1]
headers = {key: value}
self._headers.extend(headers) | 583,038 |
Defines response body data.
Arguments:
body (str|bytes): response body to use.
Returns:
self: ``pook.Response`` current instance. | def body(self, body):
if isinstance(body, bytes):
body = body.decode('utf-8')
self._body = body | 583,039 |
Defines the mock response JSON body.
Arguments:
data (dict|list|str): JSON body data.
Returns:
self: ``pook.Response`` current instance. | def json(self, data):
self._headers['Content-Type'] = 'application/json'
if not isinstance(data, str):
data = json.dumps(data, indent=4)
self._body = data | 583,040 |
Helper function to append functions into a given list.
Arguments:
target (list): receptor list to append functions.
items (iterable): iterable that yields elements to append. | def _append_funcs(target, items):
[target.append(item) for item in items
if isfunction(item) or ismethod(item)] | 583,045 |
Defines the mock URL to match.
It can be a full URL with path and query params.
Protocol schema is optional, defaults to ``http://``.
Arguments:
url (str): mock URL to match. E.g: ``server.com/api``.
Returns:
self: current Mock instance. | def url(self, url):
self._request.url = url
self.add_matcher(matcher('URLMatcher', url)) | 583,048 |
Defines the HTTP method to match.
Use ``*`` to match any method.
Arguments:
method (str): method value to match. E.g: ``GET``.
Returns:
self: current Mock instance. | def method(self, method):
self._request.method = method
self.add_matcher(matcher('MethodMatcher', method)) | 583,049 |
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance. | def path(self, path):
url = furl(self._request.rawurl)
url.path = path
self._request.url = url.url
self.add_matcher(matcher('PathMatcher', path)) | 583,050 |
Defines a URL path to match.
Only call this method if the URL has no path already defined.
Arguments:
path (str): URL path value to match. E.g: ``/api/users``.
Returns:
self: current Mock instance. | def header(self, name, value):
headers = {name: value}
self._request.headers = headers
self.add_matcher(matcher('HeadersMatcher', headers)) | 583,051 |
Defines a dictionary of arguments.
Header keys are case insensitive.
Arguments:
headers (dict): headers to match.
**headers (dict): headers to match as variadic keyword arguments.
Returns:
self: current Mock instance. | def headers(self, headers=None, **kw):
headers = kw if kw else headers
self._request.headers = headers
self.add_matcher(matcher('HeadersMatcher', headers)) | 583,052 |
Defines a new header matcher expectation that must be present in the
outgoing request in order to be satisfied, no matter what value it
hosts.
Header keys are case insensitive.
Arguments:
*names (str): header or headers names to match.
Returns:
self: cu... | def header_present(self, *names):
for name in names:
headers = {name: re.compile('(.*)')}
self.add_matcher(matcher('HeadersMatcher', headers)) | 583,053 |
Defines a list of headers that must be present in the
outgoing request in order to satisfy the matcher, no matter what value
the headers hosts.
Header keys are case insensitive.
Arguments:
headers (list|tuple): header keys to match.
Returns:
self: curre... | def headers_present(self, headers):
headers = {name: re.compile('(.*)') for name in headers}
self.add_matcher(matcher('HeadersMatcher', headers)) | 583,054 |
Defines a set of URL query params to match.
Arguments:
params (dict): set of params to match.
Returns:
self: current Mock instance. | def params(self, params):
url = furl(self._request.rawurl)
url = url.add(params)
self._request.url = url.url
self.add_matcher(matcher('QueryMatcher', params)) | 583,056 |
Defines the body data to match.
``body`` argument can be a ``str``, ``binary`` or a regular expression.
Arguments:
body (str|binary|regex): body data to match.
Returns:
self: current Mock instance. | def body(self, body):
self._request.body = body
self.add_matcher(matcher('BodyMatcher', body)) | 583,057 |
Defines the JSON body to match.
``json`` argument can be an JSON string, a JSON serializable
Python structure, such as a ``dict`` or ``list`` or it can be
a regular expression used to match the body.
Arguments:
json (str|dict|list|regex): body JSON to match.
Return... | def json(self, json):
self._request.json = json
self.add_matcher(matcher('JSONMatcher', json)) | 583,058 |
Defines a XML body value to match.
Arguments:
xml (str|regex): body XML to match.
Returns:
self: current Mock instance. | def xml(self, xml):
self._request.xml = xml
self.add_matcher(matcher('XMLMatcher', xml)) | 583,059 |
Reads the body to match from a disk file.
Arguments:
path (str): relative or absolute path to file to read from.
Returns:
self: current Mock instance. | def file(self, path):
with open(path, 'r') as f:
self.body(str(f.read())) | 583,060 |
Defines a simulated exception error that will be raised.
Arguments:
error (str|Exception): error to raise.
Returns:
self: current Mock instance. | def error(self, error):
self._error = RuntimeError(error) if isinstance(error, str) else error | 583,062 |
Defines the mock response.
Arguments:
status (int, optional): response status code. Defaults to ``200``.
**kw (dict): optional keyword arguments passed to ``pook.Response``
constructor.
Returns:
pook.Response: mock response definition instance. | def reply(self, status=200, new_response=False, **kw):
# Use or create a Response mock instance
res = Response(**kw) if new_response else self._response
# Define HTTP mandatory response status
res.status(status or res._status)
# Expose current mock instance in response f... | 583,063 |
Overload Mock instance as callable object in order to be used
as decorator definition syntax.
Arguments:
fn (function): function to decorate.
Returns:
function or pook.Mock | def __call__(self, fn):
# Support chain sequences of mock definitions
if isinstance(fn, Response):
return fn.mock
if isinstance(fn, Mock):
return fn
# Force type assertion and raise an error if it is not a function
if not isfunction(fn) and not i... | 583,065 |
Async version of activate decorator
Arguments:
fn (function): function that be wrapped by decorator.
_engine (Engine): pook engine instance
Returns:
function: decorator wrapper function. | def activate_async(fn, _engine):
@coroutine
@functools.wraps(fn)
def wrapper(*args, **kw):
_engine.activate()
try:
if iscoroutinefunction(fn):
yield from fn(*args, **kw) # noqa
else:
fn(*args, **kw)
finally:
_e... | 583,069 |
Sets a custom mock engine, replacing the built-in one.
This is particularly useful if you want to replace the built-in
HTTP traffic mock interceptor engine with your custom one.
For mock engine implementation details, see `pook.MockEngine`.
Arguments:
engine (pook.MockEngi... | def set_mock_engine(self, engine):
if not engine:
raise TypeError('engine must be a valid object')
# Instantiate mock engine
mock_engine = engine(self)
# Validate minimum viable interface
methods = ('activate', 'disable')
if not all([hasattr(mock_en... | 583,071 |
Enables real networking mode, optionally passing one or multiple
hostnames that would be used as filter.
If at least one hostname matches with the outgoing traffic, the
request will be executed via the real network.
Arguments:
*hostnames: optional list of host names to enab... | def enable_network(self, *hostnames):
def hostname_filter(hostname, req):
if isregex(hostname):
return hostname.match(req.url.hostname)
return req.url.hostname == hostname
for hostname in hostnames:
self.use_network_filter(partial(hostname_fi... | 583,072 |
Creates and registers a new HTTP mock in the current engine.
Arguments:
url (str): request URL to mock.
activate (bool): force mock engine activation.
Defaults to ``False``.
**kw (mixed): variadic keyword arguments for ``Mock`` constructor.
Returns:
... | def mock(self, url=None, **kw):
# Activate mock engine, if explicitly requested
if kw.get('activate'):
kw.pop('activate')
self.activate()
# Create the new HTTP mock expectation
mock = Mock(url=url, **kw)
# Expose current engine instance via mock
... | 583,073 |
Removes a specific mock instance by object reference.
Arguments:
mock (pook.Mock): mock instance to remove. | def remove_mock(self, mock):
self.mocks = [m for m in self.mocks if m is not mock] | 583,074 |
Verifies if real networking mode should be used for the given
request, passing it to the registered network filters.
Arguments:
request (pook.Request): outgoing HTTP request to test.
Returns:
bool | def should_use_network(self, request):
return (self.networking and
all((fn(request) for fn in self.network_filters))) | 583,079 |
Matches a given Request instance contract against the registered mocks.
If a mock passes all the matchers, its response will be returned.
Arguments:
request (pook.Request): Request contract to match.
Raises:
pook.PookNoMatches: if networking is disabled and no mock mat... | def match(self, request):
# Trigger engine-level request filters
for test in self.filters:
if not test(request, self):
return False
# Trigger engine-level request mappers
for mapper in self.mappers:
request = mapper(request, self)
... | 583,080 |
Adds one or multiple HTTP traffic interceptors to the current
mocking engine.
Interceptors are typically HTTP client specific wrapper classes that
implements the pook interceptor interface.
Arguments:
interceptors (pook.interceptors.BaseInterceptor) | def add_interceptor(self, *interceptors):
for interceptor in interceptors:
self.interceptors.append(interceptor(self.engine)) | 583,099 |
Removes a specific interceptor by name.
Arguments:
name (str): interceptor name to disable.
Returns:
bool: `True` if the interceptor was disabled, otherwise `False`. | def remove_interceptor(self, name):
for index, interceptor in enumerate(self.interceptors):
matches = (
type(interceptor).__name__ == name or
getattr(interceptor, 'name') == name
)
if matches:
self.interceptors.pop(inde... | 583,100 |
Check if full usage Id included in input reports set
Parameters:
full_usage_id Full target usage, use get_full_usage_id
Returns:
Report ID as integer value, or None if report does not exist with
target usage. Nottice that report ID 0 is a valid report. | def find_input_usage(self, full_usage_id):
for report_id, report_obj in self.__input_report_templates.items():
if full_usage_id in report_obj:
return report_id
return None | 584,727 |
Returns Hardware device path
Parameters:
h_info, interface set info handler
interface_data, device interface enumeration data
ptr_info_data, pointer to SP_DEVINFO_DATA() instance to receive details | def get_device_path(h_info, interface_data, ptr_info_data = None):
required_size = c_ulong(0)
dev_inter_detail_data = SP_DEVICE_INTERFACE_DETAIL_DATA()
dev_inter_detail_data.cb_size = sizeof(SP_DEVICE_INTERFACE_DETAIL_DATA)
# get actual storage requirement
SetupDiGetDeviceInte... | 584,783 |
Calculates the minor loss coefficient of an orifice plate in a
pipe.
Parameters:
pipe_id: Entrance pipe's inner diameter from which fluid flows.
orifice_id: Orifice's inner diameter.
orifice_l: Orifice's length from start to end.
q: Fluid's q rate.
nu: Fluid's dynamic v... | def k_value_orifice(pipe_id, orifice_id, orifice_l, q,
nu=con.WATER_NU):
if orifice_id > pipe_id:
raise ValueError('The orifice\'s inner diameter cannot be larger than'
'that of the entrance pipe.')
re = pc.re_pipe(q, pipe_id, nu) # Entrance pipe's Re... | 584,971 |
Returns the minor loss coefficient for a square reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
re: Reynold's number.
f: Darcy friction factor. | def _k_value_square_reduction(ent_pipe_id, exit_pipe_id, re, f):
if re < 2500:
return (1.2 + (160 / re)) * ((ent_pipe_id / exit_pipe_id) ** 4)
else:
return (0.6 + 0.48 * f) * (ent_pipe_id / exit_pipe_id) ** 2\
* ((ent_pipe_id / exit_pipe_id) ** 2 - 1) | 584,972 |
Returns the minor loss coefficient for a tapered reducer.
Parameters:
ent_pipe_id: Entrance pipe's inner diameter.
exit_pipe_id: Exit pipe's inner diameter.
fitting_angle: Fitting angle between entrance and exit pipes.
re: Reynold's number.
f: Darcy friction factor. | def _k_value_tapered_reduction(ent_pipe_id, exit_pipe_id, fitting_angle, re, f):
k_value_square_reduction = _k_value_square_reduction(ent_pipe_id, exit_pipe_id,
re, f)
if 45 < fitting_angle <= 180:
return k_value_square_reduction * np.sqrt(... | 584,973 |
Set the number of significant figures used to print Pint, Pandas, and
NumPy quantities.
Args:
n (int): Number of significant figures to display. | def set_sig_figs(n=4):
u.default_format = '.' + str(n) + 'g'
pd.options.display.float_format = ('{:,.' + str(n) + '}').format | 585,000 |
Interactive helper function to generate a new anonymous username.
Args:
ip: ip address of the bridge
devicetype (optional): devicetype to register with the bridge. If
unprovided, generates a device type based on the local hostname.
timeout (optional, default=5): request timeout ... | def create_new_username(ip, devicetype=None, timeout=_DEFAULT_TIMEOUT):
res = Resource(_api_url(ip), timeout)
prompt = "Press the Bridge button, then press Return: "
# Deal with one of the sillier python3 changes
if sys.version_info.major == 2:
_ = raw_input(prompt)
else:
_ = in... | 585,605 |
Create connection, use to send message and close.
Args:
transport (asyncio.DatagramTransport): Transport used for sending. | def connection_made(self, transport):
self.transport = transport
self.transport.sendto(self.message)
self.transport.close() | 585,655 |
Transform metric to JSON bytestring and send to server.
Args:
metric (dict): Complete metric to send as JSON. | async def send(self, metric):
message = json.dumps(metric).encode('utf-8')
await self.loop.create_datagram_endpoint(
lambda: UDPClientProtocol(message),
remote_addr=(self.ip, self.port)) | 585,657 |
Setup RecordChecker object.
Args:
dns_ip: DNS server IP to query. | def __init__(self, dns_ip):
self._dns_ip = dns_ip
self._resolver = ProxyResolver()
try:
self._resolver.set_proxies([self._dns_ip])
except async_dns.address.InvalidHost as e:
msg = f'RecordChecker got invalid DNS server IP: {e}.'
raise exceptio... | 585,658 |
Measures the time for a DNS record to become available.
Query a provided DNS server multiple times until the reply matches the
information in the record or until timeout is reached.
Args:
record (dict): DNS record as a dict with record properties.
timeout (int): Time th... | async def check_record(self, record, timeout=60):
start_time = time.time()
name, rr_data, r_type, ttl = self._extract_record_data(record)
r_type_code = async_dns.types.get_code(r_type)
resolvable_record = False
retries = 0
sleep_time = 5
while not reso... | 585,659 |
Check if resolver answer is equal to record data.
Args:
dns_answer_list (list): DNS answer list contains record objects.
record_name (str): Record name.
record_data_list (list): List of data values for the record.
record_ttl (int): Record time-to-live info.
... | async def _check_resolver_ans(
self, dns_answer_list, record_name,
record_data_list, record_ttl, record_type_code):
type_filtered_list = [
ans for ans in dns_answer_list if ans.qtype == record_type_code
]
# check to see that type_filtered_lst has
... | 585,660 |
Format and output metric.
Args:
metric (dict): Complete metric. | def log(self, metric):
message = self.LOGFMT.format(**metric)
if metric['context']:
message += ' context: {context}'.format(context=metric['context'])
self._logger.log(self.level, message) | 585,664 |
Generates e_j _vector in tt.vector format
---------
Parameters:
n - modes (either integer or array)
d - dimensionality (integer)
j - position of 1 in full-format e_j (integer)
tt_instance - if True, returns tt.vector;
if False, returns tt cores as a list | def unit(n, d=None, j=None, tt_instance=True):
if isinstance(n, int):
if d is None:
d = 1
n = n * _np.ones(d, dtype=_np.int32)
else:
d = len(n)
if j is None:
j = 0
rv = []
j = _ind2sub(n, j)
for k in xrange(d):
rv.append(_np.zeros((1, n[... | 585,744 |
Translates full-format index into tt.vector one's.
----------
Parameters:
siz - tt.vector modes
idx - full-vector index
Note: not vectorized. | def ind2sub(siz, idx):
n = len(siz)
subs = _np.empty((n))
k = _np.cumprod(siz[:-1])
k = _np.concatenate((_np.ones(1), k))
for i in xrange(n - 1, -1, -1):
subs[i] = _np.floor(idx / k[i])
idx = idx % k[i]
return subs.astype(_np.int32) | 585,762 |
Parses datetime information out of string input.
It invokes the SUTimeWrapper.annotate() function in Java.
Args:
input_str: The input as string that has to be parsed.
reference_date: Optional reference data for SUTime.
Returns:
A list of dicts with the resu... | def parse(self, input_str, reference_date=""):
if not jpype.isThreadAttachedToJVM():
jpype.attachThreadToJVM()
if reference_date:
return json.loads(self._sutime.annotate(input_str, reference_date))
return json.loads(self._sutime.annotate(input_str)) | 585,877 |
Write triggers to a file handle.
Parameters:
fh (file): file object.
triggers (list): list of triggers to write.
indent (str): indentation for each line. | def _write_triggers(self, fh, triggers, indent=""):
for trig in triggers:
fh.write(indent + "+ " + self._write_wrapped(trig["trigger"], indent=indent) + "\n")
d = trig
if d.get("previous"):
fh.write(indent + "% " + self._write_wrapped(d["previous"],... | 585,932 |
Syntax check a line of RiveScript code.
Args:
str cmd: The command symbol for the line of code, such as one
of ``+``, ``-``, ``*``, ``>``, etc.
str line: The remainder of the line of code, such as the text of
a trigger or reply.
Return:
... | def check_syntax(self, cmd, line):
# Run syntax checks based on the type of command.
if cmd == '!':
# ! Definition
# - Must be formatted like this:
# ! type name = value
# OR
# ! type = value
match = re.match... | 585,956 |
Initialize the parts needed to start making database connections
parameters:
config - the complete config for the app. If a real app, this
would be where a logger or other resources could be
found.
local_config - this is the namespace within th... | def __init__(self, config, local_config=None):
super(ConnectionFactory, self).__init__()
self.config = config
if local_config is None:
local_config = config
self.dsn = (
"host=%(host)s "
"dbname=%(dbname)s "
"port=%(port)s "
... | 585,985 |
return a named connection.
This function will return a named connection by either finding one
in its pool by the name or creating a new one. If no name is given,
it will use the name of the current executing thread as the name of
the connection.
parameters:
name - ... | def connection(self, name=None):
if not name:
name = self._get_default_connection_name()
if name in self.pool:
return self.pool[name]
self.pool[name] = psycopg2.connect(self.dsn)
return self.pool[name] | 585,986 |
returns a database connection wrapped in a contextmanager.
The context manager will assure that the connection is closed but will
not try to commit or rollback lingering transactions.
parameters:
name - an optional name for the database connection | def __call__(self, name=None):
conn = self.connection(name)
try:
yield conn
finally:
self.close_connection(conn) | 585,987 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.