Best Python code snippet using localstack_python
iters.py
Source:iters.py  
1from sys import version_info2from collections import deque, Iterable3from operator import add, itemgetter, attrgetter, not_4from functools import partial5from itertools import (islice,6                       chain,7                       starmap,8                       repeat,9                       tee,10                       cycle,11                       takewhile,12                       dropwhile,13                       combinations)14from .op import flip15from .func import F16from .uniform import *17def take(limit, base):18    return islice(base, limit)19def drop(limit, base):20    return islice(base, limit, None)21def takelast(n, iterable):22    "Return iterator to produce last n items from origin"23    return iter(deque(iterable, maxlen=n))24def droplast(n, iterable):25    "Return iterator to produce items from origin except last n"26    t1, t2 = tee(iterable)27    return map(itemgetter(0), zip(t1, islice(t2, n, None)))28def consume(iterator, n=None):29    """Advance the iterator n-steps ahead. If n is none, consume entirely.30    http://docs.python.org/3.4/library/itertools.html#itertools-recipes31    """32    # Use functions that consume iterators at C speed.33    if n is None:34        # feed the entire iterator into a zero-length deque35        deque(iterator, maxlen=0)36    else:37        # advance to the empty slice starting at position n38        next(islice(iterator, n, n), None)39def nth(iterable, n, default=None):40    """Returns the nth item or a default value41    http://docs.python.org/3.4/library/itertools.html#itertools-recipes42    """43    return next(islice(iterable, n, None), default)44def first_true(iterable, default=False, pred=None):45    """Returns the first true value in the iterable.46    If no true value is found, returns *default*47    http://docs.python.org/3.4/library/itertools.html#itertools-recipes48    """49    return next(filter(pred, iterable), default)50# widely-spreaded shortcuts to get first item, all but first item,51# second item, and first item of first item from iterator respectively52head = first = partial(flip(nth), 0)53tail = rest = partial(drop, 1)54second = F(rest) >> first55ffirst = F(first) >> first56# shortcut to remove all falsey items from iterable57compact = partial(filter, None)58# filterfalse under alias 'reject'59reject = filterfalse60# shortcuts to 1. return True if f(x) is logical true for every x in61# iterable (False otherwise), and 2. return the first logical true62# value of f(x) for any x in iterable (None otherwise) respectively63every = F(partial(map)) >> all64some = F(partial(map)) >> compact >> first65def iterate(f, x):66    """Return an iterator yielding x, f(x), f(f(x)) etc.67    """68    while True:69        yield x70        x = f(x)71def padnone(iterable):72    """Returns the sequence elements and then returns None indefinitely.73    Useful for emulating the behavior of the built-in map() function.74    http://docs.python.org/3.4/library/itertools.html#itertools-recipes75    """76    return chain(iterable, repeat(None))77def ncycles(iterable, n):78    """Returns the sequence elements n times79    http://docs.python.org/3.4/library/itertools.html#itertools-recipes80    """81    return chain.from_iterable(repeat(tuple(iterable), n))82def repeatfunc(func, times=None, *args):83    """Repeat calls to func with specified arguments.84    Example:  repeatfunc(random.random)85    http://docs.python.org/3.4/library/itertools.html#itertools-recipes86    """87    if times is None:88        return starmap(func, repeat(args))89    return starmap(func, repeat(args, times))90def grouper(n, iterable, fillvalue=None):91    """Collect data into fixed-length chunks or blocks, so92    grouper(3, 'ABCDEFG', 'x') --> ABC DEF Gxx93    http://docs.python.org/3.4/library/itertools.html#itertools-recipes94    """95    args = [iter(iterable)] * n96    return zip_longest(*args, fillvalue=fillvalue)97def group_by(keyfunc, iterable):98    """Returns a dict of the elements from given iterable keyed by result99    of keyfunc on each element. The value at each key will be a list of100    the corresponding elements, in the order they appeared in the iterable.101    """102    grouped = {}103    for item in iterable:104        grouped.setdefault(keyfunc(item), []).append(item)105    return grouped106def roundrobin(*iterables):107    """roundrobin('ABC', 'D', 'EF') --> A D E B F C108    Recipe originally credited to George Sakkis.109    Reimplemented to work both in Python 2+ and 3+.110    http://docs.python.org/3.4/library/itertools.html#itertools-recipes111    """112    pending = len(iterables)113    next_attr = "next" if version_info[0] == 2 else "__next__"114    nexts = cycle(map(attrgetter(next_attr), map(iter, iterables)))115    while pending:116        try:117            for n in nexts:118                yield n()119        except StopIteration:120            pending -= 1121            nexts = cycle(islice(nexts, pending))122def partition(pred, iterable):123    """Use a predicate to partition entries into false entries and true entries124    partition(is_odd, range(10)) --> 0 2 4 6 8   and  1 3 5 7 9125    http://docs.python.org/3.4/library/itertools.html#itertools-recipes126    """127    t1, t2 = tee(iterable)128    return filterfalse(pred, t1), filter(pred, t2)129def splitat(t, iterable):130    """Split iterable into two iterators after given number of iterations131    splitat(2, range(5)) --> 0 1 and 2 3 4132    """133    t1, t2 = tee(iterable)134    return islice(t1, t), islice(t2, t, None)135def splitby(pred, iterable):136    """Split iterable into two iterators at first false predicate137    splitby(is_even, range(5)) --> 0 and 1 2 3 4138    """139    t1, t2 = tee(iterable)140    return takewhile(pred, t1), dropwhile(pred, t2)141def powerset(iterable):142    """powerset([1,2,3]) --> () (1,) (2,) (3,) (1,2) (1,3) (2,3) (1,2,3)143    http://docs.python.org/3.4/library/itertools.html#itertools-recipes144    """145    s = list(iterable)146    return chain.from_iterable(combinations(s, r) for r in range(len(s)+1))147def pairwise(iterable):148    """pairwise(s) -> (s0,s1), (s1,s2), (s2, s3), ...149    http://docs.python.org/3.4/library/itertools.html#itertools-recipes150    """151    a, b = tee(iterable)152    next(b, None)153    return zip(a, b)154def iter_except(func, exception, first_=None):155    """ Call a function repeatedly until an exception is raised.156    Converts a call-until-exception interface to an iterator interface.157    Like __builtin__.iter(func, sentinel) but uses an exception instead158    of a sentinel to end the loop.159    Examples:160        iter_except(functools.partial(heappop, h), IndexError)   # priority queue iterator161        iter_except(d.popitem, KeyError)                         # non-blocking dict iterator162        iter_except(d.popleft, IndexError)                       # non-blocking deque iterator163        iter_except(q.get_nowait, Queue.Empty)                   # loop over a producer Queue164        iter_except(s.pop, KeyError)                             # non-blocking set iterator165    http://docs.python.org/3.4/library/itertools.html#itertools-recipes166    """167    try:168        if first_ is not None:169            yield first_()            # For database APIs needing an initial cast to db.first()170        while 1:171            yield func()172    except exception:173        pass174def flatten(items):175    """Flatten any level of nested iterables (not including strings, bytes or176    bytearrays).177    Reimplemented to work with all nested levels (not only one).178    http://docs.python.org/3.4/library/itertools.html#itertools-recipes179    """180    for item in items:181        is_iterable = isinstance(item, Iterable)182        is_string_or_bytes = isinstance(item, (str, bytes, bytearray))183        if is_iterable and not is_string_or_bytes:184            for i in flatten(item):185                yield i186        else:187            yield item188if version_info[0] == 3 and version_info[1] >= 3:189    from itertools import accumulate190else:191    def accumulate(iterable, func=add):192        """Make an iterator that returns accumulated sums.193        Elements may be any addable type including Decimal or Fraction.194        If the optional func argument is supplied, it should be a195        function of two arguments and it will be used instead of addition.196        Origin implementation:197        http://docs.python.org/dev/library/itertools.html#itertools.accumulate198        Backported to work with all python versions (< 3.3)199        """200        it = iter(iterable)201        total = next(it)202        yield total203        for element in it:204            total = func(total, element)...utils.py
Source:utils.py  
1"""2String and data utils, where implementation differs between Python 2 & 33"""4import sys5from copy import deepcopy6import os7PY_MAJOR, PY_MINOR = sys.version_info[:2]8if PY_MAJOR >= 3:9    from . import utils3 as utils_mod10else:11    from . import utils2 as utils_mod12STR2BYTES = utils_mod.STR2BYTES13BYTES2STR = utils_mod.BYTES2STR14NULLCHAR = utils_mod.NULLCHAR15NULLCHAR_2 = utils_mod.NULLCHAR_216strjoin = utils_mod.strjoin17is_string = utils_mod.is_string18is_string_or_bytes = utils_mod.is_string_or_bytes19ascii_string = utils_mod.ascii_string20memcopy = deepcopy21if PY_MAJOR == 2 and PY_MINOR == 5:22    def memcopy(a):23        return a24def clib_search_path(lib):25    '''Assemble path to c library.26    Parameters27    ----------28    lib : str29        Either 'ca' or 'Com'.30    Returns31    --------32    str : string33    Examples34    --------35    >>> clib_search_path('ca')36    'linux64/libca.so'37    '''38    # determine which libca / libCom dll is appropriate39    try:40        import platform41        nbits = platform.architecture()[0]42    except:43        nbits = '32bit'44    nbits = nbits.replace('bit', '')45    libfmt = 'lib%s.so'46    if os.name == 'nt':47        libsrc = 'win'48        libfmt = '%s.dll'49    elif sys.platform == 'darwin':50        libsrc = 'darwin'51        libfmt = 'lib%s.dylib'52    elif sys.platform.startswith('linux'):53        libsrc = 'linux'54    else:55        return None..._compat.py
Source:_compat.py  
...8        assert type(c) is str9        return c * n10    range = xrange11    long = long12    def is_string_or_bytes(obj):13        return isinstance(obj, basestring)14    def values_list(d):15        return d.values()16    import collections as abc17else:18    from itertools import repeat19    from io import BytesIO as StringIO20    STRING_TYPES = (bytes, str)21    def pad(c, n):22        assert type(c) is int23        return bytes(repeat(c, n))24    range = range25    long = int26    def is_string_or_bytes(obj):27        return isinstance(obj, (bytes, str))28    def values_list(d):29        return list(d.values())...Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.
You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.
Get 100 minutes of automation test minutes FREE!!
