repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
arokem/python-matlab-bridge | tools/gh_api.py | get_pull_request_files | def get_pull_request_files(project, num, auth=False):
"""get list of files in a pull request"""
url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header) | python | def get_pull_request_files(project, num, auth=False):
"""get list of files in a pull request"""
url = "https://api.github.com/repos/{project}/pulls/{num}/files".format(project=project, num=num)
if auth:
header = make_auth_header()
else:
header = None
return get_paged_request(url, headers=header) | [
"def",
"get_pull_request_files",
"(",
"project",
",",
"num",
",",
"auth",
"=",
"False",
")",
":",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls/{num}/files\"",
".",
"format",
"(",
"project",
"=",
"project",
",",
"num",
"=",
"num",
")",
"if",
"auth"... | get list of files in a pull request | [
"get",
"list",
"of",
"files",
"in",
"a",
"pull",
"request"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L110-L117 | train | 48,100 |
arokem/python-matlab-bridge | tools/gh_api.py | get_paged_request | def get_paged_request(url, headers=None, **params):
"""get a full list, handling APIv3's paging"""
results = []
params.setdefault("per_page", 100)
while True:
if '?' in url:
params = None
print("fetching %s" % url, file=sys.stderr)
else:
print("fetching %s with %s" % (url, params), file=sys.stderr)
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
results.extend(response.json())
if 'next' in response.links:
url = response.links['next']['url']
else:
break
return results | python | def get_paged_request(url, headers=None, **params):
"""get a full list, handling APIv3's paging"""
results = []
params.setdefault("per_page", 100)
while True:
if '?' in url:
params = None
print("fetching %s" % url, file=sys.stderr)
else:
print("fetching %s with %s" % (url, params), file=sys.stderr)
response = requests.get(url, headers=headers, params=params)
response.raise_for_status()
results.extend(response.json())
if 'next' in response.links:
url = response.links['next']['url']
else:
break
return results | [
"def",
"get_paged_request",
"(",
"url",
",",
"headers",
"=",
"None",
",",
"*",
"*",
"params",
")",
":",
"results",
"=",
"[",
"]",
"params",
".",
"setdefault",
"(",
"\"per_page\"",
",",
"100",
")",
"while",
"True",
":",
"if",
"'?'",
"in",
"url",
":",
... | get a full list, handling APIv3's paging | [
"get",
"a",
"full",
"list",
"handling",
"APIv3",
"s",
"paging"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L122-L139 | train | 48,101 |
arokem/python-matlab-bridge | tools/gh_api.py | get_pulls_list | def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if auth:
headers = make_auth_header()
else:
headers = None
pages = get_paged_request(url, headers=headers, **params)
return pages | python | def get_pulls_list(project, auth=False, **params):
"""get pull request list"""
params.setdefault("state", "closed")
url = "https://api.github.com/repos/{project}/pulls".format(project=project)
if auth:
headers = make_auth_header()
else:
headers = None
pages = get_paged_request(url, headers=headers, **params)
return pages | [
"def",
"get_pulls_list",
"(",
"project",
",",
"auth",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"params",
".",
"setdefault",
"(",
"\"state\"",
",",
"\"closed\"",
")",
"url",
"=",
"\"https://api.github.com/repos/{project}/pulls\"",
".",
"format",
"(",
"p... | get pull request list | [
"get",
"pull",
"request",
"list"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L141-L150 | train | 48,102 |
arokem/python-matlab-bridge | tools/gh_api.py | post_download | def post_download(project, filename, name=None, description=""):
"""Upload a file to the GitHub downloads area"""
if name is None:
name = os.path.basename(filename)
with open(filename, 'rb') as f:
filedata = f.read()
url = "https://api.github.com/repos/{project}/downloads".format(project=project)
payload = json.dumps(dict(name=name, size=len(filedata),
description=description))
response = requests.post(url, data=payload, headers=make_auth_header())
response.raise_for_status()
reply = json.loads(response.content)
s3_url = reply['s3_url']
fields = dict(
key=reply['path'],
acl=reply['acl'],
success_action_status=201,
Filename=reply['name'],
AWSAccessKeyId=reply['accesskeyid'],
Policy=reply['policy'],
Signature=reply['signature'],
file=(reply['name'], filedata),
)
fields['Content-Type'] = reply['mime_type']
data, content_type = encode_multipart_formdata(fields)
s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type})
return s3r | python | def post_download(project, filename, name=None, description=""):
"""Upload a file to the GitHub downloads area"""
if name is None:
name = os.path.basename(filename)
with open(filename, 'rb') as f:
filedata = f.read()
url = "https://api.github.com/repos/{project}/downloads".format(project=project)
payload = json.dumps(dict(name=name, size=len(filedata),
description=description))
response = requests.post(url, data=payload, headers=make_auth_header())
response.raise_for_status()
reply = json.loads(response.content)
s3_url = reply['s3_url']
fields = dict(
key=reply['path'],
acl=reply['acl'],
success_action_status=201,
Filename=reply['name'],
AWSAccessKeyId=reply['accesskeyid'],
Policy=reply['policy'],
Signature=reply['signature'],
file=(reply['name'], filedata),
)
fields['Content-Type'] = reply['mime_type']
data, content_type = encode_multipart_formdata(fields)
s3r = requests.post(s3_url, data=data, headers={'Content-Type': content_type})
return s3r | [
"def",
"post_download",
"(",
"project",
",",
"filename",
",",
"name",
"=",
"None",
",",
"description",
"=",
"\"\"",
")",
":",
"if",
"name",
"is",
"None",
":",
"name",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
"with",
"open",
"(",... | Upload a file to the GitHub downloads area | [
"Upload",
"a",
"file",
"to",
"the",
"GitHub",
"downloads",
"area"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/tools/gh_api.py#L263-L292 | train | 48,103 |
arokem/python-matlab-bridge | pymatbridge/messenger/make.py | build_matlab | def build_matlab(static=False):
"""build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq.
"""
cfg = get_config()
# To deal with spaces, remove quotes now, and add
# to the full commands themselves.
if 'matlab_bin' in cfg and cfg['matlab_bin'] != '.':
matlab_bin = cfg['matlab_bin'].strip('"')
else: # attempt to autodetect MATLAB filepath
matlab_bin = which_matlab()
if matlab_bin is None:
raise ValueError("specify 'matlab_bin' in cfg file")
# Get the extension
extcmd = esc(os.path.join(matlab_bin, "mexext"))
extension = subprocess.check_output(extcmd, shell=use_shell)
extension = extension.decode('utf-8').rstrip('\r\n')
# Build the mex file
mex = esc(os.path.join(matlab_bin, "mex"))
paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg
make_cmd = '%s -O %s -lzmq ./src/messenger.c' % (mex, paths)
if static:
make_cmd += ' -DZMQ_STATIC'
do_build(make_cmd, 'messenger.%s' % extension) | python | def build_matlab(static=False):
"""build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq.
"""
cfg = get_config()
# To deal with spaces, remove quotes now, and add
# to the full commands themselves.
if 'matlab_bin' in cfg and cfg['matlab_bin'] != '.':
matlab_bin = cfg['matlab_bin'].strip('"')
else: # attempt to autodetect MATLAB filepath
matlab_bin = which_matlab()
if matlab_bin is None:
raise ValueError("specify 'matlab_bin' in cfg file")
# Get the extension
extcmd = esc(os.path.join(matlab_bin, "mexext"))
extension = subprocess.check_output(extcmd, shell=use_shell)
extension = extension.decode('utf-8').rstrip('\r\n')
# Build the mex file
mex = esc(os.path.join(matlab_bin, "mex"))
paths = "-L%(zmq_lib)s -I%(zmq_inc)s" % cfg
make_cmd = '%s -O %s -lzmq ./src/messenger.c' % (mex, paths)
if static:
make_cmd += ' -DZMQ_STATIC'
do_build(make_cmd, 'messenger.%s' % extension) | [
"def",
"build_matlab",
"(",
"static",
"=",
"False",
")",
":",
"cfg",
"=",
"get_config",
"(",
")",
"# To deal with spaces, remove quotes now, and add",
"# to the full commands themselves.",
"if",
"'matlab_bin'",
"in",
"cfg",
"and",
"cfg",
"[",
"'matlab_bin'",
"]",
"!="... | build the messenger mex for MATLAB
static : bool
Determines if the zmq library has been statically linked.
If so, it will append the command line option -DZMQ_STATIC
when compiling the mex so it matches libzmq. | [
"build",
"the",
"messenger",
"mex",
"for",
"MATLAB"
] | 9822c7b55435662f4f033c5479cc03fea2255755 | https://github.com/arokem/python-matlab-bridge/blob/9822c7b55435662f4f033c5479cc03fea2255755/pymatbridge/messenger/make.py#L242-L270 | train | 48,104 |
sixty-north/asq | asq/queryables.py | Queryable.select | def select(
self,
selector):
'''Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select() on a closed Queryable.")
try:
selector = make_selector(selector)
except ValueError:
raise TypeError("select() parameter selector={selector} cannot be"
"converted into a callable "
"selector".format(selector=repr(selector)))
if selector is identity:
return self
return self._create(imap(selector, self)) | python | def select(
self,
selector):
'''Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select() on a closed Queryable.")
try:
selector = make_selector(selector)
except ValueError:
raise TypeError("select() parameter selector={selector} cannot be"
"converted into a callable "
"selector".format(selector=repr(selector)))
if selector is identity:
return self
return self._create(imap(selector, self)) | [
"def",
"select",
"(",
"self",
",",
"selector",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select() on a closed Queryable.\"",
")",
"try",
":",
"selector",
"=",
"make_selector",
"(",
"selector",
")",
"ex... | Transforms each element of a sequence into a new form.
Each element of the source is transformed through a selector function
to produce a corresponding element in teh result sequence.
If the selector is identity the method will return self.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the corresponding value in the generated generated sequence.
The single positional argument to the selector function is the
element value. The return value of the selector function
should be the corresponding element of the result sequence.
Returns:
A Queryable over generated sequence whose elements are the result
of invoking the selector function on each element of the source
sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable. | [
"Transforms",
"each",
"element",
"of",
"a",
"sequence",
"into",
"a",
"new",
"form",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L151-L192 | train | 48,105 |
sixty-north/asq | asq/queryables.py | Queryable.select_with_index | def select_with_index(
self,
selector=IndexedElement,
transform=identity):
'''Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_index() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_index() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(transform):
raise TypeError("select_with_index() parameter item_selector={0} is "
"not callable".format(repr(selector)))
return self._create(itertools.starmap(selector, enumerate(imap(transform, iter(self))))) | python | def select_with_index(
self,
selector=IndexedElement,
transform=identity):
'''Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_index() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_index() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(transform):
raise TypeError("select_with_index() parameter item_selector={0} is "
"not callable".format(repr(selector)))
return self._create(itertools.starmap(selector, enumerate(imap(transform, iter(self))))) | [
"def",
"select_with_index",
"(",
"self",
",",
"selector",
"=",
"IndexedElement",
",",
"transform",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_index() on a \"",
"\"closed Queryable... | Transforms each element of a sequence into a new form, incorporating
the index of the element.
Each element is transformed through a selector function which accepts
the element value and its zero-based index in the source sequence. The
generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A binary function mapping the index of a value in
the source sequence and the element value itself to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the zero-
based index of the current element and the value of the current
element. The return value should be the corresponding value in
the result sequence. The default selector produces an IndexedElement
containing the index and the element giving this function
similar behaviour to the built-in enumerate().
Returns:
A Queryable whose elements are the result of invoking the selector
function on each element of the source sequence
Raises:
ValueError: If this Queryable has been closed.
TypeError: If selector is not callable. | [
"Transforms",
"each",
"element",
"of",
"a",
"sequence",
"into",
"a",
"new",
"form",
"incorporating",
"the",
"index",
"of",
"the",
"element",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L194-L238 | train | 48,106 |
sixty-north/asq | asq/queryables.py | Queryable.select_with_correspondence | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_correspondence() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_correspondence() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(result_selector):
raise TypeError("select_with_correspondence() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(elem, selector(elem)) for elem in iter(self)) | python | def select_with_correspondence(
self,
selector,
result_selector=KeyedElement):
'''Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_with_correspondence() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("select_with_correspondence() parameter selector={0} is "
"not callable".format(repr(selector)))
if not is_callable(result_selector):
raise TypeError("select_with_correspondence() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(elem, selector(elem)) for elem in iter(self)) | [
"def",
"select_with_correspondence",
"(",
"self",
",",
"selector",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_with_correspondence() on a \"",
"\"closed Queryabl... | Apply a callable to each element in an input sequence, generating a new
sequence of 2-tuples where the first element is the input value and the
second is the transformed input value.
The generated sequence is lazily evaluated.
Note: This method uses deferred execution.
Args:
selector: A unary function mapping a value in the source sequence
to the second argument of the result selector.
result_selector: A binary callable mapping the of a value in
the source sequence and the transformed value to the
corresponding value in the generated sequence. The two
positional arguments of the selector function are the original
source element and the transformed value. The return value
should be the corresponding value in the result sequence. The
default selector produces a KeyedElement containing the index
and the element giving this function similar behaviour to the
built-in enumerate().
Returns:
When using the default selector, a Queryable whose elements are
KeyedElements where the first element is from the input sequence
and the second is the result of invoking the transform function on
the first value.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If transform is not callable. | [
"Apply",
"a",
"callable",
"to",
"each",
"element",
"in",
"an",
"input",
"sequence",
"generating",
"a",
"new",
"sequence",
"of",
"2",
"-",
"tuples",
"where",
"the",
"first",
"element",
"is",
"the",
"input",
"value",
"and",
"the",
"second",
"is",
"the",
"t... | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L240-L289 | train | 48,107 |
sixty-north/asq | asq/queryables.py | Queryable.select_many | def select_many(
self,
collection_selector=identity,
result_selector=identity):
'''Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many() on a closed "
"Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many() parameter projector={0} is not "
"callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many() parameter selector={selector} is "
" not callable".format(selector=repr(result_selector)))
sequences = self.select(collection_selector)
chained_sequence = itertools.chain.from_iterable(sequences)
return self._create(chained_sequence).select(result_selector) | python | def select_many(
self,
collection_selector=identity,
result_selector=identity):
'''Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many() on a closed "
"Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many() parameter projector={0} is not "
"callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many() parameter selector={selector} is "
" not callable".format(selector=repr(result_selector)))
sequences = self.select(collection_selector)
chained_sequence = itertools.chain.from_iterable(sequences)
return self._create(chained_sequence).select(result_selector) | [
"def",
"select_many",
"(",
"self",
",",
"collection_selector",
"=",
"identity",
",",
"result_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call select_many() on a closed \"",
"\"Queryable.... | Projects each element of a sequence to an intermediate new sequence,
flattens the resulting sequences into one sequence and optionally
transforms the flattened sequence using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector: An optional unary function mapping the elements in
the flattened intermediate sequence to corresponding elements
of the result sequence. The single argument of the
result_selector is the value of an element from the flattened
intermediate sequence. The return value should be the
corresponding value in the result sequence. The default
result_selector is the identity function.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If either collection_selector or result_selector are not
callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"flattens",
"the",
"resulting",
"sequences",
"into",
"one",
"sequence",
"and",
"optionally",
"transforms",
"the",
"flattened",
"sequence",
"using",
"a",
"selector"... | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L291-L344 | train | 48,108 |
sixty-north/asq | asq/queryables.py | Queryable.select_many_with_index | def select_many_with_index(
self,
collection_selector=IndexedElement,
result_selector=lambda source_element,
collection_element: collection_element):
'''Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many_with_index() on a "
"closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_index() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_index() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_index(collection_selector,
result_selector)) | python | def select_many_with_index(
self,
collection_selector=IndexedElement,
result_selector=lambda source_element,
collection_element: collection_element):
'''Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable.
'''
if self.closed():
raise ValueError("Attempt to call select_many_with_index() on a "
"closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_index() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_index() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_index(collection_selector,
result_selector)) | [
"def",
"select_many_with_index",
"(",
"self",
",",
"collection_selector",
"=",
"IndexedElement",
",",
"result_selector",
"=",
"lambda",
"source_element",
",",
"collection_element",
":",
"collection_element",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"r... | Projects each element of a sequence to an intermediate new sequence,
incorporating the index of the element, flattens the resulting sequence
into one sequence and optionally transforms the flattened sequence
using a selector function.
Note: This method uses deferred execution.
Args:
collection_selector: A binary function mapping each element of the
source sequence into an intermediate sequence, by incorporating
its index in the source sequence. The two positional arguments
to the function are the zero-based index of the source element
and the value of the element. The result of the function
should be an iterable derived from the index and element value.
If no collection_selector is provided, the elements of the
intermediate sequence will consist of tuples of (index,
element) from the source sequence.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
flattened intermediate sequence are returned untransformed.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence which incorporates both the index and value of
the source element, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector [and selector] are not callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"incorporating",
"the",
"index",
"of",
"the",
"element",
"flattens",
"the",
"resulting",
"sequence",
"into",
"one",
"sequence",
"and",
"optionally",
"transforms",
... | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L346-L407 | train | 48,109 |
sixty-north/asq | asq/queryables.py | Queryable.select_many_with_correspondence | def select_many_with_correspondence(
self,
collection_selector=identity,
result_selector=KeyedElement):
'''Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable.
'''
if self.closed():
raise ValueError("Attempt to call "
"select_many_with_correspondence() on a closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_correspondence() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_correspondence() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_correspondence(collection_selector,
result_selector)) | python | def select_many_with_correspondence(
self,
collection_selector=identity,
result_selector=KeyedElement):
'''Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable.
'''
if self.closed():
raise ValueError("Attempt to call "
"select_many_with_correspondence() on a closed Queryable.")
if not is_callable(collection_selector):
raise TypeError("select_many_with_correspondence() parameter "
"projector={0} is not callable".format(repr(collection_selector)))
if not is_callable(result_selector):
raise TypeError("select_many_with_correspondence() parameter "
"selector={0} is not callable".format(repr(result_selector)))
return self._create(
self._generate_select_many_with_correspondence(collection_selector,
result_selector)) | [
"def",
"select_many_with_correspondence",
"(",
"self",
",",
"collection_selector",
"=",
"identity",
",",
"result_selector",
"=",
"KeyedElement",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call \"",
"\"select_many_... | Projects each element of a sequence to an intermediate new sequence,
and flattens the resulting sequence, into one sequence and uses a
selector function to incorporate the corresponding source for each item
in the result sequence.
Note: This method uses deferred execution.
Args:
collection_selector: A unary function mapping each element of the
source iterable into an intermediate sequence. The single
argument of the collection_selector is the value of an element
from the source sequence. The return value should be an
iterable derived from that element value. The default
collection_selector, which is the identity function, assumes
that each element of the source sequence is itself iterable.
result_selector:
An optional binary function mapping the elements in the
flattened intermediate sequence together with their
corresponding source elements to elements of the result
sequence. The two positional arguments of the result_selector
are, first the source element corresponding to an element from
the intermediate sequence, and second the actual element from
the intermediate sequence. The return value should be the
corresponding value in the result sequence. If no
result_selector function is provided, the elements of the
result sequence are KeyedElement namedtuples.
Returns:
A Queryable over a generated sequence whose elements are the result
of applying the one-to-many collection_selector to each element of
the source sequence, concatenating the results into an intermediate
sequence, and then mapping each of those elements through the
result_selector which incorporates the corresponding source element
into the result sequence.
Raises:
ValueError: If this Queryable has been closed.
TypeError: If projector or selector are not callable. | [
"Projects",
"each",
"element",
"of",
"a",
"sequence",
"to",
"an",
"intermediate",
"new",
"sequence",
"and",
"flattens",
"the",
"resulting",
"sequence",
"into",
"one",
"sequence",
"and",
"uses",
"a",
"selector",
"function",
"to",
"incorporate",
"the",
"correspond... | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L417-L476 | train | 48,110 |
sixty-north/asq | asq/queryables.py | Queryable.group_by | def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_by() on a closed "
"Queryable.")
if not is_callable(key_selector):
raise TypeError("group_by() parameter key_selector={0} is not "
"callable".format(repr(key_selector)))
if not is_callable(element_selector):
raise TypeError("group_by() parameter element_selector={0} is not "
"callable".format(repr(element_selector)))
if not is_callable(result_selector):
raise TypeError("group_by() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_group_by_result(key_selector,
element_selector, result_selector)) | python | def group_by(self, key_selector=identity,
element_selector=identity,
result_selector=lambda key, grouping: grouping):
'''Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_by() on a closed "
"Queryable.")
if not is_callable(key_selector):
raise TypeError("group_by() parameter key_selector={0} is not "
"callable".format(repr(key_selector)))
if not is_callable(element_selector):
raise TypeError("group_by() parameter element_selector={0} is not "
"callable".format(repr(element_selector)))
if not is_callable(result_selector):
raise TypeError("group_by() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_group_by_result(key_selector,
element_selector, result_selector)) | [
"def",
"group_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
",",
"element_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"key",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
... | Groups the elements according to the value of a key extracted by a
selector function.
Note: This method has different behaviour to itertools.groupby in the
Python standard library because it aggregates all items with the
same key, rather than returning groups of consecutive items of the
same key.
Note: This method uses deferred execution, but consumption of a single
result will lead to evaluation of the whole source sequence.
Args:
key_selector: An optional unary function used to extract a key from
each element in the source sequence. The default is the
identity function.
element_selector: A optional unary function to map elements in the
source sequence to elements in a resulting Grouping. The
default is the identity function.
result_selector: An optional binary function to create a result
from each group. The first positional argument is the key
identifying the group. The second argument is a Grouping object
containing the members of the group. The default is a function
which simply returns the Grouping.
Returns:
A Queryable sequence of elements of the where each element
represents a group. If the default result_selector is relied upon
this is a Grouping object.
Raises:
ValueError: If the Queryable is closed().
TypeError: If key_selector is not callable.
TypeError: If element_selector is not callable.
TypeError: If result_selector is not callable. | [
"Groups",
"the",
"elements",
"according",
"to",
"the",
"value",
"of",
"a",
"key",
"extracted",
"by",
"a",
"selector",
"function",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L486-L543 | train | 48,111 |
sixty-north/asq | asq/queryables.py | Queryable.where | def where(self, predicate):
'''Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call where() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("where() parameter predicate={predicate} is not "
"callable".format(predicate=repr(predicate)))
return self._create(ifilter(predicate, self)) | python | def where(self, predicate):
'''Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call where() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("where() parameter predicate={predicate} is not "
"callable".format(predicate=repr(predicate)))
return self._create(ifilter(predicate, self)) | [
"def",
"where",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call where() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
"raise",
"TypeEr... | Filters elements according to whether they match a predicate.
Note: This method uses deferred execution.
Args:
predicate: A unary function which is applied to each element in the
source sequence. Source elements for which the predicate
returns True will be present in the result.
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the predicate is not callable. | [
"Filters",
"elements",
"according",
"to",
"whether",
"they",
"match",
"a",
"predicate",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L551-L576 | train | 48,112 |
sixty-north/asq | asq/queryables.py | Queryable.of_type | def of_type(self, classinfo):
'''Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples.
'''
if self.closed():
raise ValueError("Attempt to call of_type() on a closed "
"Queryable.")
if not is_type(classinfo):
raise TypeError("of_type() parameter classinfo={0} is not a class "
"object or a type objector a tuple of class or "
"type objects.".format(classinfo))
return self.where(lambda x: isinstance(x, classinfo)) | python | def of_type(self, classinfo):
'''Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples.
'''
if self.closed():
raise ValueError("Attempt to call of_type() on a closed "
"Queryable.")
if not is_type(classinfo):
raise TypeError("of_type() parameter classinfo={0} is not a class "
"object or a type objector a tuple of class or "
"type objects.".format(classinfo))
return self.where(lambda x: isinstance(x, classinfo)) | [
"def",
"of_type",
"(",
"self",
",",
"classinfo",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call of_type() on a closed \"",
"\"Queryable.\"",
")",
"if",
"not",
"is_type",
"(",
"classinfo",
")",
":",
"raise",... | Filters elements according to whether they are of a certain type.
Note: This method uses deferred execution.
Args:
classinfo: If classinfo is neither a class object nor a type object
it may be a tuple of class or type objects, or may recursively
contain other such tuples (other sequence types are not
accepted).
Returns:
A Queryable over those elements of the source sequence for which
the predicate is True.
Raises:
ValueError: If the Queryable is closed.
TypeError: If classinfo is not a class, type, or tuple of classes,
types, and such tuples. | [
"Filters",
"elements",
"according",
"to",
"whether",
"they",
"are",
"of",
"a",
"certain",
"type",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L578-L607 | train | 48,113 |
sixty-north/asq | asq/queryables.py | Queryable.order_by | def order_by(self, key_selector=identity):
'''Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call order_by() on a "
"closed Queryable.")
if not is_callable(key_selector):
raise TypeError("order_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
return self._create_ordered(iter(self), -1, key_selector) | python | def order_by(self, key_selector=identity):
'''Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call order_by() on a "
"closed Queryable.")
if not is_callable(key_selector):
raise TypeError("order_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
return self._create_ordered(iter(self), -1, key_selector) | [
"def",
"order_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call order_by() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"key_se... | Sorts by a key in ascending order.
Introduces a primary sorting order to the sequence. Additional sort
criteria should be specified by subsequent calls to then_by() and
then_by_descending(). Calling order_by() or order_by_descending() on
the results of a call to order_by() will introduce a new primary
ordering which will override any already established ordering.
This method performs a stable sort. The order of two elements with the
same key will be preserved.
Note: This method uses deferred execution.
Args:
key_selector: A unary function which extracts a key from each
element using which the result will be ordered.
Returns:
An OrderedQueryable over the sorted elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the key_selector is not callable. | [
"Sorts",
"by",
"a",
"key",
"in",
"ascending",
"order",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L609-L642 | train | 48,114 |
sixty-north/asq | asq/queryables.py | Queryable.take | def take(self, count=1):
'''Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call take() on a closed Queryable.")
count = max(0, count)
return self._create(itertools.islice(self, count)) | python | def take(self, count=1):
'''Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call take() on a closed Queryable.")
count = max(0, count)
return self._create(itertools.islice(self, count)) | [
"def",
"take",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take() on a closed Queryable.\"",
")",
"count",
"=",
"max",
"(",
"0",
",",
"count",
")",
"return",
"s... | Returns a specified number of elements from the start of a sequence.
If the source sequence contains fewer elements than requested only the
available elements will be returned and no exception will be raised.
Note: This method uses deferred execution.
Args:
count: An optional number of elements to take. The default is one.
Returns:
A Queryable over the first count elements of the source sequence,
or the all elements of elements in the source, whichever is fewer.
Raises:
ValueError: If the Queryable is closed() | [
"Returns",
"a",
"specified",
"number",
"of",
"elements",
"from",
"the",
"start",
"of",
"a",
"sequence",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L679-L702 | train | 48,115 |
sixty-north/asq | asq/queryables.py | Queryable.take_while | def take_while(self, predicate):
'''Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a closed "
"Queryable.")
if not is_callable(predicate):
raise TypeError("take_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
# Cannot use itertools.takewhile here because it is not lazy
return self._create(self._generate_take_while_result(predicate)) | python | def take_while(self, predicate):
'''Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a closed "
"Queryable.")
if not is_callable(predicate):
raise TypeError("take_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
# Cannot use itertools.takewhile here because it is not lazy
return self._create(self._generate_take_while_result(predicate)) | [
"def",
"take_while",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take_while() on a closed \"",
"\"Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
... | Returns elements from the start while the predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A function returning True or False with which elements
will be tested.
Returns:
A Queryable over the elements from the beginning of the source
sequence for which predicate is True.
Raises:
ValueError: If the Queryable is closed()
TypeError: If the predicate is not callable. | [
"Returns",
"elements",
"from",
"the",
"start",
"while",
"the",
"predicate",
"is",
"True",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L704-L730 | train | 48,116 |
sixty-north/asq | asq/queryables.py | Queryable.skip | def skip(self, count=1):
'''Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call skip() on a closed Queryable.")
count = max(0, count)
if count == 0:
return self
# Try an optimised version
if hasattr(self._iterable, "__getitem__"):
try:
stop = len(self._iterable)
return self._create(self._generate_optimized_skip_result(count,
stop))
except TypeError:
pass
# Fall back to the unoptimized version
return self._create(self._generate_skip_result(count)) | python | def skip(self, count=1):
'''Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call skip() on a closed Queryable.")
count = max(0, count)
if count == 0:
return self
# Try an optimised version
if hasattr(self._iterable, "__getitem__"):
try:
stop = len(self._iterable)
return self._create(self._generate_optimized_skip_result(count,
stop))
except TypeError:
pass
# Fall back to the unoptimized version
return self._create(self._generate_skip_result(count)) | [
"def",
"skip",
"(",
"self",
",",
"count",
"=",
"1",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call skip() on a closed Queryable.\"",
")",
"count",
"=",
"max",
"(",
"0",
",",
"count",
")",
"if",
"count... | Skip the first count contiguous elements of the source sequence.
If the source sequence contains fewer than count elements returns an
empty sequence and does not raise an exception.
Note: This method uses deferred execution.
Args:
count: The number of elements to skip from the beginning of the
sequence. If omitted defaults to one. If count is less than one
the result sequence will be empty.
Returns:
A Queryable over the elements of source excluding the first count
elements.
Raises:
ValueError: If the Queryable is closed(). | [
"Skip",
"the",
"first",
"count",
"contiguous",
"elements",
"of",
"the",
"source",
"sequence",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L739-L777 | train | 48,117 |
sixty-north/asq | asq/queryables.py | Queryable.skip_while | def skip_while(self, predicate):
'''Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a "
"closed Queryable.")
if not is_callable(predicate):
raise TypeError("skip_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return self._create(itertools.dropwhile(predicate, self)) | python | def skip_while(self, predicate):
'''Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call take_while() on a "
"closed Queryable.")
if not is_callable(predicate):
raise TypeError("skip_while() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return self._create(itertools.dropwhile(predicate, self)) | [
"def",
"skip_while",
"(",
"self",
",",
"predicate",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call take_while() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
... | Omit elements from the start for which a predicate is True.
Note: This method uses deferred execution.
Args:
predicate: A single argument predicate function.
Returns:
A Queryable over the sequence of elements beginning with the first
element for which the predicate returns False.
Raises:
ValueError: If the Queryable is closed().
TypeError: If predicate is not callable. | [
"Omit",
"elements",
"from",
"the",
"start",
"for",
"which",
"a",
"predicate",
"is",
"True",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L789-L813 | train | 48,118 |
sixty-north/asq | asq/queryables.py | Queryable.concat | def concat(self, second_iterable):
'''Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable.
'''
if self.closed():
raise ValueError("Attempt to call concat() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute concat() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)) | python | def concat(self, second_iterable):
'''Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable.
'''
if self.closed():
raise ValueError("Attempt to call concat() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute concat() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)) | [
"def",
"concat",
"(",
"self",
",",
"second_iterable",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call concat() on a closed Queryable.\"",
")",
"if",
"not",
"is_iterable",
"(",
"second_iterable",
")",
":",
"rai... | Concatenates two sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The sequence to concatenate on to the sequence.
Returns:
A Queryable over the concatenated sequences.
Raises:
ValueError: If the Queryable is closed().
TypeError: If second_iterable is not in fact iterable. | [
"Concatenates",
"two",
"sequences",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L815-L837 | train | 48,119 |
sixty-north/asq | asq/queryables.py | Queryable.reverse | def reverse(self):
'''Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call reverse() on a "
"closed Queryable.")
# Attempt an optimised version
try:
r = reversed(self._iterable)
return self._create(r)
except TypeError:
pass
# Fall through to a sequential version
return self._create(self._generate_reverse_result()) | python | def reverse(self):
'''Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call reverse() on a "
"closed Queryable.")
# Attempt an optimised version
try:
r = reversed(self._iterable)
return self._create(r)
except TypeError:
pass
# Fall through to a sequential version
return self._create(self._generate_reverse_result()) | [
"def",
"reverse",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call reverse() on a \"",
"\"closed Queryable.\"",
")",
"# Attempt an optimised version",
"try",
":",
"r",
"=",
"reversed",
"(",
"self",
... | Returns the sequence reversed.
Note: This method uses deferred execution, but the whole source
sequence is consumed once execution commences.
Returns:
The source sequence in reverse order.
Raises:
ValueError: If the Queryable is closed(). | [
"Returns",
"the",
"sequence",
"reversed",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L839-L863 | train | 48,120 |
sixty-north/asq | asq/queryables.py | Queryable.element_at | def element_at(self, index):
'''Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
if index < 0:
raise OutOfRangeError("Attempt to use negative index.")
# Attempt to use __getitem__
try:
return self._iterable[index]
except IndexError:
raise OutOfRangeError("Index out of range.")
except TypeError:
pass
# Fall back to iterating
for i, item in enumerate(self):
if i == index:
return item
raise OutOfRangeError("element_at(index) out of range.") | python | def element_at(self, index):
'''Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range.
'''
if self.closed():
raise ValueError("Attempt to call element_at() on a "
"closed Queryable.")
if index < 0:
raise OutOfRangeError("Attempt to use negative index.")
# Attempt to use __getitem__
try:
return self._iterable[index]
except IndexError:
raise OutOfRangeError("Index out of range.")
except TypeError:
pass
# Fall back to iterating
for i, item in enumerate(self):
if i == index:
return item
raise OutOfRangeError("element_at(index) out of range.") | [
"def",
"element_at",
"(",
"self",
",",
"index",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call element_at() on a \"",
"\"closed Queryable.\"",
")",
"if",
"index",
"<",
"0",
":",
"raise",
"OutOfRangeError",
... | Return the element at ordinal index.
Note: This method uses immediate execution.
Args:
index: The index of the element to be returned.
Returns:
The element at ordinal index in the source sequence.
Raises:
ValueError: If the Queryable is closed().
ValueError: If index is out of range. | [
"Return",
"the",
"element",
"at",
"ordinal",
"index",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L871-L905 | train | 48,121 |
sixty-north/asq | asq/queryables.py | Queryable.any | def any(self, predicate=None):
'''Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call any() on a closed Queryable.")
if predicate is None:
predicate = lambda x: True
if not is_callable(predicate):
raise TypeError("any() parameter predicate={predicate} is not callable".format(predicate=repr(predicate)))
for item in self.select(predicate):
if item:
return True
return False | python | def any(self, predicate=None):
'''Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed()
'''
if self.closed():
raise ValueError("Attempt to call any() on a closed Queryable.")
if predicate is None:
predicate = lambda x: True
if not is_callable(predicate):
raise TypeError("any() parameter predicate={predicate} is not callable".format(predicate=repr(predicate)))
for item in self.select(predicate):
if item:
return True
return False | [
"def",
"any",
"(",
"self",
",",
"predicate",
"=",
"None",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call any() on a closed Queryable.\"",
")",
"if",
"predicate",
"is",
"None",
":",
"predicate",
"=",
"lamb... | Determine if the source sequence contains any elements which satisfy
the predicate.
Only enough of the sequence to satisfy the predicate once is consumed.
Note: This method uses immediate execution.
Args:
predicate: An optional single argument function used to test each
element. If omitted, or None, this method returns True if there
is at least one element in the source.
Returns:
True if the sequence contains at least one element which satisfies
the predicate, otherwise False.
Raises:
ValueError: If the Queryable is closed() | [
"Determine",
"if",
"the",
"source",
"sequence",
"contains",
"any",
"elements",
"which",
"satisfy",
"the",
"predicate",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L956-L988 | train | 48,122 |
sixty-north/asq | asq/queryables.py | Queryable.all | def all(self, predicate=bool):
'''Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call all() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("all() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return all(self.select(predicate)) | python | def all(self, predicate=bool):
'''Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable.
'''
if self.closed():
raise ValueError("Attempt to call all() on a closed Queryable.")
if not is_callable(predicate):
raise TypeError("all() parameter predicate={0} is "
"not callable".format(repr(predicate)))
return all(self.select(predicate)) | [
"def",
"all",
"(",
"self",
",",
"predicate",
"=",
"bool",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call all() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"predicate",
")",
":",
"rais... | Determine if all elements in the source sequence satisfy a condition.
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
predicate (callable): An optional single argument function used to
test each elements. If omitted, the bool() function is used
resulting in the elements being tested directly.
Returns:
True if all elements in the sequence meet the predicate condition,
otherwise False.
Raises:
ValueError: If the Queryable is closed()
TypeError: If predicate is not callable. | [
"Determine",
"if",
"all",
"elements",
"in",
"the",
"source",
"sequence",
"satisfy",
"a",
"condition",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L990-L1017 | train | 48,123 |
sixty-north/asq | asq/queryables.py | Queryable.sum | def sum(self, selector=identity):
'''Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call sum() on a closed Queryable.")
if not is_callable(selector):
raise TypeError("sum() parameter selector={0} is "
"not callable".format(repr(selector)))
return sum(self.select(selector)) | python | def sum(self, selector=identity):
'''Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call sum() on a closed Queryable.")
if not is_callable(selector):
raise TypeError("sum() parameter selector={0} is "
"not callable".format(repr(selector)))
return sum(self.select(selector)) | [
"def",
"sum",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call sum() on a closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",
")",
":",
"ra... | Return the arithmetic sum of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The total value of the projected sequence, or zero for an empty
sequence.
Raises:
ValueError: If the Queryable has been closed. | [
"Return",
"the",
"arithmetic",
"sum",
"of",
"the",
"values",
"in",
"the",
"sequence",
".."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1076-L1103 | train | 48,124 |
sixty-north/asq | asq/queryables.py | Queryable.average | def average(self, selector=identity):
'''Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty.
'''
if self.closed():
raise ValueError("Attempt to call average() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("average() parameter selector={0} is "
"not callable".format(repr(selector)))
total = 0
count = 0
for item in self.select(selector):
total += item
count += 1
if count == 0:
raise ValueError("Cannot compute average() of an empty sequence.")
return total / count | python | def average(self, selector=identity):
'''Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty.
'''
if self.closed():
raise ValueError("Attempt to call average() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("average() parameter selector={0} is "
"not callable".format(repr(selector)))
total = 0
count = 0
for item in self.select(selector):
total += item
count += 1
if count == 0:
raise ValueError("Cannot compute average() of an empty sequence.")
return total / count | [
"def",
"average",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call average() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",
... | Return the arithmetic mean of the values in the sequence..
All of the source sequence will be consumed.
Note: This method uses immediate execution.
Args:
selector: An optional single argument function which will be used
to project the elements of the sequence. If omitted, the
identity function is used.
Returns:
The arithmetic mean value of the projected sequence.
Raises:
ValueError: If the Queryable has been closed.
ValueError: I the source sequence is empty. | [
"Return",
"the",
"arithmetic",
"mean",
"of",
"the",
"values",
"in",
"the",
"sequence",
".."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1105-L1139 | train | 48,125 |
sixty-north/asq | asq/queryables.py | Queryable.contains | def contains(self, value, equality_comparer=operator.eq):
'''Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call contains() on a "
"closed Queryable.")
if not is_callable(equality_comparer):
raise TypeError("contains() parameter equality_comparer={0} is "
"not callable".format(repr(equality_comparer)))
if equality_comparer is operator.eq:
return value in self._iterable
for item in self:
if equality_comparer(value, item):
return True
return False | python | def contains(self, value, equality_comparer=operator.eq):
'''Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call contains() on a "
"closed Queryable.")
if not is_callable(equality_comparer):
raise TypeError("contains() parameter equality_comparer={0} is "
"not callable".format(repr(equality_comparer)))
if equality_comparer is operator.eq:
return value in self._iterable
for item in self:
if equality_comparer(value, item):
return True
return False | [
"def",
"contains",
"(",
"self",
",",
"value",
",",
"equality_comparer",
"=",
"operator",
".",
"eq",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call contains() on a \"",
"\"closed Queryable.\"",
")",
"if",
"n... | Determines whether the sequence contains a particular value.
Execution is immediate. Depending on the type of the sequence, all or
none of the sequence may be consumed by this operation.
Note: This method uses immediate execution.
Args:
value: The value to test for membership of the sequence
Returns:
True if value is in the sequence, otherwise False.
Raises:
ValueError: If the Queryable has been closed. | [
"Determines",
"whether",
"the",
"sequence",
"contains",
"a",
"particular",
"value",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1141-L1173 | train | 48,126 |
sixty-north/asq | asq/queryables.py | Queryable.default_if_empty | def default_if_empty(self, default):
'''If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call default_if_empty() on a "
"closed Queryable.")
return self._create(self._generate_default_if_empty_result(default)) | python | def default_if_empty(self, default):
'''If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call default_if_empty() on a "
"closed Queryable.")
return self._create(self._generate_default_if_empty_result(default)) | [
"def",
"default_if_empty",
"(",
"self",
",",
"default",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call default_if_empty() on a \"",
"\"closed Queryable.\"",
")",
"return",
"self",
".",
"_create",
"(",
"self",
... | If the source sequence is empty return a single element sequence
containing the supplied default value, otherwise return the source
sequence unchanged.
Note: This method uses deferred execution.
Args:
default: The element to be returned if the source sequence is empty.
Returns:
The source sequence, or if the source sequence is empty an sequence
containing a single element with the supplied default value.
Raises:
ValueError: If the Queryable has been closed. | [
"If",
"the",
"source",
"sequence",
"is",
"empty",
"return",
"a",
"single",
"element",
"sequence",
"containing",
"the",
"supplied",
"default",
"value",
"otherwise",
"return",
"the",
"source",
"sequence",
"unchanged",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1175-L1197 | train | 48,127 |
sixty-north/asq | asq/queryables.py | Queryable.distinct | def distinct(self, selector=identity):
'''Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call distinct() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("distinct() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_distinct_result(selector)) | python | def distinct(self, selector=identity):
'''Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call distinct() on a "
"closed Queryable.")
if not is_callable(selector):
raise TypeError("distinct() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_distinct_result(selector)) | [
"def",
"distinct",
"(",
"self",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call distinct() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"selector",... | Eliminate duplicate elements from a sequence.
Note: This method uses deferred execution.
Args:
selector: An optional single argument function the result of which
is the value compared for uniqueness against elements already
consumed. If omitted, the element value itself is compared for
uniqueness.
Returns:
Unique elements of the source sequence as determined by the
selector function. Note that it is unprojected elements that are
returned, even if a selector was provided.
Raises:
ValueError: If the Queryable is closed.
TypeError: If the selector is not callable. | [
"Eliminate",
"duplicate",
"elements",
"from",
"a",
"sequence",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1216-L1244 | train | 48,128 |
sixty-north/asq | asq/queryables.py | Queryable.difference | def difference(self, second_iterable, selector=identity):
'''Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call difference() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute difference() with second_iterable"
"of non-iterable {0}".format(str(type(second_iterable))[7: -2]))
if not is_callable(selector):
raise TypeError("difference() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_difference_result(second_iterable,
selector)) | python | def difference(self, second_iterable, selector=identity):
'''Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call difference() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute difference() with second_iterable"
"of non-iterable {0}".format(str(type(second_iterable))[7: -2]))
if not is_callable(selector):
raise TypeError("difference() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_difference_result(second_iterable,
selector)) | [
"def",
"difference",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call difference() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is... | Returns those elements which are in the source sequence which are not
in the second_iterable.
This method is equivalent to the Except() LINQ operator, renamed to a
valid Python identifier.
Note: This method uses deferred execution, but as soon as execution
commences the entirety of the second_iterable is consumed;
therefore, although the source sequence may be infinite the
second_iterable must be finite.
Args:
second_iterable: Elements from this sequence are excluded from the
returned sequence. This sequence will be consumed in its
entirety, so must be finite.
selector: A optional single argument function with selects from the
elements of both sequences the values which will be
compared for equality. If omitted the identity function will
be used.
Returns:
A sequence containing all elements in the source sequence except
those which are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"in",
"the",
"source",
"sequence",
"which",
"are",
"not",
"in",
"the",
"second_iterable",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1255-L1299 | train | 48,129 |
sixty-north/asq | asq/queryables.py | Queryable.intersect | def intersect(self, second_iterable, selector=identity):
'''Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call intersect() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute intersect() with second_iterable "
"of non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(selector):
raise TypeError("intersect() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_intersect_result(second_iterable,
selector)) | python | def intersect(self, second_iterable, selector=identity):
'''Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call intersect() on a "
"closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute intersect() with second_iterable "
"of non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(selector):
raise TypeError("intersect() parameter selector={0} is "
"not callable".format(repr(selector)))
return self._create(self._generate_intersect_result(second_iterable,
selector)) | [
"def",
"intersect",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call intersect() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_i... | Returns those elements which are both in the source sequence and in
the second_iterable.
Note: This method uses deferred execution.
Args:
second_iterable: Elements are returned if they are also in the
sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence which
are also members of the second sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"both",
"in",
"the",
"source",
"sequence",
"and",
"in",
"the",
"second_iterable",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1310-L1347 | train | 48,130 |
sixty-north/asq | asq/queryables.py | Queryable.union | def union(self, second_iterable, selector=identity):
'''Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call union() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute union() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)).distinct(selector) | python | def union(self, second_iterable, selector=identity):
'''Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call union() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute union() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
return self._create(itertools.chain(self, second_iterable)).distinct(selector) | [
"def",
"union",
"(",
"self",
",",
"second_iterable",
",",
"selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call union() on a closed Queryable.\"",
")",
"if",
"not",
"is_iterable",
"(",
... | Returns those elements which are either in the source sequence or in
the second_iterable, or in both.
Note: This method uses deferred execution.
Args:
second_iterable: Elements from this sequence are returns if they
are not also in the source sequence.
selector: An optional single argument function which is used to
project the elements in the source and second_iterables prior
to comparing them. If omitted the identity function will be
used.
Returns:
A sequence containing all elements in the source sequence and second
sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the second_iterable is not in fact iterable.
TypeError: If the selector is not callable. | [
"Returns",
"those",
"elements",
"which",
"are",
"either",
"in",
"the",
"source",
"sequence",
"or",
"in",
"the",
"second_iterable",
"or",
"in",
"both",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1358-L1389 | train | 48,131 |
sixty-north/asq | asq/queryables.py | Queryable.join | def join(self, inner_iterable, outer_key_selector=identity,
inner_key_selector=identity,
result_selector=lambda outer, inner: (outer, inner)):
'''Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute join() with inner_iterable of "
"non-iterable {0}".format(str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("join() parameter outer_key_selector={0} is not "
"callable".format(repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("join() parameter inner_key_selector={0} is not "
"callable".format(repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("join() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | python | def join(self, inner_iterable, outer_key_selector=identity,
inner_key_selector=identity,
result_selector=lambda outer, inner: (outer, inner)):
'''Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute join() with inner_iterable of "
"non-iterable {0}".format(str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("join() parameter outer_key_selector={0} is not "
"callable".format(repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("join() parameter inner_key_selector={0} is not "
"callable".format(repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("join() parameter result_selector={0} is not "
"callable".format(repr(result_selector)))
return self._create(self._generate_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | [
"def",
"join",
"(",
"self",
",",
"inner_iterable",
",",
"outer_key_selector",
"=",
"identity",
",",
"inner_key_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"outer",
",",
"inner",
":",
"(",
"outer",
",",
"inner",
")",
")",
":",
"if",
"... | Perform an inner join with a second sequence using selected keys.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from two matching elements of the outer and inner. If
omitted the result elements will be a 2-tuple pair of the
matching outer and inner elements.
Returns:
A Queryable whose elements are the result of performing an inner-
join on two sequences.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable. | [
"Perform",
"an",
"inner",
"join",
"with",
"a",
"second",
"sequence",
"using",
"selected",
"keys",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1391-L1452 | train | 48,132 |
sixty-north/asq | asq/queryables.py | Queryable.group_join | def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,
result_selector=lambda outer, grouping: grouping):
'''Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute group_join() with inner_iterable of non-iterable {type}".format(
type=str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("group_join() parameter outer_key_selector={outer_key_selector} is not callable".format(
outer_key_selector=repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("group_join() parameter inner_key_selector={inner_key_selector} is not callable".format(
inner_key_selector=repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("group_join() parameter result_selector={result_selector} is not callable".format(
result_selector=repr(result_selector)))
return self._create(self._generate_group_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | python | def group_join(self, inner_iterable, outer_key_selector=identity, inner_key_selector=identity,
result_selector=lambda outer, grouping: grouping):
'''Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call group_join() on a closed Queryable.")
if not is_iterable(inner_iterable):
raise TypeError("Cannot compute group_join() with inner_iterable of non-iterable {type}".format(
type=str(type(inner_iterable))[7: -1]))
if not is_callable(outer_key_selector):
raise TypeError("group_join() parameter outer_key_selector={outer_key_selector} is not callable".format(
outer_key_selector=repr(outer_key_selector)))
if not is_callable(inner_key_selector):
raise TypeError("group_join() parameter inner_key_selector={inner_key_selector} is not callable".format(
inner_key_selector=repr(inner_key_selector)))
if not is_callable(result_selector):
raise TypeError("group_join() parameter result_selector={result_selector} is not callable".format(
result_selector=repr(result_selector)))
return self._create(self._generate_group_join_result(inner_iterable, outer_key_selector,
inner_key_selector, result_selector)) | [
"def",
"group_join",
"(",
"self",
",",
"inner_iterable",
",",
"outer_key_selector",
"=",
"identity",
",",
"inner_key_selector",
"=",
"identity",
",",
"result_selector",
"=",
"lambda",
"outer",
",",
"grouping",
":",
"grouping",
")",
":",
"if",
"self",
".",
"clo... | Match elements of two sequences using keys and group the results.
The group_join() query produces a hierarchical result, with all of the
inner elements in the result grouped against the matching outer
element.
The order of elements from outer is maintained. For each of these the
order of elements from inner is also preserved.
Note: This method uses deferred execution.
Args:
inner_iterable: The sequence to join with the outer sequence.
outer_key_selector: An optional unary function to extract keys from
elements of the outer (source) sequence. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
inner_key_selector: An optional unary function to extract keys
from elements of the inner_iterable. The first positional
argument of the function should accept outer elements and the
result value should be the key. If omitted, the identity
function is used.
result_selector: An optional binary function to create a result
element from an outer element and the Grouping of matching
inner elements. The first positional argument is the outer
elements and the second in the Grouping of inner elements
which match the outer element according to the key selectors
used. If omitted, the result elements will be the Groupings
directly.
Returns:
A Queryable over a sequence with one element for each group in the
result as returned by the result_selector. If the default result
selector is used, the result is a sequence of Grouping objects.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If the inner_iterable is not in fact iterable.
TypeError: If the outer_key_selector is not callable.
TypeError: If the inner_key_selector is not callable.
TypeError: If the result_selector is not callable. | [
"Match",
"elements",
"of",
"two",
"sequences",
"using",
"keys",
"and",
"group",
"the",
"results",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1461-L1529 | train | 48,133 |
sixty-north/asq | asq/queryables.py | Queryable.aggregate | def aggregate(self, reducer, seed=default, result_selector=identity):
'''Apply a function over a sequence to produce a single result.
Apply a binary function cumulatively to the elements of the source
sequence so as to reduce the iterable to a single value.
Note: This method uses immediate execution.
Args:
reducer: A binary function the first positional argument of which
is an accumulated value and the second is the update value from
the source sequence. The return value should be the new
accumulated value after the update value has been incorporated.
seed: An optional value used to initialise the accumulator before
iteration over the source sequence. If seed is omitted the
and the source sequence contains only one item, then that item
is returned.
result_selector: An optional unary function applied to the final
accumulator value to produce the result. If omitted, defaults
to the identity function.
Raises:
ValueError: If called on an empty sequence with no seed value.
TypeError: If reducer is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call aggregate() on a "
"closed Queryable.")
if not is_callable(reducer):
raise TypeError("aggregate() parameter reducer={0} is "
"not callable".format(repr(reducer)))
if not is_callable(result_selector):
raise TypeError("aggregate() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
if seed is default:
try:
return result_selector(fold(reducer, self))
except TypeError as e:
if 'empty sequence' in str(e):
raise ValueError("Cannot aggregate() empty sequence with "
"no seed value")
return result_selector(fold(reducer, self, seed)) | python | def aggregate(self, reducer, seed=default, result_selector=identity):
'''Apply a function over a sequence to produce a single result.
Apply a binary function cumulatively to the elements of the source
sequence so as to reduce the iterable to a single value.
Note: This method uses immediate execution.
Args:
reducer: A binary function the first positional argument of which
is an accumulated value and the second is the update value from
the source sequence. The return value should be the new
accumulated value after the update value has been incorporated.
seed: An optional value used to initialise the accumulator before
iteration over the source sequence. If seed is omitted the
and the source sequence contains only one item, then that item
is returned.
result_selector: An optional unary function applied to the final
accumulator value to produce the result. If omitted, defaults
to the identity function.
Raises:
ValueError: If called on an empty sequence with no seed value.
TypeError: If reducer is not callable.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call aggregate() on a "
"closed Queryable.")
if not is_callable(reducer):
raise TypeError("aggregate() parameter reducer={0} is "
"not callable".format(repr(reducer)))
if not is_callable(result_selector):
raise TypeError("aggregate() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
if seed is default:
try:
return result_selector(fold(reducer, self))
except TypeError as e:
if 'empty sequence' in str(e):
raise ValueError("Cannot aggregate() empty sequence with "
"no seed value")
return result_selector(fold(reducer, self, seed)) | [
"def",
"aggregate",
"(",
"self",
",",
"reducer",
",",
"seed",
"=",
"default",
",",
"result_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call aggregate() on a \"",
"\"closed Queryable.... | Apply a function over a sequence to produce a single result.
Apply a binary function cumulatively to the elements of the source
sequence so as to reduce the iterable to a single value.
Note: This method uses immediate execution.
Args:
reducer: A binary function the first positional argument of which
is an accumulated value and the second is the update value from
the source sequence. The return value should be the new
accumulated value after the update value has been incorporated.
seed: An optional value used to initialise the accumulator before
iteration over the source sequence. If seed is omitted the
and the source sequence contains only one item, then that item
is returned.
result_selector: An optional unary function applied to the final
accumulator value to produce the result. If omitted, defaults
to the identity function.
Raises:
ValueError: If called on an empty sequence with no seed value.
TypeError: If reducer is not callable.
TypeError: If result_selector is not callable. | [
"Apply",
"a",
"function",
"over",
"a",
"sequence",
"to",
"produce",
"a",
"single",
"result",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1904-L1951 | train | 48,134 |
sixty-north/asq | asq/queryables.py | Queryable.zip | def zip(self, second_iterable, result_selector=lambda x, y: (x, y)):
'''Elementwise combination of two sequences.
The source sequence and the second iterable are merged element-by-
element using a function to combine them into the single corresponding
element of the result sequence. The length of the result sequence is
equal to the length of the shorter of the two input sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The second sequence to be combined with the source
sequence.
result_selector: An optional binary function for combining
corresponding elements of the source sequences into an
element of the result sequence. The first and second positional
arguments are the elements from the source sequences. The
result should be the result sequence element. If omitted, the
result sequence will consist of 2-tuple pairs of corresponding
elements from the source sequences.
Returns:
A Queryable over the merged elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call zip() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute zip() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(result_selector):
raise TypeError("zip() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(*t) for t in izip(self, second_iterable)) | python | def zip(self, second_iterable, result_selector=lambda x, y: (x, y)):
'''Elementwise combination of two sequences.
The source sequence and the second iterable are merged element-by-
element using a function to combine them into the single corresponding
element of the result sequence. The length of the result sequence is
equal to the length of the shorter of the two input sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The second sequence to be combined with the source
sequence.
result_selector: An optional binary function for combining
corresponding elements of the source sequences into an
element of the result sequence. The first and second positional
arguments are the elements from the source sequences. The
result should be the result sequence element. If omitted, the
result sequence will consist of 2-tuple pairs of corresponding
elements from the source sequences.
Returns:
A Queryable over the merged elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If result_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call zip() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute zip() with second_iterable of "
"non-iterable {0}".format(str(type(second_iterable))[7: -1]))
if not is_callable(result_selector):
raise TypeError("zip() parameter result_selector={0} is "
"not callable".format(repr(result_selector)))
return self._create(result_selector(*t) for t in izip(self, second_iterable)) | [
"def",
"zip",
"(",
"self",
",",
"second_iterable",
",",
"result_selector",
"=",
"lambda",
"x",
",",
"y",
":",
"(",
"x",
",",
"y",
")",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call zip() on a closed ... | Elementwise combination of two sequences.
The source sequence and the second iterable are merged element-by-
element using a function to combine them into the single corresponding
element of the result sequence. The length of the result sequence is
equal to the length of the shorter of the two input sequences.
Note: This method uses deferred execution.
Args:
second_iterable: The second sequence to be combined with the source
sequence.
result_selector: An optional binary function for combining
corresponding elements of the source sequences into an
element of the result sequence. The first and second positional
arguments are the elements from the source sequences. The
result should be the result sequence element. If omitted, the
result sequence will consist of 2-tuple pairs of corresponding
elements from the source sequences.
Returns:
A Queryable over the merged elements.
Raises:
ValueError: If the Queryable is closed.
TypeError: If result_selector is not callable. | [
"Elementwise",
"combination",
"of",
"two",
"sequences",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1953-L1993 | train | 48,135 |
sixty-north/asq | asq/queryables.py | Queryable.to_list | def to_list(self):
'''Convert the source sequence to a list.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_list() on a closed Queryable.")
# Maybe use with closable(self) construct to achieve this.
if isinstance(self._iterable, list):
return self._iterable
lst = list(self)
# Ideally we would close here. Why can't we - what is the problem?
#self.close()
return lst | python | def to_list(self):
'''Convert the source sequence to a list.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_list() on a closed Queryable.")
# Maybe use with closable(self) construct to achieve this.
if isinstance(self._iterable, list):
return self._iterable
lst = list(self)
# Ideally we would close here. Why can't we - what is the problem?
#self.close()
return lst | [
"def",
"to_list",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_list() on a closed Queryable.\"",
")",
"# Maybe use with closable(self) construct to achieve this.",
"if",
"isinstance",
"(",
"self",
"... | Convert the source sequence to a list.
Note: This method uses immediate execution. | [
"Convert",
"the",
"source",
"sequence",
"to",
"a",
"list",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L1995-L2009 | train | 48,136 |
sixty-north/asq | asq/queryables.py | Queryable.to_tuple | def to_tuple(self):
'''Convert the source sequence to a tuple.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_tuple() on a closed Queryable.")
if isinstance(self._iterable, tuple):
return self._iterable
tup = tuple(self)
# Ideally we would close here
#self.close()
return tup | python | def to_tuple(self):
'''Convert the source sequence to a tuple.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_tuple() on a closed Queryable.")
if isinstance(self._iterable, tuple):
return self._iterable
tup = tuple(self)
# Ideally we would close here
#self.close()
return tup | [
"def",
"to_tuple",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_tuple() on a closed Queryable.\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"_iterable",
",",
"tuple",
")",
":",
"return",... | Convert the source sequence to a tuple.
Note: This method uses immediate execution. | [
"Convert",
"the",
"source",
"sequence",
"to",
"a",
"tuple",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2011-L2024 | train | 48,137 |
sixty-north/asq | asq/queryables.py | Queryable.to_set | def to_set(self):
'''Convert the source sequence to a set.
Note: This method uses immediate execution.
Raises:
ValueError: If duplicate keys are in the projected source sequence.
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call to_set() on a closed Queryable.")
if isinstance(self._iterable, set):
return self._iterable
s = set()
for item in self:
if item in s:
raise ValueError("Duplicate item value {0} in sequence "
"during to_set()".format(repr(item)))
s.add(item)
# Ideally we would close here
#self.close()
return s | python | def to_set(self):
'''Convert the source sequence to a set.
Note: This method uses immediate execution.
Raises:
ValueError: If duplicate keys are in the projected source sequence.
ValueError: If the Queryable is closed().
'''
if self.closed():
raise ValueError("Attempt to call to_set() on a closed Queryable.")
if isinstance(self._iterable, set):
return self._iterable
s = set()
for item in self:
if item in s:
raise ValueError("Duplicate item value {0} in sequence "
"during to_set()".format(repr(item)))
s.add(item)
# Ideally we would close here
#self.close()
return s | [
"def",
"to_set",
"(",
"self",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_set() on a closed Queryable.\"",
")",
"if",
"isinstance",
"(",
"self",
".",
"_iterable",
",",
"set",
")",
":",
"return",
"se... | Convert the source sequence to a set.
Note: This method uses immediate execution.
Raises:
ValueError: If duplicate keys are in the projected source sequence.
ValueError: If the Queryable is closed(). | [
"Convert",
"the",
"source",
"sequence",
"to",
"a",
"set",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2026-L2048 | train | 48,138 |
sixty-north/asq | asq/queryables.py | Queryable.to_lookup | def to_lookup(self, key_selector=identity, value_selector=identity):
'''Returns a Lookup object, using the provided selector to generate a
key for each item.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_lookup() on a closed Queryable.")
if not is_callable(key_selector):
raise TypeError("to_lookup() parameter key_selector={key_selector} is not callable".format(
key_selector=repr(key_selector)))
if not is_callable(value_selector):
raise TypeError("to_lookup() parameter value_selector={value_selector} is not callable".format(
value_selector=repr(value_selector)))
key_value_pairs = self.select(lambda item: (key_selector(item), value_selector(item)))
lookup = Lookup(key_value_pairs)
# Ideally we would close here
#self.close()
return lookup | python | def to_lookup(self, key_selector=identity, value_selector=identity):
'''Returns a Lookup object, using the provided selector to generate a
key for each item.
Note: This method uses immediate execution.
'''
if self.closed():
raise ValueError("Attempt to call to_lookup() on a closed Queryable.")
if not is_callable(key_selector):
raise TypeError("to_lookup() parameter key_selector={key_selector} is not callable".format(
key_selector=repr(key_selector)))
if not is_callable(value_selector):
raise TypeError("to_lookup() parameter value_selector={value_selector} is not callable".format(
value_selector=repr(value_selector)))
key_value_pairs = self.select(lambda item: (key_selector(item), value_selector(item)))
lookup = Lookup(key_value_pairs)
# Ideally we would close here
#self.close()
return lookup | [
"def",
"to_lookup",
"(",
"self",
",",
"key_selector",
"=",
"identity",
",",
"value_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_lookup() on a closed Queryable.\"",
")",
"if",
... | Returns a Lookup object, using the provided selector to generate a
key for each item.
Note: This method uses immediate execution. | [
"Returns",
"a",
"Lookup",
"object",
"using",
"the",
"provided",
"selector",
"to",
"generate",
"a",
"key",
"for",
"each",
"item",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2050-L2071 | train | 48,139 |
sixty-north/asq | asq/queryables.py | Queryable.to_str | def to_str(self, separator=''):
'''Build a string from the source sequence.
The elements of the query result will each coerced to a string and then
the resulting strings concatenated to return a single string. This
allows the natural processing of character sequences as strings. An
optional separator which will be inserted between each item may be
specified.
Note: this method uses immediate execution.
Args:
separator: An optional separator which will be coerced to a string
and inserted between each source item in the resulting string.
Returns:
A single string which is the result of stringifying each element
and concatenating the results into a single string.
Raises:
TypeError: If any element cannot be coerced to a string.
TypeError: If the separator cannot be coerced to a string.
ValueError: If the Queryable is closed.
'''
if self.closed():
raise ValueError("Attempt to call to_str() on a closed Queryable.")
return str(separator).join(self.select(str)) | python | def to_str(self, separator=''):
'''Build a string from the source sequence.
The elements of the query result will each coerced to a string and then
the resulting strings concatenated to return a single string. This
allows the natural processing of character sequences as strings. An
optional separator which will be inserted between each item may be
specified.
Note: this method uses immediate execution.
Args:
separator: An optional separator which will be coerced to a string
and inserted between each source item in the resulting string.
Returns:
A single string which is the result of stringifying each element
and concatenating the results into a single string.
Raises:
TypeError: If any element cannot be coerced to a string.
TypeError: If the separator cannot be coerced to a string.
ValueError: If the Queryable is closed.
'''
if self.closed():
raise ValueError("Attempt to call to_str() on a closed Queryable.")
return str(separator).join(self.select(str)) | [
"def",
"to_str",
"(",
"self",
",",
"separator",
"=",
"''",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_str() on a closed Queryable.\"",
")",
"return",
"str",
"(",
"separator",
")",
".",
"join",
"(",... | Build a string from the source sequence.
The elements of the query result will each coerced to a string and then
the resulting strings concatenated to return a single string. This
allows the natural processing of character sequences as strings. An
optional separator which will be inserted between each item may be
specified.
Note: this method uses immediate execution.
Args:
separator: An optional separator which will be coerced to a string
and inserted between each source item in the resulting string.
Returns:
A single string which is the result of stringifying each element
and concatenating the results into a single string.
Raises:
TypeError: If any element cannot be coerced to a string.
TypeError: If the separator cannot be coerced to a string.
ValueError: If the Queryable is closed. | [
"Build",
"a",
"string",
"from",
"the",
"source",
"sequence",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2106-L2133 | train | 48,140 |
sixty-north/asq | asq/queryables.py | Queryable.sequence_equal | def sequence_equal(self, second_iterable, equality_comparer=operator.eq):
'''
Determine whether two sequences are equal by elementwise comparison.
Sequence equality is defined as the two sequences being equal length
and corresponding elements being equal as determined by the equality
comparer.
Note: This method uses immediate execution.
Args:
second_iterable: The sequence which will be compared with the
source sequence.
equality_comparer: An optional binary predicate function which is
used to compare corresponding elements. Should return True if
the elements are equal, otherwise False. The default equality
comparer is operator.eq which calls __eq__ on elements of the
source sequence with the corresponding element of the second
sequence as a parameter.
Returns:
True if the sequences are equal, otherwise False.
Raises:
ValueError: If the Queryable is closed.
TypeError: If second_iterable is not in fact iterable.
TypeError: If equality_comparer is not callable.
'''
if self.closed():
raise ValueError("Attempt to call to_tuple() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute sequence_equal() with second_iterable of non-iterable {type}".format(
type=str(type(second_iterable))[7: -1]))
if not is_callable(equality_comparer):
raise TypeError("aggregate() parameter equality_comparer={equality_comparer} is not callable".format(
equality_comparer=repr(equality_comparer)))
# Try to check the lengths directly as an optimization
try:
if len(self._iterable) != len(second_iterable):
return False
except TypeError:
pass
sentinel = object()
for first, second in izip_longest(self, second_iterable, fillvalue=sentinel):
if first is sentinel or second is sentinel:
return False
if not equality_comparer(first, second):
return False
return True | python | def sequence_equal(self, second_iterable, equality_comparer=operator.eq):
'''
Determine whether two sequences are equal by elementwise comparison.
Sequence equality is defined as the two sequences being equal length
and corresponding elements being equal as determined by the equality
comparer.
Note: This method uses immediate execution.
Args:
second_iterable: The sequence which will be compared with the
source sequence.
equality_comparer: An optional binary predicate function which is
used to compare corresponding elements. Should return True if
the elements are equal, otherwise False. The default equality
comparer is operator.eq which calls __eq__ on elements of the
source sequence with the corresponding element of the second
sequence as a parameter.
Returns:
True if the sequences are equal, otherwise False.
Raises:
ValueError: If the Queryable is closed.
TypeError: If second_iterable is not in fact iterable.
TypeError: If equality_comparer is not callable.
'''
if self.closed():
raise ValueError("Attempt to call to_tuple() on a closed Queryable.")
if not is_iterable(second_iterable):
raise TypeError("Cannot compute sequence_equal() with second_iterable of non-iterable {type}".format(
type=str(type(second_iterable))[7: -1]))
if not is_callable(equality_comparer):
raise TypeError("aggregate() parameter equality_comparer={equality_comparer} is not callable".format(
equality_comparer=repr(equality_comparer)))
# Try to check the lengths directly as an optimization
try:
if len(self._iterable) != len(second_iterable):
return False
except TypeError:
pass
sentinel = object()
for first, second in izip_longest(self, second_iterable, fillvalue=sentinel):
if first is sentinel or second is sentinel:
return False
if not equality_comparer(first, second):
return False
return True | [
"def",
"sequence_equal",
"(",
"self",
",",
"second_iterable",
",",
"equality_comparer",
"=",
"operator",
".",
"eq",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call to_tuple() on a closed Queryable.\"",
")",
"if"... | Determine whether two sequences are equal by elementwise comparison.
Sequence equality is defined as the two sequences being equal length
and corresponding elements being equal as determined by the equality
comparer.
Note: This method uses immediate execution.
Args:
second_iterable: The sequence which will be compared with the
source sequence.
equality_comparer: An optional binary predicate function which is
used to compare corresponding elements. Should return True if
the elements are equal, otherwise False. The default equality
comparer is operator.eq which calls __eq__ on elements of the
source sequence with the corresponding element of the second
sequence as a parameter.
Returns:
True if the sequences are equal, otherwise False.
Raises:
ValueError: If the Queryable is closed.
TypeError: If second_iterable is not in fact iterable.
TypeError: If equality_comparer is not callable. | [
"Determine",
"whether",
"two",
"sequences",
"are",
"equal",
"by",
"elementwise",
"comparison",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2135-L2189 | train | 48,141 |
sixty-north/asq | asq/queryables.py | Queryable.log | def log(self, logger=None, label=None, eager=False):
'''
Log query result consumption details to a logger.
Args:
logger: Any object which supports a debug() method which accepts a
str, such as a Python standard library logger object from the
logging module. If logger is not provided or is None, this
method has no logging side effects.
label: An optional label which will be inserted into each line of
logging output produced by this particular use of log
eager: An optional boolean which controls how the query result will
be consumed. If True, the sequence will be consumed and logged
in its entirety. If False (the default) the sequence will be
evaluated and logged lazily as it consumed.
Warning: Use of eager=True requires use of sufficient memory to
hold the entire sequence which is obviously not possible with
infinite sequences. Use with care!
Returns:
A queryable over the unaltered source sequence.
Raises:
AttributeError: If logger does not support a debug() method.
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call log() on a closed Queryable.")
if logger is None:
return self
if label is None:
label = repr(self)
if eager:
return self._create(self._eager_log_result(logger, label))
return self._create(self._generate_lazy_log_result(logger, label)) | python | def log(self, logger=None, label=None, eager=False):
'''
Log query result consumption details to a logger.
Args:
logger: Any object which supports a debug() method which accepts a
str, such as a Python standard library logger object from the
logging module. If logger is not provided or is None, this
method has no logging side effects.
label: An optional label which will be inserted into each line of
logging output produced by this particular use of log
eager: An optional boolean which controls how the query result will
be consumed. If True, the sequence will be consumed and logged
in its entirety. If False (the default) the sequence will be
evaluated and logged lazily as it consumed.
Warning: Use of eager=True requires use of sufficient memory to
hold the entire sequence which is obviously not possible with
infinite sequences. Use with care!
Returns:
A queryable over the unaltered source sequence.
Raises:
AttributeError: If logger does not support a debug() method.
ValueError: If the Queryable has been closed.
'''
if self.closed():
raise ValueError("Attempt to call log() on a closed Queryable.")
if logger is None:
return self
if label is None:
label = repr(self)
if eager:
return self._create(self._eager_log_result(logger, label))
return self._create(self._generate_lazy_log_result(logger, label)) | [
"def",
"log",
"(",
"self",
",",
"logger",
"=",
"None",
",",
"label",
"=",
"None",
",",
"eager",
"=",
"False",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call log() on a closed Queryable.\"",
")",
"if",
... | Log query result consumption details to a logger.
Args:
logger: Any object which supports a debug() method which accepts a
str, such as a Python standard library logger object from the
logging module. If logger is not provided or is None, this
method has no logging side effects.
label: An optional label which will be inserted into each line of
logging output produced by this particular use of log
eager: An optional boolean which controls how the query result will
be consumed. If True, the sequence will be consumed and logged
in its entirety. If False (the default) the sequence will be
evaluated and logged lazily as it consumed.
Warning: Use of eager=True requires use of sufficient memory to
hold the entire sequence which is obviously not possible with
infinite sequences. Use with care!
Returns:
A queryable over the unaltered source sequence.
Raises:
AttributeError: If logger does not support a debug() method.
ValueError: If the Queryable has been closed. | [
"Log",
"query",
"result",
"consumption",
"details",
"to",
"a",
"logger",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2213-L2254 | train | 48,142 |
sixty-north/asq | asq/queryables.py | Queryable.scan | def scan(self, func=operator.add):
'''
An inclusive prefix sum which returns the cumulative application of the
supplied function up to an including the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
Returns:
A Queryable such that the nth element is the sum of the first n
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable.
'''
if self.closed():
raise ValueError("Attempt to call scan() on a "
"closed Queryable.")
if not is_callable(func):
raise TypeError("scan() parameter func={0} is "
"not callable".format(repr(func)))
return self._create(self._generate_scan_result(func)) | python | def scan(self, func=operator.add):
'''
An inclusive prefix sum which returns the cumulative application of the
supplied function up to an including the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
Returns:
A Queryable such that the nth element is the sum of the first n
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable.
'''
if self.closed():
raise ValueError("Attempt to call scan() on a "
"closed Queryable.")
if not is_callable(func):
raise TypeError("scan() parameter func={0} is "
"not callable".format(repr(func)))
return self._create(self._generate_scan_result(func)) | [
"def",
"scan",
"(",
"self",
",",
"func",
"=",
"operator",
".",
"add",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call scan() on a \"",
"\"closed Queryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"func",... | An inclusive prefix sum which returns the cumulative application of the
supplied function up to an including the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
Returns:
A Queryable such that the nth element is the sum of the first n
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable. | [
"An",
"inclusive",
"prefix",
"sum",
"which",
"returns",
"the",
"cumulative",
"application",
"of",
"the",
"supplied",
"function",
"up",
"to",
"an",
"including",
"the",
"current",
"element",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2295-L2321 | train | 48,143 |
sixty-north/asq | asq/queryables.py | Queryable.pre_scan | def pre_scan(self, func=operator.add, seed=0):
'''
An exclusive prefix sum which returns the cumulative application of the
supplied function up to but excluding the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
seed: The first element of the prefix sum and therefore also the
first element of the returned sequence.
Returns:
A Queryable such that the nth element is the sum of the first n-1
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable.
'''
if self.closed():
raise ValueError("Attempt to call pre_scan() on a "
"closed Queryable.")
if not is_callable(func):
raise TypeError("pre_scan() parameter func={0} is "
"not callable".format(repr(func)))
return self._create(self._generate_pre_scan_result(func, seed)) | python | def pre_scan(self, func=operator.add, seed=0):
'''
An exclusive prefix sum which returns the cumulative application of the
supplied function up to but excluding the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
seed: The first element of the prefix sum and therefore also the
first element of the returned sequence.
Returns:
A Queryable such that the nth element is the sum of the first n-1
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable.
'''
if self.closed():
raise ValueError("Attempt to call pre_scan() on a "
"closed Queryable.")
if not is_callable(func):
raise TypeError("pre_scan() parameter func={0} is "
"not callable".format(repr(func)))
return self._create(self._generate_pre_scan_result(func, seed)) | [
"def",
"pre_scan",
"(",
"self",
",",
"func",
"=",
"operator",
".",
"add",
",",
"seed",
"=",
"0",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call pre_scan() on a \"",
"\"closed Queryable.\"",
")",
"if",
"... | An exclusive prefix sum which returns the cumulative application of the
supplied function up to but excluding the current element.
Args:
func: An optional binary function which is commutative - that is,
the order of the arguments is unimportant. Defaults to a
summing operator.
seed: The first element of the prefix sum and therefore also the
first element of the returned sequence.
Returns:
A Queryable such that the nth element is the sum of the first n-1
elements of the source sequence.
Raises:
ValueError: If the Queryable has been closed.
TypeError: If func is not callable. | [
"An",
"exclusive",
"prefix",
"sum",
"which",
"returns",
"the",
"cumulative",
"application",
"of",
"the",
"supplied",
"function",
"up",
"to",
"but",
"excluding",
"the",
"current",
"element",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2337-L2366 | train | 48,144 |
sixty-north/asq | asq/queryables.py | OrderedQueryable.then_by | def then_by(self, key_selector=identity):
'''Introduce subsequent ordering to the sequence with an optional key.
The returned sequence will be sorted in ascending order by the
selected key.
Note: This method uses deferred execution.
Args:
key_selector: A unary function the only positional argument to
which is the element value from which the key will be
selected. The return value should be the key from that
element.
Returns:
An OrderedQueryable over the sorted items.
Raises:
ValueError: If the OrderedQueryable is closed().
TypeError: If key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call then_by() on a "
"closed OrderedQueryable.")
if not is_callable(key_selector):
raise TypeError("then_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
self._funcs.append((-1, key_selector))
return self | python | def then_by(self, key_selector=identity):
'''Introduce subsequent ordering to the sequence with an optional key.
The returned sequence will be sorted in ascending order by the
selected key.
Note: This method uses deferred execution.
Args:
key_selector: A unary function the only positional argument to
which is the element value from which the key will be
selected. The return value should be the key from that
element.
Returns:
An OrderedQueryable over the sorted items.
Raises:
ValueError: If the OrderedQueryable is closed().
TypeError: If key_selector is not callable.
'''
if self.closed():
raise ValueError("Attempt to call then_by() on a "
"closed OrderedQueryable.")
if not is_callable(key_selector):
raise TypeError("then_by() parameter key_selector={key_selector} "
"is not callable".format(key_selector=repr(key_selector)))
self._funcs.append((-1, key_selector))
return self | [
"def",
"then_by",
"(",
"self",
",",
"key_selector",
"=",
"identity",
")",
":",
"if",
"self",
".",
"closed",
"(",
")",
":",
"raise",
"ValueError",
"(",
"\"Attempt to call then_by() on a \"",
"\"closed OrderedQueryable.\"",
")",
"if",
"not",
"is_callable",
"(",
"k... | Introduce subsequent ordering to the sequence with an optional key.
The returned sequence will be sorted in ascending order by the
selected key.
Note: This method uses deferred execution.
Args:
key_selector: A unary function the only positional argument to
which is the element value from which the key will be
selected. The return value should be the key from that
element.
Returns:
An OrderedQueryable over the sorted items.
Raises:
ValueError: If the OrderedQueryable is closed().
TypeError: If key_selector is not callable. | [
"Introduce",
"subsequent",
"ordering",
"to",
"the",
"sequence",
"with",
"an",
"optional",
"key",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/queryables.py#L2526-L2556 | train | 48,145 |
sixty-north/asq | asq/parallel_queryable.py | geometric_partitions | def geometric_partitions(iterable, floor=1, ceiling=32768):
'''
Partition an iterable into chunks. Returns an iterator over partitions.
'''
partition_size = floor
run_length = multiprocessing.cpu_count()
run_count = 0
try:
while True:
#print("partition_size =", partition_size)
# Split the iterable and replace the original iterator to avoid
# advancing it
partition, iterable = itertools.tee(iterable)
# Yield the first partition, limited to the partition size
yield Queryable(partition).take(partition_size)
# Advance to the start of the next partition, this will raise
# StopIteration if the iterator is exhausted
for i in range(partition_size):
next(iterable)
# If we've reached the end of a run of this size, double the
# partition size
run_count += 1
if run_count >= run_length:
partition_size *= 2
run_count = 0
# Unless we have hit the ceiling
if partition_size > ceiling:
partition_size = ceiling
except StopIteration:
pass | python | def geometric_partitions(iterable, floor=1, ceiling=32768):
'''
Partition an iterable into chunks. Returns an iterator over partitions.
'''
partition_size = floor
run_length = multiprocessing.cpu_count()
run_count = 0
try:
while True:
#print("partition_size =", partition_size)
# Split the iterable and replace the original iterator to avoid
# advancing it
partition, iterable = itertools.tee(iterable)
# Yield the first partition, limited to the partition size
yield Queryable(partition).take(partition_size)
# Advance to the start of the next partition, this will raise
# StopIteration if the iterator is exhausted
for i in range(partition_size):
next(iterable)
# If we've reached the end of a run of this size, double the
# partition size
run_count += 1
if run_count >= run_length:
partition_size *= 2
run_count = 0
# Unless we have hit the ceiling
if partition_size > ceiling:
partition_size = ceiling
except StopIteration:
pass | [
"def",
"geometric_partitions",
"(",
"iterable",
",",
"floor",
"=",
"1",
",",
"ceiling",
"=",
"32768",
")",
":",
"partition_size",
"=",
"floor",
"run_length",
"=",
"multiprocessing",
".",
"cpu_count",
"(",
")",
"run_count",
"=",
"0",
"try",
":",
"while",
"T... | Partition an iterable into chunks. Returns an iterator over partitions. | [
"Partition",
"an",
"iterable",
"into",
"chunks",
".",
"Returns",
"an",
"iterator",
"over",
"partitions",
"."
] | db0c4cbcf2118435136d4b63c62a12711441088e | https://github.com/sixty-north/asq/blob/db0c4cbcf2118435136d4b63c62a12711441088e/asq/parallel_queryable.py#L268-L303 | train | 48,146 |
leonardt/hwtypes | hwtypes/bit_vector.py | BitVector.adc | def adc(self, other : 'BitVector', carry : Bit) -> tp.Tuple['BitVector', Bit]:
"""
add with carry
returns a two element tuple of the form (result, carry)
"""
T = type(self)
other = _coerce(T, other)
carry = _coerce(T.unsized_t[1], carry)
a = self.zext(1)
b = other.zext(1)
c = carry.zext(T.size)
res = a + b + c
return res[0:-1], res[-1] | python | def adc(self, other : 'BitVector', carry : Bit) -> tp.Tuple['BitVector', Bit]:
"""
add with carry
returns a two element tuple of the form (result, carry)
"""
T = type(self)
other = _coerce(T, other)
carry = _coerce(T.unsized_t[1], carry)
a = self.zext(1)
b = other.zext(1)
c = carry.zext(T.size)
res = a + b + c
return res[0:-1], res[-1] | [
"def",
"adc",
"(",
"self",
",",
"other",
":",
"'BitVector'",
",",
"carry",
":",
"Bit",
")",
"->",
"tp",
".",
"Tuple",
"[",
"'BitVector'",
",",
"Bit",
"]",
":",
"T",
"=",
"type",
"(",
"self",
")",
"other",
"=",
"_coerce",
"(",
"T",
",",
"other",
... | add with carry
returns a two element tuple of the form (result, carry) | [
"add",
"with",
"carry"
] | 65439bb5e1d8f9afa7852c00a8378b622a9f986e | https://github.com/leonardt/hwtypes/blob/65439bb5e1d8f9afa7852c00a8378b622a9f986e/hwtypes/bit_vector.py#L273-L289 | train | 48,147 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/table.py | make_table | def make_table(headers=None, rows=None):
"""Make a table from headers and rows."""
if callable(headers):
headers = headers()
if callable(rows):
rows = rows()
assert isinstance(headers, list)
assert isinstance(rows, list)
assert all(len(row) == len(headers) for row in rows)
plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]
plain_headers = []
column_widths = []
for k, v in enumerate(headers):
v = six.text_type(v)
plain = strip_ansi(v)
plain_headers.append(plain)
column_widths.append(len(plain))
if len(v) == len(plain):
# Value was unstyled, make it bold
v = click.style(v, bold=True)
headers[k] = v
plain_rows = []
for row in rows:
plain_row = []
for k, v in enumerate(row):
v = six.text_type(v)
plain = strip_ansi(v)
plain_row.append(plain)
column_widths[k] = max(column_widths[k], len(plain))
plain_rows.append(plain_row)
return Table(
headers=headers,
plain_headers=plain_headers,
rows=rows,
plain_rows=plain_rows,
column_widths=column_widths,
) | python | def make_table(headers=None, rows=None):
"""Make a table from headers and rows."""
if callable(headers):
headers = headers()
if callable(rows):
rows = rows()
assert isinstance(headers, list)
assert isinstance(rows, list)
assert all(len(row) == len(headers) for row in rows)
plain_headers = [strip_ansi(six.text_type(v)) for v in headers]
plain_rows = [row for row in [strip_ansi(six.text_type(v)) for v in rows]]
plain_headers = []
column_widths = []
for k, v in enumerate(headers):
v = six.text_type(v)
plain = strip_ansi(v)
plain_headers.append(plain)
column_widths.append(len(plain))
if len(v) == len(plain):
# Value was unstyled, make it bold
v = click.style(v, bold=True)
headers[k] = v
plain_rows = []
for row in rows:
plain_row = []
for k, v in enumerate(row):
v = six.text_type(v)
plain = strip_ansi(v)
plain_row.append(plain)
column_widths[k] = max(column_widths[k], len(plain))
plain_rows.append(plain_row)
return Table(
headers=headers,
plain_headers=plain_headers,
rows=rows,
plain_rows=plain_rows,
column_widths=column_widths,
) | [
"def",
"make_table",
"(",
"headers",
"=",
"None",
",",
"rows",
"=",
"None",
")",
":",
"if",
"callable",
"(",
"headers",
")",
":",
"headers",
"=",
"headers",
"(",
")",
"if",
"callable",
"(",
"rows",
")",
":",
"rows",
"=",
"rows",
"(",
")",
"assert",... | Make a table from headers and rows. | [
"Make",
"a",
"table",
"from",
"headers",
"and",
"rows",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/table.py#L17-L62 | train | 48,148 |
venmo/slouch | slouch/__init__.py | _dual_decorator | def _dual_decorator(func):
"""This is a decorator that converts a paramaterized decorator for
no-param use.
source: http://stackoverflow.com/questions/3888158
"""
@functools.wraps(func)
def inner(*args, **kwargs):
if ((len(args) == 1 and not kwargs and callable(args[0])
and not (type(args[0]) == type and issubclass(args[0], BaseException)))):
return func()(args[0])
elif len(args) == 2 and inspect.isclass(args[0]) and callable(args[1]):
return func(args[0], **kwargs)(args[1])
else:
return func(*args, **kwargs)
return inner | python | def _dual_decorator(func):
"""This is a decorator that converts a paramaterized decorator for
no-param use.
source: http://stackoverflow.com/questions/3888158
"""
@functools.wraps(func)
def inner(*args, **kwargs):
if ((len(args) == 1 and not kwargs and callable(args[0])
and not (type(args[0]) == type and issubclass(args[0], BaseException)))):
return func()(args[0])
elif len(args) == 2 and inspect.isclass(args[0]) and callable(args[1]):
return func(args[0], **kwargs)(args[1])
else:
return func(*args, **kwargs)
return inner | [
"def",
"_dual_decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"inner",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"(",
"(",
"len",
"(",
"args",
")",
"==",
"1",
"and",
"not",
"kwargs",
... | This is a decorator that converts a paramaterized decorator for
no-param use.
source: http://stackoverflow.com/questions/3888158 | [
"This",
"is",
"a",
"decorator",
"that",
"converts",
"a",
"paramaterized",
"decorator",
"for",
"no",
"-",
"param",
"use",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L20-L36 | train | 48,149 |
venmo/slouch | slouch/__init__.py | Bot.command | def command(cls, name=None):
"""
A decorator to convert a function to a command.
A command's docstring must be a docopt usage string.
See docopt.org for what it supports.
Commands receive three arguments:
* opts: a dictionary output by docopt
* bot: the Bot instance handling the command (eg for storing state between commands)
* event: the Slack event that triggered the command (eg for finding the message's sender)
Additional options may be passed in as keyword arguments:
* name: the string used to execute the command (no spaces allowed)
They must return one of three things:
* a string of response text. It will be sent via the RTM api to the channel where
the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting.
* None, to send no response.
* a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage.
Use this to send more complex messages, such as those with custom link text or DMs.
For example, to respond with a DM containing custom link text, return
`{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`.
Note that this api has higher latency than the RTM api; use it only when necessary.
"""
# adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py
def decorator(func):
@functools.wraps(func)
def _cmd_wrapper(rest, *args, **kwargs):
try:
usage = _cmd_wrapper.__doc__.partition('\n')[0]
opts = docopt(usage, rest)
except (SystemExit, DocoptExit) as e:
# opts did not match
return str(e)
return func(opts, *args, **kwargs)
cls.commands[name or func.__name__] = _cmd_wrapper
return _cmd_wrapper
return decorator | python | def command(cls, name=None):
"""
A decorator to convert a function to a command.
A command's docstring must be a docopt usage string.
See docopt.org for what it supports.
Commands receive three arguments:
* opts: a dictionary output by docopt
* bot: the Bot instance handling the command (eg for storing state between commands)
* event: the Slack event that triggered the command (eg for finding the message's sender)
Additional options may be passed in as keyword arguments:
* name: the string used to execute the command (no spaces allowed)
They must return one of three things:
* a string of response text. It will be sent via the RTM api to the channel where
the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting.
* None, to send no response.
* a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage.
Use this to send more complex messages, such as those with custom link text or DMs.
For example, to respond with a DM containing custom link text, return
`{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`.
Note that this api has higher latency than the RTM api; use it only when necessary.
"""
# adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py
def decorator(func):
@functools.wraps(func)
def _cmd_wrapper(rest, *args, **kwargs):
try:
usage = _cmd_wrapper.__doc__.partition('\n')[0]
opts = docopt(usage, rest)
except (SystemExit, DocoptExit) as e:
# opts did not match
return str(e)
return func(opts, *args, **kwargs)
cls.commands[name or func.__name__] = _cmd_wrapper
return _cmd_wrapper
return decorator | [
"def",
"command",
"(",
"cls",
",",
"name",
"=",
"None",
")",
":",
"# adapted from https://github.com/docopt/docopt/blob/master/examples/interactive_example.py",
"def",
"decorator",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"_cmd... | A decorator to convert a function to a command.
A command's docstring must be a docopt usage string.
See docopt.org for what it supports.
Commands receive three arguments:
* opts: a dictionary output by docopt
* bot: the Bot instance handling the command (eg for storing state between commands)
* event: the Slack event that triggered the command (eg for finding the message's sender)
Additional options may be passed in as keyword arguments:
* name: the string used to execute the command (no spaces allowed)
They must return one of three things:
* a string of response text. It will be sent via the RTM api to the channel where
the bot received the message. Slack will format it as per https://api.slack.com/docs/message-formatting.
* None, to send no response.
* a dictionary of kwargs representing a message to send via https://api.slack.com/methods/chat.postMessage.
Use this to send more complex messages, such as those with custom link text or DMs.
For example, to respond with a DM containing custom link text, return
`{'text': '<http://example.com|my text>', 'channel': event['user'], 'username': bot.name}`.
Note that this api has higher latency than the RTM api; use it only when necessary. | [
"A",
"decorator",
"to",
"convert",
"a",
"function",
"to",
"a",
"command",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L83-L129 | train | 48,150 |
venmo/slouch | slouch/__init__.py | Bot.help_text | def help_text(cls):
"""Return a slack-formatted list of commands with their usage."""
docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()]
# Don't want to include 'usage: ' or explanation.
usage_lines = [doc.partition('\n')[0] for doc in docs]
terse_lines = [line[len('Usage: '):] for line in usage_lines]
terse_lines.sort()
return '\n'.join(['Available commands:\n'] + terse_lines) | python | def help_text(cls):
"""Return a slack-formatted list of commands with their usage."""
docs = [cmd_func.__doc__ for cmd_func in cls.commands.values()]
# Don't want to include 'usage: ' or explanation.
usage_lines = [doc.partition('\n')[0] for doc in docs]
terse_lines = [line[len('Usage: '):] for line in usage_lines]
terse_lines.sort()
return '\n'.join(['Available commands:\n'] + terse_lines) | [
"def",
"help_text",
"(",
"cls",
")",
":",
"docs",
"=",
"[",
"cmd_func",
".",
"__doc__",
"for",
"cmd_func",
"in",
"cls",
".",
"commands",
".",
"values",
"(",
")",
"]",
"# Don't want to include 'usage: ' or explanation.",
"usage_lines",
"=",
"[",
"doc",
".",
"... | Return a slack-formatted list of commands with their usage. | [
"Return",
"a",
"slack",
"-",
"formatted",
"list",
"of",
"commands",
"with",
"their",
"usage",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L132-L140 | train | 48,151 |
venmo/slouch | slouch/__init__.py | Bot.run_forever | def run_forever(self):
"""Run the bot, blocking forever."""
res = self.slack.rtm.start()
self.log.info("current channels: %s",
','.join(c['name'] for c in res.body['channels']
if c['is_member']))
self.id = res.body['self']['id']
self.name = res.body['self']['name']
self.my_mention = "<@%s>" % self.id
self.ws = websocket.WebSocketApp(
res.body['url'],
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close,
on_open=self._on_open)
self.prepare_connection(self.config)
self.ws.run_forever() | python | def run_forever(self):
"""Run the bot, blocking forever."""
res = self.slack.rtm.start()
self.log.info("current channels: %s",
','.join(c['name'] for c in res.body['channels']
if c['is_member']))
self.id = res.body['self']['id']
self.name = res.body['self']['name']
self.my_mention = "<@%s>" % self.id
self.ws = websocket.WebSocketApp(
res.body['url'],
on_message=self._on_message,
on_error=self._on_error,
on_close=self._on_close,
on_open=self._on_open)
self.prepare_connection(self.config)
self.ws.run_forever() | [
"def",
"run_forever",
"(",
"self",
")",
":",
"res",
"=",
"self",
".",
"slack",
".",
"rtm",
".",
"start",
"(",
")",
"self",
".",
"log",
".",
"info",
"(",
"\"current channels: %s\"",
",",
"','",
".",
"join",
"(",
"c",
"[",
"'name'",
"]",
"for",
"c",
... | Run the bot, blocking forever. | [
"Run",
"the",
"bot",
"blocking",
"forever",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L199-L216 | train | 48,152 |
venmo/slouch | slouch/__init__.py | Bot._bot_identifier | def _bot_identifier(self, message):
"""Return the identifier used to address this bot in this message.
If one is not found, return None.
:param message: a message dict from the slack api.
"""
text = message['text']
formatters = [
lambda identifier: "%s " % identifier,
lambda identifier: "%s:" % identifier,
]
my_identifiers = [formatter(identifier) for identifier in [self.name, self.my_mention] for formatter in formatters]
for identifier in my_identifiers:
if text.startswith(identifier):
self.log.debug("sent to me:\n%s", pprint.pformat(message))
return identifier
return None | python | def _bot_identifier(self, message):
"""Return the identifier used to address this bot in this message.
If one is not found, return None.
:param message: a message dict from the slack api.
"""
text = message['text']
formatters = [
lambda identifier: "%s " % identifier,
lambda identifier: "%s:" % identifier,
]
my_identifiers = [formatter(identifier) for identifier in [self.name, self.my_mention] for formatter in formatters]
for identifier in my_identifiers:
if text.startswith(identifier):
self.log.debug("sent to me:\n%s", pprint.pformat(message))
return identifier
return None | [
"def",
"_bot_identifier",
"(",
"self",
",",
"message",
")",
":",
"text",
"=",
"message",
"[",
"'text'",
"]",
"formatters",
"=",
"[",
"lambda",
"identifier",
":",
"\"%s \"",
"%",
"identifier",
",",
"lambda",
"identifier",
":",
"\"%s:\"",
"%",
"identifier",
... | Return the identifier used to address this bot in this message.
If one is not found, return None.
:param message: a message dict from the slack api. | [
"Return",
"the",
"identifier",
"used",
"to",
"address",
"this",
"bot",
"in",
"this",
"message",
".",
"If",
"one",
"is",
"not",
"found",
"return",
"None",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L218-L238 | train | 48,153 |
venmo/slouch | slouch/__init__.py | Bot._send_rtm_message | def _send_rtm_message(self, channel_id, text):
"""Send a Slack message to a channel over RTM.
:param channel_id: a slack channel id.
:param text: a slack message. Serverside formatting is done
in a similar way to normal user message; see
`Slack's docs <https://api.slack.com/docs/formatting>`__.
"""
message = {
'id': self._current_message_id,
'type': 'message',
'channel': channel_id,
'text': text,
}
self.ws.send(json.dumps(message))
self._current_message_id += 1 | python | def _send_rtm_message(self, channel_id, text):
"""Send a Slack message to a channel over RTM.
:param channel_id: a slack channel id.
:param text: a slack message. Serverside formatting is done
in a similar way to normal user message; see
`Slack's docs <https://api.slack.com/docs/formatting>`__.
"""
message = {
'id': self._current_message_id,
'type': 'message',
'channel': channel_id,
'text': text,
}
self.ws.send(json.dumps(message))
self._current_message_id += 1 | [
"def",
"_send_rtm_message",
"(",
"self",
",",
"channel_id",
",",
"text",
")",
":",
"message",
"=",
"{",
"'id'",
":",
"self",
".",
"_current_message_id",
",",
"'type'",
":",
"'message'",
",",
"'channel'",
":",
"channel_id",
",",
"'text'",
":",
"text",
",",
... | Send a Slack message to a channel over RTM.
:param channel_id: a slack channel id.
:param text: a slack message. Serverside formatting is done
in a similar way to normal user message; see
`Slack's docs <https://api.slack.com/docs/formatting>`__. | [
"Send",
"a",
"Slack",
"message",
"to",
"a",
"channel",
"over",
"RTM",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L303-L319 | train | 48,154 |
venmo/slouch | slouch/__init__.py | Bot._send_api_message | def _send_api_message(self, message):
"""Send a Slack message via the chat.postMessage api.
:param message: a dict of kwargs to be passed to slacker.
"""
self.slack.chat.post_message(**message)
self.log.debug("sent api message %r", message) | python | def _send_api_message(self, message):
"""Send a Slack message via the chat.postMessage api.
:param message: a dict of kwargs to be passed to slacker.
"""
self.slack.chat.post_message(**message)
self.log.debug("sent api message %r", message) | [
"def",
"_send_api_message",
"(",
"self",
",",
"message",
")",
":",
"self",
".",
"slack",
".",
"chat",
".",
"post_message",
"(",
"*",
"*",
"message",
")",
"self",
".",
"log",
".",
"debug",
"(",
"\"sent api message %r\"",
",",
"message",
")"
] | Send a Slack message via the chat.postMessage api.
:param message: a dict of kwargs to be passed to slacker. | [
"Send",
"a",
"Slack",
"message",
"via",
"the",
"chat",
".",
"postMessage",
"api",
"."
] | 000b03bc220a0d7aa5b06f59caf423e2b63a81d7 | https://github.com/venmo/slouch/blob/000b03bc220a0d7aa5b06f59caf423e2b63a81d7/slouch/__init__.py#L321-L328 | train | 48,155 |
marrow/schema | marrow/schema/validate/compound.py | Compound._validators | def _validators(self):
"""Iterate across the complete set of child validators."""
for validator in self.__validators__.values():
yield validator
if self.validators:
for validator in self.validators:
yield validator | python | def _validators(self):
"""Iterate across the complete set of child validators."""
for validator in self.__validators__.values():
yield validator
if self.validators:
for validator in self.validators:
yield validator | [
"def",
"_validators",
"(",
"self",
")",
":",
"for",
"validator",
"in",
"self",
".",
"__validators__",
".",
"values",
"(",
")",
":",
"yield",
"validator",
"if",
"self",
".",
"validators",
":",
"for",
"validator",
"in",
"self",
".",
"validators",
":",
"yie... | Iterate across the complete set of child validators. | [
"Iterate",
"across",
"the",
"complete",
"set",
"of",
"child",
"validators",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/validate/compound.py#L24-L32 | train | 48,156 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | make_user_agent | def make_user_agent(prefix=None):
"""Get a suitable user agent for identifying the CLI process."""
prefix = (prefix or platform.platform(terse=1)).strip().lower()
return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % {
"version": get_cli_version(),
"api_version": get_api_version(),
"prefix": prefix,
} | python | def make_user_agent(prefix=None):
"""Get a suitable user agent for identifying the CLI process."""
prefix = (prefix or platform.platform(terse=1)).strip().lower()
return "cloudsmith-cli/%(prefix)s cli:%(version)s api:%(api_version)s" % {
"version": get_cli_version(),
"api_version": get_api_version(),
"prefix": prefix,
} | [
"def",
"make_user_agent",
"(",
"prefix",
"=",
"None",
")",
":",
"prefix",
"=",
"(",
"prefix",
"or",
"platform",
".",
"platform",
"(",
"terse",
"=",
"1",
")",
")",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"return",
"\"cloudsmith-cli/%(prefix)s cli:... | Get a suitable user agent for identifying the CLI process. | [
"Get",
"a",
"suitable",
"user",
"agent",
"for",
"identifying",
"the",
"CLI",
"process",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L18-L25 | train | 48,157 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | pretty_print_list_info | def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = "green" if num_results else "red"
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page_range = page_info.calculate_range(num_results)
page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % {
"page": click.style(str(page_info.page), bold=True),
"page_size": click.style(str(page_info.page_size), bold=True),
"page_total": click.style(str(page_info.page_total), bold=True),
}
range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % {
"num_results": num_results_text,
"from": click.style(str(page_range[0]), fg=num_results_fg),
"to": click.style(str(page_range[1]), fg=num_results_fg),
"total": click.style(str(page_info.count), fg=num_results_fg),
}
else:
page_info_text = ""
range_results_text = num_results_text
click.secho(
"Results: %(range_results)s %(suffix)s%(page_info)s"
% {
"range_results": range_results_text,
"page_info": " (%s)" % page_info_text if page_info_text else "",
"suffix": suffix or "item(s)",
}
) | python | def pretty_print_list_info(num_results, page_info=None, suffix=None):
"""Pretty print list info, with pagination, for user display."""
num_results_fg = "green" if num_results else "red"
num_results_text = click.style(str(num_results), fg=num_results_fg)
if page_info and page_info.is_valid:
page_range = page_info.calculate_range(num_results)
page_info_text = "page: %(page)s/%(page_total)s, page size: %(page_size)s" % {
"page": click.style(str(page_info.page), bold=True),
"page_size": click.style(str(page_info.page_size), bold=True),
"page_total": click.style(str(page_info.page_total), bold=True),
}
range_results_text = "%(from)s-%(to)s (%(num_results)s) of %(total)s" % {
"num_results": num_results_text,
"from": click.style(str(page_range[0]), fg=num_results_fg),
"to": click.style(str(page_range[1]), fg=num_results_fg),
"total": click.style(str(page_info.count), fg=num_results_fg),
}
else:
page_info_text = ""
range_results_text = num_results_text
click.secho(
"Results: %(range_results)s %(suffix)s%(page_info)s"
% {
"range_results": range_results_text,
"page_info": " (%s)" % page_info_text if page_info_text else "",
"suffix": suffix or "item(s)",
}
) | [
"def",
"pretty_print_list_info",
"(",
"num_results",
",",
"page_info",
"=",
"None",
",",
"suffix",
"=",
"None",
")",
":",
"num_results_fg",
"=",
"\"green\"",
"if",
"num_results",
"else",
"\"red\"",
"num_results_text",
"=",
"click",
".",
"style",
"(",
"str",
"(... | Pretty print list info, with pagination, for user display. | [
"Pretty",
"print",
"list",
"info",
"with",
"pagination",
"for",
"user",
"display",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L28-L57 | train | 48,158 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | pretty_print_table | def pretty_print_table(headers, rows):
"""Pretty print a table from headers and rows."""
table = make_table(headers=headers, rows=rows)
pretty_print_table_instance(table) | python | def pretty_print_table(headers, rows):
"""Pretty print a table from headers and rows."""
table = make_table(headers=headers, rows=rows)
pretty_print_table_instance(table) | [
"def",
"pretty_print_table",
"(",
"headers",
",",
"rows",
")",
":",
"table",
"=",
"make_table",
"(",
"headers",
"=",
"headers",
",",
"rows",
"=",
"rows",
")",
"pretty_print_table_instance",
"(",
"table",
")"
] | Pretty print a table from headers and rows. | [
"Pretty",
"print",
"a",
"table",
"from",
"headers",
"and",
"rows",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L60-L63 | train | 48,159 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | pretty_print_table_instance | def pretty_print_table_instance(table):
"""Pretty print a table instance."""
assert isinstance(table, Table)
def pretty_print_row(styled, plain):
"""Pretty print a row."""
click.secho(
" | ".join(
v + " " * (table.column_widths[k] - len(plain[k]))
for k, v in enumerate(styled)
)
)
pretty_print_row(table.headers, table.plain_headers)
for k, row in enumerate(table.rows):
pretty_print_row(row, table.plain_rows[k]) | python | def pretty_print_table_instance(table):
"""Pretty print a table instance."""
assert isinstance(table, Table)
def pretty_print_row(styled, plain):
"""Pretty print a row."""
click.secho(
" | ".join(
v + " " * (table.column_widths[k] - len(plain[k]))
for k, v in enumerate(styled)
)
)
pretty_print_row(table.headers, table.plain_headers)
for k, row in enumerate(table.rows):
pretty_print_row(row, table.plain_rows[k]) | [
"def",
"pretty_print_table_instance",
"(",
"table",
")",
":",
"assert",
"isinstance",
"(",
"table",
",",
"Table",
")",
"def",
"pretty_print_row",
"(",
"styled",
",",
"plain",
")",
":",
"\"\"\"Pretty print a row.\"\"\"",
"click",
".",
"secho",
"(",
"\" | \"",
"."... | Pretty print a table instance. | [
"Pretty",
"print",
"a",
"table",
"instance",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L66-L81 | train | 48,160 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | print_rate_limit_info | def print_rate_limit_info(opts, rate_info, atexit=False):
"""Tell the user when we're being rate limited."""
if not rate_info:
return
show_info = (
opts.always_show_rate_limit
or atexit
or rate_info.interval > opts.rate_limit_warning
)
if not show_info:
return
click.echo(err=True)
click.secho(
"Throttling (rate limited) for: %(throttle)s seconds ... "
% {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)},
err=True,
reset=False,
) | python | def print_rate_limit_info(opts, rate_info, atexit=False):
"""Tell the user when we're being rate limited."""
if not rate_info:
return
show_info = (
opts.always_show_rate_limit
or atexit
or rate_info.interval > opts.rate_limit_warning
)
if not show_info:
return
click.echo(err=True)
click.secho(
"Throttling (rate limited) for: %(throttle)s seconds ... "
% {"throttle": click.style(six.text_type(rate_info.interval), reverse=True)},
err=True,
reset=False,
) | [
"def",
"print_rate_limit_info",
"(",
"opts",
",",
"rate_info",
",",
"atexit",
"=",
"False",
")",
":",
"if",
"not",
"rate_info",
":",
"return",
"show_info",
"=",
"(",
"opts",
".",
"always_show_rate_limit",
"or",
"atexit",
"or",
"rate_info",
".",
"interval",
"... | Tell the user when we're being rate limited. | [
"Tell",
"the",
"user",
"when",
"we",
"re",
"being",
"rate",
"limited",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L84-L104 | train | 48,161 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | maybe_print_as_json | def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagination"] = page_info.as_dict(num_results=len(data))
if opts.output == "pretty_json":
dump = json.dumps(root, indent=4, sort_keys=True)
else:
dump = json.dumps(root, sort_keys=True)
click.echo(dump)
return True | python | def maybe_print_as_json(opts, data, page_info=None):
"""Maybe print data as JSON."""
if opts.output not in ("json", "pretty_json"):
return False
root = {"data": data}
if page_info is not None and page_info.is_valid:
meta = root["meta"] = {}
meta["pagination"] = page_info.as_dict(num_results=len(data))
if opts.output == "pretty_json":
dump = json.dumps(root, indent=4, sort_keys=True)
else:
dump = json.dumps(root, sort_keys=True)
click.echo(dump)
return True | [
"def",
"maybe_print_as_json",
"(",
"opts",
",",
"data",
",",
"page_info",
"=",
"None",
")",
":",
"if",
"opts",
".",
"output",
"not",
"in",
"(",
"\"json\"",
",",
"\"pretty_json\"",
")",
":",
"return",
"False",
"root",
"=",
"{",
"\"data\"",
":",
"data",
... | Maybe print data as JSON. | [
"Maybe",
"print",
"data",
"as",
"JSON",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L107-L124 | train | 48,162 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/utils.py | confirm_operation | def confirm_operation(prompt, prefix=None, assume_yes=False, err=False):
"""Prompt the user for confirmation for dangerous actions."""
if assume_yes:
return True
prefix = prefix or click.style(
"Are you %s certain you want to" % (click.style("absolutely", bold=True))
)
prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt}
if click.confirm(prompt, err=err):
return True
click.echo(err=err)
click.secho("OK, phew! Close call. :-)", fg="green", err=err)
return False | python | def confirm_operation(prompt, prefix=None, assume_yes=False, err=False):
"""Prompt the user for confirmation for dangerous actions."""
if assume_yes:
return True
prefix = prefix or click.style(
"Are you %s certain you want to" % (click.style("absolutely", bold=True))
)
prompt = "%(prefix)s %(prompt)s?" % {"prefix": prefix, "prompt": prompt}
if click.confirm(prompt, err=err):
return True
click.echo(err=err)
click.secho("OK, phew! Close call. :-)", fg="green", err=err)
return False | [
"def",
"confirm_operation",
"(",
"prompt",
",",
"prefix",
"=",
"None",
",",
"assume_yes",
"=",
"False",
",",
"err",
"=",
"False",
")",
":",
"if",
"assume_yes",
":",
"return",
"True",
"prefix",
"=",
"prefix",
"or",
"click",
".",
"style",
"(",
"\"Are you %... | Prompt the user for confirmation for dangerous actions. | [
"Prompt",
"the",
"user",
"for",
"confirmation",
"for",
"dangerous",
"actions",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/utils.py#L127-L143 | train | 48,163 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/token.py | validate_login | def validate_login(ctx, param, value):
"""Ensure that login is not blank."""
# pylint: disable=unused-argument
value = value.strip()
if not value:
raise click.BadParameter("The value cannot be blank.", param=param)
return value | python | def validate_login(ctx, param, value):
"""Ensure that login is not blank."""
# pylint: disable=unused-argument
value = value.strip()
if not value:
raise click.BadParameter("The value cannot be blank.", param=param)
return value | [
"def",
"validate_login",
"(",
"ctx",
",",
"param",
",",
"value",
")",
":",
"# pylint: disable=unused-argument",
"value",
"=",
"value",
".",
"strip",
"(",
")",
"if",
"not",
"value",
":",
"raise",
"click",
".",
"BadParameter",
"(",
"\"The value cannot be blank.\""... | Ensure that login is not blank. | [
"Ensure",
"that",
"login",
"is",
"not",
"blank",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/token.py#L22-L28 | train | 48,164 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/token.py | create_config_files | def create_config_files(ctx, opts, api_key):
"""Create default config files."""
# pylint: disable=unused-argument
config_reader = opts.get_config_reader()
creds_reader = opts.get_creds_reader()
has_config = config_reader.has_default_file()
has_creds = creds_reader.has_default_file()
if has_config and has_creds:
create = False
else:
click.echo()
create = click.confirm(
"No default config file(s) found, do you want to create them?"
)
click.echo()
if not create:
click.secho(
"For reference here are your default config file locations:", fg="yellow"
)
else:
click.secho(
"Great! Let me just create your default configs for you now ...", fg="green"
)
configs = (
ConfigValues(reader=config_reader, present=has_config, mode=None, data={}),
ConfigValues(
reader=creds_reader,
present=has_creds,
mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP,
data={"api_key": api_key},
),
)
has_errors = False
for config in configs:
click.echo(
"%(name)s config file: %(filepath)s ... "
% {
"name": click.style(config.reader.config_name.capitalize(), bold=True),
"filepath": click.style(
config.reader.get_default_filepath(), fg="magenta"
),
},
nl=False,
)
if not config.present and create:
try:
ok = config.reader.create_default_file(
data=config.data, mode=config.mode
)
except (OSError, IOError) as exc:
ok = False
error_message = exc.strerror
has_errors = True
if ok:
click.secho("CREATED", fg="green")
else:
click.secho("ERROR", fg="red")
click.secho(
"The following error occurred while trying to "
"create the file: %(message)s"
% {"message": click.style(error_message, fg="red")}
)
continue
click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow")
return create, has_errors | python | def create_config_files(ctx, opts, api_key):
"""Create default config files."""
# pylint: disable=unused-argument
config_reader = opts.get_config_reader()
creds_reader = opts.get_creds_reader()
has_config = config_reader.has_default_file()
has_creds = creds_reader.has_default_file()
if has_config and has_creds:
create = False
else:
click.echo()
create = click.confirm(
"No default config file(s) found, do you want to create them?"
)
click.echo()
if not create:
click.secho(
"For reference here are your default config file locations:", fg="yellow"
)
else:
click.secho(
"Great! Let me just create your default configs for you now ...", fg="green"
)
configs = (
ConfigValues(reader=config_reader, present=has_config, mode=None, data={}),
ConfigValues(
reader=creds_reader,
present=has_creds,
mode=stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IWGRP,
data={"api_key": api_key},
),
)
has_errors = False
for config in configs:
click.echo(
"%(name)s config file: %(filepath)s ... "
% {
"name": click.style(config.reader.config_name.capitalize(), bold=True),
"filepath": click.style(
config.reader.get_default_filepath(), fg="magenta"
),
},
nl=False,
)
if not config.present and create:
try:
ok = config.reader.create_default_file(
data=config.data, mode=config.mode
)
except (OSError, IOError) as exc:
ok = False
error_message = exc.strerror
has_errors = True
if ok:
click.secho("CREATED", fg="green")
else:
click.secho("ERROR", fg="red")
click.secho(
"The following error occurred while trying to "
"create the file: %(message)s"
% {"message": click.style(error_message, fg="red")}
)
continue
click.secho("EXISTS" if config.present else "NOT CREATED", fg="yellow")
return create, has_errors | [
"def",
"create_config_files",
"(",
"ctx",
",",
"opts",
",",
"api_key",
")",
":",
"# pylint: disable=unused-argument",
"config_reader",
"=",
"opts",
".",
"get_config_reader",
"(",
")",
"creds_reader",
"=",
"opts",
".",
"get_creds_reader",
"(",
")",
"has_config",
"=... | Create default config files. | [
"Create",
"default",
"config",
"files",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/token.py#L31-L103 | train | 48,165 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/commands/status.py | status | def status(ctx, opts, owner_repo_package):
"""
Get the synchronisation status for a package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
"""
owner, repo, slug = owner_repo_package
click.echo(
"Getting status of %(package)s in %(owner)s/%(repo)s ... "
% {
"owner": click.style(owner, bold=True),
"repo": click.style(repo, bold=True),
"package": click.style(slug, bold=True),
},
nl=False,
)
context_msg = "Failed to get status of package!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
res = get_package_status(owner, repo, slug)
ok, failed, _, status_str, stage_str, reason = res
click.secho("OK", fg="green")
if not stage_str:
package_status = status_str
else:
package_status = "%(status)s / %(stage)s" % {
"status": status_str,
"stage": stage_str,
}
if ok:
status_colour = "green"
elif failed:
status_colour = "red"
else:
status_colour = "magenta"
click.secho(
"The package status is: %(status)s"
% {"status": click.style(package_status, fg=status_colour)}
)
if reason:
click.secho(
"Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")},
fg=status_colour,
) | python | def status(ctx, opts, owner_repo_package):
"""
Get the synchronisation status for a package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'.
"""
owner, repo, slug = owner_repo_package
click.echo(
"Getting status of %(package)s in %(owner)s/%(repo)s ... "
% {
"owner": click.style(owner, bold=True),
"repo": click.style(repo, bold=True),
"package": click.style(slug, bold=True),
},
nl=False,
)
context_msg = "Failed to get status of package!"
with handle_api_exceptions(ctx, opts=opts, context_msg=context_msg):
with maybe_spinner(opts):
res = get_package_status(owner, repo, slug)
ok, failed, _, status_str, stage_str, reason = res
click.secho("OK", fg="green")
if not stage_str:
package_status = status_str
else:
package_status = "%(status)s / %(stage)s" % {
"status": status_str,
"stage": stage_str,
}
if ok:
status_colour = "green"
elif failed:
status_colour = "red"
else:
status_colour = "magenta"
click.secho(
"The package status is: %(status)s"
% {"status": click.style(package_status, fg=status_colour)}
)
if reason:
click.secho(
"Reason given: %(reason)s" % {"reason": click.style(reason, fg="yellow")},
fg=status_colour,
) | [
"def",
"status",
"(",
"ctx",
",",
"opts",
",",
"owner_repo_package",
")",
":",
"owner",
",",
"repo",
",",
"slug",
"=",
"owner_repo_package",
"click",
".",
"echo",
"(",
"\"Getting status of %(package)s in %(owner)s/%(repo)s ... \"",
"%",
"{",
"\"owner\"",
":",
"cli... | Get the synchronisation status for a package.
- OWNER/REPO/PACKAGE: Specify the OWNER namespace (i.e. user or org), the
REPO name where the package is stored, and the PACKAGE name (slug) of the
package itself. All separated by a slash.
Example: 'your-org/awesome-repo/better-pkg'. | [
"Get",
"the",
"synchronisation",
"status",
"for",
"a",
"package",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/commands/status.py#L25-L79 | train | 48,166 |
marrow/schema | marrow/schema/declarative.py | Container._process_arguments | def _process_arguments(self, args, kw):
"""Map positional to keyword arguments, identify invalid assignments, and return the result.
This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of
effort to ensure raised exceptions are as Python-like as possible.
"""
# Ensure we were not passed too many arguments.
if len(args) > len(self.__attributes__):
raise TypeError('{0} takes no more than {1} argument{2} ({3} given)'.format(
self.__class__.__name__,
len(self.__attributes__),
'' if len(self.__attributes__) == 1 else 's',
len(args)
))
# Retrieve the names associated with the positional parameters.
names = [name for name in self.__attributes__.keys() if name[0] != '_' or name == '__name__'][:len(args)]
# Sets provide a convienent way to identify intersections.
duplicates = set(kw.keys()) & set(names)
# Given duplicate values, explode gloriously.
if duplicates:
raise TypeError('{0} got multiple values for keyword argument{1}: {2}'.format(
self.__class__.__name__,
'' if len(duplicates) == 1 else 's',
', '.join(duplicates)
))
def field_values(args, kw):
"""A little closure to yield out fields and their assigned values in field order."""
for i, arg in enumerate(self.__attributes__.keys()):
if len(args):
yield arg, args.popleft()
if arg in kw:
yield arg, kw.pop(arg)
result = odict(field_values(deque(args), dict(kw)))
# Again use sets, this time to identify unknown keys.
unknown = set(kw.keys()) - set(result.keys())
# Given unknown keys, explode gloriously.
if unknown:
raise TypeError('{0} got unexpected keyword argument{1}: {2}'.format(
self.__class__.__name__,
'' if len(unknown) == 1 else 's',
', '.join(unknown)
))
return result | python | def _process_arguments(self, args, kw):
"""Map positional to keyword arguments, identify invalid assignments, and return the result.
This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of
effort to ensure raised exceptions are as Python-like as possible.
"""
# Ensure we were not passed too many arguments.
if len(args) > len(self.__attributes__):
raise TypeError('{0} takes no more than {1} argument{2} ({3} given)'.format(
self.__class__.__name__,
len(self.__attributes__),
'' if len(self.__attributes__) == 1 else 's',
len(args)
))
# Retrieve the names associated with the positional parameters.
names = [name for name in self.__attributes__.keys() if name[0] != '_' or name == '__name__'][:len(args)]
# Sets provide a convienent way to identify intersections.
duplicates = set(kw.keys()) & set(names)
# Given duplicate values, explode gloriously.
if duplicates:
raise TypeError('{0} got multiple values for keyword argument{1}: {2}'.format(
self.__class__.__name__,
'' if len(duplicates) == 1 else 's',
', '.join(duplicates)
))
def field_values(args, kw):
"""A little closure to yield out fields and their assigned values in field order."""
for i, arg in enumerate(self.__attributes__.keys()):
if len(args):
yield arg, args.popleft()
if arg in kw:
yield arg, kw.pop(arg)
result = odict(field_values(deque(args), dict(kw)))
# Again use sets, this time to identify unknown keys.
unknown = set(kw.keys()) - set(result.keys())
# Given unknown keys, explode gloriously.
if unknown:
raise TypeError('{0} got unexpected keyword argument{1}: {2}'.format(
self.__class__.__name__,
'' if len(unknown) == 1 else 's',
', '.join(unknown)
))
return result | [
"def",
"_process_arguments",
"(",
"self",
",",
"args",
",",
"kw",
")",
":",
"# Ensure we were not passed too many arguments.",
"if",
"len",
"(",
"args",
")",
">",
"len",
"(",
"self",
".",
"__attributes__",
")",
":",
"raise",
"TypeError",
"(",
"'{0} takes no more... | Map positional to keyword arguments, identify invalid assignments, and return the result.
This is likely generic enough to be useful as a standalone utility function, and goes to a fair amount of
effort to ensure raised exceptions are as Python-like as possible. | [
"Map",
"positional",
"to",
"keyword",
"arguments",
"identify",
"invalid",
"assignments",
"and",
"return",
"the",
"result",
".",
"This",
"is",
"likely",
"generic",
"enough",
"to",
"be",
"useful",
"as",
"a",
"standalone",
"utility",
"function",
"and",
"goes",
"t... | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/declarative.py#L51-L104 | train | 48,167 |
marrow/schema | marrow/schema/transform/type.py | Boolean.native | def native(self, value, context=None):
"""Convert a foreign value to a native boolean."""
value = super().native(value, context)
if self.none and (value is None):
return None
try:
value = value.lower()
except AttributeError:
return bool(value)
if value in self.truthy:
return True
if value in self.falsy:
return False
raise Concern("Unable to convert {0!r} to a boolean value.", value) | python | def native(self, value, context=None):
"""Convert a foreign value to a native boolean."""
value = super().native(value, context)
if self.none and (value is None):
return None
try:
value = value.lower()
except AttributeError:
return bool(value)
if value in self.truthy:
return True
if value in self.falsy:
return False
raise Concern("Unable to convert {0!r} to a boolean value.", value) | [
"def",
"native",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"value",
"=",
"super",
"(",
")",
".",
"native",
"(",
"value",
",",
"context",
")",
"if",
"self",
".",
"none",
"and",
"(",
"value",
"is",
"None",
")",
":",
"return"... | Convert a foreign value to a native boolean. | [
"Convert",
"a",
"foreign",
"value",
"to",
"a",
"native",
"boolean",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/type.py#L22-L41 | train | 48,168 |
marrow/schema | marrow/schema/transform/type.py | Boolean.foreign | def foreign(self, value, context=None):
"""Convert a native value to a textual boolean."""
if self.none and value is None:
return ''
try:
value = self.native(value, context)
except Concern:
# The value might not be in the lists; bool() evaluate it instead.
value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value)
if value in self.truthy or value:
return self.truthy[self.use]
return self.falsy[self.use] | python | def foreign(self, value, context=None):
"""Convert a native value to a textual boolean."""
if self.none and value is None:
return ''
try:
value = self.native(value, context)
except Concern:
# The value might not be in the lists; bool() evaluate it instead.
value = bool(value.strip() if self.strip and hasattr(value, 'strip') else value)
if value in self.truthy or value:
return self.truthy[self.use]
return self.falsy[self.use] | [
"def",
"foreign",
"(",
"self",
",",
"value",
",",
"context",
"=",
"None",
")",
":",
"if",
"self",
".",
"none",
"and",
"value",
"is",
"None",
":",
"return",
"''",
"try",
":",
"value",
"=",
"self",
".",
"native",
"(",
"value",
",",
"context",
")",
... | Convert a native value to a textual boolean. | [
"Convert",
"a",
"native",
"value",
"to",
"a",
"textual",
"boolean",
"."
] | 0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152 | https://github.com/marrow/schema/blob/0c4c3e3b8c79d8bfeb8d7265cfa5b12a2e643152/marrow/schema/transform/type.py#L43-L58 | train | 48,169 |
cloudsmith-io/cloudsmith-cli | setup.py | get_root_path | def get_root_path():
"""Get the root path for the application."""
root_path = __file__
return os.path.dirname(os.path.realpath(root_path)) | python | def get_root_path():
"""Get the root path for the application."""
root_path = __file__
return os.path.dirname(os.path.realpath(root_path)) | [
"def",
"get_root_path",
"(",
")",
":",
"root_path",
"=",
"__file__",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"realpath",
"(",
"root_path",
")",
")"
] | Get the root path for the application. | [
"Get",
"the",
"root",
"path",
"for",
"the",
"application",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/setup.py#L10-L13 | train | 48,170 |
skulumani/kinematics | kinematics/sphere.py | rand | def rand(n, **kwargs):
"""Random vector from the n-Sphere
This function will return a random vector which is an element of the n-Sphere.
The n-Sphere is defined as a vector in R^n+1 with a norm of one.
Basically, we'll find a random vector in R^n+1 and normalize it.
This uses the method of Marsaglia 1972.
Parameters
----------
None
Returns
-------
rvec
Random (n+1,) numpy vector with a norm of 1
"""
rvec = np.random.randn(3)
rvec = rvec / np.linalg.norm(rvec)
return rvec | python | def rand(n, **kwargs):
"""Random vector from the n-Sphere
This function will return a random vector which is an element of the n-Sphere.
The n-Sphere is defined as a vector in R^n+1 with a norm of one.
Basically, we'll find a random vector in R^n+1 and normalize it.
This uses the method of Marsaglia 1972.
Parameters
----------
None
Returns
-------
rvec
Random (n+1,) numpy vector with a norm of 1
"""
rvec = np.random.randn(3)
rvec = rvec / np.linalg.norm(rvec)
return rvec | [
"def",
"rand",
"(",
"n",
",",
"*",
"*",
"kwargs",
")",
":",
"rvec",
"=",
"np",
".",
"random",
".",
"randn",
"(",
"3",
")",
"rvec",
"=",
"rvec",
"/",
"np",
".",
"linalg",
".",
"norm",
"(",
"rvec",
")",
"return",
"rvec"
] | Random vector from the n-Sphere
This function will return a random vector which is an element of the n-Sphere.
The n-Sphere is defined as a vector in R^n+1 with a norm of one.
Basically, we'll find a random vector in R^n+1 and normalize it.
This uses the method of Marsaglia 1972.
Parameters
----------
None
Returns
-------
rvec
Random (n+1,) numpy vector with a norm of 1 | [
"Random",
"vector",
"from",
"the",
"n",
"-",
"Sphere"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L13-L34 | train | 48,171 |
skulumani/kinematics | kinematics/sphere.py | tan_rand | def tan_rand(q, seed=9):
"""Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere and also random
"""
# probably need a check in case we get a parallel vector
rs = np.random.RandomState(seed)
rvec = rs.rand(q.shape[0])
qd = np.cross(rvec, q)
qd = qd / np.linalg.norm(qd)
while np.dot(q, qd) > 1e-6:
rvec = rs.rand(q.shape[0])
qd = np.cross(rvec, q)
qd = qd / np.linalg.norm(qd)
return qd | python | def tan_rand(q, seed=9):
"""Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere and also random
"""
# probably need a check in case we get a parallel vector
rs = np.random.RandomState(seed)
rvec = rs.rand(q.shape[0])
qd = np.cross(rvec, q)
qd = qd / np.linalg.norm(qd)
while np.dot(q, qd) > 1e-6:
rvec = rs.rand(q.shape[0])
qd = np.cross(rvec, q)
qd = qd / np.linalg.norm(qd)
return qd | [
"def",
"tan_rand",
"(",
"q",
",",
"seed",
"=",
"9",
")",
":",
"# probably need a check in case we get a parallel vector",
"rs",
"=",
"np",
".",
"random",
".",
"RandomState",
"(",
"seed",
")",
"rvec",
"=",
"rs",
".",
"rand",
"(",
"q",
".",
"shape",
"[",
"... | Find a random vector in the tangent space of the n sphere
This function will find a random orthogonal vector to q.
Parameters
----------
q
(n+1,) array which is in the n-sphere
Returns
-------
qd
(n+1,) array which is orthogonal to n-sphere and also random | [
"Find",
"a",
"random",
"vector",
"in",
"the",
"tangent",
"space",
"of",
"the",
"n",
"sphere"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L36-L64 | train | 48,172 |
skulumani/kinematics | kinematics/sphere.py | perturb_vec | def perturb_vec(q, cone_half_angle=2):
r"""Perturb a vector randomly
qp = perturb_vec(q, cone_half_angle=2)
Parameters
----------
q : (n,) numpy array
Vector to perturb
cone_half_angle : float
Maximum angle to perturb the vector in degrees
Returns
-------
perturbed : (n,) numpy array
Perturbed numpy array
Author
------
Shankar Kulumani GWU skulumani@gwu.edu
References
----------
.. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle
"""
rand_vec = tan_rand(q)
cross_vector = attitude.unit_vector(np.cross(q, rand_vec))
s = np.random.uniform(0, 1, 1)
r = np.random.uniform(0, 1, 1)
h = np.cos(np.deg2rad(cone_half_angle))
phi = 2 * np.pi * s
z = h + ( 1- h) * r
sinT = np.sqrt(1 - z**2)
x = np.cos(phi) * sinT
y = np.sin(phi) * sinT
perturbed = rand_vec * x + cross_vector * y + q * z
return perturbed | python | def perturb_vec(q, cone_half_angle=2):
r"""Perturb a vector randomly
qp = perturb_vec(q, cone_half_angle=2)
Parameters
----------
q : (n,) numpy array
Vector to perturb
cone_half_angle : float
Maximum angle to perturb the vector in degrees
Returns
-------
perturbed : (n,) numpy array
Perturbed numpy array
Author
------
Shankar Kulumani GWU skulumani@gwu.edu
References
----------
.. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle
"""
rand_vec = tan_rand(q)
cross_vector = attitude.unit_vector(np.cross(q, rand_vec))
s = np.random.uniform(0, 1, 1)
r = np.random.uniform(0, 1, 1)
h = np.cos(np.deg2rad(cone_half_angle))
phi = 2 * np.pi * s
z = h + ( 1- h) * r
sinT = np.sqrt(1 - z**2)
x = np.cos(phi) * sinT
y = np.sin(phi) * sinT
perturbed = rand_vec * x + cross_vector * y + q * z
return perturbed | [
"def",
"perturb_vec",
"(",
"q",
",",
"cone_half_angle",
"=",
"2",
")",
":",
"rand_vec",
"=",
"tan_rand",
"(",
"q",
")",
"cross_vector",
"=",
"attitude",
".",
"unit_vector",
"(",
"np",
".",
"cross",
"(",
"q",
",",
"rand_vec",
")",
")",
"s",
"=",
"np",... | r"""Perturb a vector randomly
qp = perturb_vec(q, cone_half_angle=2)
Parameters
----------
q : (n,) numpy array
Vector to perturb
cone_half_angle : float
Maximum angle to perturb the vector in degrees
Returns
-------
perturbed : (n,) numpy array
Perturbed numpy array
Author
------
Shankar Kulumani GWU skulumani@gwu.edu
References
----------
.. [1] https://stackoverflow.com/questions/2659257/perturb-vector-by-some-angle | [
"r",
"Perturb",
"a",
"vector",
"randomly"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/sphere.py#L66-L109 | train | 48,173 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/decorators.py | common_package_action_options | def common_package_action_options(f):
"""Add common options for package actions."""
@click.option(
"-s",
"--skip-errors",
default=False,
is_flag=True,
help="Skip/ignore errors when copying packages.",
)
@click.option(
"-W",
"--no-wait-for-sync",
default=False,
is_flag=True,
help="Don't wait for package synchronisation to complete before " "exiting.",
)
@click.option(
"-I",
"--wait-interval",
default=5.0,
type=float,
show_default=True,
help="The time in seconds to wait between checking synchronisation.",
)
@click.option(
"--sync-attempts",
default=3,
type=int,
help="Number of times to attempt package synchronisation. If the "
"package fails the first time, the client will attempt to "
"automatically resynchronise it.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_package_action_options(f):
"""Add common options for package actions."""
@click.option(
"-s",
"--skip-errors",
default=False,
is_flag=True,
help="Skip/ignore errors when copying packages.",
)
@click.option(
"-W",
"--no-wait-for-sync",
default=False,
is_flag=True,
help="Don't wait for package synchronisation to complete before " "exiting.",
)
@click.option(
"-I",
"--wait-interval",
default=5.0,
type=float,
show_default=True,
help="The time in seconds to wait between checking synchronisation.",
)
@click.option(
"--sync-attempts",
default=3,
type=int,
help="Number of times to attempt package synchronisation. If the "
"package fails the first time, the client will attempt to "
"automatically resynchronise it.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_package_action_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-s\"",
",",
"\"--skip-errors\"",
",",
"default",
"=",
"False",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"\"Skip/ignore errors when copying packages.\"",
",",
"... | Add common options for package actions. | [
"Add",
"common",
"options",
"for",
"package",
"actions",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L13-L52 | train | 48,174 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/decorators.py | common_cli_config_options | def common_cli_config_options(f):
"""Add common CLI config options to commands."""
@click.option(
"-C",
"--config-file",
envvar="CLOUDSMITH_CONFIG_FILE",
type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
help="The path to your config.ini file.",
)
@click.option(
"--credentials-file",
envvar="CLOUDSMITH_CREDENTIALS_FILE",
type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
help="The path to your credentials.ini file.",
)
@click.option(
"-P",
"--profile",
default=None,
envvar="CLOUDSMITH_PROFILE",
help="The name of the profile to use for configuration.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
profile = kwargs.pop("profile")
config_file = kwargs.pop("config_file")
creds_file = kwargs.pop("credentials_file")
opts.load_config_file(path=config_file, profile=profile)
opts.load_creds_file(path=creds_file, profile=profile)
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_cli_config_options(f):
"""Add common CLI config options to commands."""
@click.option(
"-C",
"--config-file",
envvar="CLOUDSMITH_CONFIG_FILE",
type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
help="The path to your config.ini file.",
)
@click.option(
"--credentials-file",
envvar="CLOUDSMITH_CREDENTIALS_FILE",
type=click.Path(dir_okay=True, exists=True, writable=False, resolve_path=True),
help="The path to your credentials.ini file.",
)
@click.option(
"-P",
"--profile",
default=None,
envvar="CLOUDSMITH_PROFILE",
help="The name of the profile to use for configuration.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
profile = kwargs.pop("profile")
config_file = kwargs.pop("config_file")
creds_file = kwargs.pop("credentials_file")
opts.load_config_file(path=config_file, profile=profile)
opts.load_creds_file(path=creds_file, profile=profile)
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_cli_config_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-C\"",
",",
"\"--config-file\"",
",",
"envvar",
"=",
"\"CLOUDSMITH_CONFIG_FILE\"",
",",
"type",
"=",
"click",
".",
"Path",
"(",
"dir_okay",
"=",
"True",
",",
"exists... | Add common CLI config options to commands. | [
"Add",
"common",
"CLI",
"config",
"options",
"to",
"commands",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L55-L91 | train | 48,175 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/decorators.py | common_cli_output_options | def common_cli_output_options(f):
"""Add common CLI output options to commands."""
@click.option(
"-d",
"--debug",
default=False,
is_flag=True,
help="Produce debug output during processing.",
)
@click.option(
"-F",
"--output-format",
default="pretty",
type=click.Choice(["pretty", "json", "pretty_json"]),
help="Determines how output is formatted. This is only supported by a "
"subset of the commands at the moment (e.g. list).",
)
@click.option(
"-v",
"--verbose",
is_flag=True,
default=False,
help="Produce more output during processing.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
opts.debug = kwargs.pop("debug")
opts.output = kwargs.pop("output_format")
opts.verbose = kwargs.pop("verbose")
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_cli_output_options(f):
"""Add common CLI output options to commands."""
@click.option(
"-d",
"--debug",
default=False,
is_flag=True,
help="Produce debug output during processing.",
)
@click.option(
"-F",
"--output-format",
default="pretty",
type=click.Choice(["pretty", "json", "pretty_json"]),
help="Determines how output is formatted. This is only supported by a "
"subset of the commands at the moment (e.g. list).",
)
@click.option(
"-v",
"--verbose",
is_flag=True,
default=False,
help="Produce more output during processing.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
opts.debug = kwargs.pop("debug")
opts.output = kwargs.pop("output_format")
opts.verbose = kwargs.pop("verbose")
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_cli_output_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-d\"",
",",
"\"--debug\"",
",",
"default",
"=",
"False",
",",
"is_flag",
"=",
"True",
",",
"help",
"=",
"\"Produce debug output during processing.\"",
",",
")",
"@",
... | Add common CLI output options to commands. | [
"Add",
"common",
"CLI",
"output",
"options",
"to",
"commands",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L94-L130 | train | 48,176 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/decorators.py | common_cli_list_options | def common_cli_list_options(f):
"""Add common list options to commands."""
@click.option(
"-p",
"--page",
default=1,
type=int,
help="The page to view for lists, where 1 is the first page",
callback=validators.validate_page,
)
@click.option(
"-l",
"--page-size",
default=30,
type=int,
help="The amount of items to view per page for lists.",
callback=validators.validate_page_size,
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_cli_list_options(f):
"""Add common list options to commands."""
@click.option(
"-p",
"--page",
default=1,
type=int,
help="The page to view for lists, where 1 is the first page",
callback=validators.validate_page,
)
@click.option(
"-l",
"--page-size",
default=30,
type=int,
help="The amount of items to view per page for lists.",
callback=validators.validate_page_size,
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_cli_list_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-p\"",
",",
"\"--page\"",
",",
"default",
"=",
"1",
",",
"type",
"=",
"int",
",",
"help",
"=",
"\"The page to view for lists, where 1 is the first page\"",
",",
"callback"... | Add common list options to commands. | [
"Add",
"common",
"list",
"options",
"to",
"commands",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L133-L160 | train | 48,177 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/decorators.py | common_api_auth_options | def common_api_auth_options(f):
"""Add common API authentication options to commands."""
@click.option(
"-k",
"--api-key",
hide_input=True,
envvar="CLOUDSMITH_API_KEY",
help="The API key for authenticating with the API.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
opts.api_key = kwargs.pop("api_key")
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | python | def common_api_auth_options(f):
"""Add common API authentication options to commands."""
@click.option(
"-k",
"--api-key",
hide_input=True,
envvar="CLOUDSMITH_API_KEY",
help="The API key for authenticating with the API.",
)
@click.pass_context
@functools.wraps(f)
def wrapper(ctx, *args, **kwargs):
# pylint: disable=missing-docstring
opts = config.get_or_create_options(ctx)
opts.api_key = kwargs.pop("api_key")
kwargs["opts"] = opts
return ctx.invoke(f, *args, **kwargs)
return wrapper | [
"def",
"common_api_auth_options",
"(",
"f",
")",
":",
"@",
"click",
".",
"option",
"(",
"\"-k\"",
",",
"\"--api-key\"",
",",
"hide_input",
"=",
"True",
",",
"envvar",
"=",
"\"CLOUDSMITH_API_KEY\"",
",",
"help",
"=",
"\"The API key for authenticating with the API.\""... | Add common API authentication options to commands. | [
"Add",
"common",
"API",
"authentication",
"options",
"to",
"commands",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/decorators.py#L163-L182 | train | 48,178 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/entitlements.py | list_entitlements | def list_entitlements(owner, repo, page, page_size, show_tokens):
"""Get a list of entitlements on a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
data, _, headers = client.entitlements_list_with_http_info(
owner=owner,
repo=repo,
page=page,
page_size=page_size,
show_tokens=show_tokens,
)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
entitlements = [ent.to_dict() for ent in data] # pylint: disable=no-member
return entitlements, page_info | python | def list_entitlements(owner, repo, page, page_size, show_tokens):
"""Get a list of entitlements on a repository."""
client = get_entitlements_api()
with catch_raise_api_exception():
data, _, headers = client.entitlements_list_with_http_info(
owner=owner,
repo=repo,
page=page,
page_size=page_size,
show_tokens=show_tokens,
)
ratelimits.maybe_rate_limit(client, headers)
page_info = PageInfo.from_headers(headers)
entitlements = [ent.to_dict() for ent in data] # pylint: disable=no-member
return entitlements, page_info | [
"def",
"list_entitlements",
"(",
"owner",
",",
"repo",
",",
"page",
",",
"page_size",
",",
"show_tokens",
")",
":",
"client",
"=",
"get_entitlements_api",
"(",
")",
"with",
"catch_raise_api_exception",
"(",
")",
":",
"data",
",",
"_",
",",
"headers",
"=",
... | Get a list of entitlements on a repository. | [
"Get",
"a",
"list",
"of",
"entitlements",
"on",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L18-L34 | train | 48,179 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/entitlements.py | create_entitlement | def create_entitlement(owner, repo, name, token, show_tokens):
"""Create an entitlement in a repository."""
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api_exception():
data, _, headers = client.entitlements_create_with_http_info(
owner=owner, repo=repo, data=data, show_tokens=show_tokens
)
ratelimits.maybe_rate_limit(client, headers)
return data.to_dict() | python | def create_entitlement(owner, repo, name, token, show_tokens):
"""Create an entitlement in a repository."""
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api_exception():
data, _, headers = client.entitlements_create_with_http_info(
owner=owner, repo=repo, data=data, show_tokens=show_tokens
)
ratelimits.maybe_rate_limit(client, headers)
return data.to_dict() | [
"def",
"create_entitlement",
"(",
"owner",
",",
"repo",
",",
"name",
",",
"token",
",",
"show_tokens",
")",
":",
"client",
"=",
"get_entitlements_api",
"(",
")",
"data",
"=",
"{",
"}",
"if",
"name",
"is",
"not",
"None",
":",
"data",
"[",
"\"name\"",
"]... | Create an entitlement in a repository. | [
"Create",
"an",
"entitlement",
"in",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L37-L54 | train | 48,180 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/entitlements.py | update_entitlement | def update_entitlement(owner, repo, identifier, name, token, show_tokens):
"""Update an entitlement in a repository."""
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api_exception():
data, _, headers = client.entitlements_partial_update_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data=data,
show_tokens=show_tokens,
)
ratelimits.maybe_rate_limit(client, headers)
return data.to_dict() | python | def update_entitlement(owner, repo, identifier, name, token, show_tokens):
"""Update an entitlement in a repository."""
client = get_entitlements_api()
data = {}
if name is not None:
data["name"] = name
if token is not None:
data["token"] = token
with catch_raise_api_exception():
data, _, headers = client.entitlements_partial_update_with_http_info(
owner=owner,
repo=repo,
identifier=identifier,
data=data,
show_tokens=show_tokens,
)
ratelimits.maybe_rate_limit(client, headers)
return data.to_dict() | [
"def",
"update_entitlement",
"(",
"owner",
",",
"repo",
",",
"identifier",
",",
"name",
",",
"token",
",",
"show_tokens",
")",
":",
"client",
"=",
"get_entitlements_api",
"(",
")",
"data",
"=",
"{",
"}",
"if",
"name",
"is",
"not",
"None",
":",
"data",
... | Update an entitlement in a repository. | [
"Update",
"an",
"entitlement",
"in",
"a",
"repository",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/entitlements.py#L69-L90 | train | 48,181 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/init.py | initialise_api | def initialise_api(
debug=False,
host=None,
key=None,
proxy=None,
user_agent=None,
headers=None,
rate_limit=True,
rate_limit_callback=None,
error_retry_max=None,
error_retry_backoff=None,
error_retry_codes=None,
):
"""Initialise the API."""
config = cloudsmith_api.Configuration()
config.debug = debug
config.host = host if host else config.host
config.proxy = proxy if proxy else config.proxy
config.user_agent = user_agent
config.headers = headers
config.rate_limit = rate_limit
config.rate_limit_callback = rate_limit_callback
config.error_retry_max = error_retry_max
config.error_retry_backoff = error_retry_backoff
config.error_retry_codes = error_retry_codes
if headers:
if "Authorization" in config.headers:
encoded = config.headers["Authorization"].split(" ")[1]
decoded = base64.b64decode(encoded)
values = decoded.decode("utf-8")
config.username, config.password = values.split(":")
set_api_key(config, key)
return config | python | def initialise_api(
debug=False,
host=None,
key=None,
proxy=None,
user_agent=None,
headers=None,
rate_limit=True,
rate_limit_callback=None,
error_retry_max=None,
error_retry_backoff=None,
error_retry_codes=None,
):
"""Initialise the API."""
config = cloudsmith_api.Configuration()
config.debug = debug
config.host = host if host else config.host
config.proxy = proxy if proxy else config.proxy
config.user_agent = user_agent
config.headers = headers
config.rate_limit = rate_limit
config.rate_limit_callback = rate_limit_callback
config.error_retry_max = error_retry_max
config.error_retry_backoff = error_retry_backoff
config.error_retry_codes = error_retry_codes
if headers:
if "Authorization" in config.headers:
encoded = config.headers["Authorization"].split(" ")[1]
decoded = base64.b64decode(encoded)
values = decoded.decode("utf-8")
config.username, config.password = values.split(":")
set_api_key(config, key)
return config | [
"def",
"initialise_api",
"(",
"debug",
"=",
"False",
",",
"host",
"=",
"None",
",",
"key",
"=",
"None",
",",
"proxy",
"=",
"None",
",",
"user_agent",
"=",
"None",
",",
"headers",
"=",
"None",
",",
"rate_limit",
"=",
"True",
",",
"rate_limit_callback",
... | Initialise the API. | [
"Initialise",
"the",
"API",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L13-L47 | train | 48,182 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/init.py | set_api_key | def set_api_key(config, key):
"""Configure a new API key."""
if not key and "X-Api-Key" in config.api_key:
del config.api_key["X-Api-Key"]
else:
config.api_key["X-Api-Key"] = key | python | def set_api_key(config, key):
"""Configure a new API key."""
if not key and "X-Api-Key" in config.api_key:
del config.api_key["X-Api-Key"]
else:
config.api_key["X-Api-Key"] = key | [
"def",
"set_api_key",
"(",
"config",
",",
"key",
")",
":",
"if",
"not",
"key",
"and",
"\"X-Api-Key\"",
"in",
"config",
".",
"api_key",
":",
"del",
"config",
".",
"api_key",
"[",
"\"X-Api-Key\"",
"]",
"else",
":",
"config",
".",
"api_key",
"[",
"\"X-Api-K... | Configure a new API key. | [
"Configure",
"a",
"new",
"API",
"key",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/init.py#L69-L74 | train | 48,183 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/api/files.py | upload_file | def upload_file(upload_url, upload_fields, filepath, callback=None):
"""Upload a pre-signed file to Cloudsmith."""
upload_fields = list(six.iteritems(upload_fields))
upload_fields.append(
("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
)
encoder = MultipartEncoder(upload_fields)
monitor = MultipartEncoderMonitor(encoder, callback=callback)
config = cloudsmith_api.Configuration()
if config.proxy:
proxies = {"http": config.proxy, "https": config.proxy}
else:
proxies = None
headers = {"content-type": monitor.content_type}
client = get_files_api()
headers["user-agent"] = client.api_client.user_agent
session = create_requests_session()
resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies)
try:
resp.raise_for_status()
except requests.RequestException as exc:
raise ApiException(
resp.status_code, headers=exc.response.headers, body=exc.response.content
) | python | def upload_file(upload_url, upload_fields, filepath, callback=None):
"""Upload a pre-signed file to Cloudsmith."""
upload_fields = list(six.iteritems(upload_fields))
upload_fields.append(
("file", (os.path.basename(filepath), click.open_file(filepath, "rb")))
)
encoder = MultipartEncoder(upload_fields)
monitor = MultipartEncoderMonitor(encoder, callback=callback)
config = cloudsmith_api.Configuration()
if config.proxy:
proxies = {"http": config.proxy, "https": config.proxy}
else:
proxies = None
headers = {"content-type": monitor.content_type}
client = get_files_api()
headers["user-agent"] = client.api_client.user_agent
session = create_requests_session()
resp = session.post(upload_url, data=monitor, headers=headers, proxies=proxies)
try:
resp.raise_for_status()
except requests.RequestException as exc:
raise ApiException(
resp.status_code, headers=exc.response.headers, body=exc.response.content
) | [
"def",
"upload_file",
"(",
"upload_url",
",",
"upload_fields",
",",
"filepath",
",",
"callback",
"=",
"None",
")",
":",
"upload_fields",
"=",
"list",
"(",
"six",
".",
"iteritems",
"(",
"upload_fields",
")",
")",
"upload_fields",
".",
"append",
"(",
"(",
"\... | Upload a pre-signed file to Cloudsmith. | [
"Upload",
"a",
"pre",
"-",
"signed",
"file",
"to",
"Cloudsmith",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/api/files.py#L59-L87 | train | 48,184 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/exceptions.py | handle_api_exceptions | def handle_api_exceptions(
ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
"""Context manager that handles API exceptions."""
# flake8: ignore=C901
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
try:
yield
except ApiException as exc:
if nl:
click.echo(err=use_stderr)
click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
else:
click.secho("ERROR", fg="red", err=use_stderr)
context_msg = context_msg or "Failed to perform operation!"
click.secho(
"%(context)s (status: %(code)s - %(code_text)s)"
% {
"context": context_msg,
"code": exc.status,
"code_text": exc.status_description,
},
fg="red",
err=use_stderr,
)
detail, fields = get_details(exc)
if detail or fields:
click.echo(err=use_stderr)
if detail:
click.secho(
"Detail: %(detail)s"
% {"detail": click.style(detail, fg="red", bold=False)},
bold=True,
err=use_stderr,
)
if fields:
for k, v in six.iteritems(fields):
field = "%s Field" % k.capitalize()
click.secho(
"%(field)s: %(message)s"
% {
"field": click.style(field, bold=True),
"message": click.style(v, fg="red"),
},
err=use_stderr,
)
hint = get_error_hint(ctx, opts, exc)
if hint:
click.echo(
"Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
err=use_stderr,
)
if opts.verbose and not opts.debug:
if exc.headers:
click.echo(err=use_stderr)
click.echo("Headers in Reply:", err=use_stderr)
for k, v in six.iteritems(exc.headers):
click.echo(
"%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
)
if reraise_on_error:
six.reraise(*sys.exc_info())
if exit_on_error:
ctx.exit(exc.status or 1) | python | def handle_api_exceptions(
ctx, opts, context_msg=None, nl=False, exit_on_error=True, reraise_on_error=False
):
"""Context manager that handles API exceptions."""
# flake8: ignore=C901
# Use stderr for messages if the output is something else (e.g. # JSON)
use_stderr = opts.output != "pretty"
try:
yield
except ApiException as exc:
if nl:
click.echo(err=use_stderr)
click.secho("ERROR: ", fg="red", nl=False, err=use_stderr)
else:
click.secho("ERROR", fg="red", err=use_stderr)
context_msg = context_msg or "Failed to perform operation!"
click.secho(
"%(context)s (status: %(code)s - %(code_text)s)"
% {
"context": context_msg,
"code": exc.status,
"code_text": exc.status_description,
},
fg="red",
err=use_stderr,
)
detail, fields = get_details(exc)
if detail or fields:
click.echo(err=use_stderr)
if detail:
click.secho(
"Detail: %(detail)s"
% {"detail": click.style(detail, fg="red", bold=False)},
bold=True,
err=use_stderr,
)
if fields:
for k, v in six.iteritems(fields):
field = "%s Field" % k.capitalize()
click.secho(
"%(field)s: %(message)s"
% {
"field": click.style(field, bold=True),
"message": click.style(v, fg="red"),
},
err=use_stderr,
)
hint = get_error_hint(ctx, opts, exc)
if hint:
click.echo(
"Hint: %(hint)s" % {"hint": click.style(hint, fg="yellow")},
err=use_stderr,
)
if opts.verbose and not opts.debug:
if exc.headers:
click.echo(err=use_stderr)
click.echo("Headers in Reply:", err=use_stderr)
for k, v in six.iteritems(exc.headers):
click.echo(
"%(key)s = %(value)s" % {"key": k, "value": v}, err=use_stderr
)
if reraise_on_error:
six.reraise(*sys.exc_info())
if exit_on_error:
ctx.exit(exc.status or 1) | [
"def",
"handle_api_exceptions",
"(",
"ctx",
",",
"opts",
",",
"context_msg",
"=",
"None",
",",
"nl",
"=",
"False",
",",
"exit_on_error",
"=",
"True",
",",
"reraise_on_error",
"=",
"False",
")",
":",
"# flake8: ignore=C901",
"# Use stderr for messages if the output i... | Context manager that handles API exceptions. | [
"Context",
"manager",
"that",
"handles",
"API",
"exceptions",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/exceptions.py#L16-L89 | train | 48,185 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/cli/exceptions.py | get_details | def get_details(exc):
"""Get the details from the exception."""
detail = None
fields = collections.OrderedDict()
if exc.detail:
detail = exc.detail
if exc.fields:
for k, v in six.iteritems(exc.fields):
try:
field_detail = v["detail"]
except (TypeError, KeyError):
field_detail = v
if isinstance(field_detail, (list, tuple)):
field_detail = " ".join(field_detail)
if k == "non_field_errors":
if detail:
detail += " " + field_detail
else:
detail = field_detail
continue
fields[k] = field_detail
return detail, fields | python | def get_details(exc):
"""Get the details from the exception."""
detail = None
fields = collections.OrderedDict()
if exc.detail:
detail = exc.detail
if exc.fields:
for k, v in six.iteritems(exc.fields):
try:
field_detail = v["detail"]
except (TypeError, KeyError):
field_detail = v
if isinstance(field_detail, (list, tuple)):
field_detail = " ".join(field_detail)
if k == "non_field_errors":
if detail:
detail += " " + field_detail
else:
detail = field_detail
continue
fields[k] = field_detail
return detail, fields | [
"def",
"get_details",
"(",
"exc",
")",
":",
"detail",
"=",
"None",
"fields",
"=",
"collections",
".",
"OrderedDict",
"(",
")",
"if",
"exc",
".",
"detail",
":",
"detail",
"=",
"exc",
".",
"detail",
"if",
"exc",
".",
"fields",
":",
"for",
"k",
",",
"... | Get the details from the exception. | [
"Get",
"the",
"details",
"from",
"the",
"exception",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/cli/exceptions.py#L92-L119 | train | 48,186 |
kalefranz/auxlib | auxlib/configuration.py | make_env_key | def make_env_key(app_name, key):
"""Creates an environment key-equivalent for the given key"""
key = key.replace('-', '_').replace(' ', '_')
return str("_".join((x.upper() for x in (app_name, key)))) | python | def make_env_key(app_name, key):
"""Creates an environment key-equivalent for the given key"""
key = key.replace('-', '_').replace(' ', '_')
return str("_".join((x.upper() for x in (app_name, key)))) | [
"def",
"make_env_key",
"(",
"app_name",
",",
"key",
")",
":",
"key",
"=",
"key",
".",
"replace",
"(",
"'-'",
",",
"'_'",
")",
".",
"replace",
"(",
"' '",
",",
"'_'",
")",
"return",
"str",
"(",
"\"_\"",
".",
"join",
"(",
"(",
"x",
".",
"upper",
... | Creates an environment key-equivalent for the given key | [
"Creates",
"an",
"environment",
"key",
"-",
"equivalent",
"for",
"the",
"given",
"key"
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L45-L48 | train | 48,187 |
kalefranz/auxlib | auxlib/configuration.py | Configuration.unset_env | def unset_env(self, key):
"""Removes an environment variable using the prepended app_name convention with `key`."""
os.environ.pop(make_env_key(self.appname, key), None)
self._registered_env_keys.discard(key)
self._clear_memoization() | python | def unset_env(self, key):
"""Removes an environment variable using the prepended app_name convention with `key`."""
os.environ.pop(make_env_key(self.appname, key), None)
self._registered_env_keys.discard(key)
self._clear_memoization() | [
"def",
"unset_env",
"(",
"self",
",",
"key",
")",
":",
"os",
".",
"environ",
".",
"pop",
"(",
"make_env_key",
"(",
"self",
".",
"appname",
",",
"key",
")",
",",
"None",
")",
"self",
".",
"_registered_env_keys",
".",
"discard",
"(",
"key",
")",
"self"... | Removes an environment variable using the prepended app_name convention with `key`. | [
"Removes",
"an",
"environment",
"variable",
"using",
"the",
"prepended",
"app_name",
"convention",
"with",
"key",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L146-L150 | train | 48,188 |
kalefranz/auxlib | auxlib/configuration.py | Configuration._reload | def _reload(self, force=False):
"""Reloads the configuration from the file and environment variables. Useful if using
`os.environ` instead of this class' `set_env` method, or if the underlying configuration
file is changed externally.
"""
self._config_map = dict()
self._registered_env_keys = set()
self.__reload_sources(force)
self.__load_environment_keys()
self.verify()
self._clear_memoization() | python | def _reload(self, force=False):
"""Reloads the configuration from the file and environment variables. Useful if using
`os.environ` instead of this class' `set_env` method, or if the underlying configuration
file is changed externally.
"""
self._config_map = dict()
self._registered_env_keys = set()
self.__reload_sources(force)
self.__load_environment_keys()
self.verify()
self._clear_memoization() | [
"def",
"_reload",
"(",
"self",
",",
"force",
"=",
"False",
")",
":",
"self",
".",
"_config_map",
"=",
"dict",
"(",
")",
"self",
".",
"_registered_env_keys",
"=",
"set",
"(",
")",
"self",
".",
"__reload_sources",
"(",
"force",
")",
"self",
".",
"__load_... | Reloads the configuration from the file and environment variables. Useful if using
`os.environ` instead of this class' `set_env` method, or if the underlying configuration
file is changed externally. | [
"Reloads",
"the",
"configuration",
"from",
"the",
"file",
"and",
"environment",
"variables",
".",
"Useful",
"if",
"using",
"os",
".",
"environ",
"instead",
"of",
"this",
"class",
"set_env",
"method",
"or",
"if",
"the",
"underlying",
"configuration",
"file",
"i... | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/configuration.py#L152-L162 | train | 48,189 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/rest.py | create_requests_session | def create_requests_session(
retries=None,
backoff_factor=None,
status_forcelist=None,
pools_size=4,
maxsize=4,
ssl_verify=None,
ssl_cert=None,
proxy=None,
session=None,
):
"""Create a requests session that retries some errors."""
# pylint: disable=too-many-branches
config = Configuration()
if retries is None:
if config.error_retry_max is None:
retries = 5
else:
retries = config.error_retry_max
if backoff_factor is None:
if config.error_retry_backoff is None:
backoff_factor = 0.23
else:
backoff_factor = config.error_retry_backoff
if status_forcelist is None:
if config.error_retry_codes is None:
status_forcelist = [500, 502, 503, 504]
else:
status_forcelist = config.error_retry_codes
if ssl_verify is None:
ssl_verify = config.verify_ssl
if ssl_cert is None:
if config.cert_file and config.key_file:
ssl_cert = (config.cert_file, config.key_file)
elif config.cert_file:
ssl_cert = config.cert_file
if proxy is None:
proxy = Configuration().proxy
session = session or requests.Session()
session.verify = ssl_verify
session.cert = ssl_cert
if proxy:
session.proxies = {"http": proxy, "https": proxy}
retry = Retry(
backoff_factor=backoff_factor,
connect=retries,
method_whitelist=False,
read=retries,
status_forcelist=tuple(status_forcelist),
total=retries,
)
adapter = HTTPAdapter(
max_retries=retry,
pool_connections=pools_size,
pool_maxsize=maxsize,
pool_block=True,
)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session | python | def create_requests_session(
retries=None,
backoff_factor=None,
status_forcelist=None,
pools_size=4,
maxsize=4,
ssl_verify=None,
ssl_cert=None,
proxy=None,
session=None,
):
"""Create a requests session that retries some errors."""
# pylint: disable=too-many-branches
config = Configuration()
if retries is None:
if config.error_retry_max is None:
retries = 5
else:
retries = config.error_retry_max
if backoff_factor is None:
if config.error_retry_backoff is None:
backoff_factor = 0.23
else:
backoff_factor = config.error_retry_backoff
if status_forcelist is None:
if config.error_retry_codes is None:
status_forcelist = [500, 502, 503, 504]
else:
status_forcelist = config.error_retry_codes
if ssl_verify is None:
ssl_verify = config.verify_ssl
if ssl_cert is None:
if config.cert_file and config.key_file:
ssl_cert = (config.cert_file, config.key_file)
elif config.cert_file:
ssl_cert = config.cert_file
if proxy is None:
proxy = Configuration().proxy
session = session or requests.Session()
session.verify = ssl_verify
session.cert = ssl_cert
if proxy:
session.proxies = {"http": proxy, "https": proxy}
retry = Retry(
backoff_factor=backoff_factor,
connect=retries,
method_whitelist=False,
read=retries,
status_forcelist=tuple(status_forcelist),
total=retries,
)
adapter = HTTPAdapter(
max_retries=retry,
pool_connections=pools_size,
pool_maxsize=maxsize,
pool_block=True,
)
session.mount("http://", adapter)
session.mount("https://", adapter)
return session | [
"def",
"create_requests_session",
"(",
"retries",
"=",
"None",
",",
"backoff_factor",
"=",
"None",
",",
"status_forcelist",
"=",
"None",
",",
"pools_size",
"=",
"4",
",",
"maxsize",
"=",
"4",
",",
"ssl_verify",
"=",
"None",
",",
"ssl_cert",
"=",
"None",
",... | Create a requests session that retries some errors. | [
"Create",
"a",
"requests",
"session",
"that",
"retries",
"some",
"errors",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L21-L92 | train | 48,190 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/rest.py | RestResponse.getheader | def getheader(self, name, default=None):
"""
Return a given response header.
"""
return self.response.headers.get(name, default) | python | def getheader(self, name, default=None):
"""
Return a given response header.
"""
return self.response.headers.get(name, default) | [
"def",
"getheader",
"(",
"self",
",",
"name",
",",
"default",
"=",
"None",
")",
":",
"return",
"self",
".",
"response",
".",
"headers",
".",
"get",
"(",
"name",
",",
"default",
")"
] | Return a given response header. | [
"Return",
"a",
"given",
"response",
"header",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/rest.py#L120-L124 | train | 48,191 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/utils.py | get_root_path | def get_root_path():
"""Get the root directory for the application."""
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir)) | python | def get_root_path():
"""Get the root directory for the application."""
return os.path.realpath(os.path.join(os.path.dirname(__file__), os.pardir)) | [
"def",
"get_root_path",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"realpath",
"(",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
",",
"os",
".",
"pardir",
")",
")"
] | Get the root directory for the application. | [
"Get",
"the",
"root",
"directory",
"for",
"the",
"application",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L21-L23 | train | 48,192 |
cloudsmith-io/cloudsmith-cli | cloudsmith_cli/core/utils.py | calculate_file_md5 | def calculate_file_md5(filepath, blocksize=2 ** 20):
"""Calculate an MD5 hash for a file."""
checksum = hashlib.md5()
with click.open_file(filepath, "rb") as f:
def update_chunk():
"""Add chunk to checksum."""
buf = f.read(blocksize)
if buf:
checksum.update(buf)
return bool(buf)
while update_chunk():
pass
return checksum.hexdigest() | python | def calculate_file_md5(filepath, blocksize=2 ** 20):
"""Calculate an MD5 hash for a file."""
checksum = hashlib.md5()
with click.open_file(filepath, "rb") as f:
def update_chunk():
"""Add chunk to checksum."""
buf = f.read(blocksize)
if buf:
checksum.update(buf)
return bool(buf)
while update_chunk():
pass
return checksum.hexdigest() | [
"def",
"calculate_file_md5",
"(",
"filepath",
",",
"blocksize",
"=",
"2",
"**",
"20",
")",
":",
"checksum",
"=",
"hashlib",
".",
"md5",
"(",
")",
"with",
"click",
".",
"open_file",
"(",
"filepath",
",",
"\"rb\"",
")",
"as",
"f",
":",
"def",
"update_chu... | Calculate an MD5 hash for a file. | [
"Calculate",
"an",
"MD5",
"hash",
"for",
"a",
"file",
"."
] | 5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e | https://github.com/cloudsmith-io/cloudsmith-cli/blob/5bc245ca5d0bfa85380be48e7c206b4c86cc6c8e/cloudsmith_cli/core/utils.py#L38-L54 | train | 48,193 |
kalefranz/auxlib | auxlib/packaging.py | _get_version_from_git_tag | def _get_version_from_git_tag(path):
"""Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash.
"""
m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '')
if m is None:
return None
version, post_commit, hash = m.groups()
return version if post_commit == '0' else "{0}.post{1}+{2}".format(version, post_commit, hash) | python | def _get_version_from_git_tag(path):
"""Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash.
"""
m = GIT_DESCRIBE_REGEX.match(_git_describe_tags(path) or '')
if m is None:
return None
version, post_commit, hash = m.groups()
return version if post_commit == '0' else "{0}.post{1}+{2}".format(version, post_commit, hash) | [
"def",
"_get_version_from_git_tag",
"(",
"path",
")",
":",
"m",
"=",
"GIT_DESCRIBE_REGEX",
".",
"match",
"(",
"_git_describe_tags",
"(",
"path",
")",
"or",
"''",
")",
"if",
"m",
"is",
"None",
":",
"return",
"None",
"version",
",",
"post_commit",
",",
"hash... | Return a PEP440-compliant version derived from the git status.
If that fails for any reason, return the changeset hash. | [
"Return",
"a",
"PEP440",
"-",
"compliant",
"version",
"derived",
"from",
"the",
"git",
"status",
".",
"If",
"that",
"fails",
"for",
"any",
"reason",
"return",
"the",
"changeset",
"hash",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/packaging.py#L142-L150 | train | 48,194 |
kalefranz/auxlib | auxlib/packaging.py | get_version | def get_version(dunder_file):
"""Returns a version string for the current package, derived
either from git or from a .version file.
This function is expected to run in two contexts. In a development
context, where .git/ exists, the version is pulled from git tags.
Using the BuildPyCommand and SDistCommand classes for cmdclass in
setup.py will write a .version file into any dist.
In an installed context, the .version file written at dist build
time is the source of version information.
"""
path = abspath(expanduser(dirname(dunder_file)))
try:
return _get_version_from_version_file(path) or _get_version_from_git_tag(path)
except CalledProcessError as e:
log.warn(repr(e))
return None
except Exception as e:
log.exception(e)
return None | python | def get_version(dunder_file):
"""Returns a version string for the current package, derived
either from git or from a .version file.
This function is expected to run in two contexts. In a development
context, where .git/ exists, the version is pulled from git tags.
Using the BuildPyCommand and SDistCommand classes for cmdclass in
setup.py will write a .version file into any dist.
In an installed context, the .version file written at dist build
time is the source of version information.
"""
path = abspath(expanduser(dirname(dunder_file)))
try:
return _get_version_from_version_file(path) or _get_version_from_git_tag(path)
except CalledProcessError as e:
log.warn(repr(e))
return None
except Exception as e:
log.exception(e)
return None | [
"def",
"get_version",
"(",
"dunder_file",
")",
":",
"path",
"=",
"abspath",
"(",
"expanduser",
"(",
"dirname",
"(",
"dunder_file",
")",
")",
")",
"try",
":",
"return",
"_get_version_from_version_file",
"(",
"path",
")",
"or",
"_get_version_from_git_tag",
"(",
... | Returns a version string for the current package, derived
either from git or from a .version file.
This function is expected to run in two contexts. In a development
context, where .git/ exists, the version is pulled from git tags.
Using the BuildPyCommand and SDistCommand classes for cmdclass in
setup.py will write a .version file into any dist.
In an installed context, the .version file written at dist build
time is the source of version information. | [
"Returns",
"a",
"version",
"string",
"for",
"the",
"current",
"package",
"derived",
"either",
"from",
"git",
"or",
"from",
"a",
".",
"version",
"file",
"."
] | 6ff2d6b57d128d0b9ed8f01ad83572e938da064f | https://github.com/kalefranz/auxlib/blob/6ff2d6b57d128d0b9ed8f01ad83572e938da064f/auxlib/packaging.py#L153-L174 | train | 48,195 |
skulumani/kinematics | kinematics/attitude.py | rot1 | def rot1(angle, form='c'):
"""Euler rotation about first axis
This computes the rotation matrix associated with a rotation about the first
axis. It will output matrices assuming column or row format vectors.
For example, to transform a vector from reference frame b to reference frame a:
Column Vectors : a = rot1(angle, 'c').dot(b)
Row Vectors : a = b.dot(rot1(angle, 'r'))
It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T
Parameters
----------
angle : float
Angle of rotation about first axis. In radians
form : str
Flag to choose between row or column vector convention.
Returns
-------
mat : numpy.ndarray of shape (3,3)
Rotation matrix
"""
cos_a = np.cos(angle)
sin_a = np.sin(angle)
rot_mat = np.identity(3)
if form=='c':
rot_mat[1, 1] = cos_a
rot_mat[1, 2] = -sin_a
rot_mat[2, 1] = sin_a
rot_mat[2, 2] = cos_a
elif form=='r':
rot_mat[1, 1] = cos_a
rot_mat[1, 2] = sin_a
rot_mat[2, 1] = -sin_a
rot_mat[2, 2] = cos_a
else:
print("Unknown input. 'r' or 'c' for row/column notation.")
return 1
return rot_mat | python | def rot1(angle, form='c'):
"""Euler rotation about first axis
This computes the rotation matrix associated with a rotation about the first
axis. It will output matrices assuming column or row format vectors.
For example, to transform a vector from reference frame b to reference frame a:
Column Vectors : a = rot1(angle, 'c').dot(b)
Row Vectors : a = b.dot(rot1(angle, 'r'))
It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T
Parameters
----------
angle : float
Angle of rotation about first axis. In radians
form : str
Flag to choose between row or column vector convention.
Returns
-------
mat : numpy.ndarray of shape (3,3)
Rotation matrix
"""
cos_a = np.cos(angle)
sin_a = np.sin(angle)
rot_mat = np.identity(3)
if form=='c':
rot_mat[1, 1] = cos_a
rot_mat[1, 2] = -sin_a
rot_mat[2, 1] = sin_a
rot_mat[2, 2] = cos_a
elif form=='r':
rot_mat[1, 1] = cos_a
rot_mat[1, 2] = sin_a
rot_mat[2, 1] = -sin_a
rot_mat[2, 2] = cos_a
else:
print("Unknown input. 'r' or 'c' for row/column notation.")
return 1
return rot_mat | [
"def",
"rot1",
"(",
"angle",
",",
"form",
"=",
"'c'",
")",
":",
"cos_a",
"=",
"np",
".",
"cos",
"(",
"angle",
")",
"sin_a",
"=",
"np",
".",
"sin",
"(",
"angle",
")",
"rot_mat",
"=",
"np",
".",
"identity",
"(",
"3",
")",
"if",
"form",
"==",
"'... | Euler rotation about first axis
This computes the rotation matrix associated with a rotation about the first
axis. It will output matrices assuming column or row format vectors.
For example, to transform a vector from reference frame b to reference frame a:
Column Vectors : a = rot1(angle, 'c').dot(b)
Row Vectors : a = b.dot(rot1(angle, 'r'))
It should be clear that rot1(angle, 'c') = rot1(angle, 'r').T
Parameters
----------
angle : float
Angle of rotation about first axis. In radians
form : str
Flag to choose between row or column vector convention.
Returns
-------
mat : numpy.ndarray of shape (3,3)
Rotation matrix | [
"Euler",
"rotation",
"about",
"first",
"axis"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L45-L88 | train | 48,196 |
skulumani/kinematics | kinematics/attitude.py | dcm2body313 | def dcm2body313(dcm):
"""Convert DCM to body Euler 3-1-3 angles
"""
theta = np.zeros(3)
theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1])
theta[1] = np.arccos(dcm[2, 2])
theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2])
return theta | python | def dcm2body313(dcm):
"""Convert DCM to body Euler 3-1-3 angles
"""
theta = np.zeros(3)
theta[0] = np.arctan2(dcm[2, 0], dcm[2, 1])
theta[1] = np.arccos(dcm[2, 2])
theta[2] = np.arctan2(dcm[0, 2], -dcm[1, 2])
return theta | [
"def",
"dcm2body313",
"(",
"dcm",
")",
":",
"theta",
"=",
"np",
".",
"zeros",
"(",
"3",
")",
"theta",
"[",
"0",
"]",
"=",
"np",
".",
"arctan2",
"(",
"dcm",
"[",
"2",
",",
"0",
"]",
",",
"dcm",
"[",
"2",
",",
"1",
"]",
")",
"theta",
"[",
"... | Convert DCM to body Euler 3-1-3 angles | [
"Convert",
"DCM",
"to",
"body",
"Euler",
"3",
"-",
"1",
"-",
"3",
"angles"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L180-L190 | train | 48,197 |
skulumani/kinematics | kinematics/attitude.py | vee_map | def vee_map(skew):
"""Return the vee map of a vector
"""
vec = 1/2 * np.array([skew[2,1] - skew[1,2],
skew[0,2] - skew[2,0],
skew[1,0] - skew[0,1]])
return vec | python | def vee_map(skew):
"""Return the vee map of a vector
"""
vec = 1/2 * np.array([skew[2,1] - skew[1,2],
skew[0,2] - skew[2,0],
skew[1,0] - skew[0,1]])
return vec | [
"def",
"vee_map",
"(",
"skew",
")",
":",
"vec",
"=",
"1",
"/",
"2",
"*",
"np",
".",
"array",
"(",
"[",
"skew",
"[",
"2",
",",
"1",
"]",
"-",
"skew",
"[",
"1",
",",
"2",
"]",
",",
"skew",
"[",
"0",
",",
"2",
"]",
"-",
"skew",
"[",
"2",
... | Return the vee map of a vector | [
"Return",
"the",
"vee",
"map",
"of",
"a",
"vector"
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L262-L271 | train | 48,198 |
skulumani/kinematics | kinematics/attitude.py | dcmtoquat | def dcmtoquat(dcm):
"""Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
"""
quat = np.zeros(4)
quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)
quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)
return quat | python | def dcmtoquat(dcm):
"""Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w]
"""
quat = np.zeros(4)
quat[-1] = 1/2*np.sqrt(np.trace(dcm)+1)
quat[0:3] = 1/4/quat[-1]*vee_map(dcm-dcm.T)
return quat | [
"def",
"dcmtoquat",
"(",
"dcm",
")",
":",
"quat",
"=",
"np",
".",
"zeros",
"(",
"4",
")",
"quat",
"[",
"-",
"1",
"]",
"=",
"1",
"/",
"2",
"*",
"np",
".",
"sqrt",
"(",
"np",
".",
"trace",
"(",
"dcm",
")",
"+",
"1",
")",
"quat",
"[",
"0",
... | Convert DCM to quaternion
This function will convert a rotation matrix, also called a direction
cosine matrix into the equivalent quaternion.
Parameters:
----------
dcm - (3,3) numpy array
Numpy rotation matrix which defines a rotation from the b to a frame
Returns:
--------
quat - (4,) numpy array
Array defining a quaterion where the quaternion is defined in terms of
a vector and a scalar part. The vector is related to the eigen axis
and equivalent in both reference frames [x y z w] | [
"Convert",
"DCM",
"to",
"quaternion",
"This",
"function",
"will",
"convert",
"a",
"rotation",
"matrix",
"also",
"called",
"a",
"direction",
"cosine",
"matrix",
"into",
"the",
"equivalent",
"quaternion",
"."
] | e8cb45efb40539982025ed0f85d6561f9f10fef0 | https://github.com/skulumani/kinematics/blob/e8cb45efb40539982025ed0f85d6561f9f10fef0/kinematics/attitude.py#L273-L295 | train | 48,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.