repository_name stringlengths 7 55 | func_path_in_repository stringlengths 4 223 | func_name stringlengths 1 134 | whole_func_string stringlengths 75 104k | language stringclasses 1
value | func_code_string stringlengths 75 104k | func_code_tokens listlengths 19 28.4k | func_documentation_string stringlengths 1 46.9k | func_documentation_tokens listlengths 1 1.97k | split_name stringclasses 1
value | func_code_url stringlengths 87 315 |
|---|---|---|---|---|---|---|---|---|---|---|
shazow/unstdlib.py | unstdlib/sqlalchemy.py | enumerate_query_by_limit | def enumerate_query_by_limit(q, limit=1000):
"""
Enumerate over SQLAlchemy query object ``q`` and yield individual results
fetched in batches of size ``limit`` using SQL LIMIT and OFFSET.
"""
for offset in count(0, limit):
r = q.offset(offset).limit(limit).all()
for row in r:
... | python | def enumerate_query_by_limit(q, limit=1000):
"""
Enumerate over SQLAlchemy query object ``q`` and yield individual results
fetched in batches of size ``limit`` using SQL LIMIT and OFFSET.
"""
for offset in count(0, limit):
r = q.offset(offset).limit(limit).all()
for row in r:
... | [
"def",
"enumerate_query_by_limit",
"(",
"q",
",",
"limit",
"=",
"1000",
")",
":",
"for",
"offset",
"in",
"count",
"(",
"0",
",",
"limit",
")",
":",
"r",
"=",
"q",
".",
"offset",
"(",
"offset",
")",
".",
"limit",
"(",
"limit",
")",
".",
"all",
"("... | Enumerate over SQLAlchemy query object ``q`` and yield individual results
fetched in batches of size ``limit`` using SQL LIMIT and OFFSET. | [
"Enumerate",
"over",
"SQLAlchemy",
"query",
"object",
"q",
"and",
"yield",
"individual",
"results",
"fetched",
"in",
"batches",
"of",
"size",
"limit",
"using",
"SQL",
"LIMIT",
"and",
"OFFSET",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/sqlalchemy.py#L7-L19 |
shazow/unstdlib.py | unstdlib/formencode.py | validate_many | def validate_many(d, schema):
"""Validate a dictionary of data against the provided schema.
Returns a list of values positioned in the same order as given in ``schema``, each
value is validated with the corresponding validator. Raises formencode.Invalid if
validation failed.
Similar to get_many bu... | python | def validate_many(d, schema):
"""Validate a dictionary of data against the provided schema.
Returns a list of values positioned in the same order as given in ``schema``, each
value is validated with the corresponding validator. Raises formencode.Invalid if
validation failed.
Similar to get_many bu... | [
"def",
"validate_many",
"(",
"d",
",",
"schema",
")",
":",
"return",
"[",
"validator",
".",
"to_python",
"(",
"d",
".",
"get",
"(",
"key",
")",
",",
"state",
"=",
"key",
")",
"for",
"key",
",",
"validator",
"in",
"schema",
"]"
] | Validate a dictionary of data against the provided schema.
Returns a list of values positioned in the same order as given in ``schema``, each
value is validated with the corresponding validator. Raises formencode.Invalid if
validation failed.
Similar to get_many but using formencode validation.
:... | [
"Validate",
"a",
"dictionary",
"of",
"data",
"against",
"the",
"provided",
"schema",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/formencode.py#L12-L35 |
shazow/unstdlib.py | unstdlib/standard/functools_.py | assert_hashable | def assert_hashable(*args, **kw):
""" Verify that each argument is hashable.
Passes silently if successful. Raises descriptive TypeError otherwise.
Example::
>>> assert_hashable(1, 'foo', bar='baz')
>>> assert_hashable(1, [], baz='baz')
Traceback (most recent call last):
... | python | def assert_hashable(*args, **kw):
""" Verify that each argument is hashable.
Passes silently if successful. Raises descriptive TypeError otherwise.
Example::
>>> assert_hashable(1, 'foo', bar='baz')
>>> assert_hashable(1, [], baz='baz')
Traceback (most recent call last):
... | [
"def",
"assert_hashable",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"try",
":",
"for",
"i",
",",
"arg",
"in",
"enumerate",
"(",
"args",
")",
":",
"hash",
"(",
"arg",
")",
"except",
"TypeError",
":",
"raise",
"TypeError",
"(",
"'Argument in pos... | Verify that each argument is hashable.
Passes silently if successful. Raises descriptive TypeError otherwise.
Example::
>>> assert_hashable(1, 'foo', bar='baz')
>>> assert_hashable(1, [], baz='baz')
Traceback (most recent call last):
...
TypeError: Argument in positi... | [
"Verify",
"that",
"each",
"argument",
"is",
"hashable",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/functools_.py#L13-L39 |
shazow/unstdlib.py | unstdlib/standard/functools_.py | memoized | def memoized(fn=None, cache=None):
""" Memoize a function into an optionally-specificed cache container.
If the `cache` container is not specified, then the instance container is
accessible from the wrapped function's `memoize_cache` property.
Example::
>>> @memoized
... def foo(bar):... | python | def memoized(fn=None, cache=None):
""" Memoize a function into an optionally-specificed cache container.
If the `cache` container is not specified, then the instance container is
accessible from the wrapped function's `memoize_cache` property.
Example::
>>> @memoized
... def foo(bar):... | [
"def",
"memoized",
"(",
"fn",
"=",
"None",
",",
"cache",
"=",
"None",
")",
":",
"if",
"fn",
":",
"# This is a hack to support both @memoize and @memoize(...)",
"return",
"memoized",
"(",
"cache",
"=",
"cache",
")",
"(",
"fn",
")",
"if",
"cache",
"is",
"None"... | Memoize a function into an optionally-specificed cache container.
If the `cache` container is not specified, then the instance container is
accessible from the wrapped function's `memoize_cache` property.
Example::
>>> @memoized
... def foo(bar):
... print("Not cached.")
... | [
"Memoize",
"a",
"function",
"into",
"an",
"optionally",
"-",
"specificed",
"cache",
"container",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/functools_.py#L59-L110 |
shazow/unstdlib.py | unstdlib/standard/functools_.py | memoized_method | def memoized_method(method=None, cache_factory=None):
""" Memoize a class's method.
Arguments are similar to to `memoized`, except that the cache container is
specified with `cache_factory`: a function called with no arguments to
create the caching container for the instance.
Note that, unlike `me... | python | def memoized_method(method=None, cache_factory=None):
""" Memoize a class's method.
Arguments are similar to to `memoized`, except that the cache container is
specified with `cache_factory`: a function called with no arguments to
create the caching container for the instance.
Note that, unlike `me... | [
"def",
"memoized_method",
"(",
"method",
"=",
"None",
",",
"cache_factory",
"=",
"None",
")",
":",
"if",
"method",
"is",
"None",
":",
"return",
"lambda",
"f",
":",
"memoized_method",
"(",
"f",
",",
"cache_factory",
"=",
"cache_factory",
")",
"cache_factory",... | Memoize a class's method.
Arguments are similar to to `memoized`, except that the cache container is
specified with `cache_factory`: a function called with no arguments to
create the caching container for the instance.
Note that, unlike `memoized`, the result cache will be stored on the
instance, ... | [
"Memoize",
"a",
"class",
"s",
"method",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/functools_.py#L129-L199 |
shazow/unstdlib.py | unstdlib/standard/functools_.py | deprecated | def deprecated(message, exception=PendingDeprecationWarning):
"""Throw a warning when a function/method will be soon deprecated
Supports passing a ``message`` and an ``exception`` class
(uses ``PendingDeprecationWarning`` by default). This is useful if you
want to alternatively pass a ``DeprecationWarn... | python | def deprecated(message, exception=PendingDeprecationWarning):
"""Throw a warning when a function/method will be soon deprecated
Supports passing a ``message`` and an ``exception`` class
(uses ``PendingDeprecationWarning`` by default). This is useful if you
want to alternatively pass a ``DeprecationWarn... | [
"def",
"deprecated",
"(",
"message",
",",
"exception",
"=",
"PendingDeprecationWarning",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"warnin... | Throw a warning when a function/method will be soon deprecated
Supports passing a ``message`` and an ``exception`` class
(uses ``PendingDeprecationWarning`` by default). This is useful if you
want to alternatively pass a ``DeprecationWarning`` exception for already
deprecated functions/methods.
Ex... | [
"Throw",
"a",
"warning",
"when",
"a",
"function",
"/",
"method",
"will",
"be",
"soon",
"deprecated"
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/functools_.py#L202-L233 |
shazow/unstdlib.py | unstdlib/standard/list_.py | groupby_count | def groupby_count(i, key=None, force_keys=None):
""" Aggregate iterator values into buckets based on how frequently the
values appear.
Example::
>>> list(groupby_count([1, 1, 1, 2, 3]))
[(1, 3), (2, 1), (3, 1)]
"""
counter = defaultdict(lambda: 0)
if not key:
key = lamb... | python | def groupby_count(i, key=None, force_keys=None):
""" Aggregate iterator values into buckets based on how frequently the
values appear.
Example::
>>> list(groupby_count([1, 1, 1, 2, 3]))
[(1, 3), (2, 1), (3, 1)]
"""
counter = defaultdict(lambda: 0)
if not key:
key = lamb... | [
"def",
"groupby_count",
"(",
"i",
",",
"key",
"=",
"None",
",",
"force_keys",
"=",
"None",
")",
":",
"counter",
"=",
"defaultdict",
"(",
"lambda",
":",
"0",
")",
"if",
"not",
"key",
":",
"key",
"=",
"lambda",
"o",
":",
"o",
"for",
"k",
"in",
"i",... | Aggregate iterator values into buckets based on how frequently the
values appear.
Example::
>>> list(groupby_count([1, 1, 1, 2, 3]))
[(1, 3), (2, 1), (3, 1)] | [
"Aggregate",
"iterator",
"values",
"into",
"buckets",
"based",
"on",
"how",
"frequently",
"the",
"values",
"appear",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L16-L36 |
shazow/unstdlib.py | unstdlib/standard/list_.py | is_iterable | def is_iterable(maybe_iter, unless=(string_types, dict)):
""" Return whether ``maybe_iter`` is an iterable, unless it's an instance of one
of the base class, or tuple of base classes, given in ``unless``.
Example::
>>> is_iterable('foo')
False
>>> is_iterable(['foo'])
True
... | python | def is_iterable(maybe_iter, unless=(string_types, dict)):
""" Return whether ``maybe_iter`` is an iterable, unless it's an instance of one
of the base class, or tuple of base classes, given in ``unless``.
Example::
>>> is_iterable('foo')
False
>>> is_iterable(['foo'])
True
... | [
"def",
"is_iterable",
"(",
"maybe_iter",
",",
"unless",
"=",
"(",
"string_types",
",",
"dict",
")",
")",
":",
"try",
":",
"iter",
"(",
"maybe_iter",
")",
"except",
"TypeError",
":",
"return",
"False",
"return",
"not",
"isinstance",
"(",
"maybe_iter",
",",
... | Return whether ``maybe_iter`` is an iterable, unless it's an instance of one
of the base class, or tuple of base classes, given in ``unless``.
Example::
>>> is_iterable('foo')
False
>>> is_iterable(['foo'])
True
>>> is_iterable(['foo'], unless=list)
False
... | [
"Return",
"whether",
"maybe_iter",
"is",
"an",
"iterable",
"unless",
"it",
"s",
"an",
"instance",
"of",
"one",
"of",
"the",
"base",
"class",
"or",
"tuple",
"of",
"base",
"classes",
"given",
"in",
"unless",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L39-L58 |
shazow/unstdlib.py | unstdlib/standard/list_.py | iterate | def iterate(maybe_iter, unless=(string_types, dict)):
""" Always return an iterable.
Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single
element iterable containing ``maybe_iter``. By default, strings and dicts
are treated as non-iterable. This can be overridden by passing in a t... | python | def iterate(maybe_iter, unless=(string_types, dict)):
""" Always return an iterable.
Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single
element iterable containing ``maybe_iter``. By default, strings and dicts
are treated as non-iterable. This can be overridden by passing in a t... | [
"def",
"iterate",
"(",
"maybe_iter",
",",
"unless",
"=",
"(",
"string_types",
",",
"dict",
")",
")",
":",
"if",
"is_iterable",
"(",
"maybe_iter",
",",
"unless",
"=",
"unless",
")",
":",
"return",
"maybe_iter",
"return",
"[",
"maybe_iter",
"]"
] | Always return an iterable.
Returns ``maybe_iter`` if it is an iterable, otherwise it returns a single
element iterable containing ``maybe_iter``. By default, strings and dicts
are treated as non-iterable. This can be overridden by passing in a type
or tuple of types for ``unless``.
:param maybe_it... | [
"Always",
"return",
"an",
"iterable",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L61-L89 |
shazow/unstdlib.py | unstdlib/standard/list_.py | iterate_items | def iterate_items(dictish):
""" Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)]
"""
if hasattr(di... | python | def iterate_items(dictish):
""" Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)]
"""
if hasattr(di... | [
"def",
"iterate_items",
"(",
"dictish",
")",
":",
"if",
"hasattr",
"(",
"dictish",
",",
"'iteritems'",
")",
":",
"return",
"dictish",
".",
"iteritems",
"(",
")",
"if",
"hasattr",
"(",
"dictish",
",",
"'items'",
")",
":",
"return",
"dictish",
".",
"items"... | Return a consistent (key, value) iterable on dict-like objects,
including lists of tuple pairs.
Example:
>>> list(iterate_items({'a': 1}))
[('a', 1)]
>>> list(iterate_items([('a', 1), ('b', 2)]))
[('a', 1), ('b', 2)] | [
"Return",
"a",
"consistent",
"(",
"key",
"value",
")",
"iterable",
"on",
"dict",
"-",
"like",
"objects",
"including",
"lists",
"of",
"tuple",
"pairs",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L92-L107 |
shazow/unstdlib.py | unstdlib/standard/list_.py | iterate_chunks | def iterate_chunks(i, size=10):
"""
Iterate over an iterator ``i`` in ``size`` chunks, yield chunks.
Similar to pagination.
Example::
>>> list(iterate_chunks([1, 2, 3, 4], size=2))
[[1, 2], [3, 4]]
"""
accumulator = []
for n, i in enumerate(i):
accumulator.append(i... | python | def iterate_chunks(i, size=10):
"""
Iterate over an iterator ``i`` in ``size`` chunks, yield chunks.
Similar to pagination.
Example::
>>> list(iterate_chunks([1, 2, 3, 4], size=2))
[[1, 2], [3, 4]]
"""
accumulator = []
for n, i in enumerate(i):
accumulator.append(i... | [
"def",
"iterate_chunks",
"(",
"i",
",",
"size",
"=",
"10",
")",
":",
"accumulator",
"=",
"[",
"]",
"for",
"n",
",",
"i",
"in",
"enumerate",
"(",
"i",
")",
":",
"accumulator",
".",
"append",
"(",
"i",
")",
"if",
"(",
"n",
"+",
"1",
")",
"%",
"... | Iterate over an iterator ``i`` in ``size`` chunks, yield chunks.
Similar to pagination.
Example::
>>> list(iterate_chunks([1, 2, 3, 4], size=2))
[[1, 2], [3, 4]] | [
"Iterate",
"over",
"an",
"iterator",
"i",
"in",
"size",
"chunks",
"yield",
"chunks",
".",
"Similar",
"to",
"pagination",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L110-L129 |
shazow/unstdlib.py | unstdlib/standard/list_.py | listify | def listify(fn=None, wrapper=list):
"""
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
.... | python | def listify(fn=None, wrapper=list):
"""
A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
.... | [
"def",
"listify",
"(",
"fn",
"=",
"None",
",",
"wrapper",
"=",
"list",
")",
":",
"def",
"listify_return",
"(",
"fn",
")",
":",
"@",
"wraps",
"(",
"fn",
")",
"def",
"listify_helper",
"(",
"*",
"args",
",",
"*",
"*",
"kw",
")",
":",
"return",
"wrap... | A decorator which wraps a function's return value in ``list(...)``.
Useful when an algorithm can be expressed more cleanly as a generator but
the function should return an list.
Example::
>>> @listify
... def get_lengths(iterable):
... for i in iterable:
... yi... | [
"A",
"decorator",
"which",
"wraps",
"a",
"function",
"s",
"return",
"value",
"in",
"list",
"(",
"...",
")",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/list_.py#L149-L179 |
shazow/unstdlib.py | unstdlib/standard/type_.py | is_subclass | def is_subclass(o, bases):
"""
Similar to the ``issubclass`` builtin, but does not raise a ``TypeError``
if either ``o`` or ``bases`` is not an instance of ``type``.
Example::
>>> is_subclass(IOError, Exception)
True
>>> is_subclass(Exception, None)
False
>>> is... | python | def is_subclass(o, bases):
"""
Similar to the ``issubclass`` builtin, but does not raise a ``TypeError``
if either ``o`` or ``bases`` is not an instance of ``type``.
Example::
>>> is_subclass(IOError, Exception)
True
>>> is_subclass(Exception, None)
False
>>> is... | [
"def",
"is_subclass",
"(",
"o",
",",
"bases",
")",
":",
"try",
":",
"return",
"_issubclass",
"(",
"o",
",",
"bases",
")",
"except",
"TypeError",
":",
"pass",
"if",
"not",
"isinstance",
"(",
"o",
",",
"type",
")",
":",
"return",
"False",
"if",
"not",
... | Similar to the ``issubclass`` builtin, but does not raise a ``TypeError``
if either ``o`` or ``bases`` is not an instance of ``type``.
Example::
>>> is_subclass(IOError, Exception)
True
>>> is_subclass(Exception, None)
False
>>> is_subclass(None, Exception)
Fals... | [
"Similar",
"to",
"the",
"issubclass",
"builtin",
"but",
"does",
"not",
"raise",
"a",
"TypeError",
"if",
"either",
"o",
"or",
"bases",
"is",
"not",
"an",
"instance",
"of",
"type",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/type_.py#L6-L35 |
shazow/unstdlib.py | unstdlib/standard/dict_.py | get_many | def get_many(d, required=[], optional=[], one_of=[]):
"""
Returns a predictable number of elements out of ``d`` in a list for auto-expanding.
Keys in ``required`` will raise KeyError if not found in ``d``.
Keys in ``optional`` will return None if not found in ``d``.
Keys in ``one_of`` will raise Ke... | python | def get_many(d, required=[], optional=[], one_of=[]):
"""
Returns a predictable number of elements out of ``d`` in a list for auto-expanding.
Keys in ``required`` will raise KeyError if not found in ``d``.
Keys in ``optional`` will return None if not found in ``d``.
Keys in ``one_of`` will raise Ke... | [
"def",
"get_many",
"(",
"d",
",",
"required",
"=",
"[",
"]",
",",
"optional",
"=",
"[",
"]",
",",
"one_of",
"=",
"[",
"]",
")",
":",
"d",
"=",
"d",
"or",
"{",
"}",
"r",
"=",
"[",
"d",
"[",
"k",
"]",
"for",
"k",
"in",
"required",
"]",
"r",... | Returns a predictable number of elements out of ``d`` in a list for auto-expanding.
Keys in ``required`` will raise KeyError if not found in ``d``.
Keys in ``optional`` will return None if not found in ``d``.
Keys in ``one_of`` will raise KeyError if none exist, otherwise return the first in ``d``.
Ex... | [
"Returns",
"a",
"predictable",
"number",
"of",
"elements",
"out",
"of",
"d",
"in",
"a",
"list",
"for",
"auto",
"-",
"expanding",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/dict_.py#L6-L30 |
shazow/unstdlib.py | unstdlib/standard/string_.py | random_string | def random_string(length=6, alphabet=string.ascii_letters+string.digits):
"""
Return a random string of given length and alphabet.
Default alphabet is url-friendly (base62).
"""
return ''.join([random.choice(alphabet) for i in xrange(length)]) | python | def random_string(length=6, alphabet=string.ascii_letters+string.digits):
"""
Return a random string of given length and alphabet.
Default alphabet is url-friendly (base62).
"""
return ''.join([random.choice(alphabet) for i in xrange(length)]) | [
"def",
"random_string",
"(",
"length",
"=",
"6",
",",
"alphabet",
"=",
"string",
".",
"ascii_letters",
"+",
"string",
".",
"digits",
")",
":",
"return",
"''",
".",
"join",
"(",
"[",
"random",
".",
"choice",
"(",
"alphabet",
")",
"for",
"i",
"in",
"xr... | Return a random string of given length and alphabet.
Default alphabet is url-friendly (base62). | [
"Return",
"a",
"random",
"string",
"of",
"given",
"length",
"and",
"alphabet",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L44-L50 |
shazow/unstdlib.py | unstdlib/standard/string_.py | number_to_string | def number_to_string(n, alphabet):
"""
Given an non-negative integer ``n``, convert it to a string composed of
the given ``alphabet`` mapping, where the position of each element in
``alphabet`` is its radix value.
Examples::
>>> number_to_string(12345678, '01')
'1011110001100001010... | python | def number_to_string(n, alphabet):
"""
Given an non-negative integer ``n``, convert it to a string composed of
the given ``alphabet`` mapping, where the position of each element in
``alphabet`` is its radix value.
Examples::
>>> number_to_string(12345678, '01')
'1011110001100001010... | [
"def",
"number_to_string",
"(",
"n",
",",
"alphabet",
")",
":",
"result",
"=",
"''",
"base",
"=",
"len",
"(",
"alphabet",
")",
"current",
"=",
"int",
"(",
"n",
")",
"if",
"current",
"<",
"0",
":",
"raise",
"ValueError",
"(",
"\"invalid n (must be non-neg... | Given an non-negative integer ``n``, convert it to a string composed of
the given ``alphabet`` mapping, where the position of each element in
``alphabet`` is its radix value.
Examples::
>>> number_to_string(12345678, '01')
'101111000110000101001110'
>>> number_to_string(12345678, ... | [
"Given",
"an",
"non",
"-",
"negative",
"integer",
"n",
"convert",
"it",
"to",
"a",
"string",
"composed",
"of",
"the",
"given",
"alphabet",
"mapping",
"where",
"the",
"position",
"of",
"each",
"element",
"in",
"alphabet",
"is",
"its",
"radix",
"value",
"."
... | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L53-L83 |
shazow/unstdlib.py | unstdlib/standard/string_.py | string_to_number | def string_to_number(s, alphabet):
"""
Given a string ``s``, convert it to an integer composed of the given
``alphabet`` mapping, where the position of each element in ``alphabet`` is
its radix value.
Examples::
>>> string_to_number('101111000110000101001110', '01')
12345678
... | python | def string_to_number(s, alphabet):
"""
Given a string ``s``, convert it to an integer composed of the given
``alphabet`` mapping, where the position of each element in ``alphabet`` is
its radix value.
Examples::
>>> string_to_number('101111000110000101001110', '01')
12345678
... | [
"def",
"string_to_number",
"(",
"s",
",",
"alphabet",
")",
":",
"base",
"=",
"len",
"(",
"alphabet",
")",
"inverse_alphabet",
"=",
"dict",
"(",
"zip",
"(",
"alphabet",
",",
"xrange",
"(",
"0",
",",
"base",
")",
")",
")",
"n",
"=",
"0",
"exp",
"=",
... | Given a string ``s``, convert it to an integer composed of the given
``alphabet`` mapping, where the position of each element in ``alphabet`` is
its radix value.
Examples::
>>> string_to_number('101111000110000101001110', '01')
12345678
>>> string_to_number('babbbbaaabbaaaababaabb... | [
"Given",
"a",
"string",
"s",
"convert",
"it",
"to",
"an",
"integer",
"composed",
"of",
"the",
"given",
"alphabet",
"mapping",
"where",
"the",
"position",
"of",
"each",
"element",
"in",
"alphabet",
"is",
"its",
"radix",
"value",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L86-L112 |
shazow/unstdlib.py | unstdlib/standard/string_.py | bytes_to_number | def bytes_to_number(b, endian='big'):
"""
Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of str... | python | def bytes_to_number(b, endian='big'):
"""
Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of str... | [
"def",
"bytes_to_number",
"(",
"b",
",",
"endian",
"=",
"'big'",
")",
":",
"if",
"endian",
"==",
"'big'",
":",
"b",
"=",
"reversed",
"(",
"b",
")",
"n",
"=",
"0",
"for",
"i",
",",
"ch",
"in",
"enumerate",
"(",
"bytearray",
"(",
"b",
")",
")",
"... | Convert a string to an integer.
:param b:
String or bytearray to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of string_to_number with a full base-256
ASCII alpha... | [
"Convert",
"a",
"string",
"to",
"an",
"integer",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L115-L149 |
shazow/unstdlib.py | unstdlib/standard/string_.py | number_to_bytes | def number_to_bytes(n, endian='big'):
"""
Convert an integer to a corresponding string of bytes..
:param n:
Integer to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case ve... | python | def number_to_bytes(n, endian='big'):
"""
Convert an integer to a corresponding string of bytes..
:param n:
Integer to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case ve... | [
"def",
"number_to_bytes",
"(",
"n",
",",
"endian",
"=",
"'big'",
")",
":",
"res",
"=",
"[",
"]",
"while",
"n",
":",
"n",
",",
"ch",
"=",
"divmod",
"(",
"n",
",",
"256",
")",
"if",
"PY3",
":",
"res",
".",
"append",
"(",
"ch",
")",
"else",
":",... | Convert an integer to a corresponding string of bytes..
:param n:
Integer to convert.
:param endian:
Byte order to convert into ('big' or 'little' endian-ness, default
'big')
Assumes bytes are 8 bits.
This is a special-case version of number_to_string with a full base-256
... | [
"Convert",
"an",
"integer",
"to",
"a",
"corresponding",
"string",
"of",
"bytes",
".."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L152-L193 |
shazow/unstdlib.py | unstdlib/standard/string_.py | to_str | def to_str(obj, encoding='utf-8', **encode_args):
r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
... | python | def to_str(obj, encoding='utf-8', **encode_args):
r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
... | [
"def",
"to_str",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"*",
"*",
"encode_args",
")",
":",
"# Note: On py3, ``b'x'.__str__()`` returns ``\"b'x'\"``, so we need to do the",
"# explicit check first.",
"if",
"isinstance",
"(",
"obj",
",",
"binary_type",
")",
":"... | r"""
Returns a ``str`` of ``obj``, encoding using ``encoding`` if necessary. For
example::
>>> some_str = b"\xff"
>>> some_unicode = u"\u1234"
>>> some_exception = Exception(u'Error: ' + some_unicode)
>>> r(to_str(some_str))
b'\xff'
>>> r(to_str(some_unicode))
... | [
"r",
"Returns",
"a",
"str",
"of",
"obj",
"encoding",
"using",
"encoding",
"if",
"necessary",
".",
"For",
"example",
"::"
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L196-L227 |
shazow/unstdlib.py | unstdlib/standard/string_.py | to_unicode | def to_unicode(obj, encoding='utf-8', fallback='latin1', **decode_args):
r"""
Returns a ``unicode`` of ``obj``, decoding using ``encoding`` if necessary.
If decoding fails, the ``fallback`` encoding (default ``latin1``) is used.
Examples::
>>> r(to_unicode(b'\xe1\x88\xb4'))
u'\u1234'
... | python | def to_unicode(obj, encoding='utf-8', fallback='latin1', **decode_args):
r"""
Returns a ``unicode`` of ``obj``, decoding using ``encoding`` if necessary.
If decoding fails, the ``fallback`` encoding (default ``latin1``) is used.
Examples::
>>> r(to_unicode(b'\xe1\x88\xb4'))
u'\u1234'
... | [
"def",
"to_unicode",
"(",
"obj",
",",
"encoding",
"=",
"'utf-8'",
",",
"fallback",
"=",
"'latin1'",
",",
"*",
"*",
"decode_args",
")",
":",
"# Note: on py3, the `bytes` type defines an unhelpful \"__str__\" function,",
"# so we need to do this check (see comments in ``to_str``)... | r"""
Returns a ``unicode`` of ``obj``, decoding using ``encoding`` if necessary.
If decoding fails, the ``fallback`` encoding (default ``latin1``) is used.
Examples::
>>> r(to_unicode(b'\xe1\x88\xb4'))
u'\u1234'
>>> r(to_unicode(b'\xff'))
u'\xff'
>>> r(to_unicode(u'... | [
"r",
"Returns",
"a",
"unicode",
"of",
"obj",
"decoding",
"using",
"encoding",
"if",
"necessary",
".",
"If",
"decoding",
"fails",
"the",
"fallback",
"encoding",
"(",
"default",
"latin1",
")",
"is",
"used",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L230-L264 |
shazow/unstdlib.py | unstdlib/standard/string_.py | to_float | def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... | python | def to_float(s, default=0.0, allow_nan=False):
"""
Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_... | [
"def",
"to_float",
"(",
"s",
",",
"default",
"=",
"0.0",
",",
"allow_nan",
"=",
"False",
")",
":",
"try",
":",
"f",
"=",
"float",
"(",
"s",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
")",
":",
"return",
"default",
"if",
"not",
"allow_nan",
... | Return input converted into a float. If failed, then return ``default``.
Note that, by default, ``allow_nan=False``, so ``to_float`` will not return
``nan``, ``inf``, or ``-inf``.
Examples::
>>> to_float('1.5')
1.5
>>> to_float(1)
1.0
>>> to_float('')
0.0
... | [
"Return",
"input",
"converted",
"into",
"a",
"float",
".",
"If",
"failed",
"then",
"return",
"default",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L294-L329 |
shazow/unstdlib.py | unstdlib/standard/string_.py | format_int | def format_int(n, singular=_Default, plural=_Default):
"""
Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If
plural is not specified, then it is assumed to be same as singular but
suffixed with an 's'.
:param n:
Integer which determines pluralness.
:param singu... | python | def format_int(n, singular=_Default, plural=_Default):
"""
Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If
plural is not specified, then it is assumed to be same as singular but
suffixed with an 's'.
:param n:
Integer which determines pluralness.
:param singu... | [
"def",
"format_int",
"(",
"n",
",",
"singular",
"=",
"_Default",
",",
"plural",
"=",
"_Default",
")",
":",
"n",
"=",
"int",
"(",
"n",
")",
"if",
"singular",
"in",
"(",
"None",
",",
"_Default",
")",
":",
"if",
"plural",
"is",
"_Default",
":",
"plura... | Return `singular.format(n)` if n is 1, or `plural.format(n)` otherwise. If
plural is not specified, then it is assumed to be same as singular but
suffixed with an 's'.
:param n:
Integer which determines pluralness.
:param singular:
String with a format() placeholder for n. (Default: `u... | [
"Return",
"singular",
".",
"format",
"(",
"n",
")",
"if",
"n",
"is",
"1",
"or",
"plural",
".",
"format",
"(",
"n",
")",
"otherwise",
".",
"If",
"plural",
"is",
"not",
"specified",
"then",
"it",
"is",
"assumed",
"to",
"be",
"same",
"as",
"singular",
... | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L332-L375 |
shazow/unstdlib.py | unstdlib/standard/string_.py | dollars_to_cents | def dollars_to_cents(s, allow_negative=False):
"""
Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_ce... | python | def dollars_to_cents(s, allow_negative=False):
"""
Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_ce... | [
"def",
"dollars_to_cents",
"(",
"s",
",",
"allow_negative",
"=",
"False",
")",
":",
"# TODO: Implement cents_to_dollars",
"if",
"not",
"s",
":",
"return",
"if",
"isinstance",
"(",
"s",
",",
"string_types",
")",
":",
"s",
"=",
"''",
".",
"join",
"(",
"RE_NU... | Given a string or integer representing dollars, return an integer of
equivalent cents, in an input-resilient way.
This works by stripping any non-numeric characters before attempting to
cast the value.
Examples::
>>> dollars_to_cents('$1')
100
>>> dollars_to_cents('1')
... | [
"Given",
"a",
"string",
"or",
"integer",
"representing",
"dollars",
"return",
"an",
"integer",
"of",
"equivalent",
"cents",
"in",
"an",
"input",
"-",
"resilient",
"way",
".",
"This",
"works",
"by",
"stripping",
"any",
"non",
"-",
"numeric",
"characters",
"be... | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L381-L415 |
shazow/unstdlib.py | unstdlib/standard/string_.py | slugify | def slugify(s, delimiter='-'):
"""
Normalize `s` into ASCII and replace non-word characters with `delimiter`.
"""
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() | python | def slugify(s, delimiter='-'):
"""
Normalize `s` into ASCII and replace non-word characters with `delimiter`.
"""
s = unicodedata.normalize('NFKD', to_unicode(s)).encode('ascii', 'ignore').decode('ascii')
return RE_SLUG.sub(delimiter, s).strip(delimiter).lower() | [
"def",
"slugify",
"(",
"s",
",",
"delimiter",
"=",
"'-'",
")",
":",
"s",
"=",
"unicodedata",
".",
"normalize",
"(",
"'NFKD'",
",",
"to_unicode",
"(",
"s",
")",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")",
".",
"decode",
"(",
"'ascii'",
... | Normalize `s` into ASCII and replace non-word characters with `delimiter`. | [
"Normalize",
"s",
"into",
"ASCII",
"and",
"replace",
"non",
"-",
"word",
"characters",
"with",
"delimiter",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/standard/string_.py#L420-L425 |
shazow/unstdlib.py | unstdlib/html.py | get_cache_buster | def get_cache_buster(src_path, method='importtime'):
""" Return a string that can be used as a parameter for cache-busting URLs
for this asset.
:param src_path:
Filesystem path to the file we're generating a cache-busting value for.
:param method:
Method for cache-busting. Supported va... | python | def get_cache_buster(src_path, method='importtime'):
""" Return a string that can be used as a parameter for cache-busting URLs
for this asset.
:param src_path:
Filesystem path to the file we're generating a cache-busting value for.
:param method:
Method for cache-busting. Supported va... | [
"def",
"get_cache_buster",
"(",
"src_path",
",",
"method",
"=",
"'importtime'",
")",
":",
"try",
":",
"fn",
"=",
"_BUST_METHODS",
"[",
"method",
"]",
"except",
"KeyError",
":",
"raise",
"KeyError",
"(",
"'Unsupported busting method value: %s'",
"%",
"method",
")... | Return a string that can be used as a parameter for cache-busting URLs
for this asset.
:param src_path:
Filesystem path to the file we're generating a cache-busting value for.
:param method:
Method for cache-busting. Supported values: importtime, mtime, md5
The default is 'importti... | [
"Return",
"a",
"string",
"that",
"can",
"be",
"used",
"as",
"a",
"parameter",
"for",
"cache",
"-",
"busting",
"URLs",
"for",
"this",
"asset",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/html.py#L46-L75 |
shazow/unstdlib.py | unstdlib/html.py | _generate_dom_attrs | def _generate_dom_attrs(attrs, allow_no_value=True):
""" Yield compiled DOM attribute key-value strings.
If the value is `True`, then it is treated as no-value. If `None`, then it
is skipped.
"""
for attr in iterate_items(attrs):
if isinstance(attr, basestring):
attr = (attr, Tr... | python | def _generate_dom_attrs(attrs, allow_no_value=True):
""" Yield compiled DOM attribute key-value strings.
If the value is `True`, then it is treated as no-value. If `None`, then it
is skipped.
"""
for attr in iterate_items(attrs):
if isinstance(attr, basestring):
attr = (attr, Tr... | [
"def",
"_generate_dom_attrs",
"(",
"attrs",
",",
"allow_no_value",
"=",
"True",
")",
":",
"for",
"attr",
"in",
"iterate_items",
"(",
"attrs",
")",
":",
"if",
"isinstance",
"(",
"attr",
",",
"basestring",
")",
":",
"attr",
"=",
"(",
"attr",
",",
"True",
... | Yield compiled DOM attribute key-value strings.
If the value is `True`, then it is treated as no-value. If `None`, then it
is skipped. | [
"Yield",
"compiled",
"DOM",
"attribute",
"key",
"-",
"value",
"strings",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/html.py#L78-L95 |
shazow/unstdlib.py | unstdlib/html.py | tag | def tag(tagname, content='', attrs=None):
""" Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Opt... | python | def tag(tagname, content='', attrs=None):
""" Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Opt... | [
"def",
"tag",
"(",
"tagname",
",",
"content",
"=",
"''",
",",
"attrs",
"=",
"None",
")",
":",
"attrs_str",
"=",
"attrs",
"and",
"' '",
".",
"join",
"(",
"_generate_dom_attrs",
"(",
"attrs",
")",
")",
"open_tag",
"=",
"tagname",
"if",
"attrs_str",
":",
... | Helper for programmatically building HTML tags.
Note that this barely does any escaping, and will happily spit out
dangerous user input if used as such.
:param tagname:
Tag name of the DOM element we want to return.
:param content:
Optional content of the DOM element. If `None`, then ... | [
"Helper",
"for",
"programmatically",
"building",
"HTML",
"tags",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/html.py#L107-L146 |
shazow/unstdlib.py | unstdlib/html.py | javascript_link | def javascript_link(src_url, src_path=None, cache_bust=None, content='', extra_attrs=None):
""" Helper for programmatically building HTML JavaScript source include
links, with optional cache busting.
:param src_url:
Goes into the `src` attribute of the `<script src="...">` tag.
:param src_path... | python | def javascript_link(src_url, src_path=None, cache_bust=None, content='', extra_attrs=None):
""" Helper for programmatically building HTML JavaScript source include
links, with optional cache busting.
:param src_url:
Goes into the `src` attribute of the `<script src="...">` tag.
:param src_path... | [
"def",
"javascript_link",
"(",
"src_url",
",",
"src_path",
"=",
"None",
",",
"cache_bust",
"=",
"None",
",",
"content",
"=",
"''",
",",
"extra_attrs",
"=",
"None",
")",
":",
"if",
"cache_bust",
":",
"append_suffix",
"=",
"get_cache_buster",
"(",
"src_path",
... | Helper for programmatically building HTML JavaScript source include
links, with optional cache busting.
:param src_url:
Goes into the `src` attribute of the `<script src="...">` tag.
:param src_path:
Optional filesystem path to the source file, used when `cache_bust` is
enabled.
... | [
"Helper",
"for",
"programmatically",
"building",
"HTML",
"JavaScript",
"source",
"include",
"links",
"with",
"optional",
"cache",
"busting",
"."
] | train | https://github.com/shazow/unstdlib.py/blob/e0632fe165cfbfdb5a7e4bc7b412c9d6f2ebad83/unstdlib/html.py#L164-L202 |
rackerlabs/lambda-uploader | setup.py | package_meta | def package_meta():
"""Read __init__.py for global package metadata.
Do this without importing the package.
"""
_version_re = re.compile(r'__version__\s+=\s+(.*)')
_url_re = re.compile(r'__url__\s+=\s+(.*)')
_license_re = re.compile(r'__license__\s+=\s+(.*)')
with open('lambda_uploader/__in... | python | def package_meta():
"""Read __init__.py for global package metadata.
Do this without importing the package.
"""
_version_re = re.compile(r'__version__\s+=\s+(.*)')
_url_re = re.compile(r'__url__\s+=\s+(.*)')
_license_re = re.compile(r'__license__\s+=\s+(.*)')
with open('lambda_uploader/__in... | [
"def",
"package_meta",
"(",
")",
":",
"_version_re",
"=",
"re",
".",
"compile",
"(",
"r'__version__\\s+=\\s+(.*)'",
")",
"_url_re",
"=",
"re",
".",
"compile",
"(",
"r'__url__\\s+=\\s+(.*)'",
")",
"_license_re",
"=",
"re",
".",
"compile",
"(",
"r'__license__\\s+=... | Read __init__.py for global package metadata.
Do this without importing the package. | [
"Read",
"__init__",
".",
"py",
"for",
"global",
"package",
"metadata",
".",
"Do",
"this",
"without",
"importing",
"the",
"package",
"."
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/setup.py#L37-L57 |
rackerlabs/lambda-uploader | lambda_uploader/subscribers.py | create_subscriptions | def create_subscriptions(config, profile_name):
''' Adds supported subscriptions '''
if 'kinesis' in config.subscription.keys():
data = config.subscription['kinesis']
function_name = config.name
stream_name = data['stream']
batch_size = data['batch_size']
starting_positio... | python | def create_subscriptions(config, profile_name):
''' Adds supported subscriptions '''
if 'kinesis' in config.subscription.keys():
data = config.subscription['kinesis']
function_name = config.name
stream_name = data['stream']
batch_size = data['batch_size']
starting_positio... | [
"def",
"create_subscriptions",
"(",
"config",
",",
"profile_name",
")",
":",
"if",
"'kinesis'",
"in",
"config",
".",
"subscription",
".",
"keys",
"(",
")",
":",
"data",
"=",
"config",
".",
"subscription",
"[",
"'kinesis'",
"]",
"function_name",
"=",
"config"... | Adds supported subscriptions | [
"Adds",
"supported",
"subscriptions"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/subscribers.py#L77-L93 |
rackerlabs/lambda-uploader | lambda_uploader/subscribers.py | KinesisSubscriber.subscribe | def subscribe(self):
''' Subscribes the lambda to the Kinesis stream '''
try:
LOG.debug('Creating Kinesis subscription')
if self.starting_position_ts:
self._lambda_client \
.create_event_source_mapping(
EventSourceArn=se... | python | def subscribe(self):
''' Subscribes the lambda to the Kinesis stream '''
try:
LOG.debug('Creating Kinesis subscription')
if self.starting_position_ts:
self._lambda_client \
.create_event_source_mapping(
EventSourceArn=se... | [
"def",
"subscribe",
"(",
"self",
")",
":",
"try",
":",
"LOG",
".",
"debug",
"(",
"'Creating Kinesis subscription'",
")",
"if",
"self",
".",
"starting_position_ts",
":",
"self",
".",
"_lambda_client",
".",
"create_event_source_mapping",
"(",
"EventSourceArn",
"=",
... | Subscribes the lambda to the Kinesis stream | [
"Subscribes",
"the",
"lambda",
"to",
"the",
"Kinesis",
"stream"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/subscribers.py#L37-L74 |
rackerlabs/lambda-uploader | lambda_uploader/uploader.py | PackageUploader._format_vpc_config | def _format_vpc_config(self):
'''
Returns {} if the VPC config is set to None by Config,
returns the formatted config otherwise
'''
if self._config.raw['vpc']:
return {
'SubnetIds': self._config.raw['vpc']['subnets'],
'SecurityGroupIds'... | python | def _format_vpc_config(self):
'''
Returns {} if the VPC config is set to None by Config,
returns the formatted config otherwise
'''
if self._config.raw['vpc']:
return {
'SubnetIds': self._config.raw['vpc']['subnets'],
'SecurityGroupIds'... | [
"def",
"_format_vpc_config",
"(",
"self",
")",
":",
"if",
"self",
".",
"_config",
".",
"raw",
"[",
"'vpc'",
"]",
":",
"return",
"{",
"'SubnetIds'",
":",
"self",
".",
"_config",
".",
"raw",
"[",
"'vpc'",
"]",
"[",
"'subnets'",
"]",
",",
"'SecurityGroupI... | Returns {} if the VPC config is set to None by Config,
returns the formatted config otherwise | [
"Returns",
"{}",
"if",
"the",
"VPC",
"config",
"is",
"set",
"to",
"None",
"by",
"Config",
"returns",
"the",
"formatted",
"config",
"otherwise"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/uploader.py#L203-L217 |
rackerlabs/lambda-uploader | lambda_uploader/uploader.py | PackageUploader._upload_s3 | def _upload_s3(self, zip_file):
'''
Uploads the lambda package to s3
'''
s3_client = self._aws_session.client('s3')
transfer = boto3.s3.transfer.S3Transfer(s3_client)
transfer.upload_file(zip_file, self._config.s3_bucket,
self._config.s3_packa... | python | def _upload_s3(self, zip_file):
'''
Uploads the lambda package to s3
'''
s3_client = self._aws_session.client('s3')
transfer = boto3.s3.transfer.S3Transfer(s3_client)
transfer.upload_file(zip_file, self._config.s3_bucket,
self._config.s3_packa... | [
"def",
"_upload_s3",
"(",
"self",
",",
"zip_file",
")",
":",
"s3_client",
"=",
"self",
".",
"_aws_session",
".",
"client",
"(",
"'s3'",
")",
"transfer",
"=",
"boto3",
".",
"s3",
".",
"transfer",
".",
"S3Transfer",
"(",
"s3_client",
")",
"transfer",
".",
... | Uploads the lambda package to s3 | [
"Uploads",
"the",
"lambda",
"package",
"to",
"s3"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/uploader.py#L219-L226 |
rackerlabs/lambda-uploader | lambda_uploader/shell.py | main | def main(arv=None):
"""lambda-uploader command line interface."""
# Check for Python 2.7 or later
if sys.version_info[0] < 3 and not sys.version_info[1] == 7:
raise RuntimeError('lambda-uploader requires Python 2.7 or later')
import argparse
parser = argparse.ArgumentParser(
de... | python | def main(arv=None):
"""lambda-uploader command line interface."""
# Check for Python 2.7 or later
if sys.version_info[0] < 3 and not sys.version_info[1] == 7:
raise RuntimeError('lambda-uploader requires Python 2.7 or later')
import argparse
parser = argparse.ArgumentParser(
de... | [
"def",
"main",
"(",
"arv",
"=",
"None",
")",
":",
"# Check for Python 2.7 or later",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"<",
"3",
"and",
"not",
"sys",
".",
"version_info",
"[",
"1",
"]",
"==",
"7",
":",
"raise",
"RuntimeError",
"(",
"'lam... | lambda-uploader command line interface. | [
"lambda",
"-",
"uploader",
"command",
"line",
"interface",
"."
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/shell.py#L117-L203 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | build_package | def build_package(path, requires, virtualenv=None, ignore=None,
extra_files=None, zipfile_name=ZIPFILE_NAME,
pyexec=None):
'''Builds the zip file and creates the package with it'''
pkg = Package(path, zipfile_name, pyexec)
if extra_files:
for fil in extra_files:
... | python | def build_package(path, requires, virtualenv=None, ignore=None,
extra_files=None, zipfile_name=ZIPFILE_NAME,
pyexec=None):
'''Builds the zip file and creates the package with it'''
pkg = Package(path, zipfile_name, pyexec)
if extra_files:
for fil in extra_files:
... | [
"def",
"build_package",
"(",
"path",
",",
"requires",
",",
"virtualenv",
"=",
"None",
",",
"ignore",
"=",
"None",
",",
"extra_files",
"=",
"None",
",",
"zipfile_name",
"=",
"ZIPFILE_NAME",
",",
"pyexec",
"=",
"None",
")",
":",
"pkg",
"=",
"Package",
"(",... | Builds the zip file and creates the package with it | [
"Builds",
"the",
"zip",
"file",
"and",
"creates",
"the",
"package",
"with",
"it"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L39-L53 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.build | def build(self, ignore=None):
'''Calls all necessary methods to build the Lambda Package'''
self._prepare_workspace()
self.install_dependencies()
self.package(ignore) | python | def build(self, ignore=None):
'''Calls all necessary methods to build the Lambda Package'''
self._prepare_workspace()
self.install_dependencies()
self.package(ignore) | [
"def",
"build",
"(",
"self",
",",
"ignore",
"=",
"None",
")",
":",
"self",
".",
"_prepare_workspace",
"(",
")",
"self",
".",
"install_dependencies",
"(",
")",
"self",
".",
"package",
"(",
"ignore",
")"
] | Calls all necessary methods to build the Lambda Package | [
"Calls",
"all",
"necessary",
"methods",
"to",
"build",
"the",
"Lambda",
"Package"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L76-L80 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.clean_workspace | def clean_workspace(self):
'''Clean up the temporary workspace if one exists'''
if os.path.isdir(self._temp_workspace):
shutil.rmtree(self._temp_workspace) | python | def clean_workspace(self):
'''Clean up the temporary workspace if one exists'''
if os.path.isdir(self._temp_workspace):
shutil.rmtree(self._temp_workspace) | [
"def",
"clean_workspace",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isdir",
"(",
"self",
".",
"_temp_workspace",
")",
":",
"shutil",
".",
"rmtree",
"(",
"self",
".",
"_temp_workspace",
")"
] | Clean up the temporary workspace if one exists | [
"Clean",
"up",
"the",
"temporary",
"workspace",
"if",
"one",
"exists"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L82-L85 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.clean_zipfile | def clean_zipfile(self):
'''remove existing zipfile'''
if os.path.isfile(self.zip_file):
os.remove(self.zip_file) | python | def clean_zipfile(self):
'''remove existing zipfile'''
if os.path.isfile(self.zip_file):
os.remove(self.zip_file) | [
"def",
"clean_zipfile",
"(",
"self",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"self",
".",
"zip_file",
")",
":",
"os",
".",
"remove",
"(",
"self",
".",
"zip_file",
")"
] | remove existing zipfile | [
"remove",
"existing",
"zipfile"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L87-L90 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.requirements | def requirements(self, requires):
'''
Sets the requirements for the package.
It will take either a valid path to a requirements file or
a list of requirements.
'''
if requires:
if isinstance(requires, basestring) and \
os.path.isfile(os.path.ab... | python | def requirements(self, requires):
'''
Sets the requirements for the package.
It will take either a valid path to a requirements file or
a list of requirements.
'''
if requires:
if isinstance(requires, basestring) and \
os.path.isfile(os.path.ab... | [
"def",
"requirements",
"(",
"self",
",",
"requires",
")",
":",
"if",
"requires",
":",
"if",
"isinstance",
"(",
"requires",
",",
"basestring",
")",
"and",
"os",
".",
"path",
".",
"isfile",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"requires",
")",
... | Sets the requirements for the package.
It will take either a valid path to a requirements file or
a list of requirements. | [
"Sets",
"the",
"requirements",
"for",
"the",
"package",
"."
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L92-L112 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.virtualenv | def virtualenv(self, virtualenv):
'''
Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped.
'''
# If a boole... | python | def virtualenv(self, virtualenv):
'''
Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped.
'''
# If a boole... | [
"def",
"virtualenv",
"(",
"self",
",",
"virtualenv",
")",
":",
"# If a boolean is passed then set the internal _skip_virtualenv flag",
"if",
"isinstance",
"(",
"virtualenv",
",",
"bool",
")",
":",
"self",
".",
"_skip_virtualenv",
"=",
"virtualenv",
"else",
":",
"self"... | Sets the virtual environment for the lambda package
If this is not set then package_dependencies will create a new one.
Takes a path to a virtualenv or a boolean if the virtualenv creation
should be skipped. | [
"Sets",
"the",
"virtual",
"environment",
"for",
"the",
"lambda",
"package"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L114-L133 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.install_dependencies | def install_dependencies(self):
''' Creates a virtualenv and installs requirements '''
# If virtualenv is set to skip then do nothing
if self._skip_virtualenv:
LOG.info('Skip Virtualenv set ... nothing to do')
return
has_reqs = _isfile(self._requirements_file) or... | python | def install_dependencies(self):
''' Creates a virtualenv and installs requirements '''
# If virtualenv is set to skip then do nothing
if self._skip_virtualenv:
LOG.info('Skip Virtualenv set ... nothing to do')
return
has_reqs = _isfile(self._requirements_file) or... | [
"def",
"install_dependencies",
"(",
"self",
")",
":",
"# If virtualenv is set to skip then do nothing",
"if",
"self",
".",
"_skip_virtualenv",
":",
"LOG",
".",
"info",
"(",
"'Skip Virtualenv set ... nothing to do'",
")",
"return",
"has_reqs",
"=",
"_isfile",
"(",
"self"... | Creates a virtualenv and installs requirements | [
"Creates",
"a",
"virtualenv",
"and",
"installs",
"requirements"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L141-L157 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package._build_new_virtualenv | def _build_new_virtualenv(self):
'''Build a new virtualenvironment if self._virtualenv is set to None'''
if self._virtualenv is None:
# virtualenv was "None" which means "do default"
self._pkg_venv = os.path.join(self._temp_workspace, 'venv')
self._venv_pip = 'bin/pip... | python | def _build_new_virtualenv(self):
'''Build a new virtualenvironment if self._virtualenv is set to None'''
if self._virtualenv is None:
# virtualenv was "None" which means "do default"
self._pkg_venv = os.path.join(self._temp_workspace, 'venv')
self._venv_pip = 'bin/pip... | [
"def",
"_build_new_virtualenv",
"(",
"self",
")",
":",
"if",
"self",
".",
"_virtualenv",
"is",
"None",
":",
"# virtualenv was \"None\" which means \"do default\"",
"self",
".",
"_pkg_venv",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_workspace",
... | Build a new virtualenvironment if self._virtualenv is set to None | [
"Build",
"a",
"new",
"virtualenvironment",
"if",
"self",
".",
"_virtualenv",
"is",
"set",
"to",
"None"
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L168-L189 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package._install_requirements | def _install_requirements(self):
'''
Create a new virtualenvironment and install requirements
if there are any.
'''
if not hasattr(self, '_pkg_venv'):
err = 'Must call build_new_virtualenv before install_requirements'
raise Exception(err)
cmd = No... | python | def _install_requirements(self):
'''
Create a new virtualenvironment and install requirements
if there are any.
'''
if not hasattr(self, '_pkg_venv'):
err = 'Must call build_new_virtualenv before install_requirements'
raise Exception(err)
cmd = No... | [
"def",
"_install_requirements",
"(",
"self",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_pkg_venv'",
")",
":",
"err",
"=",
"'Must call build_new_virtualenv before install_requirements'",
"raise",
"Exception",
"(",
"err",
")",
"cmd",
"=",
"None",
"if",
... | Create a new virtualenvironment and install requirements
if there are any. | [
"Create",
"a",
"new",
"virtualenvironment",
"and",
"install",
"requirements",
"if",
"there",
"are",
"any",
"."
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L207-L237 |
rackerlabs/lambda-uploader | lambda_uploader/package.py | Package.package | def package(self, ignore=None):
"""
Create a zip file of the lambda script and its dependencies.
:param list ignore: a list of regular expression strings to match paths
of files in the source of the lambda script against and ignore
those files when creating the zip file.... | python | def package(self, ignore=None):
"""
Create a zip file of the lambda script and its dependencies.
:param list ignore: a list of regular expression strings to match paths
of files in the source of the lambda script against and ignore
those files when creating the zip file.... | [
"def",
"package",
"(",
"self",
",",
"ignore",
"=",
"None",
")",
":",
"ignore",
"=",
"ignore",
"or",
"[",
"]",
"package",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_temp_workspace",
",",
"'lambda_package'",
")",
"# Copy site packages into pack... | Create a zip file of the lambda script and its dependencies.
:param list ignore: a list of regular expression strings to match paths
of files in the source of the lambda script against and ignore
those files when creating the zip file. The paths to be matched are
local to th... | [
"Create",
"a",
"zip",
"file",
"of",
"the",
"lambda",
"script",
"and",
"its",
"dependencies",
"."
] | train | https://github.com/rackerlabs/lambda-uploader/blob/a5036e60d45d1a4fdc07df071f5b6e3b113388d4/lambda_uploader/package.py#L239-L294 |
Parallels/artifactory | artifactory.py | encode_properties | def encode_properties(parameters):
"""
Performs encoding of url parameters from dictionary to a string. It does
not escape backslash because it is not needed.
See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties
"""
result = []
for para... | python | def encode_properties(parameters):
"""
Performs encoding of url parameters from dictionary to a string. It does
not escape backslash because it is not needed.
See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties
"""
result = []
for para... | [
"def",
"encode_properties",
"(",
"parameters",
")",
":",
"result",
"=",
"[",
"]",
"for",
"param",
"in",
"iter",
"(",
"sorted",
"(",
"parameters",
")",
")",
":",
"if",
"isinstance",
"(",
"parameters",
"[",
"param",
"]",
",",
"(",
"list",
",",
"tuple",
... | Performs encoding of url parameters from dictionary to a string. It does
not escape backslash because it is not needed.
See: http://www.jfrog.com/confluence/display/RTF/Artifactory+REST+API#ArtifactoryRESTAPI-SetItemProperties | [
"Performs",
"encoding",
"of",
"url",
"parameters",
"from",
"dictionary",
"to",
"a",
"string",
".",
"It",
"does",
"not",
"escape",
"backslash",
"because",
"it",
"is",
"not",
"needed",
"."
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L271-L288 |
Parallels/artifactory | artifactory.py | _ArtifactoryFlavour.splitroot | def splitroot(self, part, sep=sep):
"""
Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is ... | python | def splitroot(self, part, sep=sep):
"""
Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is ... | [
"def",
"splitroot",
"(",
"self",
",",
"part",
",",
"sep",
"=",
"sep",
")",
":",
"drv",
"=",
"''",
"root",
"=",
"''",
"base",
"=",
"get_global_base_url",
"(",
"part",
")",
"if",
"base",
"and",
"without_http_prefix",
"(",
"part",
")",
".",
"startswith",
... | Splits path string into drive, root and relative path
Uses '/artifactory/' as a splitting point in URI. Everything
before it, including '/artifactory/' itself is treated as drive.
The next folder is treated as root, and everything else is taken
for relative path. | [
"Splits",
"path",
"string",
"into",
"drive",
"root",
"and",
"relative",
"path"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L316-L355 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.rest_get | def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | python | def rest_get(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a GET request to url with optional authentication
"""
res = requests.get(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | [
"def",
"rest_get",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
... | Perform a GET request to url with optional authentication | [
"Perform",
"a",
"GET",
"request",
"to",
"url",
"with",
"optional",
"authentication"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L412-L418 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.rest_put | def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | python | def rest_put(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.put(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
return ... | [
"def",
"rest_put",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"put",
"(",
"url",
",",
... | Perform a PUT request to url with optional authentication | [
"Perform",
"a",
"PUT",
"request",
"to",
"url",
"with",
"optional",
"authentication"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L420-L426 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.rest_post | def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
retu... | python | def rest_post(self, url, params=None, headers=None, auth=None, verify=True, cert=None):
"""
Perform a PUT request to url with optional authentication
"""
res = requests.post(url, params=params, headers=headers, auth=auth, verify=verify,
cert=cert)
retu... | [
"def",
"rest_post",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"post",
"(",
"url",
",",
... | Perform a PUT request to url with optional authentication | [
"Perform",
"a",
"PUT",
"request",
"to",
"url",
"with",
"optional",
"authentication"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L428-L434 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.rest_del | def rest_del(self, url, params=None, auth=None, verify=True, cert=None):
"""
Perform a DELETE request to url with optional authentication
"""
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert)
return res.text, res.status_code | python | def rest_del(self, url, params=None, auth=None, verify=True, cert=None):
"""
Perform a DELETE request to url with optional authentication
"""
res = requests.delete(url, params=params, auth=auth, verify=verify, cert=cert)
return res.text, res.status_code | [
"def",
"rest_del",
"(",
"self",
",",
"url",
",",
"params",
"=",
"None",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"delete",
"(",
"url",
",",
"params",
"=",
"params",
","... | Perform a DELETE request to url with optional authentication | [
"Perform",
"a",
"DELETE",
"request",
"to",
"url",
"with",
"optional",
"authentication"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L436-L441 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.rest_get_stream | def rest_get_stream(self, url, auth=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with optional authentication
This is specifically to download files.
"""
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, r... | python | def rest_get_stream(self, url, auth=None, verify=True, cert=None):
"""
Perform a chunked GET request to url with optional authentication
This is specifically to download files.
"""
res = requests.get(url, auth=auth, stream=True, verify=verify, cert=cert)
return res.raw, r... | [
"def",
"rest_get_stream",
"(",
"self",
",",
"url",
",",
"auth",
"=",
"None",
",",
"verify",
"=",
"True",
",",
"cert",
"=",
"None",
")",
":",
"res",
"=",
"requests",
".",
"get",
"(",
"url",
",",
"auth",
"=",
"auth",
",",
"stream",
"=",
"True",
","... | Perform a chunked GET request to url with optional authentication
This is specifically to download files. | [
"Perform",
"a",
"chunked",
"GET",
"request",
"to",
"url",
"with",
"optional",
"authentication",
"This",
"is",
"specifically",
"to",
"download",
"files",
"."
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L451-L457 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.get_stat_json | def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).str... | python | def get_stat_json(self, pathobj):
"""
Request remote file/directory status info
Returns a json object as specified by Artifactory REST API
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).str... | [
"def",
"get_stat_json",
"(",
"self",
",",
"pathobj",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"pathobj",
".",
"drive",
",",
"'api/storage'",
",",
"str",
"(",
"pathobj",
".",
"relative_to",
"(",
"pathobj",
".",
"drive",
")",
")",
".",
"stri... | Request remote file/directory status info
Returns a json object as specified by Artifactory REST API | [
"Request",
"remote",
"file",
"/",
"directory",
"status",
"info",
"Returns",
"a",
"json",
"object",
"as",
"specified",
"by",
"Artifactory",
"REST",
"API"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L459-L475 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.open | def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.ver... | python | def open(self, pathobj):
"""
Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek()
"""
url = str(pathobj)
raw, code = self.rest_get_stream(url, auth=pathobj.auth, verify=pathobj.ver... | [
"def",
"open",
"(",
"self",
",",
"pathobj",
")",
":",
"url",
"=",
"str",
"(",
"pathobj",
")",
"raw",
",",
"code",
"=",
"self",
".",
"rest_get_stream",
"(",
"url",
",",
"auth",
"=",
"pathobj",
".",
"auth",
",",
"verify",
"=",
"pathobj",
".",
"verify... | Opens the remote file and returns a file-like object HTTPResponse
Given the nature of HTTP streaming, this object doesn't support
seek() | [
"Opens",
"the",
"remote",
"file",
"and",
"returns",
"a",
"file",
"-",
"like",
"object",
"HTTPResponse",
"Given",
"the",
"nature",
"of",
"HTTP",
"streaming",
"this",
"object",
"doesn",
"t",
"support",
"seek",
"()"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L649-L662 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.deploy | def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):
"""
Uploads a given file-like object
HTTP chunked encoding will be attempted
"""
if isinstance(fobj, urllib3.response.HTTPResponse):
fobj = HTTPResponseWrapper(fobj)
url = str(pathobj)
... | python | def deploy(self, pathobj, fobj, md5=None, sha1=None, parameters=None):
"""
Uploads a given file-like object
HTTP chunked encoding will be attempted
"""
if isinstance(fobj, urllib3.response.HTTPResponse):
fobj = HTTPResponseWrapper(fobj)
url = str(pathobj)
... | [
"def",
"deploy",
"(",
"self",
",",
"pathobj",
",",
"fobj",
",",
"md5",
"=",
"None",
",",
"sha1",
"=",
"None",
",",
"parameters",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"fobj",
",",
"urllib3",
".",
"response",
".",
"HTTPResponse",
")",
":",
... | Uploads a given file-like object
HTTP chunked encoding will be attempted | [
"Uploads",
"a",
"given",
"file",
"-",
"like",
"object",
"HTTP",
"chunked",
"encoding",
"will",
"be",
"attempted"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L664-L692 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.move | def move(self, src, dst):
"""
Move artifact from src to dst
"""
url = '/'.join([src.drive,
'api/move',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')}
text, code =... | python | def move(self, src, dst):
"""
Move artifact from src to dst
"""
url = '/'.join([src.drive,
'api/move',
str(src.relative_to(src.drive)).rstrip('/')])
params = {'to': str(dst.relative_to(dst.drive)).rstrip('/')}
text, code =... | [
"def",
"move",
"(",
"self",
",",
"src",
",",
"dst",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"src",
".",
"drive",
",",
"'api/move'",
",",
"str",
"(",
"src",
".",
"relative_to",
"(",
"src",
".",
"drive",
")",
")",
".",
"rstrip",
"(",
... | Move artifact from src to dst | [
"Move",
"artifact",
"from",
"src",
"to",
"dst"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L714-L731 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.set_properties | def set_properties(self, pathobj, props, recursive):
"""
Set artifact properties
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': encode_properties(props... | python | def set_properties(self, pathobj, props, recursive):
"""
Set artifact properties
"""
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).strip('/')])
params = {'properties': encode_properties(props... | [
"def",
"set_properties",
"(",
"self",
",",
"pathobj",
",",
"props",
",",
"recursive",
")",
":",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"pathobj",
".",
"drive",
",",
"'api/storage'",
",",
"str",
"(",
"pathobj",
".",
"relative_to",
"(",
"pathobj",
"."... | Set artifact properties | [
"Set",
"artifact",
"properties"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L758-L780 |
Parallels/artifactory | artifactory.py | _ArtifactoryAccessor.del_properties | def del_properties(self, pathobj, props, recursive):
"""
Delete artifact properties
"""
if isinstance(props, str):
props = (props,)
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).s... | python | def del_properties(self, pathobj, props, recursive):
"""
Delete artifact properties
"""
if isinstance(props, str):
props = (props,)
url = '/'.join([pathobj.drive,
'api/storage',
str(pathobj.relative_to(pathobj.drive)).s... | [
"def",
"del_properties",
"(",
"self",
",",
"pathobj",
",",
"props",
",",
"recursive",
")",
":",
"if",
"isinstance",
"(",
"props",
",",
"str",
")",
":",
"props",
"=",
"(",
"props",
",",
")",
"url",
"=",
"'/'",
".",
"join",
"(",
"[",
"pathobj",
".",
... | Delete artifact properties | [
"Delete",
"artifact",
"properties"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L782-L807 |
Parallels/artifactory | artifactory.py | ArtifactoryPath.relative_to | def relative_to(self, *other):
"""
Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
"""
obj = super(ArtifactoryPath, self).relative_to(*other... | python | def relative_to(self, *other):
"""
Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError.
"""
obj = super(ArtifactoryPath, self).relative_to(*other... | [
"def",
"relative_to",
"(",
"self",
",",
"*",
"other",
")",
":",
"obj",
"=",
"super",
"(",
"ArtifactoryPath",
",",
"self",
")",
".",
"relative_to",
"(",
"*",
"other",
")",
"obj",
".",
"auth",
"=",
"self",
".",
"auth",
"obj",
".",
"verify",
"=",
"sel... | Return the relative path to another path identified by the passed
arguments. If the operation is not possible (because this is not
a subpath of the other path), raise ValueError. | [
"Return",
"the",
"relative",
"path",
"to",
"another",
"path",
"identified",
"by",
"the",
"passed",
"arguments",
".",
"If",
"the",
"operation",
"is",
"not",
"possible",
"(",
"because",
"this",
"is",
"not",
"a",
"subpath",
"of",
"the",
"other",
"path",
")",
... | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L923-L933 |
Parallels/artifactory | artifactory.py | ArtifactoryPath.set_properties | def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
... | python | def set_properties(self, properties, recursive=True):
"""
Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
... | [
"def",
"set_properties",
"(",
"self",
",",
"properties",
",",
"recursive",
"=",
"True",
")",
":",
"if",
"not",
"properties",
":",
"return",
"return",
"self",
".",
"_accessor",
".",
"set_properties",
"(",
"self",
",",
"properties",
",",
"recursive",
")"
] | Adds new or modifies existing properties listed in properties
properties - is a dict which contains the property names and values to set.
Property values can be a list or tuple to set multiple values
for a key.
recursive - on folders property attachment is rec... | [
"Adds",
"new",
"or",
"modifies",
"existing",
"properties",
"listed",
"in",
"properties"
] | train | https://github.com/Parallels/artifactory/blob/09ddcc4ae15095eec2347d39774c3f8aca6c4654/artifactory.py#L1234-L1247 |
bbitmaster/ale_python_interface | ale_python_interface/ale_python_interface.py | ALEInterface.getScreenDims | def getScreenDims(self):
"""returns a tuple that contains (screen_width,screen_height)
"""
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenHeight(self.obj)
return (width,height) | python | def getScreenDims(self):
"""returns a tuple that contains (screen_width,screen_height)
"""
width = ale_lib.getScreenWidth(self.obj)
height = ale_lib.getScreenHeight(self.obj)
return (width,height) | [
"def",
"getScreenDims",
"(",
"self",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenHeight",
"(",
"self",
".",
"obj",
")",
"return",
"(",
"width",
",",
"height",
")"
] | returns a tuple that contains (screen_width,screen_height) | [
"returns",
"a",
"tuple",
"that",
"contains",
"(",
"screen_width",
"screen_height",
")"
] | train | https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L67-L72 |
bbitmaster/ale_python_interface | ale_python_interface/ale_python_interface.py | ALEInterface.getScreen | def getScreen(self,screen_data=None):
"""This function fills screen_data with the RAW Pixel data
screen_data MUST be a numpy array of uint8/int8. This could be initialized like so:
screen_data = np.array(w*h,dtype=np.uint8)
Notice, it must be width*height in size also
If it is No... | python | def getScreen(self,screen_data=None):
"""This function fills screen_data with the RAW Pixel data
screen_data MUST be a numpy array of uint8/int8. This could be initialized like so:
screen_data = np.array(w*h,dtype=np.uint8)
Notice, it must be width*height in size also
If it is No... | [
"def",
"getScreen",
"(",
"self",
",",
"screen_data",
"=",
"None",
")",
":",
"if",
"(",
"screen_data",
"is",
"None",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenWidth",
... | This function fills screen_data with the RAW Pixel data
screen_data MUST be a numpy array of uint8/int8. This could be initialized like so:
screen_data = np.array(w*h,dtype=np.uint8)
Notice, it must be width*height in size also
If it is None, then this function will initialize it
... | [
"This",
"function",
"fills",
"screen_data",
"with",
"the",
"RAW",
"Pixel",
"data",
"screen_data",
"MUST",
"be",
"a",
"numpy",
"array",
"of",
"uint8",
"/",
"int8",
".",
"This",
"could",
"be",
"initialized",
"like",
"so",
":",
"screen_data",
"=",
"np",
".",
... | train | https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L75-L88 |
bbitmaster/ale_python_interface | ale_python_interface/ale_python_interface.py | ALEInterface.getScreenRGB | def getScreenRGB(self,screen_data=None):
"""This function fills screen_data with the data
screen_data MUST be a numpy array of uint32/int32. This can be initialized like so:
screen_data = np.array(w*h,dtype=np.uint32)
Notice, it must be width*height in size also
If it is None, th... | python | def getScreenRGB(self,screen_data=None):
"""This function fills screen_data with the data
screen_data MUST be a numpy array of uint32/int32. This can be initialized like so:
screen_data = np.array(w*h,dtype=np.uint32)
Notice, it must be width*height in size also
If it is None, th... | [
"def",
"getScreenRGB",
"(",
"self",
",",
"screen_data",
"=",
"None",
")",
":",
"if",
"(",
"screen_data",
"is",
"None",
")",
":",
"width",
"=",
"ale_lib",
".",
"getScreenWidth",
"(",
"self",
".",
"obj",
")",
"height",
"=",
"ale_lib",
".",
"getScreenWidth"... | This function fills screen_data with the data
screen_data MUST be a numpy array of uint32/int32. This can be initialized like so:
screen_data = np.array(w*h,dtype=np.uint32)
Notice, it must be width*height in size also
If it is None, then this function will initialize it | [
"This",
"function",
"fills",
"screen_data",
"with",
"the",
"data",
"screen_data",
"MUST",
"be",
"a",
"numpy",
"array",
"of",
"uint32",
"/",
"int32",
".",
"This",
"can",
"be",
"initialized",
"like",
"so",
":",
"screen_data",
"=",
"np",
".",
"array",
"(",
... | train | https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L90-L102 |
bbitmaster/ale_python_interface | ale_python_interface/ale_python_interface.py | ALEInterface.getRAM | def getRAM(self,ram=None):
"""This function grabs the atari RAM.
ram MUST be a numpy array of uint8/int8. This can be initialized like so:
ram = np.array(ram_size,dtype=uint8)
Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function.
If it is None, ... | python | def getRAM(self,ram=None):
"""This function grabs the atari RAM.
ram MUST be a numpy array of uint8/int8. This can be initialized like so:
ram = np.array(ram_size,dtype=uint8)
Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function.
If it is None, ... | [
"def",
"getRAM",
"(",
"self",
",",
"ram",
"=",
"None",
")",
":",
"if",
"(",
"ram",
"is",
"None",
")",
":",
"ram_size",
"=",
"ale_lib",
".",
"getRAMSize",
"(",
"self",
".",
"obj",
")",
"ram",
"=",
"np",
".",
"zeros",
"(",
"ram_size",
",",
"dtype",... | This function grabs the atari RAM.
ram MUST be a numpy array of uint8/int8. This can be initialized like so:
ram = np.array(ram_size,dtype=uint8)
Notice: It must be ram_size where ram_size can be retrieved via the getRAMSize function.
If it is None, then this function will initialize it. | [
"This",
"function",
"grabs",
"the",
"atari",
"RAM",
".",
"ram",
"MUST",
"be",
"a",
"numpy",
"array",
"of",
"uint8",
"/",
"int8",
".",
"This",
"can",
"be",
"initialized",
"like",
"so",
":",
"ram",
"=",
"np",
".",
"array",
"(",
"ram_size",
"dtype",
"="... | train | https://github.com/bbitmaster/ale_python_interface/blob/253062be8e07fb738ea25982387b20af3712b615/ale_python_interface/ale_python_interface.py#L107-L117 |
gpoulter/python-ngram | scripts/csvjoin.py | lowstrip | def lowstrip(term):
"""Convert to lowercase and strip spaces"""
term = re.sub('\s+', ' ', term)
term = term.lower()
return term | python | def lowstrip(term):
"""Convert to lowercase and strip spaces"""
term = re.sub('\s+', ' ', term)
term = term.lower()
return term | [
"def",
"lowstrip",
"(",
"term",
")",
":",
"term",
"=",
"re",
".",
"sub",
"(",
"'\\s+'",
",",
"' '",
",",
"term",
")",
"term",
"=",
"term",
".",
"lower",
"(",
")",
"return",
"term"
] | Convert to lowercase and strip spaces | [
"Convert",
"to",
"lowercase",
"and",
"strip",
"spaces"
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/scripts/csvjoin.py#L16-L20 |
gpoulter/python-ngram | scripts/csvjoin.py | main | def main(left_path, left_column, right_path, right_column,
outfile, titles, join, minscore, count, warp):
"""Perform the similarity join"""
right_file = csv.reader(open(right_path, 'r'))
if titles:
right_header = next(right_file)
index = NGram((tuple(r) for r in right_file),
... | python | def main(left_path, left_column, right_path, right_column,
outfile, titles, join, minscore, count, warp):
"""Perform the similarity join"""
right_file = csv.reader(open(right_path, 'r'))
if titles:
right_header = next(right_file)
index = NGram((tuple(r) for r in right_file),
... | [
"def",
"main",
"(",
"left_path",
",",
"left_column",
",",
"right_path",
",",
"right_column",
",",
"outfile",
",",
"titles",
",",
"join",
",",
"minscore",
",",
"count",
",",
"warp",
")",
":",
"right_file",
"=",
"csv",
".",
"reader",
"(",
"open",
"(",
"r... | Perform the similarity join | [
"Perform",
"the",
"similarity",
"join"
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/scripts/csvjoin.py#L22-L46 |
gpoulter/python-ngram | scripts/csvjoin.py | console_main | def console_main():
"""Process command-line arguments."""
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument('-t', '--titles', action='store_true',
help='input files have column titles')
parser.add_argument(
'-j', '--j... | python | def console_main():
"""Process command-line arguments."""
from argparse import ArgumentParser
parser = ArgumentParser(description=__doc__)
parser.add_argument('-t', '--titles', action='store_true',
help='input files have column titles')
parser.add_argument(
'-j', '--j... | [
"def",
"console_main",
"(",
")",
":",
"from",
"argparse",
"import",
"ArgumentParser",
"parser",
"=",
"ArgumentParser",
"(",
"description",
"=",
"__doc__",
")",
"parser",
".",
"add_argument",
"(",
"'-t'",
",",
"'--titles'",
",",
"action",
"=",
"'store_true'",
"... | Process command-line arguments. | [
"Process",
"command",
"-",
"line",
"arguments",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/scripts/csvjoin.py#L48-L84 |
gpoulter/python-ngram | ngram.py | NGram.copy | def copy(self, items=None):
"""Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram import NGram
>>> from ... | python | def copy(self, items=None):
"""Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram import NGram
>>> from ... | [
"def",
"copy",
"(",
"self",
",",
"items",
"=",
"None",
")",
":",
"return",
"NGram",
"(",
"items",
"if",
"items",
"is",
"not",
"None",
"else",
"self",
",",
"self",
".",
"threshold",
",",
"self",
".",
"warp",
",",
"self",
".",
"_key",
",",
"self",
... | Return a new NGram object with the same settings, and
referencing the same items. Copy is shallow in that
each item is not recursively copied. Optionally specify
alternate items to populate the copy.
>>> from ngram import NGram
>>> from copy import deepcopy
>>> n = NG... | [
"Return",
"a",
"new",
"NGram",
"object",
"with",
"the",
"same",
"settings",
"and",
"referencing",
"the",
"same",
"items",
".",
"Copy",
"is",
"shallow",
"in",
"that",
"each",
"item",
"is",
"not",
"recursively",
"copied",
".",
"Optionally",
"specify",
"alterna... | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L127-L148 |
gpoulter/python-ngram | ngram.py | NGram._split | def _split(self, string):
"""Iterates over the ngrams of a string (no padding).
>>> from ngram import NGram
>>> n = NGram()
>>> list(n._split("hamegg"))
['ham', 'ame', 'meg', 'egg']
"""
for i in range(len(string) - self.N + 1):
yield string[i:i + self... | python | def _split(self, string):
"""Iterates over the ngrams of a string (no padding).
>>> from ngram import NGram
>>> n = NGram()
>>> list(n._split("hamegg"))
['ham', 'ame', 'meg', 'egg']
"""
for i in range(len(string) - self.N + 1):
yield string[i:i + self... | [
"def",
"_split",
"(",
"self",
",",
"string",
")",
":",
"for",
"i",
"in",
"range",
"(",
"len",
"(",
"string",
")",
"-",
"self",
".",
"N",
"+",
"1",
")",
":",
"yield",
"string",
"[",
"i",
":",
"i",
"+",
"self",
".",
"N",
"]"
] | Iterates over the ngrams of a string (no padding).
>>> from ngram import NGram
>>> n = NGram()
>>> list(n._split("hamegg"))
['ham', 'ame', 'meg', 'egg'] | [
"Iterates",
"over",
"the",
"ngrams",
"of",
"a",
"string",
"(",
"no",
"padding",
")",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L170-L179 |
gpoulter/python-ngram | ngram.py | NGram.add | def add(self, item):
"""Add an item to the N-gram index (if it has not already been added).
>>> from ngram import NGram
>>> n = NGram()
>>> n.add("ham")
>>> list(n)
['ham']
>>> n.add("spam")
>>> sorted(list(n))
['ham', 'spam']
"""
... | python | def add(self, item):
"""Add an item to the N-gram index (if it has not already been added).
>>> from ngram import NGram
>>> n = NGram()
>>> n.add("ham")
>>> list(n)
['ham']
>>> n.add("spam")
>>> sorted(list(n))
['ham', 'spam']
"""
... | [
"def",
"add",
"(",
"self",
",",
"item",
")",
":",
"if",
"item",
"not",
"in",
"self",
":",
"# Add the item to the base set",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"add",
"(",
"item",
")",
"# Record length of padded string",
"padded_item",
"=",
"self",... | Add an item to the N-gram index (if it has not already been added).
>>> from ngram import NGram
>>> n = NGram()
>>> n.add("ham")
>>> list(n)
['ham']
>>> n.add("spam")
>>> sorted(list(n))
['ham', 'spam'] | [
"Add",
"an",
"item",
"to",
"the",
"N",
"-",
"gram",
"index",
"(",
"if",
"it",
"has",
"not",
"already",
"been",
"added",
")",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L212-L234 |
gpoulter/python-ngram | ngram.py | NGram.items_sharing_ngrams | def items_sharing_ngrams(self, query):
"""Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NGram
>>> n =... | python | def items_sharing_ngrams(self, query):
"""Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NGram
>>> n =... | [
"def",
"items_sharing_ngrams",
"(",
"self",
",",
"query",
")",
":",
"# From matched string to number of N-grams shared with query string",
"shared",
"=",
"{",
"}",
"# Dictionary mapping n-gram to string to number of occurrences of that",
"# ngram in the string that remain to be matched."... | Retrieve the subset of items that share n-grams the query string.
:param query: look up items that share N-grams with this string.
:return: mapping from matched string to the number of shared N-grams.
>>> from ngram import NGram
>>> n = NGram(["ham","spam","eggs"])
>>> sorted(n... | [
"Retrieve",
"the",
"subset",
"of",
"items",
"that",
"share",
"n",
"-",
"grams",
"the",
"query",
"string",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L267-L294 |
gpoulter/python-ngram | ngram.py | NGram.searchitem | def searchitem(self, item, threshold=None):
"""Search the index for items whose key exceeds the threshold
similarity to the key of the given item.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGram
>>> n = NGram([(0, "SPAM"), (1, ... | python | def searchitem(self, item, threshold=None):
"""Search the index for items whose key exceeds the threshold
similarity to the key of the given item.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGram
>>> n = NGram([(0, "SPAM"), (1, ... | [
"def",
"searchitem",
"(",
"self",
",",
"item",
",",
"threshold",
"=",
"None",
")",
":",
"return",
"self",
".",
"search",
"(",
"self",
".",
"key",
"(",
"item",
")",
",",
"threshold",
")"
] | Search the index for items whose key exceeds the threshold
similarity to the key of the given item.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGram
>>> n = NGram([(0, "SPAM"), (1, "SPAN"), (2, "EG"),
... (3, "SPANN")], key=lamb... | [
"Search",
"the",
"index",
"for",
"items",
"whose",
"key",
"exceeds",
"the",
"threshold",
"similarity",
"to",
"the",
"key",
"of",
"the",
"given",
"item",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L296-L308 |
gpoulter/python-ngram | ngram.py | NGram.search | def search(self, query, threshold=None):
"""Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decre... | python | def search(self, query, threshold=None):
"""Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decre... | [
"def",
"search",
"(",
"self",
",",
"query",
",",
"threshold",
"=",
"None",
")",
":",
"threshold",
"=",
"threshold",
"if",
"threshold",
"is",
"not",
"None",
"else",
"self",
".",
"threshold",
"results",
"=",
"[",
"]",
"# Identify possible results",
"for",
"m... | Search the index for items whose key exceeds threshold
similarity to the query string.
:param query: returned items will have at least `threshold` \
similarity to the query string.
:return: list of pairs of (item, similarity) by decreasing similarity.
>>> from ngram import NGr... | [
"Search",
"the",
"index",
"for",
"items",
"whose",
"key",
"exceeds",
"threshold",
"similarity",
"to",
"the",
"query",
"string",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L310-L339 |
gpoulter/python-ngram | ngram.py | NGram.finditem | def finditem(self, item, threshold=None):
"""Return most similar item to the provided one, or None if
nothing exceeds the threshold.
>>> from ngram import NGram
>>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")],
... key=lambda x:x[1].lower())
>>> n... | python | def finditem(self, item, threshold=None):
"""Return most similar item to the provided one, or None if
nothing exceeds the threshold.
>>> from ngram import NGram
>>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")],
... key=lambda x:x[1].lower())
>>> n... | [
"def",
"finditem",
"(",
"self",
",",
"item",
",",
"threshold",
"=",
"None",
")",
":",
"results",
"=",
"self",
".",
"searchitem",
"(",
"item",
",",
"threshold",
")",
"if",
"results",
":",
"return",
"results",
"[",
"0",
"]",
"[",
"0",
"]",
"else",
":... | Return most similar item to the provided one, or None if
nothing exceeds the threshold.
>>> from ngram import NGram
>>> n = NGram([(0, "Spam"), (1, "Ham"), (2, "Eggsy"), (3, "Egggsy")],
... key=lambda x:x[1].lower())
>>> n.finditem((3, 'Hom'))
(1, 'Ham')
>>> ... | [
"Return",
"most",
"similar",
"item",
"to",
"the",
"provided",
"one",
"or",
"None",
"if",
"nothing",
"exceeds",
"the",
"threshold",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L341-L358 |
gpoulter/python-ngram | ngram.py | NGram.find | def find(self, query, threshold=None):
"""Simply return the best match to the query, None on no match.
>>> from ngram import NGram
>>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1)
>>> n.find('Hom')
'Ham'
>>> n.find("Spom")
'Spam'
>>> n.fi... | python | def find(self, query, threshold=None):
"""Simply return the best match to the query, None on no match.
>>> from ngram import NGram
>>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1)
>>> n.find('Hom')
'Ham'
>>> n.find("Spom")
'Spam'
>>> n.fi... | [
"def",
"find",
"(",
"self",
",",
"query",
",",
"threshold",
"=",
"None",
")",
":",
"results",
"=",
"self",
".",
"search",
"(",
"query",
",",
"threshold",
")",
"if",
"results",
":",
"return",
"results",
"[",
"0",
"]",
"[",
"0",
"]",
"else",
":",
"... | Simply return the best match to the query, None on no match.
>>> from ngram import NGram
>>> n = NGram(["Spam","Eggs","Ham"], key=lambda x:x.lower(), N=1)
>>> n.find('Hom')
'Ham'
>>> n.find("Spom")
'Spam'
>>> n.find("Spom", 0.8) | [
"Simply",
"return",
"the",
"best",
"match",
"to",
"the",
"query",
"None",
"on",
"no",
"match",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L360-L375 |
gpoulter/python-ngram | ngram.py | NGram.ngram_similarity | def ngram_similarity(samegrams, allgrams, warp=1.0):
"""Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:... | python | def ngram_similarity(samegrams, allgrams, warp=1.0):
"""Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:... | [
"def",
"ngram_similarity",
"(",
"samegrams",
",",
"allgrams",
",",
"warp",
"=",
"1.0",
")",
":",
"if",
"abs",
"(",
"warp",
"-",
"1.0",
")",
"<",
"1e-9",
":",
"similarity",
"=",
"float",
"(",
"samegrams",
")",
"/",
"allgrams",
"else",
":",
"diffgrams",
... | Similarity for two sets of n-grams.
:note: ``similarity = (a**e - d**e)/a**e`` where `a` is \
"all n-grams", `d` is "different n-grams" and `e` is the warp.
:param samegrams: number of n-grams shared by the two strings.
:param allgrams: total of the distinct n-grams across the two str... | [
"Similarity",
"for",
"two",
"sets",
"of",
"n",
"-",
"grams",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L378-L407 |
gpoulter/python-ngram | ngram.py | NGram.compare | def compare(s1, s2, **kwargs):
"""Compares two strings and returns their similarity.
:param s1: first string
:param s2: second string
:param kwargs: additional keyword arguments passed to __init__.
:return: similarity between 0.0 and 1.0.
>>> from ngram import NGram
... | python | def compare(s1, s2, **kwargs):
"""Compares two strings and returns their similarity.
:param s1: first string
:param s2: second string
:param kwargs: additional keyword arguments passed to __init__.
:return: similarity between 0.0 and 1.0.
>>> from ngram import NGram
... | [
"def",
"compare",
"(",
"s1",
",",
"s2",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"s1",
"is",
"None",
"or",
"s2",
"is",
"None",
":",
"if",
"s1",
"==",
"s2",
":",
"return",
"1.0",
"return",
"0.0",
"try",
":",
"return",
"NGram",
"(",
"[",
"s1",
... | Compares two strings and returns their similarity.
:param s1: first string
:param s2: second string
:param kwargs: additional keyword arguments passed to __init__.
:return: similarity between 0.0 and 1.0.
>>> from ngram import NGram
>>> NGram.compare('spa', 'spam')
... | [
"Compares",
"two",
"strings",
"and",
"returns",
"their",
"similarity",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L410-L435 |
gpoulter/python-ngram | ngram.py | NGram.clear | def clear(self):
"""Remove all elements from this set.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> sorted(list(n))
['eggs', 'spam']
>>> n.clear()
>>> list(n)
[]
"""
super(NGram, self).clear()
self._grams = {}
... | python | def clear(self):
"""Remove all elements from this set.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> sorted(list(n))
['eggs', 'spam']
>>> n.clear()
>>> list(n)
[]
"""
super(NGram, self).clear()
self._grams = {}
... | [
"def",
"clear",
"(",
"self",
")",
":",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"clear",
"(",
")",
"self",
".",
"_grams",
"=",
"{",
"}",
"self",
".",
"length",
"=",
"{",
"}"
] | Remove all elements from this set.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> sorted(list(n))
['eggs', 'spam']
>>> n.clear()
>>> list(n)
[] | [
"Remove",
"all",
"elements",
"from",
"this",
"set",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L466-L479 |
gpoulter/python-ngram | ngram.py | NGram.union | def union(self, *others):
"""Return the union of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.union(b)))
['eggs', 'ham', 'spam']
"""
return self.copy(super(NGra... | python | def union(self, *others):
"""Return the union of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.union(b)))
['eggs', 'ham', 'spam']
"""
return self.copy(super(NGra... | [
"def",
"union",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"copy",
"(",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"union",
"(",
"*",
"others",
")",
")"
] | Return the union of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.union(b)))
['eggs', 'ham', 'spam'] | [
"Return",
"the",
"union",
"of",
"two",
"or",
"more",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L481-L490 |
gpoulter/python-ngram | ngram.py | NGram.difference | def difference(self, *others):
"""Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs']
"""
return self.copy(super(NGram, self)... | python | def difference(self, *others):
"""Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs']
"""
return self.copy(super(NGram, self)... | [
"def",
"difference",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"copy",
"(",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"difference",
"(",
"*",
"others",
")",
")"
] | Return the difference of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.difference(b))
['eggs'] | [
"Return",
"the",
"difference",
"of",
"two",
"or",
"more",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L492-L501 |
gpoulter/python-ngram | ngram.py | NGram.intersection | def intersection(self, *others):
"""Return the intersection of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.intersection(b))
['spam']
"""
return self.copy(super(NGram,... | python | def intersection(self, *others):
"""Return the intersection of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.intersection(b))
['spam']
"""
return self.copy(super(NGram,... | [
"def",
"intersection",
"(",
"self",
",",
"*",
"others",
")",
":",
"return",
"self",
".",
"copy",
"(",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"intersection",
"(",
"*",
"others",
")",
")"
] | Return the intersection of two or more sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> list(a.intersection(b))
['spam'] | [
"Return",
"the",
"intersection",
"of",
"two",
"or",
"more",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L516-L525 |
gpoulter/python-ngram | ngram.py | NGram.intersection_update | def intersection_update(self, *others):
"""Update the set with the intersection of itself and other sets.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.intersection_update(other)
>>> list(n)
['spam']
""... | python | def intersection_update(self, *others):
"""Update the set with the intersection of itself and other sets.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.intersection_update(other)
>>> list(n)
['spam']
""... | [
"def",
"intersection_update",
"(",
"self",
",",
"*",
"others",
")",
":",
"self",
".",
"difference_update",
"(",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"difference",
"(",
"*",
"others",
")",
")"
] | Update the set with the intersection of itself and other sets.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.intersection_update(other)
>>> list(n)
['spam'] | [
"Update",
"the",
"set",
"with",
"the",
"intersection",
"of",
"itself",
"and",
"other",
"sets",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L527-L537 |
gpoulter/python-ngram | ngram.py | NGram.symmetric_difference | def symmetric_difference(self, other):
"""Return the symmetric difference of two sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.symmetric_difference(b)))
['eggs', 'ham']
"""
... | python | def symmetric_difference(self, other):
"""Return the symmetric difference of two sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.symmetric_difference(b)))
['eggs', 'ham']
"""
... | [
"def",
"symmetric_difference",
"(",
"self",
",",
"other",
")",
":",
"return",
"self",
".",
"copy",
"(",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"symmetric_difference",
"(",
"other",
")",
")"
] | Return the symmetric difference of two sets as a new set.
>>> from ngram import NGram
>>> a = NGram(['spam', 'eggs'])
>>> b = NGram(['spam', 'ham'])
>>> sorted(list(a.symmetric_difference(b)))
['eggs', 'ham'] | [
"Return",
"the",
"symmetric",
"difference",
"of",
"two",
"sets",
"as",
"a",
"new",
"set",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L539-L548 |
gpoulter/python-ngram | ngram.py | NGram.symmetric_difference_update | def symmetric_difference_update(self, other):
"""Update the set with the symmetric difference of itself and `other`.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.symmetric_difference_update(other)
>>> sorted(list(n))
... | python | def symmetric_difference_update(self, other):
"""Update the set with the symmetric difference of itself and `other`.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.symmetric_difference_update(other)
>>> sorted(list(n))
... | [
"def",
"symmetric_difference_update",
"(",
"self",
",",
"other",
")",
":",
"intersection",
"=",
"super",
"(",
"NGram",
",",
"self",
")",
".",
"intersection",
"(",
"other",
")",
"self",
".",
"update",
"(",
"other",
")",
"# add items present in other",
"self",
... | Update the set with the symmetric difference of itself and `other`.
>>> from ngram import NGram
>>> n = NGram(['spam', 'eggs'])
>>> other = set(['spam', 'ham'])
>>> n.symmetric_difference_update(other)
>>> sorted(list(n))
['eggs', 'ham'] | [
"Update",
"the",
"set",
"with",
"the",
"symmetric",
"difference",
"of",
"itself",
"and",
"other",
"."
] | train | https://github.com/gpoulter/python-ngram/blob/f8543bdc84a4d24ac60a48b36c4034f881664491/ngram.py#L550-L562 |
dbrgn/django-mathfilters | mathfilters/templatetags/mathfilters.py | sub | def sub(value, arg):
"""Subtract the arg from the value."""
try:
nvalue, narg = handle_float_decimal_combinations(
valid_numeric(value), valid_numeric(arg), '-')
return nvalue - narg
except (ValueError, TypeError):
try:
return value - arg
except Except... | python | def sub(value, arg):
"""Subtract the arg from the value."""
try:
nvalue, narg = handle_float_decimal_combinations(
valid_numeric(value), valid_numeric(arg), '-')
return nvalue - narg
except (ValueError, TypeError):
try:
return value - arg
except Except... | [
"def",
"sub",
"(",
"value",
",",
"arg",
")",
":",
"try",
":",
"nvalue",
",",
"narg",
"=",
"handle_float_decimal_combinations",
"(",
"valid_numeric",
"(",
"value",
")",
",",
"valid_numeric",
"(",
"arg",
")",
",",
"'-'",
")",
"return",
"nvalue",
"-",
"narg... | Subtract the arg from the value. | [
"Subtract",
"the",
"arg",
"from",
"the",
"value",
"."
] | train | https://github.com/dbrgn/django-mathfilters/blob/7f22f98e906d46bee487ce2d78fb995f74c1d568/mathfilters/templatetags/mathfilters.py#L37-L47 |
dbrgn/django-mathfilters | mathfilters/templatetags/mathfilters.py | absolute | def absolute(value):
"""Return the absolute value."""
try:
return abs(valid_numeric(value))
except (ValueError, TypeError):
try:
return abs(value)
except Exception:
return '' | python | def absolute(value):
"""Return the absolute value."""
try:
return abs(valid_numeric(value))
except (ValueError, TypeError):
try:
return abs(value)
except Exception:
return '' | [
"def",
"absolute",
"(",
"value",
")",
":",
"try",
":",
"return",
"abs",
"(",
"valid_numeric",
"(",
"value",
")",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"try",
":",
"return",
"abs",
"(",
"value",
")",
"except",
"Exception",
":",
... | Return the absolute value. | [
"Return",
"the",
"absolute",
"value",
"."
] | train | https://github.com/dbrgn/django-mathfilters/blob/7f22f98e906d46bee487ce2d78fb995f74c1d568/mathfilters/templatetags/mathfilters.py#L97-L105 |
Scifabric/pbs | pbs.py | cli | def cli(config, server, api_key, all, credentials, project):
"""Create the cli command line."""
# Check first for the pybossa.rc file to configure server and api-key
home = expanduser("~")
if os.path.isfile(os.path.join(home, '.pybossa.cfg')):
config.parser.read(os.path.join(home, '.pybossa.cfg'... | python | def cli(config, server, api_key, all, credentials, project):
"""Create the cli command line."""
# Check first for the pybossa.rc file to configure server and api-key
home = expanduser("~")
if os.path.isfile(os.path.join(home, '.pybossa.cfg')):
config.parser.read(os.path.join(home, '.pybossa.cfg'... | [
"def",
"cli",
"(",
"config",
",",
"server",
",",
"api_key",
",",
"all",
",",
"credentials",
",",
"project",
")",
":",
"# Check first for the pybossa.rc file to configure server and api-key",
"home",
"=",
"expanduser",
"(",
"\"~\"",
")",
"if",
"os",
".",
"path",
... | Create the cli command line. | [
"Create",
"the",
"cli",
"command",
"line",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L65-L109 |
Scifabric/pbs | pbs.py | version | def version():
"""Show pbs version."""
try:
import pkg_resources
click.echo(pkg_resources.get_distribution('pybossa-pbs').version)
except ImportError:
click.echo("pybossa-pbs package not found!") | python | def version():
"""Show pbs version."""
try:
import pkg_resources
click.echo(pkg_resources.get_distribution('pybossa-pbs').version)
except ImportError:
click.echo("pybossa-pbs package not found!") | [
"def",
"version",
"(",
")",
":",
"try",
":",
"import",
"pkg_resources",
"click",
".",
"echo",
"(",
"pkg_resources",
".",
"get_distribution",
"(",
"'pybossa-pbs'",
")",
".",
"version",
")",
"except",
"ImportError",
":",
"click",
".",
"echo",
"(",
"\"pybossa-p... | Show pbs version. | [
"Show",
"pbs",
"version",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L113-L119 |
Scifabric/pbs | pbs.py | update_project | def update_project(config, task_presenter, results,
long_description, tutorial, watch): # pragma: no cover
"""Update project templates and information."""
if watch:
res = _update_project_watch(config, task_presenter, results,
long_description, tutor... | python | def update_project(config, task_presenter, results,
long_description, tutorial, watch): # pragma: no cover
"""Update project templates and information."""
if watch:
res = _update_project_watch(config, task_presenter, results,
long_description, tutor... | [
"def",
"update_project",
"(",
"config",
",",
"task_presenter",
",",
"results",
",",
"long_description",
",",
"tutorial",
",",
"watch",
")",
":",
"# pragma: no cover",
"if",
"watch",
":",
"res",
"=",
"_update_project_watch",
"(",
"config",
",",
"task_presenter",
... | Update project templates and information. | [
"Update",
"project",
"templates",
"and",
"information",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L141-L150 |
Scifabric/pbs | pbs.py | add_tasks | def add_tasks(config, tasks_file, tasks_type, priority, redundancy):
"""Add tasks to a project."""
res = _add_tasks(config, tasks_file, tasks_type, priority, redundancy)
click.echo(res) | python | def add_tasks(config, tasks_file, tasks_type, priority, redundancy):
"""Add tasks to a project."""
res = _add_tasks(config, tasks_file, tasks_type, priority, redundancy)
click.echo(res) | [
"def",
"add_tasks",
"(",
"config",
",",
"tasks_file",
",",
"tasks_type",
",",
"priority",
",",
"redundancy",
")",
":",
"res",
"=",
"_add_tasks",
"(",
"config",
",",
"tasks_file",
",",
"tasks_type",
",",
"priority",
",",
"redundancy",
")",
"click",
".",
"ec... | Add tasks to a project. | [
"Add",
"tasks",
"to",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L162-L165 |
Scifabric/pbs | pbs.py | add_helpingmaterials | def add_helpingmaterials(config, helping_materials_file, helping_type):
"""Add helping materials to a project."""
res = _add_helpingmaterials(config, helping_materials_file, helping_type)
click.echo(res) | python | def add_helpingmaterials(config, helping_materials_file, helping_type):
"""Add helping materials to a project."""
res = _add_helpingmaterials(config, helping_materials_file, helping_type)
click.echo(res) | [
"def",
"add_helpingmaterials",
"(",
"config",
",",
"helping_materials_file",
",",
"helping_type",
")",
":",
"res",
"=",
"_add_helpingmaterials",
"(",
"config",
",",
"helping_materials_file",
",",
"helping_type",
")",
"click",
".",
"echo",
"(",
"res",
")"
] | Add helping materials to a project. | [
"Add",
"helping",
"materials",
"to",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L175-L178 |
Scifabric/pbs | pbs.py | delete_tasks | def delete_tasks(config, task_id):
"""Delete tasks from a project."""
if task_id is None:
msg = ("Are you sure you want to delete all the tasks and associated task runs?")
if click.confirm(msg):
res = _delete_tasks(config, task_id)
click.echo(res)
else:
... | python | def delete_tasks(config, task_id):
"""Delete tasks from a project."""
if task_id is None:
msg = ("Are you sure you want to delete all the tasks and associated task runs?")
if click.confirm(msg):
res = _delete_tasks(config, task_id)
click.echo(res)
else:
... | [
"def",
"delete_tasks",
"(",
"config",
",",
"task_id",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Are you sure you want to delete all the tasks and associated task runs?\"",
")",
"if",
"click",
".",
"confirm",
"(",
"msg",
")",
":",
"res",
"... | Delete tasks from a project. | [
"Delete",
"tasks",
"from",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L184-L196 |
Scifabric/pbs | pbs.py | update_task_redundancy | def update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project."""
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundancy?")
if click.confirm(msg):
res = _update_tasks_redundancy(config, task_id, redundancy)
c... | python | def update_task_redundancy(config, task_id, redundancy):
"""Update task redudancy for a project."""
if task_id is None:
msg = ("Are you sure you want to update all the tasks redundancy?")
if click.confirm(msg):
res = _update_tasks_redundancy(config, task_id, redundancy)
c... | [
"def",
"update_task_redundancy",
"(",
"config",
",",
"task_id",
",",
"redundancy",
")",
":",
"if",
"task_id",
"is",
"None",
":",
"msg",
"=",
"(",
"\"Are you sure you want to update all the tasks redundancy?\"",
")",
"if",
"click",
".",
"confirm",
"(",
"msg",
")",
... | Update task redudancy for a project. | [
"Update",
"task",
"redudancy",
"for",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/pbs.py#L202-L214 |
Scifabric/pbs | helpers.py | _create_project | def _create_project(config):
"""Create a project in a PyBossa server."""
try:
response = config.pbclient.create_project(config.project['name'],
config.project['short_name'],
config.project['description'])... | python | def _create_project(config):
"""Create a project in a PyBossa server."""
try:
response = config.pbclient.create_project(config.project['name'],
config.project['short_name'],
config.project['description'])... | [
"def",
"_create_project",
"(",
"config",
")",
":",
"try",
":",
"response",
"=",
"config",
".",
"pbclient",
".",
"create_project",
"(",
"config",
".",
"project",
"[",
"'name'",
"]",
",",
"config",
".",
"project",
"[",
"'short_name'",
"]",
",",
"config",
"... | Create a project in a PyBossa server. | [
"Create",
"a",
"project",
"in",
"a",
"PyBossa",
"server",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L57-L68 |
Scifabric/pbs | helpers.py | _update_project_watch | def _update_project_watch(config, task_presenter, results,
long_description, tutorial): # pragma: no cover
"""Update a project in a loop."""
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H... | python | def _update_project_watch(config, task_presenter, results,
long_description, tutorial): # pragma: no cover
"""Update a project in a loop."""
logging.basicConfig(level=logging.INFO,
format='%(asctime)s - %(message)s',
datefmt='%Y-%m-%d %H... | [
"def",
"_update_project_watch",
"(",
"config",
",",
"task_presenter",
",",
"results",
",",
"long_description",
",",
"tutorial",
")",
":",
"# pragma: no cover",
"logging",
".",
"basicConfig",
"(",
"level",
"=",
"logging",
".",
"INFO",
",",
"format",
"=",
"'%(asct... | Update a project in a loop. | [
"Update",
"a",
"project",
"in",
"a",
"loop",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L70-L88 |
Scifabric/pbs | helpers.py | _update_task_presenter_bundle_js | def _update_task_presenter_bundle_js(project):
"""Append to template a distribution bundle js."""
if os.path.isfile ('bundle.min.js'):
with open('bundle.min.js') as f:
js = f.read()
project.info['task_presenter'] += "<script>\n%s\n</script>" % js
return
if os.path.isfile... | python | def _update_task_presenter_bundle_js(project):
"""Append to template a distribution bundle js."""
if os.path.isfile ('bundle.min.js'):
with open('bundle.min.js') as f:
js = f.read()
project.info['task_presenter'] += "<script>\n%s\n</script>" % js
return
if os.path.isfile... | [
"def",
"_update_task_presenter_bundle_js",
"(",
"project",
")",
":",
"if",
"os",
".",
"path",
".",
"isfile",
"(",
"'bundle.min.js'",
")",
":",
"with",
"open",
"(",
"'bundle.min.js'",
")",
"as",
"f",
":",
"js",
"=",
"f",
".",
"read",
"(",
")",
"project",
... | Append to template a distribution bundle js. | [
"Append",
"to",
"template",
"a",
"distribution",
"bundle",
"js",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L90-L101 |
Scifabric/pbs | helpers.py | _update_project | def _update_project(config, task_presenter, results,
long_description, tutorial):
"""Update a project."""
try:
# Get project
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
... | python | def _update_project(config, task_presenter, results,
long_description, tutorial):
"""Update a project."""
try:
# Get project
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
... | [
"def",
"_update_project",
"(",
"config",
",",
"task_presenter",
",",
"results",
",",
"long_description",
",",
"tutorial",
")",
":",
"try",
":",
"# Get project",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
... | Update a project. | [
"Update",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L103-L138 |
Scifabric/pbs | helpers.py | _load_data | def _load_data(data_file, data_type):
"""Load data from CSV, JSON, Excel, ..., formats."""
raw_data = data_file.read()
if data_type is None:
data_type = data_file.name.split('.')[-1]
# Data list to process
data = []
# JSON type
if data_type == 'json':
data = json.loads(raw_da... | python | def _load_data(data_file, data_type):
"""Load data from CSV, JSON, Excel, ..., formats."""
raw_data = data_file.read()
if data_type is None:
data_type = data_file.name.split('.')[-1]
# Data list to process
data = []
# JSON type
if data_type == 'json':
data = json.loads(raw_da... | [
"def",
"_load_data",
"(",
"data_file",
",",
"data_type",
")",
":",
"raw_data",
"=",
"data_file",
".",
"read",
"(",
")",
"if",
"data_type",
"is",
"None",
":",
"data_type",
"=",
"data_file",
".",
"name",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"1",
"]... | Load data from CSV, JSON, Excel, ..., formats. | [
"Load",
"data",
"from",
"CSV",
"JSON",
"Excel",
"...",
"formats",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L141-L194 |
Scifabric/pbs | helpers.py | _add_tasks | def _add_tasks(config, tasks_file, tasks_type, priority, redundancy):
"""Add tasks to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
data ... | python | def _add_tasks(config, tasks_file, tasks_type, priority, redundancy):
"""Add tasks to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
data ... | [
"def",
"_add_tasks",
"(",
"config",
",",
"tasks_file",
",",
"tasks_type",
",",
"priority",
",",
"redundancy",
")",
":",
"try",
":",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
",",
"config",
".",
"pb... | Add tasks to a project. | [
"Add",
"tasks",
"to",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L197-L230 |
Scifabric/pbs | helpers.py | _add_helpingmaterials | def _add_helpingmaterials(config, helping_file, helping_type):
"""Add helping materials to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
... | python | def _add_helpingmaterials(config, helping_file, helping_type):
"""Add helping materials to a project."""
try:
project = find_project_by_short_name(config.project['short_name'],
config.pbclient,
config.all)
... | [
"def",
"_add_helpingmaterials",
"(",
"config",
",",
"helping_file",
",",
"helping_type",
")",
":",
"try",
":",
"project",
"=",
"find_project_by_short_name",
"(",
"config",
".",
"project",
"[",
"'short_name'",
"]",
",",
"config",
".",
"pbclient",
",",
"config",
... | Add helping materials to a project. | [
"Add",
"helping",
"materials",
"to",
"a",
"project",
"."
] | train | https://github.com/Scifabric/pbs/blob/3e5d5f3f0f5d20f740eaacc4d6e872a0c9fb8b38/helpers.py#L233-L277 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.