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
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
openid/python-openid | openid/consumer/consumer.py | AuthRequest.formMarkup | def formMarkup(self, realm, return_to=None, immediate=False,
form_tag_attrs=None):
"""Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@type form_tag_attrs: {unicode: unicode}
"""
message = self.getMessage(realm, return_to, immediate)
return message.toFormMarkup(self.endpoint.server_url,
form_tag_attrs) | python | def formMarkup(self, realm, return_to=None, immediate=False,
form_tag_attrs=None):
"""Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@type form_tag_attrs: {unicode: unicode}
"""
message = self.getMessage(realm, return_to, immediate)
return message.toFormMarkup(self.endpoint.server_url,
form_tag_attrs) | [
"def",
"formMarkup",
"(",
"self",
",",
"realm",
",",
"return_to",
"=",
"None",
",",
"immediate",
"=",
"False",
",",
"form_tag_attrs",
"=",
"None",
")",
":",
"message",
"=",
"self",
".",
"getMessage",
"(",
"realm",
",",
"return_to",
",",
"immediate",
")",
"return",
"message",
".",
"toFormMarkup",
"(",
"self",
".",
"endpoint",
".",
"server_url",
",",
"form_tag_attrs",
")"
] | Get html for a form to submit this request to the IDP.
@param form_tag_attrs: Dictionary of attributes to be added to
the form tag. 'accept-charset' and 'enctype' have defaults
that can be overridden. If a value is supplied for
'action' or 'method', it will be replaced.
@type form_tag_attrs: {unicode: unicode} | [
"Get",
"html",
"for",
"a",
"form",
"to",
"submit",
"this",
"request",
"to",
"the",
"IDP",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1649-L1661 | train |
openid/python-openid | openid/consumer/consumer.py | AuthRequest.htmlMarkup | def htmlMarkup(self, realm, return_to=None, immediate=False,
form_tag_attrs=None):
"""Get an autosubmitting HTML page that submits this request to the
IDP. This is just a wrapper for formMarkup.
@see: formMarkup
@returns: str
"""
return oidutil.autoSubmitHTML(self.formMarkup(realm,
return_to,
immediate,
form_tag_attrs)) | python | def htmlMarkup(self, realm, return_to=None, immediate=False,
form_tag_attrs=None):
"""Get an autosubmitting HTML page that submits this request to the
IDP. This is just a wrapper for formMarkup.
@see: formMarkup
@returns: str
"""
return oidutil.autoSubmitHTML(self.formMarkup(realm,
return_to,
immediate,
form_tag_attrs)) | [
"def",
"htmlMarkup",
"(",
"self",
",",
"realm",
",",
"return_to",
"=",
"None",
",",
"immediate",
"=",
"False",
",",
"form_tag_attrs",
"=",
"None",
")",
":",
"return",
"oidutil",
".",
"autoSubmitHTML",
"(",
"self",
".",
"formMarkup",
"(",
"realm",
",",
"return_to",
",",
"immediate",
",",
"form_tag_attrs",
")",
")"
] | Get an autosubmitting HTML page that submits this request to the
IDP. This is just a wrapper for formMarkup.
@see: formMarkup
@returns: str | [
"Get",
"an",
"autosubmitting",
"HTML",
"page",
"that",
"submits",
"this",
"request",
"to",
"the",
"IDP",
".",
"This",
"is",
"just",
"a",
"wrapper",
"for",
"formMarkup",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1663-L1675 | train |
openid/python-openid | openid/consumer/consumer.py | SuccessResponse.isSigned | def isSigned(self, ns_uri, ns_key):
"""Return whether a particular key is signed, regardless of
its namespace alias
"""
return self.message.getKey(ns_uri, ns_key) in self.signed_fields | python | def isSigned(self, ns_uri, ns_key):
"""Return whether a particular key is signed, regardless of
its namespace alias
"""
return self.message.getKey(ns_uri, ns_key) in self.signed_fields | [
"def",
"isSigned",
"(",
"self",
",",
"ns_uri",
",",
"ns_key",
")",
":",
"return",
"self",
".",
"message",
".",
"getKey",
"(",
"ns_uri",
",",
"ns_key",
")",
"in",
"self",
".",
"signed_fields"
] | Return whether a particular key is signed, regardless of
its namespace alias | [
"Return",
"whether",
"a",
"particular",
"key",
"is",
"signed",
"regardless",
"of",
"its",
"namespace",
"alias"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1759-L1763 | train |
openid/python-openid | openid/consumer/consumer.py | SuccessResponse.getSigned | def getSigned(self, ns_uri, ns_key, default=None):
"""Return the specified signed field if available,
otherwise return default
"""
if self.isSigned(ns_uri, ns_key):
return self.message.getArg(ns_uri, ns_key, default)
else:
return default | python | def getSigned(self, ns_uri, ns_key, default=None):
"""Return the specified signed field if available,
otherwise return default
"""
if self.isSigned(ns_uri, ns_key):
return self.message.getArg(ns_uri, ns_key, default)
else:
return default | [
"def",
"getSigned",
"(",
"self",
",",
"ns_uri",
",",
"ns_key",
",",
"default",
"=",
"None",
")",
":",
"if",
"self",
".",
"isSigned",
"(",
"ns_uri",
",",
"ns_key",
")",
":",
"return",
"self",
".",
"message",
".",
"getArg",
"(",
"ns_uri",
",",
"ns_key",
",",
"default",
")",
"else",
":",
"return",
"default"
] | Return the specified signed field if available,
otherwise return default | [
"Return",
"the",
"specified",
"signed",
"field",
"if",
"available",
"otherwise",
"return",
"default"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1765-L1772 | train |
openid/python-openid | openid/consumer/consumer.py | SuccessResponse.getSignedNS | def getSignedNS(self, ns_uri):
"""Get signed arguments from the response message. Return a
dict of all arguments in the specified namespace. If any of
the arguments are not signed, return None.
"""
msg_args = self.message.getArgs(ns_uri)
for key in msg_args.iterkeys():
if not self.isSigned(ns_uri, key):
logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed."
% (ns_uri, key))
return None
return msg_args | python | def getSignedNS(self, ns_uri):
"""Get signed arguments from the response message. Return a
dict of all arguments in the specified namespace. If any of
the arguments are not signed, return None.
"""
msg_args = self.message.getArgs(ns_uri)
for key in msg_args.iterkeys():
if not self.isSigned(ns_uri, key):
logging.info("SuccessResponse.getSignedNS: (%s, %s) not signed."
% (ns_uri, key))
return None
return msg_args | [
"def",
"getSignedNS",
"(",
"self",
",",
"ns_uri",
")",
":",
"msg_args",
"=",
"self",
".",
"message",
".",
"getArgs",
"(",
"ns_uri",
")",
"for",
"key",
"in",
"msg_args",
".",
"iterkeys",
"(",
")",
":",
"if",
"not",
"self",
".",
"isSigned",
"(",
"ns_uri",
",",
"key",
")",
":",
"logging",
".",
"info",
"(",
"\"SuccessResponse.getSignedNS: (%s, %s) not signed.\"",
"%",
"(",
"ns_uri",
",",
"key",
")",
")",
"return",
"None",
"return",
"msg_args"
] | Get signed arguments from the response message. Return a
dict of all arguments in the specified namespace. If any of
the arguments are not signed, return None. | [
"Get",
"signed",
"arguments",
"from",
"the",
"response",
"message",
".",
"Return",
"a",
"dict",
"of",
"all",
"arguments",
"in",
"the",
"specified",
"namespace",
".",
"If",
"any",
"of",
"the",
"arguments",
"are",
"not",
"signed",
"return",
"None",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1774-L1787 | train |
openid/python-openid | openid/consumer/consumer.py | SuccessResponse.extensionResponse | def extensionResponse(self, namespace_uri, require_signed):
"""Return response arguments in the specified namespace.
@param namespace_uri: The namespace URI of the arguments to be
returned.
@param require_signed: True if the arguments should be among
those signed in the response, False if you don't care.
If require_signed is True and the arguments are not signed,
return None.
"""
if require_signed:
return self.getSignedNS(namespace_uri)
else:
return self.message.getArgs(namespace_uri) | python | def extensionResponse(self, namespace_uri, require_signed):
"""Return response arguments in the specified namespace.
@param namespace_uri: The namespace URI of the arguments to be
returned.
@param require_signed: True if the arguments should be among
those signed in the response, False if you don't care.
If require_signed is True and the arguments are not signed,
return None.
"""
if require_signed:
return self.getSignedNS(namespace_uri)
else:
return self.message.getArgs(namespace_uri) | [
"def",
"extensionResponse",
"(",
"self",
",",
"namespace_uri",
",",
"require_signed",
")",
":",
"if",
"require_signed",
":",
"return",
"self",
".",
"getSignedNS",
"(",
"namespace_uri",
")",
"else",
":",
"return",
"self",
".",
"message",
".",
"getArgs",
"(",
"namespace_uri",
")"
] | Return response arguments in the specified namespace.
@param namespace_uri: The namespace URI of the arguments to be
returned.
@param require_signed: True if the arguments should be among
those signed in the response, False if you don't care.
If require_signed is True and the arguments are not signed,
return None. | [
"Return",
"response",
"arguments",
"in",
"the",
"specified",
"namespace",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/consumer/consumer.py#L1789-L1804 | train |
openid/python-openid | openid/yadis/filters.py | mkFilter | def mkFilter(parts):
"""Convert a filter-convertable thing into a filter
@param parts: a filter, an endpoint, a callable, or a list of any of these.
"""
# Convert the parts into a list, and pass to mkCompoundFilter
if parts is None:
parts = [BasicServiceEndpoint]
try:
parts = list(parts)
except TypeError:
return mkCompoundFilter([parts])
else:
return mkCompoundFilter(parts) | python | def mkFilter(parts):
"""Convert a filter-convertable thing into a filter
@param parts: a filter, an endpoint, a callable, or a list of any of these.
"""
# Convert the parts into a list, and pass to mkCompoundFilter
if parts is None:
parts = [BasicServiceEndpoint]
try:
parts = list(parts)
except TypeError:
return mkCompoundFilter([parts])
else:
return mkCompoundFilter(parts) | [
"def",
"mkFilter",
"(",
"parts",
")",
":",
"# Convert the parts into a list, and pass to mkCompoundFilter",
"if",
"parts",
"is",
"None",
":",
"parts",
"=",
"[",
"BasicServiceEndpoint",
"]",
"try",
":",
"parts",
"=",
"list",
"(",
"parts",
")",
"except",
"TypeError",
":",
"return",
"mkCompoundFilter",
"(",
"[",
"parts",
"]",
")",
"else",
":",
"return",
"mkCompoundFilter",
"(",
"parts",
")"
] | Convert a filter-convertable thing into a filter
@param parts: a filter, an endpoint, a callable, or a list of any of these. | [
"Convert",
"a",
"filter",
"-",
"convertable",
"thing",
"into",
"a",
"filter"
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L146-L160 | train |
openid/python-openid | openid/yadis/filters.py | TransformFilterMaker.getServiceEndpoints | def getServiceEndpoints(self, yadis_url, service_element):
"""Returns an iterator of endpoint objects produced by the
filter functions."""
endpoints = []
# Do an expansion of the service element by xrd:Type and xrd:URI
for type_uris, uri, _ in expandService(service_element):
# Create a basic endpoint object to represent this
# yadis_url, Service, Type, URI combination
endpoint = BasicServiceEndpoint(
yadis_url, type_uris, uri, service_element)
e = self.applyFilters(endpoint)
if e is not None:
endpoints.append(e)
return endpoints | python | def getServiceEndpoints(self, yadis_url, service_element):
"""Returns an iterator of endpoint objects produced by the
filter functions."""
endpoints = []
# Do an expansion of the service element by xrd:Type and xrd:URI
for type_uris, uri, _ in expandService(service_element):
# Create a basic endpoint object to represent this
# yadis_url, Service, Type, URI combination
endpoint = BasicServiceEndpoint(
yadis_url, type_uris, uri, service_element)
e = self.applyFilters(endpoint)
if e is not None:
endpoints.append(e)
return endpoints | [
"def",
"getServiceEndpoints",
"(",
"self",
",",
"yadis_url",
",",
"service_element",
")",
":",
"endpoints",
"=",
"[",
"]",
"# Do an expansion of the service element by xrd:Type and xrd:URI",
"for",
"type_uris",
",",
"uri",
",",
"_",
"in",
"expandService",
"(",
"service_element",
")",
":",
"# Create a basic endpoint object to represent this",
"# yadis_url, Service, Type, URI combination",
"endpoint",
"=",
"BasicServiceEndpoint",
"(",
"yadis_url",
",",
"type_uris",
",",
"uri",
",",
"service_element",
")",
"e",
"=",
"self",
".",
"applyFilters",
"(",
"endpoint",
")",
"if",
"e",
"is",
"not",
"None",
":",
"endpoints",
".",
"append",
"(",
"e",
")",
"return",
"endpoints"
] | Returns an iterator of endpoint objects produced by the
filter functions. | [
"Returns",
"an",
"iterator",
"of",
"endpoint",
"objects",
"produced",
"by",
"the",
"filter",
"functions",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L95-L112 | train |
openid/python-openid | openid/yadis/filters.py | TransformFilterMaker.applyFilters | def applyFilters(self, endpoint):
"""Apply filter functions to an endpoint until one of them
returns non-None."""
for filter_function in self.filter_functions:
e = filter_function(endpoint)
if e is not None:
# Once one of the filters has returned an
# endpoint, do not apply any more.
return e
return None | python | def applyFilters(self, endpoint):
"""Apply filter functions to an endpoint until one of them
returns non-None."""
for filter_function in self.filter_functions:
e = filter_function(endpoint)
if e is not None:
# Once one of the filters has returned an
# endpoint, do not apply any more.
return e
return None | [
"def",
"applyFilters",
"(",
"self",
",",
"endpoint",
")",
":",
"for",
"filter_function",
"in",
"self",
".",
"filter_functions",
":",
"e",
"=",
"filter_function",
"(",
"endpoint",
")",
"if",
"e",
"is",
"not",
"None",
":",
"# Once one of the filters has returned an",
"# endpoint, do not apply any more.",
"return",
"e",
"return",
"None"
] | Apply filter functions to an endpoint until one of them
returns non-None. | [
"Apply",
"filter",
"functions",
"to",
"an",
"endpoint",
"until",
"one",
"of",
"them",
"returns",
"non",
"-",
"None",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L114-L124 | train |
openid/python-openid | openid/yadis/filters.py | CompoundFilter.getServiceEndpoints | def getServiceEndpoints(self, yadis_url, service_element):
"""Generate all endpoint objects for all of the subfilters of
this filter and return their concatenation."""
endpoints = []
for subfilter in self.subfilters:
endpoints.extend(
subfilter.getServiceEndpoints(yadis_url, service_element))
return endpoints | python | def getServiceEndpoints(self, yadis_url, service_element):
"""Generate all endpoint objects for all of the subfilters of
this filter and return their concatenation."""
endpoints = []
for subfilter in self.subfilters:
endpoints.extend(
subfilter.getServiceEndpoints(yadis_url, service_element))
return endpoints | [
"def",
"getServiceEndpoints",
"(",
"self",
",",
"yadis_url",
",",
"service_element",
")",
":",
"endpoints",
"=",
"[",
"]",
"for",
"subfilter",
"in",
"self",
".",
"subfilters",
":",
"endpoints",
".",
"extend",
"(",
"subfilter",
".",
"getServiceEndpoints",
"(",
"yadis_url",
",",
"service_element",
")",
")",
"return",
"endpoints"
] | Generate all endpoint objects for all of the subfilters of
this filter and return their concatenation. | [
"Generate",
"all",
"endpoint",
"objects",
"for",
"all",
"of",
"the",
"subfilters",
"of",
"this",
"filter",
"and",
"return",
"their",
"concatenation",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/yadis/filters.py#L133-L140 | train |
openid/python-openid | openid/cryptutil.py | randomString | def randomString(length, chrs=None):
"""Produce a string of length random bytes, chosen from chrs."""
if chrs is None:
return getBytes(length)
else:
n = len(chrs)
return ''.join([chrs[randrange(n)] for _ in xrange(length)]) | python | def randomString(length, chrs=None):
"""Produce a string of length random bytes, chosen from chrs."""
if chrs is None:
return getBytes(length)
else:
n = len(chrs)
return ''.join([chrs[randrange(n)] for _ in xrange(length)]) | [
"def",
"randomString",
"(",
"length",
",",
"chrs",
"=",
"None",
")",
":",
"if",
"chrs",
"is",
"None",
":",
"return",
"getBytes",
"(",
"length",
")",
"else",
":",
"n",
"=",
"len",
"(",
"chrs",
")",
"return",
"''",
".",
"join",
"(",
"[",
"chrs",
"[",
"randrange",
"(",
"n",
")",
"]",
"for",
"_",
"in",
"xrange",
"(",
"length",
")",
"]",
")"
] | Produce a string of length random bytes, chosen from chrs. | [
"Produce",
"a",
"string",
"of",
"length",
"random",
"bytes",
"chosen",
"from",
"chrs",
"."
] | f7e13536f0d1828d3cef5ae7a7b55cabadff37fc | https://github.com/openid/python-openid/blob/f7e13536f0d1828d3cef5ae7a7b55cabadff37fc/openid/cryptutil.py#L214-L220 | train |
ethereum/eth-hash | eth_hash/main.py | Keccak256._hasher_first_run | def _hasher_first_run(self, preimage):
'''
Invoke the backend on-demand, and check an expected hash result,
then replace this first run with the new hasher method.
This is a bit of a hacky way to minimize overhead on hash calls after this first one.
'''
new_hasher = self._backend.keccak256
assert new_hasher(b'') == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501
self.hasher = new_hasher
return new_hasher(preimage) | python | def _hasher_first_run(self, preimage):
'''
Invoke the backend on-demand, and check an expected hash result,
then replace this first run with the new hasher method.
This is a bit of a hacky way to minimize overhead on hash calls after this first one.
'''
new_hasher = self._backend.keccak256
assert new_hasher(b'') == b"\xc5\xd2F\x01\x86\xf7#<\x92~}\xb2\xdc\xc7\x03\xc0\xe5\x00\xb6S\xca\x82';\x7b\xfa\xd8\x04]\x85\xa4p" # noqa: E501
self.hasher = new_hasher
return new_hasher(preimage) | [
"def",
"_hasher_first_run",
"(",
"self",
",",
"preimage",
")",
":",
"new_hasher",
"=",
"self",
".",
"_backend",
".",
"keccak256",
"assert",
"new_hasher",
"(",
"b''",
")",
"==",
"b\"\\xc5\\xd2F\\x01\\x86\\xf7#<\\x92~}\\xb2\\xdc\\xc7\\x03\\xc0\\xe5\\x00\\xb6S\\xca\\x82';\\x7b\\xfa\\xd8\\x04]\\x85\\xa4p\"",
"# noqa: E501",
"self",
".",
"hasher",
"=",
"new_hasher",
"return",
"new_hasher",
"(",
"preimage",
")"
] | Invoke the backend on-demand, and check an expected hash result,
then replace this first run with the new hasher method.
This is a bit of a hacky way to minimize overhead on hash calls after this first one. | [
"Invoke",
"the",
"backend",
"on",
"-",
"demand",
"and",
"check",
"an",
"expected",
"hash",
"result",
"then",
"replace",
"this",
"first",
"run",
"with",
"the",
"new",
"hasher",
"method",
".",
"This",
"is",
"a",
"bit",
"of",
"a",
"hacky",
"way",
"to",
"minimize",
"overhead",
"on",
"hash",
"calls",
"after",
"this",
"first",
"one",
"."
] | d05c8ac0710e2dc16aae2c8a1e406ee7cbe78871 | https://github.com/ethereum/eth-hash/blob/d05c8ac0710e2dc16aae2c8a1e406ee7cbe78871/eth_hash/main.py#L16-L25 | train |
lukasgeiter/mkdocs-awesome-pages-plugin | mkdocs_awesome_pages_plugin/utils.py | dirname | def dirname(path: Optional[str]) -> Optional[str]:
""" Returns the directory component of a pathname and None if the argument is None """
if path is not None:
return os.path.dirname(path) | python | def dirname(path: Optional[str]) -> Optional[str]:
""" Returns the directory component of a pathname and None if the argument is None """
if path is not None:
return os.path.dirname(path) | [
"def",
"dirname",
"(",
"path",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")"
] | Returns the directory component of a pathname and None if the argument is None | [
"Returns",
"the",
"directory",
"component",
"of",
"a",
"pathname",
"and",
"None",
"if",
"the",
"argument",
"is",
"None"
] | f5693418b71a0849c5fee3b3307e117983c4e2d8 | https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L19-L22 | train |
lukasgeiter/mkdocs-awesome-pages-plugin | mkdocs_awesome_pages_plugin/utils.py | basename | def basename(path: Optional[str]) -> Optional[str]:
""" Returns the final component of a pathname and None if the argument is None """
if path is not None:
return os.path.basename(path) | python | def basename(path: Optional[str]) -> Optional[str]:
""" Returns the final component of a pathname and None if the argument is None """
if path is not None:
return os.path.basename(path) | [
"def",
"basename",
"(",
"path",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"os",
".",
"path",
".",
"basename",
"(",
"path",
")"
] | Returns the final component of a pathname and None if the argument is None | [
"Returns",
"the",
"final",
"component",
"of",
"a",
"pathname",
"and",
"None",
"if",
"the",
"argument",
"is",
"None"
] | f5693418b71a0849c5fee3b3307e117983c4e2d8 | https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L25-L28 | train |
lukasgeiter/mkdocs-awesome-pages-plugin | mkdocs_awesome_pages_plugin/utils.py | normpath | def normpath(path: Optional[str]) -> Optional[str]:
""" Normalizes the path, returns None if the argument is None """
if path is not None:
return os.path.normpath(path) | python | def normpath(path: Optional[str]) -> Optional[str]:
""" Normalizes the path, returns None if the argument is None """
if path is not None:
return os.path.normpath(path) | [
"def",
"normpath",
"(",
"path",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"path",
"is",
"not",
"None",
":",
"return",
"os",
".",
"path",
".",
"normpath",
"(",
"path",
")"
] | Normalizes the path, returns None if the argument is None | [
"Normalizes",
"the",
"path",
"returns",
"None",
"if",
"the",
"argument",
"is",
"None"
] | f5693418b71a0849c5fee3b3307e117983c4e2d8 | https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L31-L34 | train |
lukasgeiter/mkdocs-awesome-pages-plugin | mkdocs_awesome_pages_plugin/utils.py | join_paths | def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]:
""" Joins two paths if neither of them is None """
if path1 is not None and path2 is not None:
return os.path.join(path1, path2) | python | def join_paths(path1: Optional[str], path2: Optional[str]) -> Optional[str]:
""" Joins two paths if neither of them is None """
if path1 is not None and path2 is not None:
return os.path.join(path1, path2) | [
"def",
"join_paths",
"(",
"path1",
":",
"Optional",
"[",
"str",
"]",
",",
"path2",
":",
"Optional",
"[",
"str",
"]",
")",
"->",
"Optional",
"[",
"str",
"]",
":",
"if",
"path1",
"is",
"not",
"None",
"and",
"path2",
"is",
"not",
"None",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"path1",
",",
"path2",
")"
] | Joins two paths if neither of them is None | [
"Joins",
"two",
"paths",
"if",
"neither",
"of",
"them",
"is",
"None"
] | f5693418b71a0849c5fee3b3307e117983c4e2d8 | https://github.com/lukasgeiter/mkdocs-awesome-pages-plugin/blob/f5693418b71a0849c5fee3b3307e117983c4e2d8/mkdocs_awesome_pages_plugin/utils.py#L37-L40 | train |
msiemens/PyGitUp | PyGitUp/git_wrapper.py | GitWrapper.stasher | def stasher(self):
"""
A stashing contextmanager.
"""
# nonlocal for python2
stashed = [False]
clean = [False]
def stash():
if clean[0] or not self.repo.is_dirty(submodules=False):
clean[0] = True
return
if stashed[0]:
return
if self.change_count > 1:
message = 'stashing {0} changes'
else:
message = 'stashing {0} change'
print(colored(
message.format(self.change_count),
'magenta'
))
try:
self._run('stash')
except GitError as e:
raise StashError(stderr=e.stderr, stdout=e.stdout)
stashed[0] = True
yield stash
if stashed[0]:
print(colored('unstashing', 'magenta'))
try:
self._run('stash', 'pop')
except GitError as e:
raise UnstashError(stderr=e.stderr, stdout=e.stdout) | python | def stasher(self):
"""
A stashing contextmanager.
"""
# nonlocal for python2
stashed = [False]
clean = [False]
def stash():
if clean[0] or not self.repo.is_dirty(submodules=False):
clean[0] = True
return
if stashed[0]:
return
if self.change_count > 1:
message = 'stashing {0} changes'
else:
message = 'stashing {0} change'
print(colored(
message.format(self.change_count),
'magenta'
))
try:
self._run('stash')
except GitError as e:
raise StashError(stderr=e.stderr, stdout=e.stdout)
stashed[0] = True
yield stash
if stashed[0]:
print(colored('unstashing', 'magenta'))
try:
self._run('stash', 'pop')
except GitError as e:
raise UnstashError(stderr=e.stderr, stdout=e.stdout) | [
"def",
"stasher",
"(",
"self",
")",
":",
"# nonlocal for python2\r",
"stashed",
"=",
"[",
"False",
"]",
"clean",
"=",
"[",
"False",
"]",
"def",
"stash",
"(",
")",
":",
"if",
"clean",
"[",
"0",
"]",
"or",
"not",
"self",
".",
"repo",
".",
"is_dirty",
"(",
"submodules",
"=",
"False",
")",
":",
"clean",
"[",
"0",
"]",
"=",
"True",
"return",
"if",
"stashed",
"[",
"0",
"]",
":",
"return",
"if",
"self",
".",
"change_count",
">",
"1",
":",
"message",
"=",
"'stashing {0} changes'",
"else",
":",
"message",
"=",
"'stashing {0} change'",
"print",
"(",
"colored",
"(",
"message",
".",
"format",
"(",
"self",
".",
"change_count",
")",
",",
"'magenta'",
")",
")",
"try",
":",
"self",
".",
"_run",
"(",
"'stash'",
")",
"except",
"GitError",
"as",
"e",
":",
"raise",
"StashError",
"(",
"stderr",
"=",
"e",
".",
"stderr",
",",
"stdout",
"=",
"e",
".",
"stdout",
")",
"stashed",
"[",
"0",
"]",
"=",
"True",
"yield",
"stash",
"if",
"stashed",
"[",
"0",
"]",
":",
"print",
"(",
"colored",
"(",
"'unstashing'",
",",
"'magenta'",
")",
")",
"try",
":",
"self",
".",
"_run",
"(",
"'stash'",
",",
"'pop'",
")",
"except",
"GitError",
"as",
"e",
":",
"raise",
"UnstashError",
"(",
"stderr",
"=",
"e",
".",
"stderr",
",",
"stdout",
"=",
"e",
".",
"stdout",
")"
] | A stashing contextmanager. | [
"A",
"stashing",
"contextmanager",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L117-L154 | train |
msiemens/PyGitUp | PyGitUp/git_wrapper.py | GitWrapper.checkout | def checkout(self, branch_name):
""" Checkout a branch by name. """
try:
find(
self.repo.branches, lambda b: b.name == branch_name
).checkout()
except OrigCheckoutError as e:
raise CheckoutError(branch_name, details=e) | python | def checkout(self, branch_name):
""" Checkout a branch by name. """
try:
find(
self.repo.branches, lambda b: b.name == branch_name
).checkout()
except OrigCheckoutError as e:
raise CheckoutError(branch_name, details=e) | [
"def",
"checkout",
"(",
"self",
",",
"branch_name",
")",
":",
"try",
":",
"find",
"(",
"self",
".",
"repo",
".",
"branches",
",",
"lambda",
"b",
":",
"b",
".",
"name",
"==",
"branch_name",
")",
".",
"checkout",
"(",
")",
"except",
"OrigCheckoutError",
"as",
"e",
":",
"raise",
"CheckoutError",
"(",
"branch_name",
",",
"details",
"=",
"e",
")"
] | Checkout a branch by name. | [
"Checkout",
"a",
"branch",
"by",
"name",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L156-L163 | train |
msiemens/PyGitUp | PyGitUp/git_wrapper.py | GitWrapper.rebase | def rebase(self, target_branch):
""" Rebase to target branch. """
current_branch = self.repo.active_branch
arguments = (
([self.config('git-up.rebase.arguments')] or []) +
[target_branch.name]
)
try:
self._run('rebase', *arguments)
except GitError as e:
raise RebaseError(current_branch.name, target_branch.name,
**e.__dict__) | python | def rebase(self, target_branch):
""" Rebase to target branch. """
current_branch = self.repo.active_branch
arguments = (
([self.config('git-up.rebase.arguments')] or []) +
[target_branch.name]
)
try:
self._run('rebase', *arguments)
except GitError as e:
raise RebaseError(current_branch.name, target_branch.name,
**e.__dict__) | [
"def",
"rebase",
"(",
"self",
",",
"target_branch",
")",
":",
"current_branch",
"=",
"self",
".",
"repo",
".",
"active_branch",
"arguments",
"=",
"(",
"(",
"[",
"self",
".",
"config",
"(",
"'git-up.rebase.arguments'",
")",
"]",
"or",
"[",
"]",
")",
"+",
"[",
"target_branch",
".",
"name",
"]",
")",
"try",
":",
"self",
".",
"_run",
"(",
"'rebase'",
",",
"*",
"arguments",
")",
"except",
"GitError",
"as",
"e",
":",
"raise",
"RebaseError",
"(",
"current_branch",
".",
"name",
",",
"target_branch",
".",
"name",
",",
"*",
"*",
"e",
".",
"__dict__",
")"
] | Rebase to target branch. | [
"Rebase",
"to",
"target",
"branch",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L165-L177 | train |
msiemens/PyGitUp | PyGitUp/git_wrapper.py | GitWrapper.push | def push(self, *args, **kwargs):
''' Push commits to remote '''
stdout = six.b('')
# Execute command
cmd = self.git.push(as_process=True, *args, **kwargs)
# Capture output
while True:
output = cmd.stdout.read(1)
sys.stdout.write(output.decode('utf-8'))
sys.stdout.flush()
stdout += output
# Check for EOF
if output == six.b(""):
break
# Wait for the process to quit
try:
cmd.wait()
except GitCommandError as error:
# Add more meta-information to errors
message = "'{0}' returned exit status {1}".format(
' '.join(str(c) for c in error.command),
error.status
)
raise GitError(message, stderr=error.stderr, stdout=stdout)
return stdout.strip() | python | def push(self, *args, **kwargs):
''' Push commits to remote '''
stdout = six.b('')
# Execute command
cmd = self.git.push(as_process=True, *args, **kwargs)
# Capture output
while True:
output = cmd.stdout.read(1)
sys.stdout.write(output.decode('utf-8'))
sys.stdout.flush()
stdout += output
# Check for EOF
if output == six.b(""):
break
# Wait for the process to quit
try:
cmd.wait()
except GitCommandError as error:
# Add more meta-information to errors
message = "'{0}' returned exit status {1}".format(
' '.join(str(c) for c in error.command),
error.status
)
raise GitError(message, stderr=error.stderr, stdout=stdout)
return stdout.strip() | [
"def",
"push",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"stdout",
"=",
"six",
".",
"b",
"(",
"''",
")",
"# Execute command\r",
"cmd",
"=",
"self",
".",
"git",
".",
"push",
"(",
"as_process",
"=",
"True",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"# Capture output\r",
"while",
"True",
":",
"output",
"=",
"cmd",
".",
"stdout",
".",
"read",
"(",
"1",
")",
"sys",
".",
"stdout",
".",
"write",
"(",
"output",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"stdout",
"+=",
"output",
"# Check for EOF\r",
"if",
"output",
"==",
"six",
".",
"b",
"(",
"\"\"",
")",
":",
"break",
"# Wait for the process to quit\r",
"try",
":",
"cmd",
".",
"wait",
"(",
")",
"except",
"GitCommandError",
"as",
"error",
":",
"# Add more meta-information to errors\r",
"message",
"=",
"\"'{0}' returned exit status {1}\"",
".",
"format",
"(",
"' '",
".",
"join",
"(",
"str",
"(",
"c",
")",
"for",
"c",
"in",
"error",
".",
"command",
")",
",",
"error",
".",
"status",
")",
"raise",
"GitError",
"(",
"message",
",",
"stderr",
"=",
"error",
".",
"stderr",
",",
"stdout",
"=",
"stdout",
")",
"return",
"stdout",
".",
"strip",
"(",
")"
] | Push commits to remote | [
"Push",
"commits",
"to",
"remote"
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L220-L252 | train |
msiemens/PyGitUp | PyGitUp/git_wrapper.py | GitWrapper.change_count | def change_count(self):
""" The number of changes in the working directory. """
status = self.git.status(porcelain=True, untracked_files='no').strip()
if not status:
return 0
else:
return len(status.split('\n')) | python | def change_count(self):
""" The number of changes in the working directory. """
status = self.git.status(porcelain=True, untracked_files='no').strip()
if not status:
return 0
else:
return len(status.split('\n')) | [
"def",
"change_count",
"(",
"self",
")",
":",
"status",
"=",
"self",
".",
"git",
".",
"status",
"(",
"porcelain",
"=",
"True",
",",
"untracked_files",
"=",
"'no'",
")",
".",
"strip",
"(",
")",
"if",
"not",
"status",
":",
"return",
"0",
"else",
":",
"return",
"len",
"(",
"status",
".",
"split",
"(",
"'\\n'",
")",
")"
] | The number of changes in the working directory. | [
"The",
"number",
"of",
"changes",
"in",
"the",
"working",
"directory",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/git_wrapper.py#L262-L268 | train |
msiemens/PyGitUp | PyGitUp/utils.py | uniq | def uniq(seq):
""" Return a copy of seq without duplicates. """
seen = set()
return [x for x in seq if str(x) not in seen and not seen.add(str(x))] | python | def uniq(seq):
""" Return a copy of seq without duplicates. """
seen = set()
return [x for x in seq if str(x) not in seen and not seen.add(str(x))] | [
"def",
"uniq",
"(",
"seq",
")",
":",
"seen",
"=",
"set",
"(",
")",
"return",
"[",
"x",
"for",
"x",
"in",
"seq",
"if",
"str",
"(",
"x",
")",
"not",
"in",
"seen",
"and",
"not",
"seen",
".",
"add",
"(",
"str",
"(",
"x",
")",
")",
"]"
] | Return a copy of seq without duplicates. | [
"Return",
"a",
"copy",
"of",
"seq",
"without",
"duplicates",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/utils.py#L24-L27 | train |
msiemens/PyGitUp | release.py | current_version | def current_version():
"""
Get the current version number from setup.py
"""
# Monkeypatch setuptools.setup so we get the verison number
import setuptools
version = [None]
def monkey_setup(**settings):
version[0] = settings['version']
old_setup = setuptools.setup
setuptools.setup = monkey_setup
import setup # setup.py
reload(setup)
setuptools.setup = old_setup
return version[0] | python | def current_version():
"""
Get the current version number from setup.py
"""
# Monkeypatch setuptools.setup so we get the verison number
import setuptools
version = [None]
def monkey_setup(**settings):
version[0] = settings['version']
old_setup = setuptools.setup
setuptools.setup = monkey_setup
import setup # setup.py
reload(setup)
setuptools.setup = old_setup
return version[0] | [
"def",
"current_version",
"(",
")",
":",
"# Monkeypatch setuptools.setup so we get the verison number",
"import",
"setuptools",
"version",
"=",
"[",
"None",
"]",
"def",
"monkey_setup",
"(",
"*",
"*",
"settings",
")",
":",
"version",
"[",
"0",
"]",
"=",
"settings",
"[",
"'version'",
"]",
"old_setup",
"=",
"setuptools",
".",
"setup",
"setuptools",
".",
"setup",
"=",
"monkey_setup",
"import",
"setup",
"# setup.py",
"reload",
"(",
"setup",
")",
"setuptools",
".",
"setup",
"=",
"old_setup",
"return",
"version",
"[",
"0",
"]"
] | Get the current version number from setup.py | [
"Get",
"the",
"current",
"version",
"number",
"from",
"setup",
".",
"py"
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/release.py#L22-L41 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | run | def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover
"""
A nicer `git pull`.
"""
if version:
if NO_DISTRIBUTE:
print(colored('Please install \'git-up\' via pip in order to '
'get version information.', 'yellow'))
else:
GitUp(sparse=True).version_info()
return
if quiet:
sys.stdout = StringIO()
try:
gitup = GitUp()
if push is not None:
gitup.settings['push.auto'] = push
# if arguments['--no-fetch'] or arguments['--no-f']:
if no_fetch:
gitup.should_fetch = False
except GitError:
sys.exit(1) # Error in constructor
else:
gitup.run() | python | def run(version, quiet, no_fetch, push, **kwargs): # pragma: no cover
"""
A nicer `git pull`.
"""
if version:
if NO_DISTRIBUTE:
print(colored('Please install \'git-up\' via pip in order to '
'get version information.', 'yellow'))
else:
GitUp(sparse=True).version_info()
return
if quiet:
sys.stdout = StringIO()
try:
gitup = GitUp()
if push is not None:
gitup.settings['push.auto'] = push
# if arguments['--no-fetch'] or arguments['--no-f']:
if no_fetch:
gitup.should_fetch = False
except GitError:
sys.exit(1) # Error in constructor
else:
gitup.run() | [
"def",
"run",
"(",
"version",
",",
"quiet",
",",
"no_fetch",
",",
"push",
",",
"*",
"*",
"kwargs",
")",
":",
"# pragma: no cover\r",
"if",
"version",
":",
"if",
"NO_DISTRIBUTE",
":",
"print",
"(",
"colored",
"(",
"'Please install \\'git-up\\' via pip in order to '",
"'get version information.'",
",",
"'yellow'",
")",
")",
"else",
":",
"GitUp",
"(",
"sparse",
"=",
"True",
")",
".",
"version_info",
"(",
")",
"return",
"if",
"quiet",
":",
"sys",
".",
"stdout",
"=",
"StringIO",
"(",
")",
"try",
":",
"gitup",
"=",
"GitUp",
"(",
")",
"if",
"push",
"is",
"not",
"None",
":",
"gitup",
".",
"settings",
"[",
"'push.auto'",
"]",
"=",
"push",
"# if arguments['--no-fetch'] or arguments['--no-f']:\r",
"if",
"no_fetch",
":",
"gitup",
".",
"should_fetch",
"=",
"False",
"except",
"GitError",
":",
"sys",
".",
"exit",
"(",
"1",
")",
"# Error in constructor\r",
"else",
":",
"gitup",
".",
"run",
"(",
")"
] | A nicer `git pull`. | [
"A",
"nicer",
"git",
"pull",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L628-L656 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.run | def run(self):
""" Run all the git-up stuff. """
try:
if self.should_fetch:
self.fetch()
self.rebase_all_branches()
if self.with_bundler():
self.check_bundler()
if self.settings['push.auto']:
self.push()
except GitError as error:
self.print_error(error)
# Used for test cases
if self.testing:
raise
else: # pragma: no cover
sys.exit(1) | python | def run(self):
""" Run all the git-up stuff. """
try:
if self.should_fetch:
self.fetch()
self.rebase_all_branches()
if self.with_bundler():
self.check_bundler()
if self.settings['push.auto']:
self.push()
except GitError as error:
self.print_error(error)
# Used for test cases
if self.testing:
raise
else: # pragma: no cover
sys.exit(1) | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"if",
"self",
".",
"should_fetch",
":",
"self",
".",
"fetch",
"(",
")",
"self",
".",
"rebase_all_branches",
"(",
")",
"if",
"self",
".",
"with_bundler",
"(",
")",
":",
"self",
".",
"check_bundler",
"(",
")",
"if",
"self",
".",
"settings",
"[",
"'push.auto'",
"]",
":",
"self",
".",
"push",
"(",
")",
"except",
"GitError",
"as",
"error",
":",
"self",
".",
"print_error",
"(",
"error",
")",
"# Used for test cases\r",
"if",
"self",
".",
"testing",
":",
"raise",
"else",
":",
"# pragma: no cover\r",
"sys",
".",
"exit",
"(",
"1",
")"
] | Run all the git-up stuff. | [
"Run",
"all",
"the",
"git",
"-",
"up",
"stuff",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L193-L214 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.fetch | def fetch(self):
"""
Fetch the recent refs from the remotes.
Unless git-up.fetch.all is set to true, all remotes with
locally existent branches will be fetched.
"""
fetch_kwargs = {'multiple': True}
fetch_args = []
if self.is_prune():
fetch_kwargs['prune'] = True
if self.settings['fetch.all']:
fetch_kwargs['all'] = True
else:
if '.' in self.remotes:
self.remotes.remove('.')
if not self.remotes:
# Only local target branches,
# `git fetch --multiple` will fail
return
fetch_args.append(self.remotes)
try:
self.git.fetch(*fetch_args, **fetch_kwargs)
except GitError as error:
error.message = "`git fetch` failed"
raise error | python | def fetch(self):
"""
Fetch the recent refs from the remotes.
Unless git-up.fetch.all is set to true, all remotes with
locally existent branches will be fetched.
"""
fetch_kwargs = {'multiple': True}
fetch_args = []
if self.is_prune():
fetch_kwargs['prune'] = True
if self.settings['fetch.all']:
fetch_kwargs['all'] = True
else:
if '.' in self.remotes:
self.remotes.remove('.')
if not self.remotes:
# Only local target branches,
# `git fetch --multiple` will fail
return
fetch_args.append(self.remotes)
try:
self.git.fetch(*fetch_args, **fetch_kwargs)
except GitError as error:
error.message = "`git fetch` failed"
raise error | [
"def",
"fetch",
"(",
"self",
")",
":",
"fetch_kwargs",
"=",
"{",
"'multiple'",
":",
"True",
"}",
"fetch_args",
"=",
"[",
"]",
"if",
"self",
".",
"is_prune",
"(",
")",
":",
"fetch_kwargs",
"[",
"'prune'",
"]",
"=",
"True",
"if",
"self",
".",
"settings",
"[",
"'fetch.all'",
"]",
":",
"fetch_kwargs",
"[",
"'all'",
"]",
"=",
"True",
"else",
":",
"if",
"'.'",
"in",
"self",
".",
"remotes",
":",
"self",
".",
"remotes",
".",
"remove",
"(",
"'.'",
")",
"if",
"not",
"self",
".",
"remotes",
":",
"# Only local target branches,\r",
"# `git fetch --multiple` will fail\r",
"return",
"fetch_args",
".",
"append",
"(",
"self",
".",
"remotes",
")",
"try",
":",
"self",
".",
"git",
".",
"fetch",
"(",
"*",
"fetch_args",
",",
"*",
"*",
"fetch_kwargs",
")",
"except",
"GitError",
"as",
"error",
":",
"error",
".",
"message",
"=",
"\"`git fetch` failed\"",
"raise",
"error"
] | Fetch the recent refs from the remotes.
Unless git-up.fetch.all is set to true, all remotes with
locally existent branches will be fetched. | [
"Fetch",
"the",
"recent",
"refs",
"from",
"the",
"remotes",
".",
"Unless",
"git",
"-",
"up",
".",
"fetch",
".",
"all",
"is",
"set",
"to",
"true",
"all",
"remotes",
"with",
"locally",
"existent",
"branches",
"will",
"be",
"fetched",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L311-L341 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.log | def log(self, branch, remote):
""" Call a log-command, if set by git-up.fetch.all. """
log_hook = self.settings['rebase.log-hook']
if log_hook:
if ON_WINDOWS: # pragma: no cover
# Running a string in CMD from Python is not that easy on
# Windows. Running 'cmd /C log_hook' produces problems when
# using multiple statements or things like 'echo'. Therefore,
# we write the string to a bat file and execute it.
# In addition, we replace occurences of $1 with %1 and so forth
# in case the user is used to Bash or sh.
# If there are occurences of %something, we'll replace it with
# %%something. This is the case when running something like
# 'git log --pretty=format:"%Cred%h..."'.
# Also, we replace a semicolon with a newline, because if you
# start with 'echo' on Windows, it will simply echo the
# semicolon and the commands behind instead of echoing and then
# running other commands
# Prepare log_hook
log_hook = re.sub(r'\$(\d+)', r'%\1', log_hook)
log_hook = re.sub(r'%(?!\d)', '%%', log_hook)
log_hook = re.sub(r'; ?', r'\n', log_hook)
# Write log_hook to an temporary file and get it's path
with NamedTemporaryFile(
prefix='PyGitUp.', suffix='.bat', delete=False
) as bat_file:
# Don't echo all commands
bat_file.file.write(b'@echo off\n')
# Run log_hook
bat_file.file.write(log_hook.encode('utf-8'))
# Run bat_file
state = subprocess.call(
[bat_file.name, branch.name, remote.name]
)
# Clean up file
os.remove(bat_file.name)
else: # pragma: no cover
# Run log_hook via 'shell -c'
state = subprocess.call(
[log_hook, 'git-up', branch.name, remote.name],
shell=True
)
if self.testing:
assert state == 0, 'log_hook returned != 0' | python | def log(self, branch, remote):
""" Call a log-command, if set by git-up.fetch.all. """
log_hook = self.settings['rebase.log-hook']
if log_hook:
if ON_WINDOWS: # pragma: no cover
# Running a string in CMD from Python is not that easy on
# Windows. Running 'cmd /C log_hook' produces problems when
# using multiple statements or things like 'echo'. Therefore,
# we write the string to a bat file and execute it.
# In addition, we replace occurences of $1 with %1 and so forth
# in case the user is used to Bash or sh.
# If there are occurences of %something, we'll replace it with
# %%something. This is the case when running something like
# 'git log --pretty=format:"%Cred%h..."'.
# Also, we replace a semicolon with a newline, because if you
# start with 'echo' on Windows, it will simply echo the
# semicolon and the commands behind instead of echoing and then
# running other commands
# Prepare log_hook
log_hook = re.sub(r'\$(\d+)', r'%\1', log_hook)
log_hook = re.sub(r'%(?!\d)', '%%', log_hook)
log_hook = re.sub(r'; ?', r'\n', log_hook)
# Write log_hook to an temporary file and get it's path
with NamedTemporaryFile(
prefix='PyGitUp.', suffix='.bat', delete=False
) as bat_file:
# Don't echo all commands
bat_file.file.write(b'@echo off\n')
# Run log_hook
bat_file.file.write(log_hook.encode('utf-8'))
# Run bat_file
state = subprocess.call(
[bat_file.name, branch.name, remote.name]
)
# Clean up file
os.remove(bat_file.name)
else: # pragma: no cover
# Run log_hook via 'shell -c'
state = subprocess.call(
[log_hook, 'git-up', branch.name, remote.name],
shell=True
)
if self.testing:
assert state == 0, 'log_hook returned != 0' | [
"def",
"log",
"(",
"self",
",",
"branch",
",",
"remote",
")",
":",
"log_hook",
"=",
"self",
".",
"settings",
"[",
"'rebase.log-hook'",
"]",
"if",
"log_hook",
":",
"if",
"ON_WINDOWS",
":",
"# pragma: no cover\r",
"# Running a string in CMD from Python is not that easy on\r",
"# Windows. Running 'cmd /C log_hook' produces problems when\r",
"# using multiple statements or things like 'echo'. Therefore,\r",
"# we write the string to a bat file and execute it.\r",
"# In addition, we replace occurences of $1 with %1 and so forth\r",
"# in case the user is used to Bash or sh.\r",
"# If there are occurences of %something, we'll replace it with\r",
"# %%something. This is the case when running something like\r",
"# 'git log --pretty=format:\"%Cred%h...\"'.\r",
"# Also, we replace a semicolon with a newline, because if you\r",
"# start with 'echo' on Windows, it will simply echo the\r",
"# semicolon and the commands behind instead of echoing and then\r",
"# running other commands\r",
"# Prepare log_hook\r",
"log_hook",
"=",
"re",
".",
"sub",
"(",
"r'\\$(\\d+)'",
",",
"r'%\\1'",
",",
"log_hook",
")",
"log_hook",
"=",
"re",
".",
"sub",
"(",
"r'%(?!\\d)'",
",",
"'%%'",
",",
"log_hook",
")",
"log_hook",
"=",
"re",
".",
"sub",
"(",
"r'; ?'",
",",
"r'\\n'",
",",
"log_hook",
")",
"# Write log_hook to an temporary file and get it's path\r",
"with",
"NamedTemporaryFile",
"(",
"prefix",
"=",
"'PyGitUp.'",
",",
"suffix",
"=",
"'.bat'",
",",
"delete",
"=",
"False",
")",
"as",
"bat_file",
":",
"# Don't echo all commands\r",
"bat_file",
".",
"file",
".",
"write",
"(",
"b'@echo off\\n'",
")",
"# Run log_hook\r",
"bat_file",
".",
"file",
".",
"write",
"(",
"log_hook",
".",
"encode",
"(",
"'utf-8'",
")",
")",
"# Run bat_file\r",
"state",
"=",
"subprocess",
".",
"call",
"(",
"[",
"bat_file",
".",
"name",
",",
"branch",
".",
"name",
",",
"remote",
".",
"name",
"]",
")",
"# Clean up file\r",
"os",
".",
"remove",
"(",
"bat_file",
".",
"name",
")",
"else",
":",
"# pragma: no cover\r",
"# Run log_hook via 'shell -c'\r",
"state",
"=",
"subprocess",
".",
"call",
"(",
"[",
"log_hook",
",",
"'git-up'",
",",
"branch",
".",
"name",
",",
"remote",
".",
"name",
"]",
",",
"shell",
"=",
"True",
")",
"if",
"self",
".",
"testing",
":",
"assert",
"state",
"==",
"0",
",",
"'log_hook returned != 0'"
] | Call a log-command, if set by git-up.fetch.all. | [
"Call",
"a",
"log",
"-",
"command",
"if",
"set",
"by",
"git",
"-",
"up",
".",
"fetch",
".",
"all",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L374-L424 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.version_info | def version_info(self):
""" Tell, what version we're running at and if it's up to date. """
# Retrive and show local version info
package = pkg.get_distribution('git-up')
local_version_str = package.version
local_version = package.parsed_version
print('GitUp version is: ' + colored('v' + local_version_str, 'green'))
if not self.settings['updates.check']:
return
# Check for updates
print('Checking for updates...', end='')
try:
# Get version information from the PyPI JSON API
reader = codecs.getreader('utf-8')
details = json.load(reader(urlopen(PYPI_URL)))
online_version = details['info']['version']
except (HTTPError, URLError, ValueError):
recent = True # To not disturb the user with HTTP/parsing errors
else:
recent = local_version >= pkg.parse_version(online_version)
if not recent:
# noinspection PyUnboundLocalVariable
print(
'\rRecent version is: '
+ colored('v' + online_version, color='yellow', attrs=['bold'])
)
print('Run \'pip install -U git-up\' to get the update.')
else:
# Clear the update line
sys.stdout.write('\r' + ' ' * 80 + '\n') | python | def version_info(self):
""" Tell, what version we're running at and if it's up to date. """
# Retrive and show local version info
package = pkg.get_distribution('git-up')
local_version_str = package.version
local_version = package.parsed_version
print('GitUp version is: ' + colored('v' + local_version_str, 'green'))
if not self.settings['updates.check']:
return
# Check for updates
print('Checking for updates...', end='')
try:
# Get version information from the PyPI JSON API
reader = codecs.getreader('utf-8')
details = json.load(reader(urlopen(PYPI_URL)))
online_version = details['info']['version']
except (HTTPError, URLError, ValueError):
recent = True # To not disturb the user with HTTP/parsing errors
else:
recent = local_version >= pkg.parse_version(online_version)
if not recent:
# noinspection PyUnboundLocalVariable
print(
'\rRecent version is: '
+ colored('v' + online_version, color='yellow', attrs=['bold'])
)
print('Run \'pip install -U git-up\' to get the update.')
else:
# Clear the update line
sys.stdout.write('\r' + ' ' * 80 + '\n') | [
"def",
"version_info",
"(",
"self",
")",
":",
"# Retrive and show local version info\r",
"package",
"=",
"pkg",
".",
"get_distribution",
"(",
"'git-up'",
")",
"local_version_str",
"=",
"package",
".",
"version",
"local_version",
"=",
"package",
".",
"parsed_version",
"print",
"(",
"'GitUp version is: '",
"+",
"colored",
"(",
"'v'",
"+",
"local_version_str",
",",
"'green'",
")",
")",
"if",
"not",
"self",
".",
"settings",
"[",
"'updates.check'",
"]",
":",
"return",
"# Check for updates\r",
"print",
"(",
"'Checking for updates...'",
",",
"end",
"=",
"''",
")",
"try",
":",
"# Get version information from the PyPI JSON API\r",
"reader",
"=",
"codecs",
".",
"getreader",
"(",
"'utf-8'",
")",
"details",
"=",
"json",
".",
"load",
"(",
"reader",
"(",
"urlopen",
"(",
"PYPI_URL",
")",
")",
")",
"online_version",
"=",
"details",
"[",
"'info'",
"]",
"[",
"'version'",
"]",
"except",
"(",
"HTTPError",
",",
"URLError",
",",
"ValueError",
")",
":",
"recent",
"=",
"True",
"# To not disturb the user with HTTP/parsing errors\r",
"else",
":",
"recent",
"=",
"local_version",
">=",
"pkg",
".",
"parse_version",
"(",
"online_version",
")",
"if",
"not",
"recent",
":",
"# noinspection PyUnboundLocalVariable\r",
"print",
"(",
"'\\rRecent version is: '",
"+",
"colored",
"(",
"'v'",
"+",
"online_version",
",",
"color",
"=",
"'yellow'",
",",
"attrs",
"=",
"[",
"'bold'",
"]",
")",
")",
"print",
"(",
"'Run \\'pip install -U git-up\\' to get the update.'",
")",
"else",
":",
"# Clear the update line\r",
"sys",
".",
"stdout",
".",
"write",
"(",
"'\\r'",
"+",
"' '",
"*",
"80",
"+",
"'\\n'",
")"
] | Tell, what version we're running at and if it's up to date. | [
"Tell",
"what",
"version",
"we",
"re",
"running",
"at",
"and",
"if",
"it",
"s",
"up",
"to",
"date",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L426-L461 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.load_config | def load_config(self):
"""
Load the configuration from git config.
"""
for key in self.settings:
value = self.config(key)
# Parse true/false
if value == '' or value is None:
continue # Not set by user, go on
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
elif value:
pass # A user-defined string, store the value later
self.settings[key] = value | python | def load_config(self):
"""
Load the configuration from git config.
"""
for key in self.settings:
value = self.config(key)
# Parse true/false
if value == '' or value is None:
continue # Not set by user, go on
if value.lower() == 'true':
value = True
elif value.lower() == 'false':
value = False
elif value:
pass # A user-defined string, store the value later
self.settings[key] = value | [
"def",
"load_config",
"(",
"self",
")",
":",
"for",
"key",
"in",
"self",
".",
"settings",
":",
"value",
"=",
"self",
".",
"config",
"(",
"key",
")",
"# Parse true/false\r",
"if",
"value",
"==",
"''",
"or",
"value",
"is",
"None",
":",
"continue",
"# Not set by user, go on\r",
"if",
"value",
".",
"lower",
"(",
")",
"==",
"'true'",
":",
"value",
"=",
"True",
"elif",
"value",
".",
"lower",
"(",
")",
"==",
"'false'",
":",
"value",
"=",
"False",
"elif",
"value",
":",
"pass",
"# A user-defined string, store the value later\r",
"self",
".",
"settings",
"[",
"key",
"]",
"=",
"value"
] | Load the configuration from git config. | [
"Load",
"the",
"configuration",
"from",
"git",
"config",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L467-L483 | train |
msiemens/PyGitUp | PyGitUp/gitup.py | GitUp.check_bundler | def check_bundler(self):
"""
Run the bundler check.
"""
def get_config(name):
return name if self.config('bundler.' + name) else ''
from pkg_resources import Requirement, resource_filename
relative_path = os.path.join('PyGitUp', 'check-bundler.rb')
bundler_script = resource_filename(Requirement.parse('git-up'),
relative_path)
assert os.path.exists(bundler_script), 'check-bundler.rb doesn\'t ' \
'exist!'
return_value = subprocess.call(
['ruby', bundler_script, get_config('autoinstall'),
get_config('local'), get_config('rbenv')]
)
if self.testing:
assert return_value == 0, 'Errors while executing check-bundler.rb' | python | def check_bundler(self):
"""
Run the bundler check.
"""
def get_config(name):
return name if self.config('bundler.' + name) else ''
from pkg_resources import Requirement, resource_filename
relative_path = os.path.join('PyGitUp', 'check-bundler.rb')
bundler_script = resource_filename(Requirement.parse('git-up'),
relative_path)
assert os.path.exists(bundler_script), 'check-bundler.rb doesn\'t ' \
'exist!'
return_value = subprocess.call(
['ruby', bundler_script, get_config('autoinstall'),
get_config('local'), get_config('rbenv')]
)
if self.testing:
assert return_value == 0, 'Errors while executing check-bundler.rb' | [
"def",
"check_bundler",
"(",
"self",
")",
":",
"def",
"get_config",
"(",
"name",
")",
":",
"return",
"name",
"if",
"self",
".",
"config",
"(",
"'bundler.'",
"+",
"name",
")",
"else",
"''",
"from",
"pkg_resources",
"import",
"Requirement",
",",
"resource_filename",
"relative_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"'PyGitUp'",
",",
"'check-bundler.rb'",
")",
"bundler_script",
"=",
"resource_filename",
"(",
"Requirement",
".",
"parse",
"(",
"'git-up'",
")",
",",
"relative_path",
")",
"assert",
"os",
".",
"path",
".",
"exists",
"(",
"bundler_script",
")",
",",
"'check-bundler.rb doesn\\'t '",
"'exist!'",
"return_value",
"=",
"subprocess",
".",
"call",
"(",
"[",
"'ruby'",
",",
"bundler_script",
",",
"get_config",
"(",
"'autoinstall'",
")",
",",
"get_config",
"(",
"'local'",
")",
",",
"get_config",
"(",
"'rbenv'",
")",
"]",
")",
"if",
"self",
".",
"testing",
":",
"assert",
"return_value",
"==",
"0",
",",
"'Errors while executing check-bundler.rb'"
] | Run the bundler check. | [
"Run",
"the",
"bundler",
"check",
"."
] | b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c | https://github.com/msiemens/PyGitUp/blob/b1f78831cb6b8d29d3a7d59f7a2b54fdd0720e9c/PyGitUp/gitup.py#L555-L576 | train |
mikemaccana/python-docx | docx.py | opendocx | def opendocx(file):
'''Open a docx file, return a document XML tree'''
mydoc = zipfile.ZipFile(file)
xmlcontent = mydoc.read('word/document.xml')
document = etree.fromstring(xmlcontent)
return document | python | def opendocx(file):
'''Open a docx file, return a document XML tree'''
mydoc = zipfile.ZipFile(file)
xmlcontent = mydoc.read('word/document.xml')
document = etree.fromstring(xmlcontent)
return document | [
"def",
"opendocx",
"(",
"file",
")",
":",
"mydoc",
"=",
"zipfile",
".",
"ZipFile",
"(",
"file",
")",
"xmlcontent",
"=",
"mydoc",
".",
"read",
"(",
"'word/document.xml'",
")",
"document",
"=",
"etree",
".",
"fromstring",
"(",
"xmlcontent",
")",
"return",
"document"
] | Open a docx file, return a document XML tree | [
"Open",
"a",
"docx",
"file",
"return",
"a",
"document",
"XML",
"tree"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L81-L86 | train |
mikemaccana/python-docx | docx.py | makeelement | def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
attrnsprefix=None):
'''Create an element & return it'''
# Deal with list of nsprefix by making namespacemap
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
namespacemap[prefix] = nsprefixes[prefix]
# FIXME: rest of code below expects a single prefix
nsprefix = nsprefix[0]
if nsprefix:
namespace = '{%s}' % nsprefixes[nsprefix]
else:
# For when namespace = None
namespace = ''
newelement = etree.Element(namespace+tagname, nsmap=namespacemap)
# Add attributes with namespaces
if attributes:
# If they haven't bothered setting attribute namespace, use an empty
# string (equivalent of no namespace)
if not attrnsprefix:
# Quick hack: it seems every element that has a 'w' nsprefix for
# its tag uses the same prefix for it's attributes
if nsprefix == 'w':
attributenamespace = namespace
else:
attributenamespace = ''
else:
attributenamespace = '{'+nsprefixes[attrnsprefix]+'}'
for tagattribute in attributes:
newelement.set(attributenamespace+tagattribute,
attributes[tagattribute])
if tagtext:
newelement.text = tagtext
return newelement | python | def makeelement(tagname, tagtext=None, nsprefix='w', attributes=None,
attrnsprefix=None):
'''Create an element & return it'''
# Deal with list of nsprefix by making namespacemap
namespacemap = None
if isinstance(nsprefix, list):
namespacemap = {}
for prefix in nsprefix:
namespacemap[prefix] = nsprefixes[prefix]
# FIXME: rest of code below expects a single prefix
nsprefix = nsprefix[0]
if nsprefix:
namespace = '{%s}' % nsprefixes[nsprefix]
else:
# For when namespace = None
namespace = ''
newelement = etree.Element(namespace+tagname, nsmap=namespacemap)
# Add attributes with namespaces
if attributes:
# If they haven't bothered setting attribute namespace, use an empty
# string (equivalent of no namespace)
if not attrnsprefix:
# Quick hack: it seems every element that has a 'w' nsprefix for
# its tag uses the same prefix for it's attributes
if nsprefix == 'w':
attributenamespace = namespace
else:
attributenamespace = ''
else:
attributenamespace = '{'+nsprefixes[attrnsprefix]+'}'
for tagattribute in attributes:
newelement.set(attributenamespace+tagattribute,
attributes[tagattribute])
if tagtext:
newelement.text = tagtext
return newelement | [
"def",
"makeelement",
"(",
"tagname",
",",
"tagtext",
"=",
"None",
",",
"nsprefix",
"=",
"'w'",
",",
"attributes",
"=",
"None",
",",
"attrnsprefix",
"=",
"None",
")",
":",
"# Deal with list of nsprefix by making namespacemap",
"namespacemap",
"=",
"None",
"if",
"isinstance",
"(",
"nsprefix",
",",
"list",
")",
":",
"namespacemap",
"=",
"{",
"}",
"for",
"prefix",
"in",
"nsprefix",
":",
"namespacemap",
"[",
"prefix",
"]",
"=",
"nsprefixes",
"[",
"prefix",
"]",
"# FIXME: rest of code below expects a single prefix",
"nsprefix",
"=",
"nsprefix",
"[",
"0",
"]",
"if",
"nsprefix",
":",
"namespace",
"=",
"'{%s}'",
"%",
"nsprefixes",
"[",
"nsprefix",
"]",
"else",
":",
"# For when namespace = None",
"namespace",
"=",
"''",
"newelement",
"=",
"etree",
".",
"Element",
"(",
"namespace",
"+",
"tagname",
",",
"nsmap",
"=",
"namespacemap",
")",
"# Add attributes with namespaces",
"if",
"attributes",
":",
"# If they haven't bothered setting attribute namespace, use an empty",
"# string (equivalent of no namespace)",
"if",
"not",
"attrnsprefix",
":",
"# Quick hack: it seems every element that has a 'w' nsprefix for",
"# its tag uses the same prefix for it's attributes",
"if",
"nsprefix",
"==",
"'w'",
":",
"attributenamespace",
"=",
"namespace",
"else",
":",
"attributenamespace",
"=",
"''",
"else",
":",
"attributenamespace",
"=",
"'{'",
"+",
"nsprefixes",
"[",
"attrnsprefix",
"]",
"+",
"'}'",
"for",
"tagattribute",
"in",
"attributes",
":",
"newelement",
".",
"set",
"(",
"attributenamespace",
"+",
"tagattribute",
",",
"attributes",
"[",
"tagattribute",
"]",
")",
"if",
"tagtext",
":",
"newelement",
".",
"text",
"=",
"tagtext",
"return",
"newelement"
] | Create an element & return it | [
"Create",
"an",
"element",
"&",
"return",
"it"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L95-L131 | train |
mikemaccana/python-docx | docx.py | heading | def heading(headingtext, headinglevel, lang='en'):
'''Make a new heading, return the heading element'''
lmap = {'en': 'Heading', 'it': 'Titolo'}
# Make our elements
paragraph = makeelement('p')
pr = makeelement('pPr')
pStyle = makeelement(
'pStyle', attributes={'val': lmap[lang]+str(headinglevel)})
run = makeelement('r')
text = makeelement('t', tagtext=headingtext)
# Add the text the run, and the run to the paragraph
pr.append(pStyle)
run.append(text)
paragraph.append(pr)
paragraph.append(run)
# Return the combined paragraph
return paragraph | python | def heading(headingtext, headinglevel, lang='en'):
'''Make a new heading, return the heading element'''
lmap = {'en': 'Heading', 'it': 'Titolo'}
# Make our elements
paragraph = makeelement('p')
pr = makeelement('pPr')
pStyle = makeelement(
'pStyle', attributes={'val': lmap[lang]+str(headinglevel)})
run = makeelement('r')
text = makeelement('t', tagtext=headingtext)
# Add the text the run, and the run to the paragraph
pr.append(pStyle)
run.append(text)
paragraph.append(pr)
paragraph.append(run)
# Return the combined paragraph
return paragraph | [
"def",
"heading",
"(",
"headingtext",
",",
"headinglevel",
",",
"lang",
"=",
"'en'",
")",
":",
"lmap",
"=",
"{",
"'en'",
":",
"'Heading'",
",",
"'it'",
":",
"'Titolo'",
"}",
"# Make our elements",
"paragraph",
"=",
"makeelement",
"(",
"'p'",
")",
"pr",
"=",
"makeelement",
"(",
"'pPr'",
")",
"pStyle",
"=",
"makeelement",
"(",
"'pStyle'",
",",
"attributes",
"=",
"{",
"'val'",
":",
"lmap",
"[",
"lang",
"]",
"+",
"str",
"(",
"headinglevel",
")",
"}",
")",
"run",
"=",
"makeelement",
"(",
"'r'",
")",
"text",
"=",
"makeelement",
"(",
"'t'",
",",
"tagtext",
"=",
"headingtext",
")",
"# Add the text the run, and the run to the paragraph",
"pr",
".",
"append",
"(",
"pStyle",
")",
"run",
".",
"append",
"(",
"text",
")",
"paragraph",
".",
"append",
"(",
"pr",
")",
"paragraph",
".",
"append",
"(",
"run",
")",
"# Return the combined paragraph",
"return",
"paragraph"
] | Make a new heading, return the heading element | [
"Make",
"a",
"new",
"heading",
"return",
"the",
"heading",
"element"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L278-L294 | train |
mikemaccana/python-docx | docx.py | clean | def clean(document):
""" Perform misc cleaning operations on documents.
Returns cleaned document.
"""
newdocument = document
# Clean empty text and r tags
for t in ('t', 'r'):
rmlist = []
for element in newdocument.iter():
if element.tag == '{%s}%s' % (nsprefixes['w'], t):
if not element.text and not len(element):
rmlist.append(element)
for element in rmlist:
element.getparent().remove(element)
return newdocument | python | def clean(document):
""" Perform misc cleaning operations on documents.
Returns cleaned document.
"""
newdocument = document
# Clean empty text and r tags
for t in ('t', 'r'):
rmlist = []
for element in newdocument.iter():
if element.tag == '{%s}%s' % (nsprefixes['w'], t):
if not element.text and not len(element):
rmlist.append(element)
for element in rmlist:
element.getparent().remove(element)
return newdocument | [
"def",
"clean",
"(",
"document",
")",
":",
"newdocument",
"=",
"document",
"# Clean empty text and r tags",
"for",
"t",
"in",
"(",
"'t'",
",",
"'r'",
")",
":",
"rmlist",
"=",
"[",
"]",
"for",
"element",
"in",
"newdocument",
".",
"iter",
"(",
")",
":",
"if",
"element",
".",
"tag",
"==",
"'{%s}%s'",
"%",
"(",
"nsprefixes",
"[",
"'w'",
"]",
",",
"t",
")",
":",
"if",
"not",
"element",
".",
"text",
"and",
"not",
"len",
"(",
"element",
")",
":",
"rmlist",
".",
"append",
"(",
"element",
")",
"for",
"element",
"in",
"rmlist",
":",
"element",
".",
"getparent",
"(",
")",
".",
"remove",
"(",
"element",
")",
"return",
"newdocument"
] | Perform misc cleaning operations on documents.
Returns cleaned document. | [
"Perform",
"misc",
"cleaning",
"operations",
"on",
"documents",
".",
"Returns",
"cleaned",
"document",
"."
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L644-L661 | train |
mikemaccana/python-docx | docx.py | findTypeParent | def findTypeParent(element, tag):
""" Finds fist parent of element of the given type
@param object element: etree element
@param string the tag parent to search for
@return object element: the found parent or None when not found
"""
p = element
while True:
p = p.getparent()
if p.tag == tag:
return p
# Not found
return None | python | def findTypeParent(element, tag):
""" Finds fist parent of element of the given type
@param object element: etree element
@param string the tag parent to search for
@return object element: the found parent or None when not found
"""
p = element
while True:
p = p.getparent()
if p.tag == tag:
return p
# Not found
return None | [
"def",
"findTypeParent",
"(",
"element",
",",
"tag",
")",
":",
"p",
"=",
"element",
"while",
"True",
":",
"p",
"=",
"p",
".",
"getparent",
"(",
")",
"if",
"p",
".",
"tag",
"==",
"tag",
":",
"return",
"p",
"# Not found",
"return",
"None"
] | Finds fist parent of element of the given type
@param object element: etree element
@param string the tag parent to search for
@return object element: the found parent or None when not found | [
"Finds",
"fist",
"parent",
"of",
"element",
"of",
"the",
"given",
"type"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L664-L680 | train |
mikemaccana/python-docx | docx.py | AdvSearch | def AdvSearch(document, search, bs=3):
'''Return set of all regex matches
This is an advanced version of python-docx.search() that takes into
account blocks of <bs> elements at a time.
What it does:
It searches the entire document body for text blocks.
Since the text to search could be spawned across multiple text blocks,
we need to adopt some sort of algorithm to handle this situation.
The smaller matching group of blocks (up to bs) is then adopted.
If the matching group has more than one block, blocks other than first
are cleared and all the replacement text is put on first block.
Examples:
original text blocks : [ 'Hel', 'lo,', ' world!' ]
search : 'Hello,'
output blocks : [ 'Hello,' ]
original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ]
search : '(__[a-z]+__)'
output blocks : [ '__name__' ]
@param instance document: The original document
@param str search: The text to search for (regexp)
append, or a list of etree elements
@param int bs: See above
@return set All occurences of search string
'''
# Compile the search regexp
searchre = re.compile(search)
matches = []
# Will match against searchels. Searchels is a list that contains last
# n text elements found in the document. 1 < n < bs
searchels = []
for element in document.iter():
if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements
if element.text:
# Add this element to searchels
searchels.append(element)
if len(searchels) > bs:
# Is searchels is too long, remove first elements
searchels.pop(0)
# Search all combinations, of searchels, starting from
# smaller up to bigger ones
# l = search lenght
# s = search start
# e = element IDs to merge
found = False
for l in range(1, len(searchels)+1):
if found:
break
for s in range(len(searchels)):
if found:
break
if s+l <= len(searchels):
e = range(s, s+l)
txtsearch = ''
for k in e:
txtsearch += searchels[k].text
# Searcs for the text in the whole txtsearch
match = searchre.search(txtsearch)
if match:
matches.append(match.group())
found = True
return set(matches) | python | def AdvSearch(document, search, bs=3):
'''Return set of all regex matches
This is an advanced version of python-docx.search() that takes into
account blocks of <bs> elements at a time.
What it does:
It searches the entire document body for text blocks.
Since the text to search could be spawned across multiple text blocks,
we need to adopt some sort of algorithm to handle this situation.
The smaller matching group of blocks (up to bs) is then adopted.
If the matching group has more than one block, blocks other than first
are cleared and all the replacement text is put on first block.
Examples:
original text blocks : [ 'Hel', 'lo,', ' world!' ]
search : 'Hello,'
output blocks : [ 'Hello,' ]
original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ]
search : '(__[a-z]+__)'
output blocks : [ '__name__' ]
@param instance document: The original document
@param str search: The text to search for (regexp)
append, or a list of etree elements
@param int bs: See above
@return set All occurences of search string
'''
# Compile the search regexp
searchre = re.compile(search)
matches = []
# Will match against searchels. Searchels is a list that contains last
# n text elements found in the document. 1 < n < bs
searchels = []
for element in document.iter():
if element.tag == '{%s}t' % nsprefixes['w']: # t (text) elements
if element.text:
# Add this element to searchels
searchels.append(element)
if len(searchels) > bs:
# Is searchels is too long, remove first elements
searchels.pop(0)
# Search all combinations, of searchels, starting from
# smaller up to bigger ones
# l = search lenght
# s = search start
# e = element IDs to merge
found = False
for l in range(1, len(searchels)+1):
if found:
break
for s in range(len(searchels)):
if found:
break
if s+l <= len(searchels):
e = range(s, s+l)
txtsearch = ''
for k in e:
txtsearch += searchels[k].text
# Searcs for the text in the whole txtsearch
match = searchre.search(txtsearch)
if match:
matches.append(match.group())
found = True
return set(matches) | [
"def",
"AdvSearch",
"(",
"document",
",",
"search",
",",
"bs",
"=",
"3",
")",
":",
"# Compile the search regexp",
"searchre",
"=",
"re",
".",
"compile",
"(",
"search",
")",
"matches",
"=",
"[",
"]",
"# Will match against searchels. Searchels is a list that contains last",
"# n text elements found in the document. 1 < n < bs",
"searchels",
"=",
"[",
"]",
"for",
"element",
"in",
"document",
".",
"iter",
"(",
")",
":",
"if",
"element",
".",
"tag",
"==",
"'{%s}t'",
"%",
"nsprefixes",
"[",
"'w'",
"]",
":",
"# t (text) elements",
"if",
"element",
".",
"text",
":",
"# Add this element to searchels",
"searchels",
".",
"append",
"(",
"element",
")",
"if",
"len",
"(",
"searchels",
")",
">",
"bs",
":",
"# Is searchels is too long, remove first elements",
"searchels",
".",
"pop",
"(",
"0",
")",
"# Search all combinations, of searchels, starting from",
"# smaller up to bigger ones",
"# l = search lenght",
"# s = search start",
"# e = element IDs to merge",
"found",
"=",
"False",
"for",
"l",
"in",
"range",
"(",
"1",
",",
"len",
"(",
"searchels",
")",
"+",
"1",
")",
":",
"if",
"found",
":",
"break",
"for",
"s",
"in",
"range",
"(",
"len",
"(",
"searchels",
")",
")",
":",
"if",
"found",
":",
"break",
"if",
"s",
"+",
"l",
"<=",
"len",
"(",
"searchels",
")",
":",
"e",
"=",
"range",
"(",
"s",
",",
"s",
"+",
"l",
")",
"txtsearch",
"=",
"''",
"for",
"k",
"in",
"e",
":",
"txtsearch",
"+=",
"searchels",
"[",
"k",
"]",
".",
"text",
"# Searcs for the text in the whole txtsearch",
"match",
"=",
"searchre",
".",
"search",
"(",
"txtsearch",
")",
"if",
"match",
":",
"matches",
".",
"append",
"(",
"match",
".",
"group",
"(",
")",
")",
"found",
"=",
"True",
"return",
"set",
"(",
"matches",
")"
] | Return set of all regex matches
This is an advanced version of python-docx.search() that takes into
account blocks of <bs> elements at a time.
What it does:
It searches the entire document body for text blocks.
Since the text to search could be spawned across multiple text blocks,
we need to adopt some sort of algorithm to handle this situation.
The smaller matching group of blocks (up to bs) is then adopted.
If the matching group has more than one block, blocks other than first
are cleared and all the replacement text is put on first block.
Examples:
original text blocks : [ 'Hel', 'lo,', ' world!' ]
search : 'Hello,'
output blocks : [ 'Hello,' ]
original text blocks : [ 'Hel', 'lo', ' __', 'name', '__!' ]
search : '(__[a-z]+__)'
output blocks : [ '__name__' ]
@param instance document: The original document
@param str search: The text to search for (regexp)
append, or a list of etree elements
@param int bs: See above
@return set All occurences of search string | [
"Return",
"set",
"of",
"all",
"regex",
"matches"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L683-L756 | train |
mikemaccana/python-docx | docx.py | getdocumenttext | def getdocumenttext(document):
'''Return the raw text of a document, as a list of paragraphs.'''
paratextlist = []
# Compile a list of all paragraph (p) elements
paralist = []
for element in document.iter():
# Find p (paragraph) elements
if element.tag == '{'+nsprefixes['w']+'}p':
paralist.append(element)
# Since a single sentence might be spread over multiple text elements,
# iterate through each paragraph, appending all text (t) children to that
# paragraphs text.
for para in paralist:
paratext = u''
# Loop through each paragraph
for element in para.iter():
# Find t (text) elements
if element.tag == '{'+nsprefixes['w']+'}t':
if element.text:
paratext = paratext+element.text
elif element.tag == '{'+nsprefixes['w']+'}tab':
paratext = paratext + '\t'
# Add our completed paragraph text to the list of paragraph text
if not len(paratext) == 0:
paratextlist.append(paratext)
return paratextlist | python | def getdocumenttext(document):
'''Return the raw text of a document, as a list of paragraphs.'''
paratextlist = []
# Compile a list of all paragraph (p) elements
paralist = []
for element in document.iter():
# Find p (paragraph) elements
if element.tag == '{'+nsprefixes['w']+'}p':
paralist.append(element)
# Since a single sentence might be spread over multiple text elements,
# iterate through each paragraph, appending all text (t) children to that
# paragraphs text.
for para in paralist:
paratext = u''
# Loop through each paragraph
for element in para.iter():
# Find t (text) elements
if element.tag == '{'+nsprefixes['w']+'}t':
if element.text:
paratext = paratext+element.text
elif element.tag == '{'+nsprefixes['w']+'}tab':
paratext = paratext + '\t'
# Add our completed paragraph text to the list of paragraph text
if not len(paratext) == 0:
paratextlist.append(paratext)
return paratextlist | [
"def",
"getdocumenttext",
"(",
"document",
")",
":",
"paratextlist",
"=",
"[",
"]",
"# Compile a list of all paragraph (p) elements",
"paralist",
"=",
"[",
"]",
"for",
"element",
"in",
"document",
".",
"iter",
"(",
")",
":",
"# Find p (paragraph) elements",
"if",
"element",
".",
"tag",
"==",
"'{'",
"+",
"nsprefixes",
"[",
"'w'",
"]",
"+",
"'}p'",
":",
"paralist",
".",
"append",
"(",
"element",
")",
"# Since a single sentence might be spread over multiple text elements,",
"# iterate through each paragraph, appending all text (t) children to that",
"# paragraphs text.",
"for",
"para",
"in",
"paralist",
":",
"paratext",
"=",
"u''",
"# Loop through each paragraph",
"for",
"element",
"in",
"para",
".",
"iter",
"(",
")",
":",
"# Find t (text) elements",
"if",
"element",
".",
"tag",
"==",
"'{'",
"+",
"nsprefixes",
"[",
"'w'",
"]",
"+",
"'}t'",
":",
"if",
"element",
".",
"text",
":",
"paratext",
"=",
"paratext",
"+",
"element",
".",
"text",
"elif",
"element",
".",
"tag",
"==",
"'{'",
"+",
"nsprefixes",
"[",
"'w'",
"]",
"+",
"'}tab'",
":",
"paratext",
"=",
"paratext",
"+",
"'\\t'",
"# Add our completed paragraph text to the list of paragraph text",
"if",
"not",
"len",
"(",
"paratext",
")",
"==",
"0",
":",
"paratextlist",
".",
"append",
"(",
"paratext",
")",
"return",
"paratextlist"
] | Return the raw text of a document, as a list of paragraphs. | [
"Return",
"the",
"raw",
"text",
"of",
"a",
"document",
"as",
"a",
"list",
"of",
"paragraphs",
"."
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L910-L935 | train |
mikemaccana/python-docx | docx.py | wordrelationships | def wordrelationships(relationshiplist):
'''Generate a Word relationships file'''
# Default list of relationships
# FIXME: using string hack instead of making element
#relationships = makeelement('Relationships', nsprefix='pr')
relationships = etree.fromstring(
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006'
'/relationships"></Relationships>')
count = 0
for relationship in relationshiplist:
# Relationship IDs (rId) start at 1.
rel_elm = makeelement('Relationship', nsprefix=None,
attributes={'Id': 'rId'+str(count+1),
'Type': relationship[0],
'Target': relationship[1]}
)
relationships.append(rel_elm)
count += 1
return relationships | python | def wordrelationships(relationshiplist):
'''Generate a Word relationships file'''
# Default list of relationships
# FIXME: using string hack instead of making element
#relationships = makeelement('Relationships', nsprefix='pr')
relationships = etree.fromstring(
'<Relationships xmlns="http://schemas.openxmlformats.org/package/2006'
'/relationships"></Relationships>')
count = 0
for relationship in relationshiplist:
# Relationship IDs (rId) start at 1.
rel_elm = makeelement('Relationship', nsprefix=None,
attributes={'Id': 'rId'+str(count+1),
'Type': relationship[0],
'Target': relationship[1]}
)
relationships.append(rel_elm)
count += 1
return relationships | [
"def",
"wordrelationships",
"(",
"relationshiplist",
")",
":",
"# Default list of relationships",
"# FIXME: using string hack instead of making element",
"#relationships = makeelement('Relationships', nsprefix='pr')",
"relationships",
"=",
"etree",
".",
"fromstring",
"(",
"'<Relationships xmlns=\"http://schemas.openxmlformats.org/package/2006'",
"'/relationships\"></Relationships>'",
")",
"count",
"=",
"0",
"for",
"relationship",
"in",
"relationshiplist",
":",
"# Relationship IDs (rId) start at 1.",
"rel_elm",
"=",
"makeelement",
"(",
"'Relationship'",
",",
"nsprefix",
"=",
"None",
",",
"attributes",
"=",
"{",
"'Id'",
":",
"'rId'",
"+",
"str",
"(",
"count",
"+",
"1",
")",
",",
"'Type'",
":",
"relationship",
"[",
"0",
"]",
",",
"'Target'",
":",
"relationship",
"[",
"1",
"]",
"}",
")",
"relationships",
".",
"append",
"(",
"rel_elm",
")",
"count",
"+=",
"1",
"return",
"relationships"
] | Generate a Word relationships file | [
"Generate",
"a",
"Word",
"relationships",
"file"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1031-L1049 | train |
mikemaccana/python-docx | docx.py | savedocx | def savedocx(
document, coreprops, appprops, contenttypes, websettings,
wordrelationships, output, imagefiledict=None):
"""
Save a modified document
"""
if imagefiledict is None:
warn(
'Using savedocx() without imagefiledict parameter will be deprec'
'ated in the future.', PendingDeprecationWarning
)
assert os.path.isdir(template_dir)
docxfile = zipfile.ZipFile(
output, mode='w', compression=zipfile.ZIP_DEFLATED)
# Move to the template data path
prev_dir = os.path.abspath('.') # save previous working dir
os.chdir(template_dir)
# Serialize our trees into out zip file
treesandfiles = {
document: 'word/document.xml',
coreprops: 'docProps/core.xml',
appprops: 'docProps/app.xml',
contenttypes: '[Content_Types].xml',
websettings: 'word/webSettings.xml',
wordrelationships: 'word/_rels/document.xml.rels'
}
for tree in treesandfiles:
log.info('Saving: %s' % treesandfiles[tree])
treestring = etree.tostring(tree, pretty_print=True)
docxfile.writestr(treesandfiles[tree], treestring)
# Add & compress images, if applicable
if imagefiledict is not None:
for imagepath, picrelid in imagefiledict.items():
archivename = 'word/media/%s_%s' % (picrelid, basename(imagepath))
log.info('Saving: %s', archivename)
docxfile.write(imagepath, archivename)
# Add & compress support files
files_to_ignore = ['.DS_Store'] # nuisance from some os's
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename in files_to_ignore:
continue
templatefile = join(dirpath, filename)
archivename = templatefile[2:]
log.info('Saving: %s', archivename)
docxfile.write(templatefile, archivename)
log.info('Saved new file to: %r', output)
docxfile.close()
os.chdir(prev_dir) # restore previous working dir
return | python | def savedocx(
document, coreprops, appprops, contenttypes, websettings,
wordrelationships, output, imagefiledict=None):
"""
Save a modified document
"""
if imagefiledict is None:
warn(
'Using savedocx() without imagefiledict parameter will be deprec'
'ated in the future.', PendingDeprecationWarning
)
assert os.path.isdir(template_dir)
docxfile = zipfile.ZipFile(
output, mode='w', compression=zipfile.ZIP_DEFLATED)
# Move to the template data path
prev_dir = os.path.abspath('.') # save previous working dir
os.chdir(template_dir)
# Serialize our trees into out zip file
treesandfiles = {
document: 'word/document.xml',
coreprops: 'docProps/core.xml',
appprops: 'docProps/app.xml',
contenttypes: '[Content_Types].xml',
websettings: 'word/webSettings.xml',
wordrelationships: 'word/_rels/document.xml.rels'
}
for tree in treesandfiles:
log.info('Saving: %s' % treesandfiles[tree])
treestring = etree.tostring(tree, pretty_print=True)
docxfile.writestr(treesandfiles[tree], treestring)
# Add & compress images, if applicable
if imagefiledict is not None:
for imagepath, picrelid in imagefiledict.items():
archivename = 'word/media/%s_%s' % (picrelid, basename(imagepath))
log.info('Saving: %s', archivename)
docxfile.write(imagepath, archivename)
# Add & compress support files
files_to_ignore = ['.DS_Store'] # nuisance from some os's
for dirpath, dirnames, filenames in os.walk('.'):
for filename in filenames:
if filename in files_to_ignore:
continue
templatefile = join(dirpath, filename)
archivename = templatefile[2:]
log.info('Saving: %s', archivename)
docxfile.write(templatefile, archivename)
log.info('Saved new file to: %r', output)
docxfile.close()
os.chdir(prev_dir) # restore previous working dir
return | [
"def",
"savedocx",
"(",
"document",
",",
"coreprops",
",",
"appprops",
",",
"contenttypes",
",",
"websettings",
",",
"wordrelationships",
",",
"output",
",",
"imagefiledict",
"=",
"None",
")",
":",
"if",
"imagefiledict",
"is",
"None",
":",
"warn",
"(",
"'Using savedocx() without imagefiledict parameter will be deprec'",
"'ated in the future.'",
",",
"PendingDeprecationWarning",
")",
"assert",
"os",
".",
"path",
".",
"isdir",
"(",
"template_dir",
")",
"docxfile",
"=",
"zipfile",
".",
"ZipFile",
"(",
"output",
",",
"mode",
"=",
"'w'",
",",
"compression",
"=",
"zipfile",
".",
"ZIP_DEFLATED",
")",
"# Move to the template data path",
"prev_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"'.'",
")",
"# save previous working dir",
"os",
".",
"chdir",
"(",
"template_dir",
")",
"# Serialize our trees into out zip file",
"treesandfiles",
"=",
"{",
"document",
":",
"'word/document.xml'",
",",
"coreprops",
":",
"'docProps/core.xml'",
",",
"appprops",
":",
"'docProps/app.xml'",
",",
"contenttypes",
":",
"'[Content_Types].xml'",
",",
"websettings",
":",
"'word/webSettings.xml'",
",",
"wordrelationships",
":",
"'word/_rels/document.xml.rels'",
"}",
"for",
"tree",
"in",
"treesandfiles",
":",
"log",
".",
"info",
"(",
"'Saving: %s'",
"%",
"treesandfiles",
"[",
"tree",
"]",
")",
"treestring",
"=",
"etree",
".",
"tostring",
"(",
"tree",
",",
"pretty_print",
"=",
"True",
")",
"docxfile",
".",
"writestr",
"(",
"treesandfiles",
"[",
"tree",
"]",
",",
"treestring",
")",
"# Add & compress images, if applicable",
"if",
"imagefiledict",
"is",
"not",
"None",
":",
"for",
"imagepath",
",",
"picrelid",
"in",
"imagefiledict",
".",
"items",
"(",
")",
":",
"archivename",
"=",
"'word/media/%s_%s'",
"%",
"(",
"picrelid",
",",
"basename",
"(",
"imagepath",
")",
")",
"log",
".",
"info",
"(",
"'Saving: %s'",
",",
"archivename",
")",
"docxfile",
".",
"write",
"(",
"imagepath",
",",
"archivename",
")",
"# Add & compress support files",
"files_to_ignore",
"=",
"[",
"'.DS_Store'",
"]",
"# nuisance from some os's",
"for",
"dirpath",
",",
"dirnames",
",",
"filenames",
"in",
"os",
".",
"walk",
"(",
"'.'",
")",
":",
"for",
"filename",
"in",
"filenames",
":",
"if",
"filename",
"in",
"files_to_ignore",
":",
"continue",
"templatefile",
"=",
"join",
"(",
"dirpath",
",",
"filename",
")",
"archivename",
"=",
"templatefile",
"[",
"2",
":",
"]",
"log",
".",
"info",
"(",
"'Saving: %s'",
",",
"archivename",
")",
"docxfile",
".",
"write",
"(",
"templatefile",
",",
"archivename",
")",
"log",
".",
"info",
"(",
"'Saved new file to: %r'",
",",
"output",
")",
"docxfile",
".",
"close",
"(",
")",
"os",
".",
"chdir",
"(",
"prev_dir",
")",
"# restore previous working dir",
"return"
] | Save a modified document | [
"Save",
"a",
"modified",
"document"
] | 4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe | https://github.com/mikemaccana/python-docx/blob/4c9b46dbebe3d2a9b82dbcd35af36584a36fd9fe/docx.py#L1052-L1107 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | _depr | def _depr(fn, usage, stacklevel=3):
"""Internal convenience function for deprecation warnings"""
warn('{0} is deprecated. Use {1} instead'.format(fn, usage),
stacklevel=stacklevel, category=DeprecationWarning) | python | def _depr(fn, usage, stacklevel=3):
"""Internal convenience function for deprecation warnings"""
warn('{0} is deprecated. Use {1} instead'.format(fn, usage),
stacklevel=stacklevel, category=DeprecationWarning) | [
"def",
"_depr",
"(",
"fn",
",",
"usage",
",",
"stacklevel",
"=",
"3",
")",
":",
"warn",
"(",
"'{0} is deprecated. Use {1} instead'",
".",
"format",
"(",
"fn",
",",
"usage",
")",
",",
"stacklevel",
"=",
"stacklevel",
",",
"category",
"=",
"DeprecationWarning",
")"
] | Internal convenience function for deprecation warnings | [
"Internal",
"convenience",
"function",
"for",
"deprecation",
"warnings"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L44-L47 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.upsert | def upsert(self, key, value, cas=0, ttl=0, format=None,
persist_to=0, replicate_to=0):
"""Unconditionally store the object in Couchbase.
:param key:
The key to set the value with. By default, the key must be
either a :class:`bytes` or :class:`str` object encodable as
UTF-8. If a custom `transcoder` class is used (see
:meth:`~__init__`), then the key object is passed directly
to the transcoder, which may serialize it how it wishes.
:type key: string or bytes
:param value: The value to set for the key.
This should be a native Python value which will be transparently
serialized to JSON by the library. Do not pass already-serialized
JSON as the value or it will be serialized again.
If you are using a different `format` setting (see `format`
parameter), and/or a custom transcoder then value for this
argument may need to conform to different criteria.
:param int cas: The _CAS_ value to use. If supplied, the value
will only be stored if it already exists with the supplied
CAS
:param int ttl: If specified, the key will expire after this
many seconds
:param int format: If specified, indicates the `format` to use
when encoding the value. If none is specified, it will use
the `default_format` For more info see
:attr:`~.default_format`
:param int persist_to:
Perform durability checking on this many nodes nodes for
persistence to disk. See :meth:`endure` for more information
:param int replicate_to: Perform durability checking on this
many replicas for presence in memory. See :meth:`endure` for
more information.
:raise: :exc:`.ArgumentError` if an argument is supplied that is
not applicable in this context. For example setting the CAS
as a string.
:raise: :exc`.CouchbaseNetworkError`
:raise: :exc:`.KeyExistsError` if the key already exists on the
server with a different CAS value.
:raise: :exc:`.ValueFormatError` if the value cannot be
serialized with chosen encoder, e.g. if you try to store a
dictionary in plain mode.
:return: :class:`~.Result`.
Simple set::
cb.upsert('key', 'value')
Force JSON document format for value::
cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON)
Insert JSON from a string::
JSONstr = '{"key1": "value1", "key2": 123}'
JSONobj = json.loads(JSONstr)
cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON)
Force UTF8 document format for value::
cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8)
Perform optimistic locking by specifying last known CAS version::
cb.upsert('foo', 'bar', cas=8835713818674332672)
Several sets at the same time (mutli-set)::
cb.upsert_multi({'foo': 'bar', 'baz': 'value'})
.. seealso:: :meth:`upsert_multi`
"""
return _Base.upsert(self, key, value, cas=cas, ttl=ttl,
format=format, persist_to=persist_to,
replicate_to=replicate_to) | python | def upsert(self, key, value, cas=0, ttl=0, format=None,
persist_to=0, replicate_to=0):
"""Unconditionally store the object in Couchbase.
:param key:
The key to set the value with. By default, the key must be
either a :class:`bytes` or :class:`str` object encodable as
UTF-8. If a custom `transcoder` class is used (see
:meth:`~__init__`), then the key object is passed directly
to the transcoder, which may serialize it how it wishes.
:type key: string or bytes
:param value: The value to set for the key.
This should be a native Python value which will be transparently
serialized to JSON by the library. Do not pass already-serialized
JSON as the value or it will be serialized again.
If you are using a different `format` setting (see `format`
parameter), and/or a custom transcoder then value for this
argument may need to conform to different criteria.
:param int cas: The _CAS_ value to use. If supplied, the value
will only be stored if it already exists with the supplied
CAS
:param int ttl: If specified, the key will expire after this
many seconds
:param int format: If specified, indicates the `format` to use
when encoding the value. If none is specified, it will use
the `default_format` For more info see
:attr:`~.default_format`
:param int persist_to:
Perform durability checking on this many nodes nodes for
persistence to disk. See :meth:`endure` for more information
:param int replicate_to: Perform durability checking on this
many replicas for presence in memory. See :meth:`endure` for
more information.
:raise: :exc:`.ArgumentError` if an argument is supplied that is
not applicable in this context. For example setting the CAS
as a string.
:raise: :exc`.CouchbaseNetworkError`
:raise: :exc:`.KeyExistsError` if the key already exists on the
server with a different CAS value.
:raise: :exc:`.ValueFormatError` if the value cannot be
serialized with chosen encoder, e.g. if you try to store a
dictionary in plain mode.
:return: :class:`~.Result`.
Simple set::
cb.upsert('key', 'value')
Force JSON document format for value::
cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON)
Insert JSON from a string::
JSONstr = '{"key1": "value1", "key2": 123}'
JSONobj = json.loads(JSONstr)
cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON)
Force UTF8 document format for value::
cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8)
Perform optimistic locking by specifying last known CAS version::
cb.upsert('foo', 'bar', cas=8835713818674332672)
Several sets at the same time (mutli-set)::
cb.upsert_multi({'foo': 'bar', 'baz': 'value'})
.. seealso:: :meth:`upsert_multi`
"""
return _Base.upsert(self, key, value, cas=cas, ttl=ttl,
format=format, persist_to=persist_to,
replicate_to=replicate_to) | [
"def",
"upsert",
"(",
"self",
",",
"key",
",",
"value",
",",
"cas",
"=",
"0",
",",
"ttl",
"=",
"0",
",",
"format",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"upsert",
"(",
"self",
",",
"key",
",",
"value",
",",
"cas",
"=",
"cas",
",",
"ttl",
"=",
"ttl",
",",
"format",
"=",
"format",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
")"
] | Unconditionally store the object in Couchbase.
:param key:
The key to set the value with. By default, the key must be
either a :class:`bytes` or :class:`str` object encodable as
UTF-8. If a custom `transcoder` class is used (see
:meth:`~__init__`), then the key object is passed directly
to the transcoder, which may serialize it how it wishes.
:type key: string or bytes
:param value: The value to set for the key.
This should be a native Python value which will be transparently
serialized to JSON by the library. Do not pass already-serialized
JSON as the value or it will be serialized again.
If you are using a different `format` setting (see `format`
parameter), and/or a custom transcoder then value for this
argument may need to conform to different criteria.
:param int cas: The _CAS_ value to use. If supplied, the value
will only be stored if it already exists with the supplied
CAS
:param int ttl: If specified, the key will expire after this
many seconds
:param int format: If specified, indicates the `format` to use
when encoding the value. If none is specified, it will use
the `default_format` For more info see
:attr:`~.default_format`
:param int persist_to:
Perform durability checking on this many nodes nodes for
persistence to disk. See :meth:`endure` for more information
:param int replicate_to: Perform durability checking on this
many replicas for presence in memory. See :meth:`endure` for
more information.
:raise: :exc:`.ArgumentError` if an argument is supplied that is
not applicable in this context. For example setting the CAS
as a string.
:raise: :exc`.CouchbaseNetworkError`
:raise: :exc:`.KeyExistsError` if the key already exists on the
server with a different CAS value.
:raise: :exc:`.ValueFormatError` if the value cannot be
serialized with chosen encoder, e.g. if you try to store a
dictionary in plain mode.
:return: :class:`~.Result`.
Simple set::
cb.upsert('key', 'value')
Force JSON document format for value::
cb.upsert('foo', {'bar': 'baz'}, format=couchbase.FMT_JSON)
Insert JSON from a string::
JSONstr = '{"key1": "value1", "key2": 123}'
JSONobj = json.loads(JSONstr)
cb.upsert("documentID", JSONobj, format=couchbase.FMT_JSON)
Force UTF8 document format for value::
cb.upsert('foo', "<xml></xml>", format=couchbase.FMT_UTF8)
Perform optimistic locking by specifying last known CAS version::
cb.upsert('foo', 'bar', cas=8835713818674332672)
Several sets at the same time (mutli-set)::
cb.upsert_multi({'foo': 'bar', 'baz': 'value'})
.. seealso:: :meth:`upsert_multi` | [
"Unconditionally",
"store",
"the",
"object",
"in",
"Couchbase",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L328-L410 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.insert | def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0):
"""Store an object in Couchbase unless it already exists.
Follows the same conventions as :meth:`upsert` but the value is
stored only if it does not exist already. Conversely, the value
is not stored if the key already exists.
Notably missing from this method is the `cas` parameter, this is
because `insert` will only succeed if a key does not already
exist on the server (and thus can have no CAS)
:raise: :exc:`.KeyExistsError` if the key already exists
.. seealso:: :meth:`upsert`, :meth:`insert_multi`
"""
return _Base.insert(self, key, value, ttl=ttl, format=format,
persist_to=persist_to, replicate_to=replicate_to) | python | def insert(self, key, value, ttl=0, format=None, persist_to=0, replicate_to=0):
"""Store an object in Couchbase unless it already exists.
Follows the same conventions as :meth:`upsert` but the value is
stored only if it does not exist already. Conversely, the value
is not stored if the key already exists.
Notably missing from this method is the `cas` parameter, this is
because `insert` will only succeed if a key does not already
exist on the server (and thus can have no CAS)
:raise: :exc:`.KeyExistsError` if the key already exists
.. seealso:: :meth:`upsert`, :meth:`insert_multi`
"""
return _Base.insert(self, key, value, ttl=ttl, format=format,
persist_to=persist_to, replicate_to=replicate_to) | [
"def",
"insert",
"(",
"self",
",",
"key",
",",
"value",
",",
"ttl",
"=",
"0",
",",
"format",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"insert",
"(",
"self",
",",
"key",
",",
"value",
",",
"ttl",
"=",
"ttl",
",",
"format",
"=",
"format",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
")"
] | Store an object in Couchbase unless it already exists.
Follows the same conventions as :meth:`upsert` but the value is
stored only if it does not exist already. Conversely, the value
is not stored if the key already exists.
Notably missing from this method is the `cas` parameter, this is
because `insert` will only succeed if a key does not already
exist on the server (and thus can have no CAS)
:raise: :exc:`.KeyExistsError` if the key already exists
.. seealso:: :meth:`upsert`, :meth:`insert_multi` | [
"Store",
"an",
"object",
"in",
"Couchbase",
"unless",
"it",
"already",
"exists",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L412-L428 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.prepend | def prepend(self, key, value, cas=0, format=None,
persist_to=0, replicate_to=0):
"""Prepend a string to an existing value in Couchbase.
.. seealso:: :meth:`append`, :meth:`prepend_multi`
"""
return _Base.prepend(self, key, value, cas=cas, format=format,
persist_to=persist_to, replicate_to=replicate_to) | python | def prepend(self, key, value, cas=0, format=None,
persist_to=0, replicate_to=0):
"""Prepend a string to an existing value in Couchbase.
.. seealso:: :meth:`append`, :meth:`prepend_multi`
"""
return _Base.prepend(self, key, value, cas=cas, format=format,
persist_to=persist_to, replicate_to=replicate_to) | [
"def",
"prepend",
"(",
"self",
",",
"key",
",",
"value",
",",
"cas",
"=",
"0",
",",
"format",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"prepend",
"(",
"self",
",",
"key",
",",
"value",
",",
"cas",
"=",
"cas",
",",
"format",
"=",
"format",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
")"
] | Prepend a string to an existing value in Couchbase.
.. seealso:: :meth:`append`, :meth:`prepend_multi` | [
"Prepend",
"a",
"string",
"to",
"an",
"existing",
"value",
"in",
"Couchbase",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L475-L482 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.get | def get(self, key, ttl=0, quiet=None, replica=False, no_format=False):
"""Obtain an object stored in Couchbase by given key.
:param string key: The key to fetch. The type of key is the same
as mentioned in :meth:`upsert`
:param int ttl: If specified, indicates that the key's expiration
time should be *modified* when retrieving the value.
:param boolean quiet: causes `get` to return None instead of
raising an exception when the key is not found. It defaults
to the value set by :attr:`~quiet` on the instance. In
`quiet` mode, the error may still be obtained by inspecting
the :attr:`~.Result.rc` attribute of the :class:`.Result`
object, or checking :attr:`.Result.success`.
Note that the default value is `None`, which means to use
the :attr:`quiet`. If it is a boolean (i.e. `True` or
`False`) it will override the `couchbase.bucket.Bucket`-level
:attr:`quiet` attribute.
:param bool replica: Whether to fetch this key from a replica
rather than querying the master server. This is primarily
useful when operations with the master fail (possibly due to
a configuration change). It should normally be used in an
exception handler like so
Using the ``replica`` option::
try:
res = c.get("key", quiet=True) # suppress not-found errors
catch CouchbaseError:
res = c.get("key", replica=True, quiet=True)
:param bool no_format: If set to ``True``, then the value will
always be delivered in the :class:`~couchbase.result.Result`
object as being of :data:`~couchbase.FMT_BYTES`. This is a
item-local equivalent of using the :attr:`data_passthrough`
option
:raise: :exc:`.NotFoundError` if the key does not exist
:raise: :exc:`.CouchbaseNetworkError`
:raise: :exc:`.ValueFormatError` if the value cannot be
deserialized with chosen decoder, e.g. if you try to
retreive an object stored with an unrecognized format
:return: A :class:`~.Result` object
Simple get::
value = cb.get('key').value
Get multiple values::
cb.get_multi(['foo', 'bar'])
# { 'foo' : <Result(...)>, 'bar' : <Result(...)> }
Inspect the flags::
rv = cb.get("key")
value, flags, cas = rv.value, rv.flags, rv.cas
Update the expiration time::
rv = cb.get("key", ttl=10)
# Expires in ten seconds
.. seealso:: :meth:`get_multi`
"""
return _Base.get(self, key, ttl=ttl, quiet=quiet,
replica=replica, no_format=no_format) | python | def get(self, key, ttl=0, quiet=None, replica=False, no_format=False):
"""Obtain an object stored in Couchbase by given key.
:param string key: The key to fetch. The type of key is the same
as mentioned in :meth:`upsert`
:param int ttl: If specified, indicates that the key's expiration
time should be *modified* when retrieving the value.
:param boolean quiet: causes `get` to return None instead of
raising an exception when the key is not found. It defaults
to the value set by :attr:`~quiet` on the instance. In
`quiet` mode, the error may still be obtained by inspecting
the :attr:`~.Result.rc` attribute of the :class:`.Result`
object, or checking :attr:`.Result.success`.
Note that the default value is `None`, which means to use
the :attr:`quiet`. If it is a boolean (i.e. `True` or
`False`) it will override the `couchbase.bucket.Bucket`-level
:attr:`quiet` attribute.
:param bool replica: Whether to fetch this key from a replica
rather than querying the master server. This is primarily
useful when operations with the master fail (possibly due to
a configuration change). It should normally be used in an
exception handler like so
Using the ``replica`` option::
try:
res = c.get("key", quiet=True) # suppress not-found errors
catch CouchbaseError:
res = c.get("key", replica=True, quiet=True)
:param bool no_format: If set to ``True``, then the value will
always be delivered in the :class:`~couchbase.result.Result`
object as being of :data:`~couchbase.FMT_BYTES`. This is a
item-local equivalent of using the :attr:`data_passthrough`
option
:raise: :exc:`.NotFoundError` if the key does not exist
:raise: :exc:`.CouchbaseNetworkError`
:raise: :exc:`.ValueFormatError` if the value cannot be
deserialized with chosen decoder, e.g. if you try to
retreive an object stored with an unrecognized format
:return: A :class:`~.Result` object
Simple get::
value = cb.get('key').value
Get multiple values::
cb.get_multi(['foo', 'bar'])
# { 'foo' : <Result(...)>, 'bar' : <Result(...)> }
Inspect the flags::
rv = cb.get("key")
value, flags, cas = rv.value, rv.flags, rv.cas
Update the expiration time::
rv = cb.get("key", ttl=10)
# Expires in ten seconds
.. seealso:: :meth:`get_multi`
"""
return _Base.get(self, key, ttl=ttl, quiet=quiet,
replica=replica, no_format=no_format) | [
"def",
"get",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"0",
",",
"quiet",
"=",
"None",
",",
"replica",
"=",
"False",
",",
"no_format",
"=",
"False",
")",
":",
"return",
"_Base",
".",
"get",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"ttl",
",",
"quiet",
"=",
"quiet",
",",
"replica",
"=",
"replica",
",",
"no_format",
"=",
"no_format",
")"
] | Obtain an object stored in Couchbase by given key.
:param string key: The key to fetch. The type of key is the same
as mentioned in :meth:`upsert`
:param int ttl: If specified, indicates that the key's expiration
time should be *modified* when retrieving the value.
:param boolean quiet: causes `get` to return None instead of
raising an exception when the key is not found. It defaults
to the value set by :attr:`~quiet` on the instance. In
`quiet` mode, the error may still be obtained by inspecting
the :attr:`~.Result.rc` attribute of the :class:`.Result`
object, or checking :attr:`.Result.success`.
Note that the default value is `None`, which means to use
the :attr:`quiet`. If it is a boolean (i.e. `True` or
`False`) it will override the `couchbase.bucket.Bucket`-level
:attr:`quiet` attribute.
:param bool replica: Whether to fetch this key from a replica
rather than querying the master server. This is primarily
useful when operations with the master fail (possibly due to
a configuration change). It should normally be used in an
exception handler like so
Using the ``replica`` option::
try:
res = c.get("key", quiet=True) # suppress not-found errors
catch CouchbaseError:
res = c.get("key", replica=True, quiet=True)
:param bool no_format: If set to ``True``, then the value will
always be delivered in the :class:`~couchbase.result.Result`
object as being of :data:`~couchbase.FMT_BYTES`. This is a
item-local equivalent of using the :attr:`data_passthrough`
option
:raise: :exc:`.NotFoundError` if the key does not exist
:raise: :exc:`.CouchbaseNetworkError`
:raise: :exc:`.ValueFormatError` if the value cannot be
deserialized with chosen decoder, e.g. if you try to
retreive an object stored with an unrecognized format
:return: A :class:`~.Result` object
Simple get::
value = cb.get('key').value
Get multiple values::
cb.get_multi(['foo', 'bar'])
# { 'foo' : <Result(...)>, 'bar' : <Result(...)> }
Inspect the flags::
rv = cb.get("key")
value, flags, cas = rv.value, rv.flags, rv.cas
Update the expiration time::
rv = cb.get("key", ttl=10)
# Expires in ten seconds
.. seealso:: :meth:`get_multi` | [
"Obtain",
"an",
"object",
"stored",
"in",
"Couchbase",
"by",
"given",
"key",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L484-L554 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.touch | def touch(self, key, ttl=0):
"""Update a key's expiration time
:param string key: The key whose expiration time should be
modified
:param int ttl: The new expiration time. If the expiration time
is `0` then the key never expires (and any existing
expiration is removed)
:return: :class:`.OperationResult`
Update the expiration time of a key ::
cb.upsert("key", ttl=100)
# expires in 100 seconds
cb.touch("key", ttl=0)
# key should never expire now
:raise: The same things that :meth:`get` does
.. seealso:: :meth:`get` - which can be used to get *and* update the
expiration, :meth:`touch_multi`
"""
return _Base.touch(self, key, ttl=ttl) | python | def touch(self, key, ttl=0):
"""Update a key's expiration time
:param string key: The key whose expiration time should be
modified
:param int ttl: The new expiration time. If the expiration time
is `0` then the key never expires (and any existing
expiration is removed)
:return: :class:`.OperationResult`
Update the expiration time of a key ::
cb.upsert("key", ttl=100)
# expires in 100 seconds
cb.touch("key", ttl=0)
# key should never expire now
:raise: The same things that :meth:`get` does
.. seealso:: :meth:`get` - which can be used to get *and* update the
expiration, :meth:`touch_multi`
"""
return _Base.touch(self, key, ttl=ttl) | [
"def",
"touch",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"touch",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"ttl",
")"
] | Update a key's expiration time
:param string key: The key whose expiration time should be
modified
:param int ttl: The new expiration time. If the expiration time
is `0` then the key never expires (and any existing
expiration is removed)
:return: :class:`.OperationResult`
Update the expiration time of a key ::
cb.upsert("key", ttl=100)
# expires in 100 seconds
cb.touch("key", ttl=0)
# key should never expire now
:raise: The same things that :meth:`get` does
.. seealso:: :meth:`get` - which can be used to get *and* update the
expiration, :meth:`touch_multi` | [
"Update",
"a",
"key",
"s",
"expiration",
"time"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L556-L578 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.lock | def lock(self, key, ttl=0):
"""Lock and retrieve a key-value entry in Couchbase.
:param key: A string which is the key to lock.
:param ttl: a TTL for which the lock should be valid.
While the lock is active, attempts to access the key (via
other :meth:`lock`, :meth:`upsert` or other mutation calls)
will fail with an :exc:`.KeyExistsError`. Note that the
value for this option is limited by the maximum allowable
lock time determined by the server (currently, this is 30
seconds). If passed a higher value, the server will silently
lower this to its maximum limit.
This function otherwise functions similarly to :meth:`get`;
specifically, it will return the value upon success. Note the
:attr:`~.Result.cas` value from the :class:`.Result` object.
This will be needed to :meth:`unlock` the key.
Note the lock will also be implicitly released if modified by
one of the :meth:`upsert` family of functions when the valid CAS
is supplied
:raise: :exc:`.TemporaryFailError` if the key is already locked.
:raise: See :meth:`get` for possible exceptions
Lock a key ::
rv = cb.lock("locked_key", ttl=5)
# This key is now locked for the next 5 seconds.
# attempts to access this key will fail until the lock
# is released.
# do important stuff...
cb.unlock("locked_key", rv.cas)
Lock a key, implicitly unlocking with :meth:`upsert` with CAS ::
rv = self.cb.lock("locked_key", ttl=5)
new_value = rv.value.upper()
cb.upsert("locked_key", new_value, rv.cas)
Poll and Lock ::
rv = None
begin_time = time.time()
while time.time() - begin_time < 15:
try:
rv = cb.lock("key", ttl=10)
break
except TemporaryFailError:
print("Key is currently locked.. waiting")
time.sleep(1)
if not rv:
raise Exception("Waited too long..")
# Do stuff..
cb.unlock("key", rv.cas)
.. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock`
"""
return _Base.lock(self, key, ttl=ttl) | python | def lock(self, key, ttl=0):
"""Lock and retrieve a key-value entry in Couchbase.
:param key: A string which is the key to lock.
:param ttl: a TTL for which the lock should be valid.
While the lock is active, attempts to access the key (via
other :meth:`lock`, :meth:`upsert` or other mutation calls)
will fail with an :exc:`.KeyExistsError`. Note that the
value for this option is limited by the maximum allowable
lock time determined by the server (currently, this is 30
seconds). If passed a higher value, the server will silently
lower this to its maximum limit.
This function otherwise functions similarly to :meth:`get`;
specifically, it will return the value upon success. Note the
:attr:`~.Result.cas` value from the :class:`.Result` object.
This will be needed to :meth:`unlock` the key.
Note the lock will also be implicitly released if modified by
one of the :meth:`upsert` family of functions when the valid CAS
is supplied
:raise: :exc:`.TemporaryFailError` if the key is already locked.
:raise: See :meth:`get` for possible exceptions
Lock a key ::
rv = cb.lock("locked_key", ttl=5)
# This key is now locked for the next 5 seconds.
# attempts to access this key will fail until the lock
# is released.
# do important stuff...
cb.unlock("locked_key", rv.cas)
Lock a key, implicitly unlocking with :meth:`upsert` with CAS ::
rv = self.cb.lock("locked_key", ttl=5)
new_value = rv.value.upper()
cb.upsert("locked_key", new_value, rv.cas)
Poll and Lock ::
rv = None
begin_time = time.time()
while time.time() - begin_time < 15:
try:
rv = cb.lock("key", ttl=10)
break
except TemporaryFailError:
print("Key is currently locked.. waiting")
time.sleep(1)
if not rv:
raise Exception("Waited too long..")
# Do stuff..
cb.unlock("key", rv.cas)
.. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock`
"""
return _Base.lock(self, key, ttl=ttl) | [
"def",
"lock",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"lock",
"(",
"self",
",",
"key",
",",
"ttl",
"=",
"ttl",
")"
] | Lock and retrieve a key-value entry in Couchbase.
:param key: A string which is the key to lock.
:param ttl: a TTL for which the lock should be valid.
While the lock is active, attempts to access the key (via
other :meth:`lock`, :meth:`upsert` or other mutation calls)
will fail with an :exc:`.KeyExistsError`. Note that the
value for this option is limited by the maximum allowable
lock time determined by the server (currently, this is 30
seconds). If passed a higher value, the server will silently
lower this to its maximum limit.
This function otherwise functions similarly to :meth:`get`;
specifically, it will return the value upon success. Note the
:attr:`~.Result.cas` value from the :class:`.Result` object.
This will be needed to :meth:`unlock` the key.
Note the lock will also be implicitly released if modified by
one of the :meth:`upsert` family of functions when the valid CAS
is supplied
:raise: :exc:`.TemporaryFailError` if the key is already locked.
:raise: See :meth:`get` for possible exceptions
Lock a key ::
rv = cb.lock("locked_key", ttl=5)
# This key is now locked for the next 5 seconds.
# attempts to access this key will fail until the lock
# is released.
# do important stuff...
cb.unlock("locked_key", rv.cas)
Lock a key, implicitly unlocking with :meth:`upsert` with CAS ::
rv = self.cb.lock("locked_key", ttl=5)
new_value = rv.value.upper()
cb.upsert("locked_key", new_value, rv.cas)
Poll and Lock ::
rv = None
begin_time = time.time()
while time.time() - begin_time < 15:
try:
rv = cb.lock("key", ttl=10)
break
except TemporaryFailError:
print("Key is currently locked.. waiting")
time.sleep(1)
if not rv:
raise Exception("Waited too long..")
# Do stuff..
cb.unlock("key", rv.cas)
.. seealso:: :meth:`get`, :meth:`lock_multi`, :meth:`unlock` | [
"Lock",
"and",
"retrieve",
"a",
"key",
"-",
"value",
"entry",
"in",
"Couchbase",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L580-L647 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.unlock | def unlock(self, key, cas):
"""Unlock a Locked Key in Couchbase.
This unlocks an item previously locked by :meth:`lock`
:param key: The key to unlock
:param cas: The cas returned from :meth:`lock`'s
:class:`.Result` object.
See :meth:`lock` for an example.
:raise: :exc:`.TemporaryFailError` if the CAS supplied does not
match the CAS on the server (possibly because it was
unlocked by previous call).
.. seealso:: :meth:`lock` :meth:`unlock_multi`
"""
return _Base.unlock(self, key, cas=cas) | python | def unlock(self, key, cas):
"""Unlock a Locked Key in Couchbase.
This unlocks an item previously locked by :meth:`lock`
:param key: The key to unlock
:param cas: The cas returned from :meth:`lock`'s
:class:`.Result` object.
See :meth:`lock` for an example.
:raise: :exc:`.TemporaryFailError` if the CAS supplied does not
match the CAS on the server (possibly because it was
unlocked by previous call).
.. seealso:: :meth:`lock` :meth:`unlock_multi`
"""
return _Base.unlock(self, key, cas=cas) | [
"def",
"unlock",
"(",
"self",
",",
"key",
",",
"cas",
")",
":",
"return",
"_Base",
".",
"unlock",
"(",
"self",
",",
"key",
",",
"cas",
"=",
"cas",
")"
] | Unlock a Locked Key in Couchbase.
This unlocks an item previously locked by :meth:`lock`
:param key: The key to unlock
:param cas: The cas returned from :meth:`lock`'s
:class:`.Result` object.
See :meth:`lock` for an example.
:raise: :exc:`.TemporaryFailError` if the CAS supplied does not
match the CAS on the server (possibly because it was
unlocked by previous call).
.. seealso:: :meth:`lock` :meth:`unlock_multi` | [
"Unlock",
"a",
"Locked",
"Key",
"in",
"Couchbase",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L649-L666 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.remove | def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0):
"""Remove the key-value entry for a given key in Couchbase.
:param key: A string which is the key to remove. The format and
type of the key follows the same conventions as in
:meth:`upsert`
:type key: string, dict, or tuple/list
:param int cas: The CAS to use for the removal operation.
If specified, the key will only be removed from the server
if it has the same CAS as specified. This is useful to
remove a key only if its value has not been changed from the
version currently visible to the client. If the CAS on the
server does not match the one specified, an exception is
thrown.
:param boolean quiet:
Follows the same semantics as `quiet` in :meth:`get`
:param int persist_to: If set, wait for the item to be removed
from the storage of at least these many nodes
:param int replicate_to: If set, wait for the item to be removed
from the cache of at least these many nodes
(excluding the master)
:raise: :exc:`.NotFoundError` if the key does not exist.
:raise: :exc:`.KeyExistsError` if a CAS was specified, but
the CAS on the server had changed
:return: A :class:`~.Result` object.
Simple remove::
ok = cb.remove("key").success
Don't complain if key does not exist::
ok = cb.remove("key", quiet=True)
Only remove if CAS matches our version::
rv = cb.get("key")
cb.remove("key", cas=rv.cas)
Remove multiple keys::
oks = cb.remove_multi(["key1", "key2", "key3"])
Remove multiple keys with CAS::
oks = cb.remove({
"key1" : cas1,
"key2" : cas2,
"key3" : cas3
})
.. seealso:: :meth:`remove_multi`, :meth:`endure`
for more information on the ``persist_to`` and
``replicate_to`` options.
"""
return _Base.remove(self, key, cas=cas, quiet=quiet,
persist_to=persist_to, replicate_to=replicate_to) | python | def remove(self, key, cas=0, quiet=None, persist_to=0, replicate_to=0):
"""Remove the key-value entry for a given key in Couchbase.
:param key: A string which is the key to remove. The format and
type of the key follows the same conventions as in
:meth:`upsert`
:type key: string, dict, or tuple/list
:param int cas: The CAS to use for the removal operation.
If specified, the key will only be removed from the server
if it has the same CAS as specified. This is useful to
remove a key only if its value has not been changed from the
version currently visible to the client. If the CAS on the
server does not match the one specified, an exception is
thrown.
:param boolean quiet:
Follows the same semantics as `quiet` in :meth:`get`
:param int persist_to: If set, wait for the item to be removed
from the storage of at least these many nodes
:param int replicate_to: If set, wait for the item to be removed
from the cache of at least these many nodes
(excluding the master)
:raise: :exc:`.NotFoundError` if the key does not exist.
:raise: :exc:`.KeyExistsError` if a CAS was specified, but
the CAS on the server had changed
:return: A :class:`~.Result` object.
Simple remove::
ok = cb.remove("key").success
Don't complain if key does not exist::
ok = cb.remove("key", quiet=True)
Only remove if CAS matches our version::
rv = cb.get("key")
cb.remove("key", cas=rv.cas)
Remove multiple keys::
oks = cb.remove_multi(["key1", "key2", "key3"])
Remove multiple keys with CAS::
oks = cb.remove({
"key1" : cas1,
"key2" : cas2,
"key3" : cas3
})
.. seealso:: :meth:`remove_multi`, :meth:`endure`
for more information on the ``persist_to`` and
``replicate_to`` options.
"""
return _Base.remove(self, key, cas=cas, quiet=quiet,
persist_to=persist_to, replicate_to=replicate_to) | [
"def",
"remove",
"(",
"self",
",",
"key",
",",
"cas",
"=",
"0",
",",
"quiet",
"=",
"None",
",",
"persist_to",
"=",
"0",
",",
"replicate_to",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"remove",
"(",
"self",
",",
"key",
",",
"cas",
"=",
"cas",
",",
"quiet",
"=",
"quiet",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
")"
] | Remove the key-value entry for a given key in Couchbase.
:param key: A string which is the key to remove. The format and
type of the key follows the same conventions as in
:meth:`upsert`
:type key: string, dict, or tuple/list
:param int cas: The CAS to use for the removal operation.
If specified, the key will only be removed from the server
if it has the same CAS as specified. This is useful to
remove a key only if its value has not been changed from the
version currently visible to the client. If the CAS on the
server does not match the one specified, an exception is
thrown.
:param boolean quiet:
Follows the same semantics as `quiet` in :meth:`get`
:param int persist_to: If set, wait for the item to be removed
from the storage of at least these many nodes
:param int replicate_to: If set, wait for the item to be removed
from the cache of at least these many nodes
(excluding the master)
:raise: :exc:`.NotFoundError` if the key does not exist.
:raise: :exc:`.KeyExistsError` if a CAS was specified, but
the CAS on the server had changed
:return: A :class:`~.Result` object.
Simple remove::
ok = cb.remove("key").success
Don't complain if key does not exist::
ok = cb.remove("key", quiet=True)
Only remove if CAS matches our version::
rv = cb.get("key")
cb.remove("key", cas=rv.cas)
Remove multiple keys::
oks = cb.remove_multi(["key1", "key2", "key3"])
Remove multiple keys with CAS::
oks = cb.remove({
"key1" : cas1,
"key2" : cas2,
"key3" : cas3
})
.. seealso:: :meth:`remove_multi`, :meth:`endure`
for more information on the ``persist_to`` and
``replicate_to`` options. | [
"Remove",
"the",
"key",
"-",
"value",
"entry",
"for",
"a",
"given",
"key",
"in",
"Couchbase",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L668-L725 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.counter | def counter(self, key, delta=1, initial=None, ttl=0):
"""Increment or decrement the numeric value of an item.
This method instructs the server to treat the item stored under
the given key as a numeric counter.
Counter operations require that the stored value
exists as a string representation of a number (e.g. ``123``). If
storing items using the :meth:`upsert` family of methods, and
using the default :const:`couchbase.FMT_JSON` then the value
will conform to this constraint.
:param string key: A key whose counter value is to be modified
:param int delta: an amount by which the key should be modified.
If the number is negative then this number will be
*subtracted* from the current value.
:param initial: The initial value for the key, if it does not
exist. If the key does not exist, this value is used, and
`delta` is ignored. If this parameter is `None` then no
initial value is used
:type initial: int or `None`
:param int ttl: The lifetime for the key, after which it will
expire
:raise: :exc:`.NotFoundError` if the key does not exist on the
bucket (and `initial` was `None`)
:raise: :exc:`.DeltaBadvalError` if the key exists, but the
existing value is not numeric
:return: A :class:`.Result` object. The current value of the
counter may be obtained by inspecting the return value's
`value` attribute.
Simple increment::
rv = cb.counter("key")
rv.value
# 42
Increment by 10::
rv = cb.counter("key", delta=10)
Decrement by 5::
rv = cb.counter("key", delta=-5)
Increment by 20, set initial value to 5 if it does not exist::
rv = cb.counter("key", delta=20, initial=5)
Increment three keys::
kv = cb.counter_multi(["foo", "bar", "baz"])
for key, result in kv.items():
print "Key %s has value %d now" % (key, result.value)
.. seealso:: :meth:`counter_multi`
"""
return _Base.counter(self, key, delta=delta, initial=initial, ttl=ttl) | python | def counter(self, key, delta=1, initial=None, ttl=0):
"""Increment or decrement the numeric value of an item.
This method instructs the server to treat the item stored under
the given key as a numeric counter.
Counter operations require that the stored value
exists as a string representation of a number (e.g. ``123``). If
storing items using the :meth:`upsert` family of methods, and
using the default :const:`couchbase.FMT_JSON` then the value
will conform to this constraint.
:param string key: A key whose counter value is to be modified
:param int delta: an amount by which the key should be modified.
If the number is negative then this number will be
*subtracted* from the current value.
:param initial: The initial value for the key, if it does not
exist. If the key does not exist, this value is used, and
`delta` is ignored. If this parameter is `None` then no
initial value is used
:type initial: int or `None`
:param int ttl: The lifetime for the key, after which it will
expire
:raise: :exc:`.NotFoundError` if the key does not exist on the
bucket (and `initial` was `None`)
:raise: :exc:`.DeltaBadvalError` if the key exists, but the
existing value is not numeric
:return: A :class:`.Result` object. The current value of the
counter may be obtained by inspecting the return value's
`value` attribute.
Simple increment::
rv = cb.counter("key")
rv.value
# 42
Increment by 10::
rv = cb.counter("key", delta=10)
Decrement by 5::
rv = cb.counter("key", delta=-5)
Increment by 20, set initial value to 5 if it does not exist::
rv = cb.counter("key", delta=20, initial=5)
Increment three keys::
kv = cb.counter_multi(["foo", "bar", "baz"])
for key, result in kv.items():
print "Key %s has value %d now" % (key, result.value)
.. seealso:: :meth:`counter_multi`
"""
return _Base.counter(self, key, delta=delta, initial=initial, ttl=ttl) | [
"def",
"counter",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"1",
",",
"initial",
"=",
"None",
",",
"ttl",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"counter",
"(",
"self",
",",
"key",
",",
"delta",
"=",
"delta",
",",
"initial",
"=",
"initial",
",",
"ttl",
"=",
"ttl",
")"
] | Increment or decrement the numeric value of an item.
This method instructs the server to treat the item stored under
the given key as a numeric counter.
Counter operations require that the stored value
exists as a string representation of a number (e.g. ``123``). If
storing items using the :meth:`upsert` family of methods, and
using the default :const:`couchbase.FMT_JSON` then the value
will conform to this constraint.
:param string key: A key whose counter value is to be modified
:param int delta: an amount by which the key should be modified.
If the number is negative then this number will be
*subtracted* from the current value.
:param initial: The initial value for the key, if it does not
exist. If the key does not exist, this value is used, and
`delta` is ignored. If this parameter is `None` then no
initial value is used
:type initial: int or `None`
:param int ttl: The lifetime for the key, after which it will
expire
:raise: :exc:`.NotFoundError` if the key does not exist on the
bucket (and `initial` was `None`)
:raise: :exc:`.DeltaBadvalError` if the key exists, but the
existing value is not numeric
:return: A :class:`.Result` object. The current value of the
counter may be obtained by inspecting the return value's
`value` attribute.
Simple increment::
rv = cb.counter("key")
rv.value
# 42
Increment by 10::
rv = cb.counter("key", delta=10)
Decrement by 5::
rv = cb.counter("key", delta=-5)
Increment by 20, set initial value to 5 if it does not exist::
rv = cb.counter("key", delta=20, initial=5)
Increment three keys::
kv = cb.counter_multi(["foo", "bar", "baz"])
for key, result in kv.items():
print "Key %s has value %d now" % (key, result.value)
.. seealso:: :meth:`counter_multi` | [
"Increment",
"or",
"decrement",
"the",
"numeric",
"value",
"of",
"an",
"item",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L727-L784 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.mutate_in | def mutate_in(self, key, *specs, **kwargs):
"""Perform multiple atomic modifications within a document.
:param key: The key of the document to modify
:param specs: A list of specs (See :mod:`.couchbase.subdocument`)
:param bool create_doc:
Whether the document should be create if it doesn't exist
:param bool insert_doc: If the document should be created anew, and the
operations performed *only* if it does not exist.
:param bool upsert_doc: If the document should be created anew if it
does not exist. If it does exist the commands are still executed.
:param kwargs: CAS, etc.
:return: A :class:`~.couchbase.result.SubdocResult` object.
Here's an example of adding a new tag to a "user" document
and incrementing a modification counter::
import couchbase.subdocument as SD
# ....
cb.mutate_in('user',
SD.array_addunique('tags', 'dog'),
SD.counter('updates', 1))
.. note::
The `insert_doc` and `upsert_doc` options are mutually exclusive.
Use `insert_doc` when you wish to create a new document with
extended attributes (xattrs).
.. seealso:: :mod:`.couchbase.subdocument`
"""
# Note we don't verify the validity of the options. lcb does that for
# us.
sdflags = kwargs.pop('_sd_doc_flags', 0)
if kwargs.pop('insert_doc', False):
sdflags |= _P.CMDSUBDOC_F_INSERT_DOC
if kwargs.pop('upsert_doc', False):
sdflags |= _P.CMDSUBDOC_F_UPSERT_DOC
kwargs['_sd_doc_flags'] = sdflags
return super(Bucket, self).mutate_in(key, specs, **kwargs) | python | def mutate_in(self, key, *specs, **kwargs):
"""Perform multiple atomic modifications within a document.
:param key: The key of the document to modify
:param specs: A list of specs (See :mod:`.couchbase.subdocument`)
:param bool create_doc:
Whether the document should be create if it doesn't exist
:param bool insert_doc: If the document should be created anew, and the
operations performed *only* if it does not exist.
:param bool upsert_doc: If the document should be created anew if it
does not exist. If it does exist the commands are still executed.
:param kwargs: CAS, etc.
:return: A :class:`~.couchbase.result.SubdocResult` object.
Here's an example of adding a new tag to a "user" document
and incrementing a modification counter::
import couchbase.subdocument as SD
# ....
cb.mutate_in('user',
SD.array_addunique('tags', 'dog'),
SD.counter('updates', 1))
.. note::
The `insert_doc` and `upsert_doc` options are mutually exclusive.
Use `insert_doc` when you wish to create a new document with
extended attributes (xattrs).
.. seealso:: :mod:`.couchbase.subdocument`
"""
# Note we don't verify the validity of the options. lcb does that for
# us.
sdflags = kwargs.pop('_sd_doc_flags', 0)
if kwargs.pop('insert_doc', False):
sdflags |= _P.CMDSUBDOC_F_INSERT_DOC
if kwargs.pop('upsert_doc', False):
sdflags |= _P.CMDSUBDOC_F_UPSERT_DOC
kwargs['_sd_doc_flags'] = sdflags
return super(Bucket, self).mutate_in(key, specs, **kwargs) | [
"def",
"mutate_in",
"(",
"self",
",",
"key",
",",
"*",
"specs",
",",
"*",
"*",
"kwargs",
")",
":",
"# Note we don't verify the validity of the options. lcb does that for",
"# us.",
"sdflags",
"=",
"kwargs",
".",
"pop",
"(",
"'_sd_doc_flags'",
",",
"0",
")",
"if",
"kwargs",
".",
"pop",
"(",
"'insert_doc'",
",",
"False",
")",
":",
"sdflags",
"|=",
"_P",
".",
"CMDSUBDOC_F_INSERT_DOC",
"if",
"kwargs",
".",
"pop",
"(",
"'upsert_doc'",
",",
"False",
")",
":",
"sdflags",
"|=",
"_P",
".",
"CMDSUBDOC_F_UPSERT_DOC",
"kwargs",
"[",
"'_sd_doc_flags'",
"]",
"=",
"sdflags",
"return",
"super",
"(",
"Bucket",
",",
"self",
")",
".",
"mutate_in",
"(",
"key",
",",
"specs",
",",
"*",
"*",
"kwargs",
")"
] | Perform multiple atomic modifications within a document.
:param key: The key of the document to modify
:param specs: A list of specs (See :mod:`.couchbase.subdocument`)
:param bool create_doc:
Whether the document should be create if it doesn't exist
:param bool insert_doc: If the document should be created anew, and the
operations performed *only* if it does not exist.
:param bool upsert_doc: If the document should be created anew if it
does not exist. If it does exist the commands are still executed.
:param kwargs: CAS, etc.
:return: A :class:`~.couchbase.result.SubdocResult` object.
Here's an example of adding a new tag to a "user" document
and incrementing a modification counter::
import couchbase.subdocument as SD
# ....
cb.mutate_in('user',
SD.array_addunique('tags', 'dog'),
SD.counter('updates', 1))
.. note::
The `insert_doc` and `upsert_doc` options are mutually exclusive.
Use `insert_doc` when you wish to create a new document with
extended attributes (xattrs).
.. seealso:: :mod:`.couchbase.subdocument` | [
"Perform",
"multiple",
"atomic",
"modifications",
"within",
"a",
"document",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L786-L828 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.lookup_in | def lookup_in(self, key, *specs, **kwargs):
"""Atomically retrieve one or more paths from a document.
:param key: The key of the document to lookup
:param spec: A list of specs (see :mod:`.couchbase.subdocument`)
:return: A :class:`.couchbase.result.SubdocResult` object.
This object contains the results and any errors of the
operation.
Example::
import couchbase.subdocument as SD
rv = cb.lookup_in('user',
SD.get('email'),
SD.get('name'),
SD.exists('friends.therock'))
email = rv[0]
name = rv[1]
friend_exists = rv.exists(2)
.. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper
"""
return super(Bucket, self).lookup_in({key: specs}, **kwargs) | python | def lookup_in(self, key, *specs, **kwargs):
"""Atomically retrieve one or more paths from a document.
:param key: The key of the document to lookup
:param spec: A list of specs (see :mod:`.couchbase.subdocument`)
:return: A :class:`.couchbase.result.SubdocResult` object.
This object contains the results and any errors of the
operation.
Example::
import couchbase.subdocument as SD
rv = cb.lookup_in('user',
SD.get('email'),
SD.get('name'),
SD.exists('friends.therock'))
email = rv[0]
name = rv[1]
friend_exists = rv.exists(2)
.. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper
"""
return super(Bucket, self).lookup_in({key: specs}, **kwargs) | [
"def",
"lookup_in",
"(",
"self",
",",
"key",
",",
"*",
"specs",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"super",
"(",
"Bucket",
",",
"self",
")",
".",
"lookup_in",
"(",
"{",
"key",
":",
"specs",
"}",
",",
"*",
"*",
"kwargs",
")"
] | Atomically retrieve one or more paths from a document.
:param key: The key of the document to lookup
:param spec: A list of specs (see :mod:`.couchbase.subdocument`)
:return: A :class:`.couchbase.result.SubdocResult` object.
This object contains the results and any errors of the
operation.
Example::
import couchbase.subdocument as SD
rv = cb.lookup_in('user',
SD.get('email'),
SD.get('name'),
SD.exists('friends.therock'))
email = rv[0]
name = rv[1]
friend_exists = rv.exists(2)
.. seealso:: :meth:`retrieve_in` which acts as a convenience wrapper | [
"Atomically",
"retrieve",
"one",
"or",
"more",
"paths",
"from",
"a",
"document",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L830-L853 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.retrieve_in | def retrieve_in(self, key, *paths, **kwargs):
"""Atomically fetch one or more paths from a document.
Convenience method for retrieval operations. This functions
identically to :meth:`lookup_in`. As such, the following two
forms are equivalent:
.. code-block:: python
import couchbase.subdocument as SD
rv = cb.lookup_in(key,
SD.get('email'),
SD.get('name'),
SD.get('friends.therock')
email, name, friend = rv
.. code-block:: python
rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock')
email, name, friend = rv
.. seealso:: :meth:`lookup_in`
"""
import couchbase.subdocument as SD
return self.lookup_in(key, *tuple(SD.get(x) for x in paths), **kwargs) | python | def retrieve_in(self, key, *paths, **kwargs):
"""Atomically fetch one or more paths from a document.
Convenience method for retrieval operations. This functions
identically to :meth:`lookup_in`. As such, the following two
forms are equivalent:
.. code-block:: python
import couchbase.subdocument as SD
rv = cb.lookup_in(key,
SD.get('email'),
SD.get('name'),
SD.get('friends.therock')
email, name, friend = rv
.. code-block:: python
rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock')
email, name, friend = rv
.. seealso:: :meth:`lookup_in`
"""
import couchbase.subdocument as SD
return self.lookup_in(key, *tuple(SD.get(x) for x in paths), **kwargs) | [
"def",
"retrieve_in",
"(",
"self",
",",
"key",
",",
"*",
"paths",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"couchbase",
".",
"subdocument",
"as",
"SD",
"return",
"self",
".",
"lookup_in",
"(",
"key",
",",
"*",
"tuple",
"(",
"SD",
".",
"get",
"(",
"x",
")",
"for",
"x",
"in",
"paths",
")",
",",
"*",
"*",
"kwargs",
")"
] | Atomically fetch one or more paths from a document.
Convenience method for retrieval operations. This functions
identically to :meth:`lookup_in`. As such, the following two
forms are equivalent:
.. code-block:: python
import couchbase.subdocument as SD
rv = cb.lookup_in(key,
SD.get('email'),
SD.get('name'),
SD.get('friends.therock')
email, name, friend = rv
.. code-block:: python
rv = cb.retrieve_in(key, 'email', 'name', 'friends.therock')
email, name, friend = rv
.. seealso:: :meth:`lookup_in` | [
"Atomically",
"fetch",
"one",
"or",
"more",
"paths",
"from",
"a",
"document",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L855-L880 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.stats | def stats(self, keys=None, keystats=False):
"""Request server statistics.
Fetches stats from each node in the cluster. Without a key
specified the server will respond with a default set of
statistical information. It returns the a `dict` with stats keys
and node-value pairs as a value.
:param keys: One or several stats to query
:type keys: string or list of string
:raise: :exc:`.CouchbaseNetworkError`
:return: `dict` where keys are stat keys and values are
host-value pairs
Find out how many items are in the bucket::
total = 0
for key, value in cb.stats()['total_items'].items():
total += value
Get memory stats (works on couchbase buckets)::
cb.stats('memory')
# {'mem_used': {...}, ...}
"""
if keys and not isinstance(keys, (tuple, list)):
keys = (keys,)
return self._stats(keys, keystats=keystats) | python | def stats(self, keys=None, keystats=False):
"""Request server statistics.
Fetches stats from each node in the cluster. Without a key
specified the server will respond with a default set of
statistical information. It returns the a `dict` with stats keys
and node-value pairs as a value.
:param keys: One or several stats to query
:type keys: string or list of string
:raise: :exc:`.CouchbaseNetworkError`
:return: `dict` where keys are stat keys and values are
host-value pairs
Find out how many items are in the bucket::
total = 0
for key, value in cb.stats()['total_items'].items():
total += value
Get memory stats (works on couchbase buckets)::
cb.stats('memory')
# {'mem_used': {...}, ...}
"""
if keys and not isinstance(keys, (tuple, list)):
keys = (keys,)
return self._stats(keys, keystats=keystats) | [
"def",
"stats",
"(",
"self",
",",
"keys",
"=",
"None",
",",
"keystats",
"=",
"False",
")",
":",
"if",
"keys",
"and",
"not",
"isinstance",
"(",
"keys",
",",
"(",
"tuple",
",",
"list",
")",
")",
":",
"keys",
"=",
"(",
"keys",
",",
")",
"return",
"self",
".",
"_stats",
"(",
"keys",
",",
"keystats",
"=",
"keystats",
")"
] | Request server statistics.
Fetches stats from each node in the cluster. Without a key
specified the server will respond with a default set of
statistical information. It returns the a `dict` with stats keys
and node-value pairs as a value.
:param keys: One or several stats to query
:type keys: string or list of string
:raise: :exc:`.CouchbaseNetworkError`
:return: `dict` where keys are stat keys and values are
host-value pairs
Find out how many items are in the bucket::
total = 0
for key, value in cb.stats()['total_items'].items():
total += value
Get memory stats (works on couchbase buckets)::
cb.stats('memory')
# {'mem_used': {...}, ...} | [
"Request",
"server",
"statistics",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L898-L925 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.observe | def observe(self, key, master_only=False):
"""Return storage information for a key.
It returns a :class:`.ValueResult` object with the ``value``
field set to a list of :class:`~.ObserveInfo` objects. Each
element in the list responds to the storage status for the key
on the given node. The length of the list (and thus the number
of :class:`~.ObserveInfo` objects) are equal to the number of
online replicas plus the master for the given key.
:param string key: The key to inspect
:param bool master_only: Whether to only retrieve information
from the master node.
.. seealso:: :ref:`observe_info`
"""
return _Base.observe(self, key, master_only=master_only) | python | def observe(self, key, master_only=False):
"""Return storage information for a key.
It returns a :class:`.ValueResult` object with the ``value``
field set to a list of :class:`~.ObserveInfo` objects. Each
element in the list responds to the storage status for the key
on the given node. The length of the list (and thus the number
of :class:`~.ObserveInfo` objects) are equal to the number of
online replicas plus the master for the given key.
:param string key: The key to inspect
:param bool master_only: Whether to only retrieve information
from the master node.
.. seealso:: :ref:`observe_info`
"""
return _Base.observe(self, key, master_only=master_only) | [
"def",
"observe",
"(",
"self",
",",
"key",
",",
"master_only",
"=",
"False",
")",
":",
"return",
"_Base",
".",
"observe",
"(",
"self",
",",
"key",
",",
"master_only",
"=",
"master_only",
")"
] | Return storage information for a key.
It returns a :class:`.ValueResult` object with the ``value``
field set to a list of :class:`~.ObserveInfo` objects. Each
element in the list responds to the storage status for the key
on the given node. The length of the list (and thus the number
of :class:`~.ObserveInfo` objects) are equal to the number of
online replicas plus the master for the given key.
:param string key: The key to inspect
:param bool master_only: Whether to only retrieve information
from the master node.
.. seealso:: :ref:`observe_info` | [
"Return",
"storage",
"information",
"for",
"a",
"key",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L977-L993 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.endure | def endure(self, key, persist_to=-1, replicate_to=-1, cas=0,
check_removed=False, timeout=5.0, interval=0.010):
"""Wait until a key has been distributed to one or more nodes
By default, when items are stored to Couchbase, the operation is
considered successful if the vBucket master (i.e. the "primary"
node) for the key has successfully stored the item in its
memory.
In most situations, this is sufficient to assume that the item
has successfully been stored. However the possibility remains
that the "master" server will go offline as soon as it sends
back the successful response and the data is lost.
The ``endure`` function allows you to provide stricter criteria
for success. The criteria may be expressed in terms of number of
nodes for which the item must exist in that node's RAM and/or on
that node's disk. Ensuring that an item exists in more than one
place is a safer way to guarantee against possible data loss.
We call these requirements `Durability Constraints`, and thus
the method is called `endure`.
:param string key: The key to endure.
:param int persist_to: The minimum number of nodes which must
contain this item on their disk before this function
returns. Ensure that you do not specify too many nodes;
otherwise this function will fail. Use the
:attr:`server_nodes` to determine how many nodes exist in
the cluster.
The maximum number of nodes an item can reside on is
currently fixed to 4 (i.e. the "master" node, and up to
three "replica" nodes). This limitation is current as of
Couchbase Server version 2.1.0.
If this parameter is set to a negative value, the maximum
number of possible nodes the key can reside on will be used.
:param int replicate_to: The minimum number of replicas which
must contain this item in their memory for this method to
succeed. As with ``persist_to``, you may specify a negative
value in which case the requirement will be set to the
maximum number possible.
:param float timeout: A timeout value in seconds before this
function fails with an exception. Typically it should take
no longer than several milliseconds on a functioning cluster
for durability requirements to be satisfied (unless
something has gone wrong).
:param float interval: The polling interval in seconds to use
for checking the key status on the respective nodes.
Internally, ``endure`` is implemented by polling each server
individually to see if the key exists on that server's disk
and memory. Once the status request is sent to all servers,
the client will check if their replies are satisfactory; if
they are then this function succeeds, otherwise the client
will wait a short amount of time and try again. This
parameter sets this "wait time".
:param bool check_removed: This flag inverts the check. Instead
of checking that a given key *exists* on the nodes, this
changes the behavior to check that the key is *removed* from
the nodes.
:param long cas: The CAS value to check against. It is possible
for an item to exist on a node but have a CAS value from a
prior operation. Passing the CAS ensures that only replies
from servers with a CAS matching this parameter are accepted.
:return: A :class:`~.OperationResult`
:raise: see :meth:`upsert` and :meth:`get` for possible errors
.. seealso:: :meth:`upsert`, :meth:`endure_multi`
"""
# We really just wrap 'endure_multi'
kv = {key: cas}
rvs = self.endure_multi(keys=kv, persist_to=persist_to,
replicate_to=replicate_to,
check_removed=check_removed, timeout=timeout,
interval=interval)
return rvs[key] | python | def endure(self, key, persist_to=-1, replicate_to=-1, cas=0,
check_removed=False, timeout=5.0, interval=0.010):
"""Wait until a key has been distributed to one or more nodes
By default, when items are stored to Couchbase, the operation is
considered successful if the vBucket master (i.e. the "primary"
node) for the key has successfully stored the item in its
memory.
In most situations, this is sufficient to assume that the item
has successfully been stored. However the possibility remains
that the "master" server will go offline as soon as it sends
back the successful response and the data is lost.
The ``endure`` function allows you to provide stricter criteria
for success. The criteria may be expressed in terms of number of
nodes for which the item must exist in that node's RAM and/or on
that node's disk. Ensuring that an item exists in more than one
place is a safer way to guarantee against possible data loss.
We call these requirements `Durability Constraints`, and thus
the method is called `endure`.
:param string key: The key to endure.
:param int persist_to: The minimum number of nodes which must
contain this item on their disk before this function
returns. Ensure that you do not specify too many nodes;
otherwise this function will fail. Use the
:attr:`server_nodes` to determine how many nodes exist in
the cluster.
The maximum number of nodes an item can reside on is
currently fixed to 4 (i.e. the "master" node, and up to
three "replica" nodes). This limitation is current as of
Couchbase Server version 2.1.0.
If this parameter is set to a negative value, the maximum
number of possible nodes the key can reside on will be used.
:param int replicate_to: The minimum number of replicas which
must contain this item in their memory for this method to
succeed. As with ``persist_to``, you may specify a negative
value in which case the requirement will be set to the
maximum number possible.
:param float timeout: A timeout value in seconds before this
function fails with an exception. Typically it should take
no longer than several milliseconds on a functioning cluster
for durability requirements to be satisfied (unless
something has gone wrong).
:param float interval: The polling interval in seconds to use
for checking the key status on the respective nodes.
Internally, ``endure`` is implemented by polling each server
individually to see if the key exists on that server's disk
and memory. Once the status request is sent to all servers,
the client will check if their replies are satisfactory; if
they are then this function succeeds, otherwise the client
will wait a short amount of time and try again. This
parameter sets this "wait time".
:param bool check_removed: This flag inverts the check. Instead
of checking that a given key *exists* on the nodes, this
changes the behavior to check that the key is *removed* from
the nodes.
:param long cas: The CAS value to check against. It is possible
for an item to exist on a node but have a CAS value from a
prior operation. Passing the CAS ensures that only replies
from servers with a CAS matching this parameter are accepted.
:return: A :class:`~.OperationResult`
:raise: see :meth:`upsert` and :meth:`get` for possible errors
.. seealso:: :meth:`upsert`, :meth:`endure_multi`
"""
# We really just wrap 'endure_multi'
kv = {key: cas}
rvs = self.endure_multi(keys=kv, persist_to=persist_to,
replicate_to=replicate_to,
check_removed=check_removed, timeout=timeout,
interval=interval)
return rvs[key] | [
"def",
"endure",
"(",
"self",
",",
"key",
",",
"persist_to",
"=",
"-",
"1",
",",
"replicate_to",
"=",
"-",
"1",
",",
"cas",
"=",
"0",
",",
"check_removed",
"=",
"False",
",",
"timeout",
"=",
"5.0",
",",
"interval",
"=",
"0.010",
")",
":",
"# We really just wrap 'endure_multi'",
"kv",
"=",
"{",
"key",
":",
"cas",
"}",
"rvs",
"=",
"self",
".",
"endure_multi",
"(",
"keys",
"=",
"kv",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
",",
"check_removed",
"=",
"check_removed",
",",
"timeout",
"=",
"timeout",
",",
"interval",
"=",
"interval",
")",
"return",
"rvs",
"[",
"key",
"]"
] | Wait until a key has been distributed to one or more nodes
By default, when items are stored to Couchbase, the operation is
considered successful if the vBucket master (i.e. the "primary"
node) for the key has successfully stored the item in its
memory.
In most situations, this is sufficient to assume that the item
has successfully been stored. However the possibility remains
that the "master" server will go offline as soon as it sends
back the successful response and the data is lost.
The ``endure`` function allows you to provide stricter criteria
for success. The criteria may be expressed in terms of number of
nodes for which the item must exist in that node's RAM and/or on
that node's disk. Ensuring that an item exists in more than one
place is a safer way to guarantee against possible data loss.
We call these requirements `Durability Constraints`, and thus
the method is called `endure`.
:param string key: The key to endure.
:param int persist_to: The minimum number of nodes which must
contain this item on their disk before this function
returns. Ensure that you do not specify too many nodes;
otherwise this function will fail. Use the
:attr:`server_nodes` to determine how many nodes exist in
the cluster.
The maximum number of nodes an item can reside on is
currently fixed to 4 (i.e. the "master" node, and up to
three "replica" nodes). This limitation is current as of
Couchbase Server version 2.1.0.
If this parameter is set to a negative value, the maximum
number of possible nodes the key can reside on will be used.
:param int replicate_to: The minimum number of replicas which
must contain this item in their memory for this method to
succeed. As with ``persist_to``, you may specify a negative
value in which case the requirement will be set to the
maximum number possible.
:param float timeout: A timeout value in seconds before this
function fails with an exception. Typically it should take
no longer than several milliseconds on a functioning cluster
for durability requirements to be satisfied (unless
something has gone wrong).
:param float interval: The polling interval in seconds to use
for checking the key status on the respective nodes.
Internally, ``endure`` is implemented by polling each server
individually to see if the key exists on that server's disk
and memory. Once the status request is sent to all servers,
the client will check if their replies are satisfactory; if
they are then this function succeeds, otherwise the client
will wait a short amount of time and try again. This
parameter sets this "wait time".
:param bool check_removed: This flag inverts the check. Instead
of checking that a given key *exists* on the nodes, this
changes the behavior to check that the key is *removed* from
the nodes.
:param long cas: The CAS value to check against. It is possible
for an item to exist on a node but have a CAS value from a
prior operation. Passing the CAS ensures that only replies
from servers with a CAS matching this parameter are accepted.
:return: A :class:`~.OperationResult`
:raise: see :meth:`upsert` and :meth:`get` for possible errors
.. seealso:: :meth:`upsert`, :meth:`endure_multi` | [
"Wait",
"until",
"a",
"key",
"has",
"been",
"distributed",
"to",
"one",
"or",
"more",
"nodes"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L995-L1077 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.endure_multi | def endure_multi(self, keys, persist_to=-1, replicate_to=-1,
timeout=5.0, interval=0.010, check_removed=False):
"""Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
* A :class:`~couchbase.result.MultiResult` object
* A ``dict`` with CAS values as the dictionary value
* A sequence of :class:`~couchbase.result.Result` objects
:return: A :class:`~.MultiResult` object
of :class:`~.OperationResult` items.
.. seealso:: :meth:`endure`
"""
return _Base.endure_multi(self, keys, persist_to=persist_to,
replicate_to=replicate_to,
timeout=timeout, interval=interval,
check_removed=check_removed) | python | def endure_multi(self, keys, persist_to=-1, replicate_to=-1,
timeout=5.0, interval=0.010, check_removed=False):
"""Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
* A :class:`~couchbase.result.MultiResult` object
* A ``dict`` with CAS values as the dictionary value
* A sequence of :class:`~couchbase.result.Result` objects
:return: A :class:`~.MultiResult` object
of :class:`~.OperationResult` items.
.. seealso:: :meth:`endure`
"""
return _Base.endure_multi(self, keys, persist_to=persist_to,
replicate_to=replicate_to,
timeout=timeout, interval=interval,
check_removed=check_removed) | [
"def",
"endure_multi",
"(",
"self",
",",
"keys",
",",
"persist_to",
"=",
"-",
"1",
",",
"replicate_to",
"=",
"-",
"1",
",",
"timeout",
"=",
"5.0",
",",
"interval",
"=",
"0.010",
",",
"check_removed",
"=",
"False",
")",
":",
"return",
"_Base",
".",
"endure_multi",
"(",
"self",
",",
"keys",
",",
"persist_to",
"=",
"persist_to",
",",
"replicate_to",
"=",
"replicate_to",
",",
"timeout",
"=",
"timeout",
",",
"interval",
"=",
"interval",
",",
"check_removed",
"=",
"check_removed",
")"
] | Check durability requirements for multiple keys
:param keys: The keys to check
The type of keys may be one of the following:
* Sequence of keys
* A :class:`~couchbase.result.MultiResult` object
* A ``dict`` with CAS values as the dictionary value
* A sequence of :class:`~couchbase.result.Result` objects
:return: A :class:`~.MultiResult` object
of :class:`~.OperationResult` items.
.. seealso:: :meth:`endure` | [
"Check",
"durability",
"requirements",
"for",
"multiple",
"keys"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1274-L1294 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.remove_multi | def remove_multi(self, kvs, quiet=None):
"""Remove multiple items from the cluster
:param kvs: Iterable of keys to delete from the cluster. If you wish
to specify a CAS for each item, then you may pass a dictionary
of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`)
:param quiet: Whether an exception should be raised if one or more
items were not found
:return: A :class:`~.MultiResult` containing :class:`~.OperationResult`
values.
"""
return _Base.remove_multi(self, kvs, quiet=quiet) | python | def remove_multi(self, kvs, quiet=None):
"""Remove multiple items from the cluster
:param kvs: Iterable of keys to delete from the cluster. If you wish
to specify a CAS for each item, then you may pass a dictionary
of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`)
:param quiet: Whether an exception should be raised if one or more
items were not found
:return: A :class:`~.MultiResult` containing :class:`~.OperationResult`
values.
"""
return _Base.remove_multi(self, kvs, quiet=quiet) | [
"def",
"remove_multi",
"(",
"self",
",",
"kvs",
",",
"quiet",
"=",
"None",
")",
":",
"return",
"_Base",
".",
"remove_multi",
"(",
"self",
",",
"kvs",
",",
"quiet",
"=",
"quiet",
")"
] | Remove multiple items from the cluster
:param kvs: Iterable of keys to delete from the cluster. If you wish
to specify a CAS for each item, then you may pass a dictionary
of keys mapping to cas, like `remove_multi({k1:cas1, k2:cas2}`)
:param quiet: Whether an exception should be raised if one or more
items were not found
:return: A :class:`~.MultiResult` containing :class:`~.OperationResult`
values. | [
"Remove",
"multiple",
"items",
"from",
"the",
"cluster"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1296-L1307 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.counter_multi | def counter_multi(self, kvs, initial=None, delta=1, ttl=0):
"""Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiration value to use for all keys
:return: A :class:`~.MultiResult` containing :class:`~.ValueResult`
values
The `kvs` can be a:
- Iterable of keys
.. code-block:: python
cb.counter_multi((k1, k2))
- A dictionary mapping a key to its delta
.. code-block:: python
cb.counter_multi({
k1: 42,
k2: 99
})
- A dictionary mapping a key to its additional options
.. code-block:: python
cb.counter_multi({
k1: {'delta': 42, 'initial': 9, 'ttl': 300},
k2: {'delta': 99, 'initial': 4, 'ttl': 700}
})
When using a dictionary, you can override settings for each key on
a per-key basis (for example, the initial value). Global settings
(global here means something passed as a parameter to the method)
will take effect for those values which do not have a given option
specified.
"""
return _Base.counter_multi(self, kvs, initial=initial, delta=delta,
ttl=ttl) | python | def counter_multi(self, kvs, initial=None, delta=1, ttl=0):
"""Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiration value to use for all keys
:return: A :class:`~.MultiResult` containing :class:`~.ValueResult`
values
The `kvs` can be a:
- Iterable of keys
.. code-block:: python
cb.counter_multi((k1, k2))
- A dictionary mapping a key to its delta
.. code-block:: python
cb.counter_multi({
k1: 42,
k2: 99
})
- A dictionary mapping a key to its additional options
.. code-block:: python
cb.counter_multi({
k1: {'delta': 42, 'initial': 9, 'ttl': 300},
k2: {'delta': 99, 'initial': 4, 'ttl': 700}
})
When using a dictionary, you can override settings for each key on
a per-key basis (for example, the initial value). Global settings
(global here means something passed as a parameter to the method)
will take effect for those values which do not have a given option
specified.
"""
return _Base.counter_multi(self, kvs, initial=initial, delta=delta,
ttl=ttl) | [
"def",
"counter_multi",
"(",
"self",
",",
"kvs",
",",
"initial",
"=",
"None",
",",
"delta",
"=",
"1",
",",
"ttl",
"=",
"0",
")",
":",
"return",
"_Base",
".",
"counter_multi",
"(",
"self",
",",
"kvs",
",",
"initial",
"=",
"initial",
",",
"delta",
"=",
"delta",
",",
"ttl",
"=",
"ttl",
")"
] | Perform counter operations on multiple items
:param kvs: Keys to operate on. See below for more options
:param initial: Initial value to use for all keys.
:param delta: Delta value for all keys.
:param ttl: Expiration value to use for all keys
:return: A :class:`~.MultiResult` containing :class:`~.ValueResult`
values
The `kvs` can be a:
- Iterable of keys
.. code-block:: python
cb.counter_multi((k1, k2))
- A dictionary mapping a key to its delta
.. code-block:: python
cb.counter_multi({
k1: 42,
k2: 99
})
- A dictionary mapping a key to its additional options
.. code-block:: python
cb.counter_multi({
k1: {'delta': 42, 'initial': 9, 'ttl': 300},
k2: {'delta': 99, 'initial': 4, 'ttl': 700}
})
When using a dictionary, you can override settings for each key on
a per-key basis (for example, the initial value). Global settings
(global here means something passed as a parameter to the method)
will take effect for those values which do not have a given option
specified. | [
"Perform",
"counter",
"operations",
"on",
"multiple",
"items"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1309-L1352 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.rget | def rget(self, key, replica_index=None, quiet=None):
"""Get an item from a replica node
:param string key: The key to fetch
:param int replica_index: The replica index to fetch.
If this is ``None`` then this method will return once any
replica responds. Use :attr:`configured_replica_count` to
figure out the upper bound for this parameter.
The value for this parameter must be a number between 0 and
the value of :attr:`configured_replica_count`-1.
:param boolean quiet: Whether to suppress errors when the key is
not found
This method (if `replica_index` is not supplied) functions like
the :meth:`get` method that has been passed the `replica`
parameter::
c.get(key, replica=True)
.. seealso:: :meth:`get` :meth:`rget_multi`
"""
if replica_index is not None:
return _Base._rgetix(self, key, replica=replica_index, quiet=quiet)
else:
return _Base._rget(self, key, quiet=quiet) | python | def rget(self, key, replica_index=None, quiet=None):
"""Get an item from a replica node
:param string key: The key to fetch
:param int replica_index: The replica index to fetch.
If this is ``None`` then this method will return once any
replica responds. Use :attr:`configured_replica_count` to
figure out the upper bound for this parameter.
The value for this parameter must be a number between 0 and
the value of :attr:`configured_replica_count`-1.
:param boolean quiet: Whether to suppress errors when the key is
not found
This method (if `replica_index` is not supplied) functions like
the :meth:`get` method that has been passed the `replica`
parameter::
c.get(key, replica=True)
.. seealso:: :meth:`get` :meth:`rget_multi`
"""
if replica_index is not None:
return _Base._rgetix(self, key, replica=replica_index, quiet=quiet)
else:
return _Base._rget(self, key, quiet=quiet) | [
"def",
"rget",
"(",
"self",
",",
"key",
",",
"replica_index",
"=",
"None",
",",
"quiet",
"=",
"None",
")",
":",
"if",
"replica_index",
"is",
"not",
"None",
":",
"return",
"_Base",
".",
"_rgetix",
"(",
"self",
",",
"key",
",",
"replica",
"=",
"replica_index",
",",
"quiet",
"=",
"quiet",
")",
"else",
":",
"return",
"_Base",
".",
"_rget",
"(",
"self",
",",
"key",
",",
"quiet",
"=",
"quiet",
")"
] | Get an item from a replica node
:param string key: The key to fetch
:param int replica_index: The replica index to fetch.
If this is ``None`` then this method will return once any
replica responds. Use :attr:`configured_replica_count` to
figure out the upper bound for this parameter.
The value for this parameter must be a number between 0 and
the value of :attr:`configured_replica_count`-1.
:param boolean quiet: Whether to suppress errors when the key is
not found
This method (if `replica_index` is not supplied) functions like
the :meth:`get` method that has been passed the `replica`
parameter::
c.get(key, replica=True)
.. seealso:: :meth:`get` :meth:`rget_multi` | [
"Get",
"an",
"item",
"from",
"a",
"replica",
"node"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1354-L1379 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.query | def query(self, design, view, use_devmode=False, **kwargs):
"""
Query a pre-defined MapReduce view, passing parameters.
This method executes a view on the cluster. It accepts various
parameters for the view and returns an iterable object
(specifically, a :class:`~.View`).
:param string design: The design document
:param string view: The view function contained within the design
document
:param boolean use_devmode: Whether the view name should be
transformed into a development-mode view. See documentation
on :meth:`~.BucketManager.design_create` for more
explanation.
:param kwargs: Extra arguments passed to the :class:`~.View`
object constructor.
:param kwargs: Additional parameters passed to the
:class:`~.View` constructor. See that class'
documentation for accepted parameters.
.. seealso::
:class:`~.View`
contains more extensive documentation and examples
:class:`couchbase.views.params.Query`
contains documentation on the available query options
:class:`~.SpatialQuery`
contains documentation on the available query options
for Geospatial views.
.. note::
To query a spatial view, you must explicitly use the
:class:`.SpatialQuery`. Passing key-value view parameters
in ``kwargs`` is not supported for spatial views.
"""
design = self._mk_devmode(design, use_devmode)
itercls = kwargs.pop('itercls', View)
return itercls(self, design, view, **kwargs) | python | def query(self, design, view, use_devmode=False, **kwargs):
"""
Query a pre-defined MapReduce view, passing parameters.
This method executes a view on the cluster. It accepts various
parameters for the view and returns an iterable object
(specifically, a :class:`~.View`).
:param string design: The design document
:param string view: The view function contained within the design
document
:param boolean use_devmode: Whether the view name should be
transformed into a development-mode view. See documentation
on :meth:`~.BucketManager.design_create` for more
explanation.
:param kwargs: Extra arguments passed to the :class:`~.View`
object constructor.
:param kwargs: Additional parameters passed to the
:class:`~.View` constructor. See that class'
documentation for accepted parameters.
.. seealso::
:class:`~.View`
contains more extensive documentation and examples
:class:`couchbase.views.params.Query`
contains documentation on the available query options
:class:`~.SpatialQuery`
contains documentation on the available query options
for Geospatial views.
.. note::
To query a spatial view, you must explicitly use the
:class:`.SpatialQuery`. Passing key-value view parameters
in ``kwargs`` is not supported for spatial views.
"""
design = self._mk_devmode(design, use_devmode)
itercls = kwargs.pop('itercls', View)
return itercls(self, design, view, **kwargs) | [
"def",
"query",
"(",
"self",
",",
"design",
",",
"view",
",",
"use_devmode",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"design",
"=",
"self",
".",
"_mk_devmode",
"(",
"design",
",",
"use_devmode",
")",
"itercls",
"=",
"kwargs",
".",
"pop",
"(",
"'itercls'",
",",
"View",
")",
"return",
"itercls",
"(",
"self",
",",
"design",
",",
"view",
",",
"*",
"*",
"kwargs",
")"
] | Query a pre-defined MapReduce view, passing parameters.
This method executes a view on the cluster. It accepts various
parameters for the view and returns an iterable object
(specifically, a :class:`~.View`).
:param string design: The design document
:param string view: The view function contained within the design
document
:param boolean use_devmode: Whether the view name should be
transformed into a development-mode view. See documentation
on :meth:`~.BucketManager.design_create` for more
explanation.
:param kwargs: Extra arguments passed to the :class:`~.View`
object constructor.
:param kwargs: Additional parameters passed to the
:class:`~.View` constructor. See that class'
documentation for accepted parameters.
.. seealso::
:class:`~.View`
contains more extensive documentation and examples
:class:`couchbase.views.params.Query`
contains documentation on the available query options
:class:`~.SpatialQuery`
contains documentation on the available query options
for Geospatial views.
.. note::
To query a spatial view, you must explicitly use the
:class:`.SpatialQuery`. Passing key-value view parameters
in ``kwargs`` is not supported for spatial views. | [
"Query",
"a",
"pre",
"-",
"defined",
"MapReduce",
"view",
"passing",
"parameters",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1435-L1477 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.n1ql_query | def n1ql_query(self, query, *args, **kwargs):
"""
Execute a N1QL query.
This method is mainly a wrapper around the :class:`~.N1QLQuery`
and :class:`~.N1QLRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.N1QLQuery`::
query = N1QLQuery(
'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno")
# Use this option for often-repeated queries
query.adhoc = False
for row in cb.n1ql_query(query):
print 'Name: {0}'.format(row['airportname'])
Using an implicit :class:`~.N1QLQuery`::
for row in cb.n1ql_query(
'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'):
print 'Name: {0}'.format(row['airportname'])
With the latter form, *args and **kwargs are forwarded to the
N1QL Request constructor, optionally selected in kwargs['iterclass'],
otherwise defaulting to :class:`~.N1QLRequest`.
:param query: The query to execute. This may either be a
:class:`.N1QLQuery` object, or a string (which will be
implicitly converted to one).
:param kwargs: Arguments for :class:`.N1QLRequest`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result
"""
if not isinstance(query, N1QLQuery):
query = N1QLQuery(query)
itercls = kwargs.pop('itercls', N1QLRequest)
return itercls(query, self, *args, **kwargs) | python | def n1ql_query(self, query, *args, **kwargs):
"""
Execute a N1QL query.
This method is mainly a wrapper around the :class:`~.N1QLQuery`
and :class:`~.N1QLRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.N1QLQuery`::
query = N1QLQuery(
'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno")
# Use this option for often-repeated queries
query.adhoc = False
for row in cb.n1ql_query(query):
print 'Name: {0}'.format(row['airportname'])
Using an implicit :class:`~.N1QLQuery`::
for row in cb.n1ql_query(
'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'):
print 'Name: {0}'.format(row['airportname'])
With the latter form, *args and **kwargs are forwarded to the
N1QL Request constructor, optionally selected in kwargs['iterclass'],
otherwise defaulting to :class:`~.N1QLRequest`.
:param query: The query to execute. This may either be a
:class:`.N1QLQuery` object, or a string (which will be
implicitly converted to one).
:param kwargs: Arguments for :class:`.N1QLRequest`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result
"""
if not isinstance(query, N1QLQuery):
query = N1QLQuery(query)
itercls = kwargs.pop('itercls', N1QLRequest)
return itercls(query, self, *args, **kwargs) | [
"def",
"n1ql_query",
"(",
"self",
",",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"query",
",",
"N1QLQuery",
")",
":",
"query",
"=",
"N1QLQuery",
"(",
"query",
")",
"itercls",
"=",
"kwargs",
".",
"pop",
"(",
"'itercls'",
",",
"N1QLRequest",
")",
"return",
"itercls",
"(",
"query",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")"
] | Execute a N1QL query.
This method is mainly a wrapper around the :class:`~.N1QLQuery`
and :class:`~.N1QLRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.N1QLQuery`::
query = N1QLQuery(
'SELECT airportname FROM `travel-sample` WHERE city=$1', "Reno")
# Use this option for often-repeated queries
query.adhoc = False
for row in cb.n1ql_query(query):
print 'Name: {0}'.format(row['airportname'])
Using an implicit :class:`~.N1QLQuery`::
for row in cb.n1ql_query(
'SELECT airportname, FROM `travel-sample` WHERE city="Reno"'):
print 'Name: {0}'.format(row['airportname'])
With the latter form, *args and **kwargs are forwarded to the
N1QL Request constructor, optionally selected in kwargs['iterclass'],
otherwise defaulting to :class:`~.N1QLRequest`.
:param query: The query to execute. This may either be a
:class:`.N1QLQuery` object, or a string (which will be
implicitly converted to one).
:param kwargs: Arguments for :class:`.N1QLRequest`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result | [
"Execute",
"a",
"N1QL",
"query",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1479-L1517 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.analytics_query | def analytics_query(self, query, host, *args, **kwargs):
"""
Execute an Analytics query.
This method is mainly a wrapper around the :class:`~.AnalyticsQuery`
and :class:`~.AnalyticsRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.AnalyticsQuery`::
query = AnalyticsQuery(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing")
for row in cb.analytics_query(query, "127.0.0.1"):
print('Entry: {0}'.format(row))
Using an implicit :class:`~.AnalyticsQuery`::
for row in cb.analytics_query(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"):
print('Entry: {0}'.format(row))
:param query: The query to execute. This may either be a
:class:`.AnalyticsQuery` object, or a string (which will be
implicitly converted to one).
:param host: The host to send the request to.
:param args: Positional arguments for :class:`.AnalyticsQuery`.
:param kwargs: Named arguments for :class:`.AnalyticsQuery`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result
"""
if not isinstance(query, AnalyticsQuery):
query = AnalyticsQuery(query, *args, **kwargs)
else:
query.update(*args, **kwargs)
return couchbase.analytics.gen_request(query, host, self) | python | def analytics_query(self, query, host, *args, **kwargs):
"""
Execute an Analytics query.
This method is mainly a wrapper around the :class:`~.AnalyticsQuery`
and :class:`~.AnalyticsRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.AnalyticsQuery`::
query = AnalyticsQuery(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing")
for row in cb.analytics_query(query, "127.0.0.1"):
print('Entry: {0}'.format(row))
Using an implicit :class:`~.AnalyticsQuery`::
for row in cb.analytics_query(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"):
print('Entry: {0}'.format(row))
:param query: The query to execute. This may either be a
:class:`.AnalyticsQuery` object, or a string (which will be
implicitly converted to one).
:param host: The host to send the request to.
:param args: Positional arguments for :class:`.AnalyticsQuery`.
:param kwargs: Named arguments for :class:`.AnalyticsQuery`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result
"""
if not isinstance(query, AnalyticsQuery):
query = AnalyticsQuery(query, *args, **kwargs)
else:
query.update(*args, **kwargs)
return couchbase.analytics.gen_request(query, host, self) | [
"def",
"analytics_query",
"(",
"self",
",",
"query",
",",
"host",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"isinstance",
"(",
"query",
",",
"AnalyticsQuery",
")",
":",
"query",
"=",
"AnalyticsQuery",
"(",
"query",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"else",
":",
"query",
".",
"update",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"couchbase",
".",
"analytics",
".",
"gen_request",
"(",
"query",
",",
"host",
",",
"self",
")"
] | Execute an Analytics query.
This method is mainly a wrapper around the :class:`~.AnalyticsQuery`
and :class:`~.AnalyticsRequest` objects, which contain the inputs
and outputs of the query.
Using an explicit :class:`~.AnalyticsQuery`::
query = AnalyticsQuery(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "Kona Brewing")
for row in cb.analytics_query(query, "127.0.0.1"):
print('Entry: {0}'.format(row))
Using an implicit :class:`~.AnalyticsQuery`::
for row in cb.analytics_query(
"SELECT VALUE bw FROM breweries bw WHERE bw.name = ?", "127.0.0.1", "Kona Brewing"):
print('Entry: {0}'.format(row))
:param query: The query to execute. This may either be a
:class:`.AnalyticsQuery` object, or a string (which will be
implicitly converted to one).
:param host: The host to send the request to.
:param args: Positional arguments for :class:`.AnalyticsQuery`.
:param kwargs: Named arguments for :class:`.AnalyticsQuery`.
:return: An iterator which yields rows. Each row is a dictionary
representing a single result | [
"Execute",
"an",
"Analytics",
"query",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1519-L1554 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.search | def search(self, index, query, **kwargs):
"""
Perform full-text searches
.. versionadded:: 2.0.9
.. warning::
The full-text search API is experimental and subject to change
:param str index: Name of the index to query
:param couchbase.fulltext.SearchQuery query: Query to issue
:param couchbase.fulltext.Params params: Additional query options
:return: An iterator over query hits
.. note:: You can avoid instantiating an explicit `Params` object
and instead pass the parameters directly to the `search` method.
.. code-block:: python
it = cb.search('name', ft.MatchQuery('nosql'), limit=10)
for hit in it:
print(hit)
"""
itercls = kwargs.pop('itercls', _FTS.SearchRequest)
iterargs = itercls.mk_kwargs(kwargs)
params = kwargs.pop('params', _FTS.Params(**kwargs))
body = _FTS.make_search_body(index, query, params)
return itercls(body, self, **iterargs) | python | def search(self, index, query, **kwargs):
"""
Perform full-text searches
.. versionadded:: 2.0.9
.. warning::
The full-text search API is experimental and subject to change
:param str index: Name of the index to query
:param couchbase.fulltext.SearchQuery query: Query to issue
:param couchbase.fulltext.Params params: Additional query options
:return: An iterator over query hits
.. note:: You can avoid instantiating an explicit `Params` object
and instead pass the parameters directly to the `search` method.
.. code-block:: python
it = cb.search('name', ft.MatchQuery('nosql'), limit=10)
for hit in it:
print(hit)
"""
itercls = kwargs.pop('itercls', _FTS.SearchRequest)
iterargs = itercls.mk_kwargs(kwargs)
params = kwargs.pop('params', _FTS.Params(**kwargs))
body = _FTS.make_search_body(index, query, params)
return itercls(body, self, **iterargs) | [
"def",
"search",
"(",
"self",
",",
"index",
",",
"query",
",",
"*",
"*",
"kwargs",
")",
":",
"itercls",
"=",
"kwargs",
".",
"pop",
"(",
"'itercls'",
",",
"_FTS",
".",
"SearchRequest",
")",
"iterargs",
"=",
"itercls",
".",
"mk_kwargs",
"(",
"kwargs",
")",
"params",
"=",
"kwargs",
".",
"pop",
"(",
"'params'",
",",
"_FTS",
".",
"Params",
"(",
"*",
"*",
"kwargs",
")",
")",
"body",
"=",
"_FTS",
".",
"make_search_body",
"(",
"index",
",",
"query",
",",
"params",
")",
"return",
"itercls",
"(",
"body",
",",
"self",
",",
"*",
"*",
"iterargs",
")"
] | Perform full-text searches
.. versionadded:: 2.0.9
.. warning::
The full-text search API is experimental and subject to change
:param str index: Name of the index to query
:param couchbase.fulltext.SearchQuery query: Query to issue
:param couchbase.fulltext.Params params: Additional query options
:return: An iterator over query hits
.. note:: You can avoid instantiating an explicit `Params` object
and instead pass the parameters directly to the `search` method.
.. code-block:: python
it = cb.search('name', ft.MatchQuery('nosql'), limit=10)
for hit in it:
print(hit) | [
"Perform",
"full",
"-",
"text",
"searches"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1559-L1588 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.is_ssl | def is_ssl(self):
"""
Read-only boolean property indicating whether SSL is used for
this connection.
If this property is true, then all communication between this
object and the Couchbase cluster is encrypted using SSL.
See :meth:`__init__` for more information on connection options.
"""
mode = self._cntl(op=_LCB.LCB_CNTL_SSL_MODE, value_type='int')
return mode & _LCB.LCB_SSL_ENABLED != 0 | python | def is_ssl(self):
"""
Read-only boolean property indicating whether SSL is used for
this connection.
If this property is true, then all communication between this
object and the Couchbase cluster is encrypted using SSL.
See :meth:`__init__` for more information on connection options.
"""
mode = self._cntl(op=_LCB.LCB_CNTL_SSL_MODE, value_type='int')
return mode & _LCB.LCB_SSL_ENABLED != 0 | [
"def",
"is_ssl",
"(",
"self",
")",
":",
"mode",
"=",
"self",
".",
"_cntl",
"(",
"op",
"=",
"_LCB",
".",
"LCB_CNTL_SSL_MODE",
",",
"value_type",
"=",
"'int'",
")",
"return",
"mode",
"&",
"_LCB",
".",
"LCB_SSL_ENABLED",
"!=",
"0"
] | Read-only boolean property indicating whether SSL is used for
this connection.
If this property is true, then all communication between this
object and the Couchbase cluster is encrypted using SSL.
See :meth:`__init__` for more information on connection options. | [
"Read",
"-",
"only",
"boolean",
"property",
"indicating",
"whether",
"SSL",
"is",
"used",
"for",
"this",
"connection",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L1740-L1751 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.flush | def flush(self):
"""
Clears the bucket's contents.
.. note::
This functionality requires that the flush option be
enabled for the bucket by the cluster administrator. You
can enable flush on the bucket using the administrative
console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html)
.. note::
This is a destructive operation, as it will clear all the
data from the bucket.
.. note::
A successful execution of this method means that the bucket
will have started the flush process. This does not
necessarily mean that the bucket is actually empty.
"""
path = '/pools/default/buckets/{0}/controller/doFlush'
path = path.format(self.bucket)
return self._http_request(type=_LCB.LCB_HTTP_TYPE_MANAGEMENT,
path=path, method=_LCB.LCB_HTTP_METHOD_POST) | python | def flush(self):
"""
Clears the bucket's contents.
.. note::
This functionality requires that the flush option be
enabled for the bucket by the cluster administrator. You
can enable flush on the bucket using the administrative
console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html)
.. note::
This is a destructive operation, as it will clear all the
data from the bucket.
.. note::
A successful execution of this method means that the bucket
will have started the flush process. This does not
necessarily mean that the bucket is actually empty.
"""
path = '/pools/default/buckets/{0}/controller/doFlush'
path = path.format(self.bucket)
return self._http_request(type=_LCB.LCB_HTTP_TYPE_MANAGEMENT,
path=path, method=_LCB.LCB_HTTP_METHOD_POST) | [
"def",
"flush",
"(",
"self",
")",
":",
"path",
"=",
"'/pools/default/buckets/{0}/controller/doFlush'",
"path",
"=",
"path",
".",
"format",
"(",
"self",
".",
"bucket",
")",
"return",
"self",
".",
"_http_request",
"(",
"type",
"=",
"_LCB",
".",
"LCB_HTTP_TYPE_MANAGEMENT",
",",
"path",
"=",
"path",
",",
"method",
"=",
"_LCB",
".",
"LCB_HTTP_METHOD_POST",
")"
] | Clears the bucket's contents.
.. note::
This functionality requires that the flush option be
enabled for the bucket by the cluster administrator. You
can enable flush on the bucket using the administrative
console (See http://docs.couchbase.com/admin/admin/UI/ui-data-buckets.html)
.. note::
This is a destructive operation, as it will clear all the
data from the bucket.
.. note::
A successful execution of this method means that the bucket
will have started the flush process. This does not
necessarily mean that the bucket is actually empty. | [
"Clears",
"the",
"bucket",
"s",
"contents",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2070-L2095 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.map_add | def map_add(self, key, mapkey, value, create=False, **kwargs):
"""
Set a value for a key in a map.
.. warning::
The functionality of the various `map_*`, `list_*`, `queue_*`
and `set_*` functions are considered experimental and are included
in the library to demonstrate new functionality.
They may change in the future or be removed entirely!
These functions are all wrappers around the :meth:`mutate_in` or
:meth:`lookup_in` methods.
:param key: The document ID of the map
:param mapkey: The key in the map to set
:param value: The value to use (anything serializable to JSON)
:param create: Whether the map should be created if it does not exist
:param kwargs: Additional arguments passed to :meth:`mutate_in`
:return: A :class:`~.OperationResult`
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified
.. Initialize a map and add a value
cb.upsert('a_map', {})
cb.map_add('a_map', 'some_key', 'some_value')
cb.map_get('a_map', 'some_key').value # => 'some_value'
cb.get('a_map').value # => {'some_key': 'some_value'}
"""
op = SD.upsert(mapkey, value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | python | def map_add(self, key, mapkey, value, create=False, **kwargs):
"""
Set a value for a key in a map.
.. warning::
The functionality of the various `map_*`, `list_*`, `queue_*`
and `set_*` functions are considered experimental and are included
in the library to demonstrate new functionality.
They may change in the future or be removed entirely!
These functions are all wrappers around the :meth:`mutate_in` or
:meth:`lookup_in` methods.
:param key: The document ID of the map
:param mapkey: The key in the map to set
:param value: The value to use (anything serializable to JSON)
:param create: Whether the map should be created if it does not exist
:param kwargs: Additional arguments passed to :meth:`mutate_in`
:return: A :class:`~.OperationResult`
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified
.. Initialize a map and add a value
cb.upsert('a_map', {})
cb.map_add('a_map', 'some_key', 'some_value')
cb.map_get('a_map', 'some_key').value # => 'some_value'
cb.get('a_map').value # => {'some_key': 'some_value'}
"""
op = SD.upsert(mapkey, value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | [
"def",
"map_add",
"(",
"self",
",",
"key",
",",
"mapkey",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"upsert",
"(",
"mapkey",
",",
"value",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")"
] | Set a value for a key in a map.
.. warning::
The functionality of the various `map_*`, `list_*`, `queue_*`
and `set_*` functions are considered experimental and are included
in the library to demonstrate new functionality.
They may change in the future or be removed entirely!
These functions are all wrappers around the :meth:`mutate_in` or
:meth:`lookup_in` methods.
:param key: The document ID of the map
:param mapkey: The key in the map to set
:param value: The value to use (anything serializable to JSON)
:param create: Whether the map should be created if it does not exist
:param kwargs: Additional arguments passed to :meth:`mutate_in`
:return: A :class:`~.OperationResult`
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified
.. Initialize a map and add a value
cb.upsert('a_map', {})
cb.map_add('a_map', 'some_key', 'some_value')
cb.map_get('a_map', 'some_key').value # => 'some_value'
cb.get('a_map').value # => {'some_key': 'some_value'} | [
"Set",
"a",
"value",
"for",
"a",
"key",
"in",
"a",
"map",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2111-L2144 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.map_get | def map_get(self, key, mapkey):
"""
Retrieve a value from a map.
:param str key: The document ID
:param str mapkey: Key within the map to retrieve
:return: :class:`~.ValueResult`
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add` for an example
"""
op = SD.get(mapkey)
sdres = self.lookup_in(key, op)
return self._wrap_dsop(sdres, True) | python | def map_get(self, key, mapkey):
"""
Retrieve a value from a map.
:param str key: The document ID
:param str mapkey: Key within the map to retrieve
:return: :class:`~.ValueResult`
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add` for an example
"""
op = SD.get(mapkey)
sdres = self.lookup_in(key, op)
return self._wrap_dsop(sdres, True) | [
"def",
"map_get",
"(",
"self",
",",
"key",
",",
"mapkey",
")",
":",
"op",
"=",
"SD",
".",
"get",
"(",
"mapkey",
")",
"sdres",
"=",
"self",
".",
"lookup_in",
"(",
"key",
",",
"op",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
",",
"True",
")"
] | Retrieve a value from a map.
:param str key: The document ID
:param str mapkey: Key within the map to retrieve
:return: :class:`~.ValueResult`
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add` for an example | [
"Retrieve",
"a",
"value",
"from",
"a",
"map",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2147-L2161 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.map_remove | def map_remove(self, key, mapkey, **kwargs):
"""
Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. Remove a map key-value pair:
cb.map_remove('a_map', 'some_key')
.. seealso:: :meth:`map_add`
"""
op = SD.remove(mapkey)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | python | def map_remove(self, key, mapkey, **kwargs):
"""
Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. Remove a map key-value pair:
cb.map_remove('a_map', 'some_key')
.. seealso:: :meth:`map_add`
"""
op = SD.remove(mapkey)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | [
"def",
"map_remove",
"(",
"self",
",",
"key",
",",
"mapkey",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"remove",
"(",
"mapkey",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")"
] | Remove an item from a map.
:param str key: The document ID
:param str mapkey: The key in the map
:param kwargs: See :meth:`mutate_in` for options
:raise: :exc:`IndexError` if the mapkey does not exist
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. Remove a map key-value pair:
cb.map_remove('a_map', 'some_key')
.. seealso:: :meth:`map_add` | [
"Remove",
"an",
"item",
"from",
"a",
"map",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2164-L2182 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.map_size | def map_size(self, key):
"""
Get the number of items in the map.
:param str key: The document ID of the map
:return int: The number of items in the map
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add`
"""
# TODO: This should use get_count, but we need to check for compat
# with server version (i.e. >= 4.6) first; otherwise it just
# disconnects.
rv = self.get(key)
return len(rv.value) | python | def map_size(self, key):
"""
Get the number of items in the map.
:param str key: The document ID of the map
:return int: The number of items in the map
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add`
"""
# TODO: This should use get_count, but we need to check for compat
# with server version (i.e. >= 4.6) first; otherwise it just
# disconnects.
rv = self.get(key)
return len(rv.value) | [
"def",
"map_size",
"(",
"self",
",",
"key",
")",
":",
"# TODO: This should use get_count, but we need to check for compat",
"# with server version (i.e. >= 4.6) first; otherwise it just",
"# disconnects.",
"rv",
"=",
"self",
".",
"get",
"(",
"key",
")",
"return",
"len",
"(",
"rv",
".",
"value",
")"
] | Get the number of items in the map.
:param str key: The document ID of the map
:return int: The number of items in the map
:raise: :cb_exc:`NotFoundError` if the document does not exist.
.. seealso:: :meth:`map_add` | [
"Get",
"the",
"number",
"of",
"items",
"in",
"the",
"map",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2185-L2200 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.list_append | def list_append(self, key, value, create=False, **kwargs):
"""
Add an item to the end of a list.
:param str key: The document ID of the list
:param value: The value to append
:param create: Whether the list should be created if it does not
exist. Note that this option only works on servers >= 4.6
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`~.OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
example::
cb.list_append('a_list', 'hello')
cb.list_append('a_list', 'world')
.. seealso:: :meth:`map_add`
"""
op = SD.array_append('', value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | python | def list_append(self, key, value, create=False, **kwargs):
"""
Add an item to the end of a list.
:param str key: The document ID of the list
:param value: The value to append
:param create: Whether the list should be created if it does not
exist. Note that this option only works on servers >= 4.6
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`~.OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
example::
cb.list_append('a_list', 'hello')
cb.list_append('a_list', 'world')
.. seealso:: :meth:`map_add`
"""
op = SD.array_append('', value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | [
"def",
"list_append",
"(",
"self",
",",
"key",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"array_append",
"(",
"''",
",",
"value",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")"
] | Add an item to the end of a list.
:param str key: The document ID of the list
:param value: The value to append
:param create: Whether the list should be created if it does not
exist. Note that this option only works on servers >= 4.6
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`~.OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
example::
cb.list_append('a_list', 'hello')
cb.list_append('a_list', 'world')
.. seealso:: :meth:`map_add` | [
"Add",
"an",
"item",
"to",
"the",
"end",
"of",
"a",
"list",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2203-L2225 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.list_prepend | def list_prepend(self, key, value, create=False, **kwargs):
"""
Add an item to the beginning of a list.
:param str key: Document ID
:param value: Value to prepend
:param bool create:
Whether the list should be created if it does not exist
:param kwargs: Additional arguments to :meth:`mutate_in`.
:return: :class:`OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
This function is identical to :meth:`list_append`, except for prepending
rather than appending the item
.. seealso:: :meth:`list_append`, :meth:`map_add`
"""
op = SD.array_prepend('', value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | python | def list_prepend(self, key, value, create=False, **kwargs):
"""
Add an item to the beginning of a list.
:param str key: Document ID
:param value: Value to prepend
:param bool create:
Whether the list should be created if it does not exist
:param kwargs: Additional arguments to :meth:`mutate_in`.
:return: :class:`OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
This function is identical to :meth:`list_append`, except for prepending
rather than appending the item
.. seealso:: :meth:`list_append`, :meth:`map_add`
"""
op = SD.array_prepend('', value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | [
"def",
"list_prepend",
"(",
"self",
",",
"key",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"array_prepend",
"(",
"''",
",",
"value",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")"
] | Add an item to the beginning of a list.
:param str key: Document ID
:param value: Value to prepend
:param bool create:
Whether the list should be created if it does not exist
:param kwargs: Additional arguments to :meth:`mutate_in`.
:return: :class:`OperationResult`.
:raise: :cb_exc:`NotFoundError` if the document does not exist.
and `create` was not specified.
This function is identical to :meth:`list_append`, except for prepending
rather than appending the item
.. seealso:: :meth:`list_append`, :meth:`map_add` | [
"Add",
"an",
"item",
"to",
"the",
"beginning",
"of",
"a",
"list",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2228-L2248 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.list_set | def list_set(self, key, index, value, **kwargs):
"""
Sets an item within a list at a given position.
:param key: The key of the document
:param index: The position to replace
:param value: The value to be inserted
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the list does not exist
:raise: :exc:`IndexError` if the index is out of bounds
example::
cb.upsert('a_list', ['hello', 'world'])
cb.list_set('a_list', 1, 'good')
cb.get('a_list').value # => ['hello', 'good']
.. seealso:: :meth:`map_add`, :meth:`list_append`
"""
op = SD.replace('[{0}]'.format(index), value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | python | def list_set(self, key, index, value, **kwargs):
"""
Sets an item within a list at a given position.
:param key: The key of the document
:param index: The position to replace
:param value: The value to be inserted
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the list does not exist
:raise: :exc:`IndexError` if the index is out of bounds
example::
cb.upsert('a_list', ['hello', 'world'])
cb.list_set('a_list', 1, 'good')
cb.get('a_list').value # => ['hello', 'good']
.. seealso:: :meth:`map_add`, :meth:`list_append`
"""
op = SD.replace('[{0}]'.format(index), value)
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres) | [
"def",
"list_set",
"(",
"self",
",",
"key",
",",
"index",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"replace",
"(",
"'[{0}]'",
".",
"format",
"(",
"index",
")",
",",
"value",
")",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")"
] | Sets an item within a list at a given position.
:param key: The key of the document
:param index: The position to replace
:param value: The value to be inserted
:param kwargs: Additional arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the list does not exist
:raise: :exc:`IndexError` if the index is out of bounds
example::
cb.upsert('a_list', ['hello', 'world'])
cb.list_set('a_list', 1, 'good')
cb.get('a_list').value # => ['hello', 'good']
.. seealso:: :meth:`map_add`, :meth:`list_append` | [
"Sets",
"an",
"item",
"within",
"a",
"list",
"at",
"a",
"given",
"position",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2251-L2273 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.set_add | def set_add(self, key, value, create=False, **kwargs):
"""
Add an item to a set if the item does not yet exist.
:param key: The document ID
:param value: Value to add
:param create: Create the set if it does not exist
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`~.OperationResult` if the item was added,
:raise: :cb_exc:`NotFoundError` if the document does not exist
and `create` was not specified.
.. seealso:: :meth:`map_add`
"""
op = SD.array_addunique('', value)
try:
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres)
except E.SubdocPathExistsError:
pass | python | def set_add(self, key, value, create=False, **kwargs):
"""
Add an item to a set if the item does not yet exist.
:param key: The document ID
:param value: Value to add
:param create: Create the set if it does not exist
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`~.OperationResult` if the item was added,
:raise: :cb_exc:`NotFoundError` if the document does not exist
and `create` was not specified.
.. seealso:: :meth:`map_add`
"""
op = SD.array_addunique('', value)
try:
sdres = self.mutate_in(key, op, **kwargs)
return self._wrap_dsop(sdres)
except E.SubdocPathExistsError:
pass | [
"def",
"set_add",
"(",
"self",
",",
"key",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"op",
"=",
"SD",
".",
"array_addunique",
"(",
"''",
",",
"value",
")",
"try",
":",
"sdres",
"=",
"self",
".",
"mutate_in",
"(",
"key",
",",
"op",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"_wrap_dsop",
"(",
"sdres",
")",
"except",
"E",
".",
"SubdocPathExistsError",
":",
"pass"
] | Add an item to a set if the item does not yet exist.
:param key: The document ID
:param value: Value to add
:param create: Create the set if it does not exist
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`~.OperationResult` if the item was added,
:raise: :cb_exc:`NotFoundError` if the document does not exist
and `create` was not specified.
.. seealso:: :meth:`map_add` | [
"Add",
"an",
"item",
"to",
"a",
"set",
"if",
"the",
"item",
"does",
"not",
"yet",
"exist",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2276-L2295 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.set_remove | def set_remove(self, key, value, **kwargs):
"""
Remove an item from a set.
:param key: The docuent ID
:param value: Value to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`OperationResult` if the item was removed, false
otherwise
:raise: :cb_exc:`NotFoundError` if the set does not exist.
.. seealso:: :meth:`set_add`, :meth:`map_add`
"""
while True:
rv = self.get(key)
try:
ix = rv.value.index(value)
kwargs['cas'] = rv.cas
return self.list_remove(key, ix, **kwargs)
except E.KeyExistsError:
pass
except ValueError:
return | python | def set_remove(self, key, value, **kwargs):
"""
Remove an item from a set.
:param key: The docuent ID
:param value: Value to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`OperationResult` if the item was removed, false
otherwise
:raise: :cb_exc:`NotFoundError` if the set does not exist.
.. seealso:: :meth:`set_add`, :meth:`map_add`
"""
while True:
rv = self.get(key)
try:
ix = rv.value.index(value)
kwargs['cas'] = rv.cas
return self.list_remove(key, ix, **kwargs)
except E.KeyExistsError:
pass
except ValueError:
return | [
"def",
"set_remove",
"(",
"self",
",",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"rv",
"=",
"self",
".",
"get",
"(",
"key",
")",
"try",
":",
"ix",
"=",
"rv",
".",
"value",
".",
"index",
"(",
"value",
")",
"kwargs",
"[",
"'cas'",
"]",
"=",
"rv",
".",
"cas",
"return",
"self",
".",
"list_remove",
"(",
"key",
",",
"ix",
",",
"*",
"*",
"kwargs",
")",
"except",
"E",
".",
"KeyExistsError",
":",
"pass",
"except",
"ValueError",
":",
"return"
] | Remove an item from a set.
:param key: The docuent ID
:param value: Value to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: A :class:`OperationResult` if the item was removed, false
otherwise
:raise: :cb_exc:`NotFoundError` if the set does not exist.
.. seealso:: :meth:`set_add`, :meth:`map_add` | [
"Remove",
"an",
"item",
"from",
"a",
"set",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2298-L2320 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.list_remove | def list_remove(self, key, index, **kwargs):
"""
Remove the element at a specific index from a list.
:param key: The document ID of the list
:param index: The index to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :exc:`IndexError` if the index does not exist
:raise: :cb_exc:`NotFoundError` if the list does not exist
"""
return self.map_remove(key, '[{0}]'.format(index), **kwargs) | python | def list_remove(self, key, index, **kwargs):
"""
Remove the element at a specific index from a list.
:param key: The document ID of the list
:param index: The index to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :exc:`IndexError` if the index does not exist
:raise: :cb_exc:`NotFoundError` if the list does not exist
"""
return self.map_remove(key, '[{0}]'.format(index), **kwargs) | [
"def",
"list_remove",
"(",
"self",
",",
"key",
",",
"index",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"map_remove",
"(",
"key",
",",
"'[{0}]'",
".",
"format",
"(",
"index",
")",
",",
"*",
"*",
"kwargs",
")"
] | Remove the element at a specific index from a list.
:param key: The document ID of the list
:param index: The index to remove
:param kwargs: Arguments to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :exc:`IndexError` if the index does not exist
:raise: :cb_exc:`NotFoundError` if the list does not exist | [
"Remove",
"the",
"element",
"at",
"a",
"specific",
"index",
"from",
"a",
"list",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2358-L2369 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.queue_push | def queue_push(self, key, value, create=False, **kwargs):
"""
Add an item to the end of a queue.
:param key: The document ID of the queue
:param value: The item to add to the queue
:param create: Whether the queue should be created if it does not exist
:param kwargs: Arguments to pass to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the queue does not exist and
`create` was not specified.
example::
# Ensure it's removed first
cb.remove('a_queue')
cb.queue_push('a_queue', 'job9999', create=True)
cb.queue_pop('a_queue').value # => job9999
"""
return self.list_prepend(key, value, **kwargs) | python | def queue_push(self, key, value, create=False, **kwargs):
"""
Add an item to the end of a queue.
:param key: The document ID of the queue
:param value: The item to add to the queue
:param create: Whether the queue should be created if it does not exist
:param kwargs: Arguments to pass to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the queue does not exist and
`create` was not specified.
example::
# Ensure it's removed first
cb.remove('a_queue')
cb.queue_push('a_queue', 'job9999', create=True)
cb.queue_pop('a_queue').value # => job9999
"""
return self.list_prepend(key, value, **kwargs) | [
"def",
"queue_push",
"(",
"self",
",",
"key",
",",
"value",
",",
"create",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"self",
".",
"list_prepend",
"(",
"key",
",",
"value",
",",
"*",
"*",
"kwargs",
")"
] | Add an item to the end of a queue.
:param key: The document ID of the queue
:param value: The item to add to the queue
:param create: Whether the queue should be created if it does not exist
:param kwargs: Arguments to pass to :meth:`mutate_in`
:return: :class:`OperationResult`
:raise: :cb_exc:`NotFoundError` if the queue does not exist and
`create` was not specified.
example::
# Ensure it's removed first
cb.remove('a_queue')
cb.queue_push('a_queue', 'job9999', create=True)
cb.queue_pop('a_queue').value # => job9999 | [
"Add",
"an",
"item",
"to",
"the",
"end",
"of",
"a",
"queue",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2383-L2403 | train |
couchbase/couchbase-python-client | couchbase/bucket.py | Bucket.queue_pop | def queue_pop(self, key, **kwargs):
"""
Remove and return the first item queue.
:param key: The document ID
:param kwargs: Arguments passed to :meth:`mutate_in`
:return: A :class:`ValueResult`
:raise: :cb_exc:`QueueEmpty` if there are no items in the queue.
:raise: :cb_exc:`NotFoundError` if the queue does not exist.
"""
while True:
try:
itm = self.list_get(key, -1)
except IndexError:
raise E.QueueEmpty
kwargs['cas'] = itm.cas
try:
self.list_remove(key, -1, **kwargs)
return itm
except E.KeyExistsError:
pass
except IndexError:
raise E.QueueEmpty | python | def queue_pop(self, key, **kwargs):
"""
Remove and return the first item queue.
:param key: The document ID
:param kwargs: Arguments passed to :meth:`mutate_in`
:return: A :class:`ValueResult`
:raise: :cb_exc:`QueueEmpty` if there are no items in the queue.
:raise: :cb_exc:`NotFoundError` if the queue does not exist.
"""
while True:
try:
itm = self.list_get(key, -1)
except IndexError:
raise E.QueueEmpty
kwargs['cas'] = itm.cas
try:
self.list_remove(key, -1, **kwargs)
return itm
except E.KeyExistsError:
pass
except IndexError:
raise E.QueueEmpty | [
"def",
"queue_pop",
"(",
"self",
",",
"key",
",",
"*",
"*",
"kwargs",
")",
":",
"while",
"True",
":",
"try",
":",
"itm",
"=",
"self",
".",
"list_get",
"(",
"key",
",",
"-",
"1",
")",
"except",
"IndexError",
":",
"raise",
"E",
".",
"QueueEmpty",
"kwargs",
"[",
"'cas'",
"]",
"=",
"itm",
".",
"cas",
"try",
":",
"self",
".",
"list_remove",
"(",
"key",
",",
"-",
"1",
",",
"*",
"*",
"kwargs",
")",
"return",
"itm",
"except",
"E",
".",
"KeyExistsError",
":",
"pass",
"except",
"IndexError",
":",
"raise",
"E",
".",
"QueueEmpty"
] | Remove and return the first item queue.
:param key: The document ID
:param kwargs: Arguments passed to :meth:`mutate_in`
:return: A :class:`ValueResult`
:raise: :cb_exc:`QueueEmpty` if there are no items in the queue.
:raise: :cb_exc:`NotFoundError` if the queue does not exist. | [
"Remove",
"and",
"return",
"the",
"first",
"item",
"queue",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucket.py#L2406-L2429 | train |
couchbase/couchbase-python-client | couchbase/asynchronous/rowsbase.py | AsyncRowsBase._callback | def _callback(self, mres):
"""
This is invoked as the row callback.
If 'rows' is true, then we are a row callback, otherwise
the request has ended and it's time to collect the other data
"""
try:
rows = self._process_payload(self.raw.rows)
if rows:
self.on_rows(rows)
if self.raw.done:
self.on_done()
finally:
if self.raw.done:
self._clear() | python | def _callback(self, mres):
"""
This is invoked as the row callback.
If 'rows' is true, then we are a row callback, otherwise
the request has ended and it's time to collect the other data
"""
try:
rows = self._process_payload(self.raw.rows)
if rows:
self.on_rows(rows)
if self.raw.done:
self.on_done()
finally:
if self.raw.done:
self._clear() | [
"def",
"_callback",
"(",
"self",
",",
"mres",
")",
":",
"try",
":",
"rows",
"=",
"self",
".",
"_process_payload",
"(",
"self",
".",
"raw",
".",
"rows",
")",
"if",
"rows",
":",
"self",
".",
"on_rows",
"(",
"rows",
")",
"if",
"self",
".",
"raw",
".",
"done",
":",
"self",
".",
"on_done",
"(",
")",
"finally",
":",
"if",
"self",
".",
"raw",
".",
"done",
":",
"self",
".",
"_clear",
"(",
")"
] | This is invoked as the row callback.
If 'rows' is true, then we are a row callback, otherwise
the request has ended and it's time to collect the other data | [
"This",
"is",
"invoked",
"as",
"the",
"row",
"callback",
".",
"If",
"rows",
"is",
"true",
"then",
"we",
"are",
"a",
"row",
"callback",
"otherwise",
"the",
"request",
"has",
"ended",
"and",
"it",
"s",
"time",
"to",
"collect",
"the",
"other",
"data"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/asynchronous/rowsbase.py#L66-L80 | train |
couchbase/couchbase-python-client | examples/item.py | Player.create | def create(cls, name, email, cb):
"""
Create the basic structure of a player
"""
it = cls(name, create_structure=True)
it.value['email'] = email
# In an actual application you'd probably want to use 'add',
# but since this app might be run multiple times, you don't
# want to get KeyExistsError
cb.upsert_multi(ItemSequence([it]))
return it | python | def create(cls, name, email, cb):
"""
Create the basic structure of a player
"""
it = cls(name, create_structure=True)
it.value['email'] = email
# In an actual application you'd probably want to use 'add',
# but since this app might be run multiple times, you don't
# want to get KeyExistsError
cb.upsert_multi(ItemSequence([it]))
return it | [
"def",
"create",
"(",
"cls",
",",
"name",
",",
"email",
",",
"cb",
")",
":",
"it",
"=",
"cls",
"(",
"name",
",",
"create_structure",
"=",
"True",
")",
"it",
".",
"value",
"[",
"'email'",
"]",
"=",
"email",
"# In an actual application you'd probably want to use 'add',",
"# but since this app might be run multiple times, you don't",
"# want to get KeyExistsError",
"cb",
".",
"upsert_multi",
"(",
"ItemSequence",
"(",
"[",
"it",
"]",
")",
")",
"return",
"it"
] | Create the basic structure of a player | [
"Create",
"the",
"basic",
"structure",
"of",
"a",
"player"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/examples/item.py#L32-L43 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager._doc_rev | def _doc_rev(self, res):
"""
Returns the rev id from the header
"""
jstr = res.headers['X-Couchbase-Meta']
jobj = json.loads(jstr)
return jobj['rev'] | python | def _doc_rev(self, res):
"""
Returns the rev id from the header
"""
jstr = res.headers['X-Couchbase-Meta']
jobj = json.loads(jstr)
return jobj['rev'] | [
"def",
"_doc_rev",
"(",
"self",
",",
"res",
")",
":",
"jstr",
"=",
"res",
".",
"headers",
"[",
"'X-Couchbase-Meta'",
"]",
"jobj",
"=",
"json",
".",
"loads",
"(",
"jstr",
")",
"return",
"jobj",
"[",
"'rev'",
"]"
] | Returns the rev id from the header | [
"Returns",
"the",
"rev",
"id",
"from",
"the",
"header"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L47-L53 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.design_create | def design_create(self, name, ddoc, use_devmode=True, syncwait=0):
"""
Store a design document
:param string name: The name of the design
:param ddoc: The actual contents of the design document
:type ddoc: string or dict
If ``ddoc`` is a string, it is passed, as-is, to the server.
Otherwise it is serialized as JSON, and its ``_id`` field is set to
``_design/{name}``.
:param bool use_devmode:
Whether a *development* mode view should be used. Development-mode
views are less resource demanding with the caveat that by default
they only operate on a subset of the data. Normally a view will
initially be created in 'development mode', and then published
using :meth:`design_publish`
:param float syncwait:
How long to poll for the action to complete. Server side design
operations are scheduled and thus this function may return before
the operation is actually completed. Specifying the timeout here
ensures the client polls during this interval to ensure the
operation has completed.
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
interval specified.
:return: An :class:`~couchbase.result.HttpResult` object.
.. seealso:: :meth:`design_get`, :meth:`design_delete`,
:meth:`design_publish`
"""
name = self._cb._mk_devmode(name, use_devmode)
fqname = "_design/{0}".format(name)
if not isinstance(ddoc, dict):
ddoc = json.loads(ddoc)
ddoc = ddoc.copy()
ddoc['_id'] = fqname
ddoc = json.dumps(ddoc)
existing = None
if syncwait:
try:
existing = self.design_get(name, use_devmode=False)
except CouchbaseError:
pass
ret = self._cb._http_request(
type=_LCB.LCB_HTTP_TYPE_VIEW, path=fqname,
method=_LCB.LCB_HTTP_METHOD_PUT, post_data=ddoc,
content_type="application/json")
self._design_poll(name, 'add', existing, syncwait,
use_devmode=use_devmode)
return ret | python | def design_create(self, name, ddoc, use_devmode=True, syncwait=0):
"""
Store a design document
:param string name: The name of the design
:param ddoc: The actual contents of the design document
:type ddoc: string or dict
If ``ddoc`` is a string, it is passed, as-is, to the server.
Otherwise it is serialized as JSON, and its ``_id`` field is set to
``_design/{name}``.
:param bool use_devmode:
Whether a *development* mode view should be used. Development-mode
views are less resource demanding with the caveat that by default
they only operate on a subset of the data. Normally a view will
initially be created in 'development mode', and then published
using :meth:`design_publish`
:param float syncwait:
How long to poll for the action to complete. Server side design
operations are scheduled and thus this function may return before
the operation is actually completed. Specifying the timeout here
ensures the client polls during this interval to ensure the
operation has completed.
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
interval specified.
:return: An :class:`~couchbase.result.HttpResult` object.
.. seealso:: :meth:`design_get`, :meth:`design_delete`,
:meth:`design_publish`
"""
name = self._cb._mk_devmode(name, use_devmode)
fqname = "_design/{0}".format(name)
if not isinstance(ddoc, dict):
ddoc = json.loads(ddoc)
ddoc = ddoc.copy()
ddoc['_id'] = fqname
ddoc = json.dumps(ddoc)
existing = None
if syncwait:
try:
existing = self.design_get(name, use_devmode=False)
except CouchbaseError:
pass
ret = self._cb._http_request(
type=_LCB.LCB_HTTP_TYPE_VIEW, path=fqname,
method=_LCB.LCB_HTTP_METHOD_PUT, post_data=ddoc,
content_type="application/json")
self._design_poll(name, 'add', existing, syncwait,
use_devmode=use_devmode)
return ret | [
"def",
"design_create",
"(",
"self",
",",
"name",
",",
"ddoc",
",",
"use_devmode",
"=",
"True",
",",
"syncwait",
"=",
"0",
")",
":",
"name",
"=",
"self",
".",
"_cb",
".",
"_mk_devmode",
"(",
"name",
",",
"use_devmode",
")",
"fqname",
"=",
"\"_design/{0}\"",
".",
"format",
"(",
"name",
")",
"if",
"not",
"isinstance",
"(",
"ddoc",
",",
"dict",
")",
":",
"ddoc",
"=",
"json",
".",
"loads",
"(",
"ddoc",
")",
"ddoc",
"=",
"ddoc",
".",
"copy",
"(",
")",
"ddoc",
"[",
"'_id'",
"]",
"=",
"fqname",
"ddoc",
"=",
"json",
".",
"dumps",
"(",
"ddoc",
")",
"existing",
"=",
"None",
"if",
"syncwait",
":",
"try",
":",
"existing",
"=",
"self",
".",
"design_get",
"(",
"name",
",",
"use_devmode",
"=",
"False",
")",
"except",
"CouchbaseError",
":",
"pass",
"ret",
"=",
"self",
".",
"_cb",
".",
"_http_request",
"(",
"type",
"=",
"_LCB",
".",
"LCB_HTTP_TYPE_VIEW",
",",
"path",
"=",
"fqname",
",",
"method",
"=",
"_LCB",
".",
"LCB_HTTP_METHOD_PUT",
",",
"post_data",
"=",
"ddoc",
",",
"content_type",
"=",
"\"application/json\"",
")",
"self",
".",
"_design_poll",
"(",
"name",
",",
"'add'",
",",
"existing",
",",
"syncwait",
",",
"use_devmode",
"=",
"use_devmode",
")",
"return",
"ret"
] | Store a design document
:param string name: The name of the design
:param ddoc: The actual contents of the design document
:type ddoc: string or dict
If ``ddoc`` is a string, it is passed, as-is, to the server.
Otherwise it is serialized as JSON, and its ``_id`` field is set to
``_design/{name}``.
:param bool use_devmode:
Whether a *development* mode view should be used. Development-mode
views are less resource demanding with the caveat that by default
they only operate on a subset of the data. Normally a view will
initially be created in 'development mode', and then published
using :meth:`design_publish`
:param float syncwait:
How long to poll for the action to complete. Server side design
operations are scheduled and thus this function may return before
the operation is actually completed. Specifying the timeout here
ensures the client polls during this interval to ensure the
operation has completed.
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
interval specified.
:return: An :class:`~couchbase.result.HttpResult` object.
.. seealso:: :meth:`design_get`, :meth:`design_delete`,
:meth:`design_publish` | [
"Store",
"a",
"design",
"document"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L130-L190 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.design_get | def design_get(self, name, use_devmode=True):
"""
Retrieve a design document
:param string name: The name of the design document
:param bool use_devmode: Whether this design document is still in
"development" mode
:return: A :class:`~couchbase.result.HttpResult` containing
a dict representing the format of the design document
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist.
.. seealso:: :meth:`design_create`, :meth:`design_list`
"""
name = self._mk_devmode(name, use_devmode)
existing = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW,
path="_design/" + name,
method=_LCB.LCB_HTTP_METHOD_GET,
content_type="application/json")
return existing | python | def design_get(self, name, use_devmode=True):
"""
Retrieve a design document
:param string name: The name of the design document
:param bool use_devmode: Whether this design document is still in
"development" mode
:return: A :class:`~couchbase.result.HttpResult` containing
a dict representing the format of the design document
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist.
.. seealso:: :meth:`design_create`, :meth:`design_list`
"""
name = self._mk_devmode(name, use_devmode)
existing = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW,
path="_design/" + name,
method=_LCB.LCB_HTTP_METHOD_GET,
content_type="application/json")
return existing | [
"def",
"design_get",
"(",
"self",
",",
"name",
",",
"use_devmode",
"=",
"True",
")",
":",
"name",
"=",
"self",
".",
"_mk_devmode",
"(",
"name",
",",
"use_devmode",
")",
"existing",
"=",
"self",
".",
"_http_request",
"(",
"type",
"=",
"_LCB",
".",
"LCB_HTTP_TYPE_VIEW",
",",
"path",
"=",
"\"_design/\"",
"+",
"name",
",",
"method",
"=",
"_LCB",
".",
"LCB_HTTP_METHOD_GET",
",",
"content_type",
"=",
"\"application/json\"",
")",
"return",
"existing"
] | Retrieve a design document
:param string name: The name of the design document
:param bool use_devmode: Whether this design document is still in
"development" mode
:return: A :class:`~couchbase.result.HttpResult` containing
a dict representing the format of the design document
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist.
.. seealso:: :meth:`design_create`, :meth:`design_list` | [
"Retrieve",
"a",
"design",
"document"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L192-L215 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.design_delete | def design_delete(self, name, use_devmode=True, syncwait=0):
"""
Delete a design document
:param string name: The name of the design document to delete
:param bool use_devmode: Whether the design to delete is a development
mode design doc.
:param float syncwait: Timeout for operation verification. See
:meth:`design_create` for more information on this parameter.
:return: An :class:`HttpResult` object.
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
specified interval.
.. seealso:: :meth:`design_create`, :meth:`design_get`
"""
name = self._mk_devmode(name, use_devmode)
existing = None
if syncwait:
try:
existing = self.design_get(name, use_devmode=False)
except CouchbaseError:
pass
ret = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW,
path="_design/" + name,
method=_LCB.LCB_HTTP_METHOD_DELETE)
self._design_poll(name, 'del', existing, syncwait)
return ret | python | def design_delete(self, name, use_devmode=True, syncwait=0):
"""
Delete a design document
:param string name: The name of the design document to delete
:param bool use_devmode: Whether the design to delete is a development
mode design doc.
:param float syncwait: Timeout for operation verification. See
:meth:`design_create` for more information on this parameter.
:return: An :class:`HttpResult` object.
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
specified interval.
.. seealso:: :meth:`design_create`, :meth:`design_get`
"""
name = self._mk_devmode(name, use_devmode)
existing = None
if syncwait:
try:
existing = self.design_get(name, use_devmode=False)
except CouchbaseError:
pass
ret = self._http_request(type=_LCB.LCB_HTTP_TYPE_VIEW,
path="_design/" + name,
method=_LCB.LCB_HTTP_METHOD_DELETE)
self._design_poll(name, 'del', existing, syncwait)
return ret | [
"def",
"design_delete",
"(",
"self",
",",
"name",
",",
"use_devmode",
"=",
"True",
",",
"syncwait",
"=",
"0",
")",
":",
"name",
"=",
"self",
".",
"_mk_devmode",
"(",
"name",
",",
"use_devmode",
")",
"existing",
"=",
"None",
"if",
"syncwait",
":",
"try",
":",
"existing",
"=",
"self",
".",
"design_get",
"(",
"name",
",",
"use_devmode",
"=",
"False",
")",
"except",
"CouchbaseError",
":",
"pass",
"ret",
"=",
"self",
".",
"_http_request",
"(",
"type",
"=",
"_LCB",
".",
"LCB_HTTP_TYPE_VIEW",
",",
"path",
"=",
"\"_design/\"",
"+",
"name",
",",
"method",
"=",
"_LCB",
".",
"LCB_HTTP_METHOD_DELETE",
")",
"self",
".",
"_design_poll",
"(",
"name",
",",
"'del'",
",",
"existing",
",",
"syncwait",
")",
"return",
"ret"
] | Delete a design document
:param string name: The name of the design document to delete
:param bool use_devmode: Whether the design to delete is a development
mode design doc.
:param float syncwait: Timeout for operation verification. See
:meth:`design_create` for more information on this parameter.
:return: An :class:`HttpResult` object.
:raise: :exc:`couchbase.exceptions.HTTPError` if the design does not
exist
:raise: :exc:`couchbase.exceptions.TimeoutError` if ``syncwait`` was
specified and the operation could not be verified within the
specified interval.
.. seealso:: :meth:`design_create`, :meth:`design_get` | [
"Delete",
"a",
"design",
"document"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L249-L284 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.design_list | def design_list(self):
"""
List all design documents for the current bucket.
:return: A :class:`~couchbase.result.HttpResult` containing
a dict, with keys being the ID of the design document.
.. note::
This information is derived using the
``pools/default/buckets/<bucket>ddocs`` endpoint, but the return
value has been modified to match that of :meth:`design_get`.
.. note::
This function returns both 'production' and 'development' mode
views. These two can be distinguished by the name of the
design document being prefixed with the ``dev_`` identifier.
The keys of the dict in ``value`` will be of the form
``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g.
``foo`` or ``dev_foo`` depending on whether ``foo`` is a
production or development mode view.
::
for name, ddoc in mgr.design_list().value.items():
if name.startswith('_design/dev_'):
print "Development view!"
else:
print "Production view!"
Example::
for name, ddoc in mgr.design_list().value.items():
print 'Design name {0}. Contents {1}'.format(name, ddoc)
.. seealso:: :meth:`design_get`
"""
ret = self._http_request(
type=_LCB.LCB_HTTP_TYPE_MANAGEMENT,
path="/pools/default/buckets/{0}/ddocs".format(self._cb.bucket),
method=_LCB.LCB_HTTP_METHOD_GET)
real_rows = {}
for r in ret.value['rows']:
real_rows[r['doc']['meta']['id']] = r['doc']['json']
# Can't use normal assignment because 'value' is read-only
ret.value.clear()
ret.value.update(real_rows)
return ret | python | def design_list(self):
"""
List all design documents for the current bucket.
:return: A :class:`~couchbase.result.HttpResult` containing
a dict, with keys being the ID of the design document.
.. note::
This information is derived using the
``pools/default/buckets/<bucket>ddocs`` endpoint, but the return
value has been modified to match that of :meth:`design_get`.
.. note::
This function returns both 'production' and 'development' mode
views. These two can be distinguished by the name of the
design document being prefixed with the ``dev_`` identifier.
The keys of the dict in ``value`` will be of the form
``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g.
``foo`` or ``dev_foo`` depending on whether ``foo`` is a
production or development mode view.
::
for name, ddoc in mgr.design_list().value.items():
if name.startswith('_design/dev_'):
print "Development view!"
else:
print "Production view!"
Example::
for name, ddoc in mgr.design_list().value.items():
print 'Design name {0}. Contents {1}'.format(name, ddoc)
.. seealso:: :meth:`design_get`
"""
ret = self._http_request(
type=_LCB.LCB_HTTP_TYPE_MANAGEMENT,
path="/pools/default/buckets/{0}/ddocs".format(self._cb.bucket),
method=_LCB.LCB_HTTP_METHOD_GET)
real_rows = {}
for r in ret.value['rows']:
real_rows[r['doc']['meta']['id']] = r['doc']['json']
# Can't use normal assignment because 'value' is read-only
ret.value.clear()
ret.value.update(real_rows)
return ret | [
"def",
"design_list",
"(",
"self",
")",
":",
"ret",
"=",
"self",
".",
"_http_request",
"(",
"type",
"=",
"_LCB",
".",
"LCB_HTTP_TYPE_MANAGEMENT",
",",
"path",
"=",
"\"/pools/default/buckets/{0}/ddocs\"",
".",
"format",
"(",
"self",
".",
"_cb",
".",
"bucket",
")",
",",
"method",
"=",
"_LCB",
".",
"LCB_HTTP_METHOD_GET",
")",
"real_rows",
"=",
"{",
"}",
"for",
"r",
"in",
"ret",
".",
"value",
"[",
"'rows'",
"]",
":",
"real_rows",
"[",
"r",
"[",
"'doc'",
"]",
"[",
"'meta'",
"]",
"[",
"'id'",
"]",
"]",
"=",
"r",
"[",
"'doc'",
"]",
"[",
"'json'",
"]",
"# Can't use normal assignment because 'value' is read-only",
"ret",
".",
"value",
".",
"clear",
"(",
")",
"ret",
".",
"value",
".",
"update",
"(",
"real_rows",
")",
"return",
"ret"
] | List all design documents for the current bucket.
:return: A :class:`~couchbase.result.HttpResult` containing
a dict, with keys being the ID of the design document.
.. note::
This information is derived using the
``pools/default/buckets/<bucket>ddocs`` endpoint, but the return
value has been modified to match that of :meth:`design_get`.
.. note::
This function returns both 'production' and 'development' mode
views. These two can be distinguished by the name of the
design document being prefixed with the ``dev_`` identifier.
The keys of the dict in ``value`` will be of the form
``_design/<VIEWNAME>`` where ``VIEWNAME`` may either be e.g.
``foo`` or ``dev_foo`` depending on whether ``foo`` is a
production or development mode view.
::
for name, ddoc in mgr.design_list().value.items():
if name.startswith('_design/dev_'):
print "Development view!"
else:
print "Production view!"
Example::
for name, ddoc in mgr.design_list().value.items():
print 'Design name {0}. Contents {1}'.format(name, ddoc)
.. seealso:: :meth:`design_get` | [
"List",
"all",
"design",
"documents",
"for",
"the",
"current",
"bucket",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L286-L338 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.n1ql_index_create | def n1ql_index_create(self, ix, **kwargs):
"""
Create an index for use with N1QL.
:param str ix: The name of the index to create
:param bool defer: Whether the building of indexes should be
deferred. If creating multiple indexes on an existing
dataset, using the `defer` option in conjunction with
:meth:`build_deferred_indexes` and :meth:`watch_indexes` may
result in substantially reduced build times.
:param bool ignore_exists: Do not throw an exception if the index
already exists.
:param list fields: A list of fields that should be supplied
as keys for the index. For non-primary indexes, this must
be specified and must contain at least one field name.
:param bool primary: Whether this is a primary index. If creating
a primary index, the name may be an empty string and `fields`
must be empty.
:param str condition: Specify a condition for indexing. Using
a condition reduces an index size
:raise: :exc:`~.KeyExistsError` if the index already exists
.. seealso:: :meth:`n1ql_index_create_primary`
"""
defer = kwargs.pop('defer', False)
ignore_exists = kwargs.pop('ignore_exists', False)
primary = kwargs.pop('primary', False)
fields = kwargs.pop('fields', [])
cond = kwargs.pop('condition', None)
if kwargs:
raise TypeError('Unknown keyword arguments', kwargs)
info = self._mk_index_def(ix, primary)
if primary and fields:
raise TypeError('Cannot create primary index with explicit fields')
elif not primary and not fields:
raise ValueError('Fields required for non-primary index')
if fields:
info.fields = fields
if primary and info.name is N1QL_PRIMARY_INDEX:
del info.name
if cond:
if primary:
raise ValueError('cannot specify condition for primary index')
info.condition = cond
options = {
'ignore_exists': ignore_exists,
'defer': defer
}
# Now actually create the indexes
return IxmgmtRequest(self._cb, 'create', info, **options).execute() | python | def n1ql_index_create(self, ix, **kwargs):
"""
Create an index for use with N1QL.
:param str ix: The name of the index to create
:param bool defer: Whether the building of indexes should be
deferred. If creating multiple indexes on an existing
dataset, using the `defer` option in conjunction with
:meth:`build_deferred_indexes` and :meth:`watch_indexes` may
result in substantially reduced build times.
:param bool ignore_exists: Do not throw an exception if the index
already exists.
:param list fields: A list of fields that should be supplied
as keys for the index. For non-primary indexes, this must
be specified and must contain at least one field name.
:param bool primary: Whether this is a primary index. If creating
a primary index, the name may be an empty string and `fields`
must be empty.
:param str condition: Specify a condition for indexing. Using
a condition reduces an index size
:raise: :exc:`~.KeyExistsError` if the index already exists
.. seealso:: :meth:`n1ql_index_create_primary`
"""
defer = kwargs.pop('defer', False)
ignore_exists = kwargs.pop('ignore_exists', False)
primary = kwargs.pop('primary', False)
fields = kwargs.pop('fields', [])
cond = kwargs.pop('condition', None)
if kwargs:
raise TypeError('Unknown keyword arguments', kwargs)
info = self._mk_index_def(ix, primary)
if primary and fields:
raise TypeError('Cannot create primary index with explicit fields')
elif not primary and not fields:
raise ValueError('Fields required for non-primary index')
if fields:
info.fields = fields
if primary and info.name is N1QL_PRIMARY_INDEX:
del info.name
if cond:
if primary:
raise ValueError('cannot specify condition for primary index')
info.condition = cond
options = {
'ignore_exists': ignore_exists,
'defer': defer
}
# Now actually create the indexes
return IxmgmtRequest(self._cb, 'create', info, **options).execute() | [
"def",
"n1ql_index_create",
"(",
"self",
",",
"ix",
",",
"*",
"*",
"kwargs",
")",
":",
"defer",
"=",
"kwargs",
".",
"pop",
"(",
"'defer'",
",",
"False",
")",
"ignore_exists",
"=",
"kwargs",
".",
"pop",
"(",
"'ignore_exists'",
",",
"False",
")",
"primary",
"=",
"kwargs",
".",
"pop",
"(",
"'primary'",
",",
"False",
")",
"fields",
"=",
"kwargs",
".",
"pop",
"(",
"'fields'",
",",
"[",
"]",
")",
"cond",
"=",
"kwargs",
".",
"pop",
"(",
"'condition'",
",",
"None",
")",
"if",
"kwargs",
":",
"raise",
"TypeError",
"(",
"'Unknown keyword arguments'",
",",
"kwargs",
")",
"info",
"=",
"self",
".",
"_mk_index_def",
"(",
"ix",
",",
"primary",
")",
"if",
"primary",
"and",
"fields",
":",
"raise",
"TypeError",
"(",
"'Cannot create primary index with explicit fields'",
")",
"elif",
"not",
"primary",
"and",
"not",
"fields",
":",
"raise",
"ValueError",
"(",
"'Fields required for non-primary index'",
")",
"if",
"fields",
":",
"info",
".",
"fields",
"=",
"fields",
"if",
"primary",
"and",
"info",
".",
"name",
"is",
"N1QL_PRIMARY_INDEX",
":",
"del",
"info",
".",
"name",
"if",
"cond",
":",
"if",
"primary",
":",
"raise",
"ValueError",
"(",
"'cannot specify condition for primary index'",
")",
"info",
".",
"condition",
"=",
"cond",
"options",
"=",
"{",
"'ignore_exists'",
":",
"ignore_exists",
",",
"'defer'",
":",
"defer",
"}",
"# Now actually create the indexes",
"return",
"IxmgmtRequest",
"(",
"self",
".",
"_cb",
",",
"'create'",
",",
"info",
",",
"*",
"*",
"options",
")",
".",
"execute",
"(",
")"
] | Create an index for use with N1QL.
:param str ix: The name of the index to create
:param bool defer: Whether the building of indexes should be
deferred. If creating multiple indexes on an existing
dataset, using the `defer` option in conjunction with
:meth:`build_deferred_indexes` and :meth:`watch_indexes` may
result in substantially reduced build times.
:param bool ignore_exists: Do not throw an exception if the index
already exists.
:param list fields: A list of fields that should be supplied
as keys for the index. For non-primary indexes, this must
be specified and must contain at least one field name.
:param bool primary: Whether this is a primary index. If creating
a primary index, the name may be an empty string and `fields`
must be empty.
:param str condition: Specify a condition for indexing. Using
a condition reduces an index size
:raise: :exc:`~.KeyExistsError` if the index already exists
.. seealso:: :meth:`n1ql_index_create_primary` | [
"Create",
"an",
"index",
"for",
"use",
"with",
"N1QL",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L355-L412 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.n1ql_index_create_primary | def n1ql_index_create_primary(self, defer=False, ignore_exists=False):
"""
Create the primary index on the bucket.
Equivalent to::
n1ql_index_create('', primary=True, **kwargs)
:param bool defer:
:param bool ignore_exists:
.. seealso:: :meth:`create_index`
"""
return self.n1ql_index_create(
'', defer=defer, primary=True, ignore_exists=ignore_exists) | python | def n1ql_index_create_primary(self, defer=False, ignore_exists=False):
"""
Create the primary index on the bucket.
Equivalent to::
n1ql_index_create('', primary=True, **kwargs)
:param bool defer:
:param bool ignore_exists:
.. seealso:: :meth:`create_index`
"""
return self.n1ql_index_create(
'', defer=defer, primary=True, ignore_exists=ignore_exists) | [
"def",
"n1ql_index_create_primary",
"(",
"self",
",",
"defer",
"=",
"False",
",",
"ignore_exists",
"=",
"False",
")",
":",
"return",
"self",
".",
"n1ql_index_create",
"(",
"''",
",",
"defer",
"=",
"defer",
",",
"primary",
"=",
"True",
",",
"ignore_exists",
"=",
"ignore_exists",
")"
] | Create the primary index on the bucket.
Equivalent to::
n1ql_index_create('', primary=True, **kwargs)
:param bool defer:
:param bool ignore_exists:
.. seealso:: :meth:`create_index` | [
"Create",
"the",
"primary",
"index",
"on",
"the",
"bucket",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L414-L428 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.n1ql_index_drop | def n1ql_index_drop(self, ix, primary=False, **kwargs):
"""
Delete an index from the cluster.
:param str ix: the name of the index
:param bool primary: if this index is a primary index
:param bool ignore_missing: Do not raise an exception if the index
does not exist
:raise: :exc:`~.NotFoundError` if the index does not exist and
`ignore_missing` was not specified
"""
info = self._mk_index_def(ix, primary)
return IxmgmtRequest(self._cb, 'drop', info, **kwargs).execute() | python | def n1ql_index_drop(self, ix, primary=False, **kwargs):
"""
Delete an index from the cluster.
:param str ix: the name of the index
:param bool primary: if this index is a primary index
:param bool ignore_missing: Do not raise an exception if the index
does not exist
:raise: :exc:`~.NotFoundError` if the index does not exist and
`ignore_missing` was not specified
"""
info = self._mk_index_def(ix, primary)
return IxmgmtRequest(self._cb, 'drop', info, **kwargs).execute() | [
"def",
"n1ql_index_drop",
"(",
"self",
",",
"ix",
",",
"primary",
"=",
"False",
",",
"*",
"*",
"kwargs",
")",
":",
"info",
"=",
"self",
".",
"_mk_index_def",
"(",
"ix",
",",
"primary",
")",
"return",
"IxmgmtRequest",
"(",
"self",
".",
"_cb",
",",
"'drop'",
",",
"info",
",",
"*",
"*",
"kwargs",
")",
".",
"execute",
"(",
")"
] | Delete an index from the cluster.
:param str ix: the name of the index
:param bool primary: if this index is a primary index
:param bool ignore_missing: Do not raise an exception if the index
does not exist
:raise: :exc:`~.NotFoundError` if the index does not exist and
`ignore_missing` was not specified | [
"Delete",
"an",
"index",
"from",
"the",
"cluster",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L430-L442 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.n1ql_index_build_deferred | def n1ql_index_build_deferred(self, other_buckets=False):
"""
Instruct the server to begin building any previously deferred index
definitions.
This method will gather a list of all pending indexes in the cluster
(including those created using the `defer` option with
:meth:`create_index`) and start building them in an efficient manner.
:param bool other_buckets: Whether to also build indexes found in
other buckets, if possible
:return: list[couchbase._ixmgmt.Index] objects. This
list contains the indexes which are being built and
may be passed to :meth:`n1ql_index_watch` to poll
their build statuses.
You can use the :meth:`n1ql_index_watch`
method to wait until all indexes have been built::
mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True)
mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True)
mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True)
indexes = mgr.n1ql_index_build_deferred()
# [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')]
mgr.n1ql_index_watch(indexes, timeout=30, interval=1)
"""
info = N1qlIndex()
if not other_buckets:
info.keyspace = self._cb.bucket
return IxmgmtRequest(self._cb, 'build', info).execute() | python | def n1ql_index_build_deferred(self, other_buckets=False):
"""
Instruct the server to begin building any previously deferred index
definitions.
This method will gather a list of all pending indexes in the cluster
(including those created using the `defer` option with
:meth:`create_index`) and start building them in an efficient manner.
:param bool other_buckets: Whether to also build indexes found in
other buckets, if possible
:return: list[couchbase._ixmgmt.Index] objects. This
list contains the indexes which are being built and
may be passed to :meth:`n1ql_index_watch` to poll
their build statuses.
You can use the :meth:`n1ql_index_watch`
method to wait until all indexes have been built::
mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True)
mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True)
mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True)
indexes = mgr.n1ql_index_build_deferred()
# [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')]
mgr.n1ql_index_watch(indexes, timeout=30, interval=1)
"""
info = N1qlIndex()
if not other_buckets:
info.keyspace = self._cb.bucket
return IxmgmtRequest(self._cb, 'build', info).execute() | [
"def",
"n1ql_index_build_deferred",
"(",
"self",
",",
"other_buckets",
"=",
"False",
")",
":",
"info",
"=",
"N1qlIndex",
"(",
")",
"if",
"not",
"other_buckets",
":",
"info",
".",
"keyspace",
"=",
"self",
".",
"_cb",
".",
"bucket",
"return",
"IxmgmtRequest",
"(",
"self",
".",
"_cb",
",",
"'build'",
",",
"info",
")",
".",
"execute",
"(",
")"
] | Instruct the server to begin building any previously deferred index
definitions.
This method will gather a list of all pending indexes in the cluster
(including those created using the `defer` option with
:meth:`create_index`) and start building them in an efficient manner.
:param bool other_buckets: Whether to also build indexes found in
other buckets, if possible
:return: list[couchbase._ixmgmt.Index] objects. This
list contains the indexes which are being built and
may be passed to :meth:`n1ql_index_watch` to poll
their build statuses.
You can use the :meth:`n1ql_index_watch`
method to wait until all indexes have been built::
mgr.n1ql_index_create('ix_fld1', fields=['field1'], defer=True)
mgr.n1ql_index_create('ix_fld2', fields['field2'], defer=True)
mgr.n1ql_index_create('ix_fld3', fields=['field3'], defer=True)
indexes = mgr.n1ql_index_build_deferred()
# [IndexInfo('field1'), IndexInfo('field2'), IndexInfo('field3')]
mgr.n1ql_index_watch(indexes, timeout=30, interval=1) | [
"Instruct",
"the",
"server",
"to",
"begin",
"building",
"any",
"previously",
"deferred",
"index",
"definitions",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L466-L497 | train |
couchbase/couchbase-python-client | couchbase/bucketmanager.py | BucketManager.n1ql_index_watch | def n1ql_index_watch(self, indexes,
timeout=30, interval=0.2, watch_primary=False):
"""
Await completion of index building
This method will wait up to `timeout` seconds for every index in
`indexes` to have been built. It will poll the cluster every
`interval` seconds.
:param list indexes: A list of indexes to check. This is returned by
:meth:`build_deferred_indexes`
:param float timeout: How long to wait for the indexes to become ready.
:param float interval: How often to poll the cluster.
:param bool watch_primary: Whether to also watch the primary index.
This parameter should only be used when manually constructing a
list of string indexes
:raise: :exc:`~.TimeoutError` if the timeout was reached before all
indexes were built
:raise: :exc:`~.NotFoundError` if one of the indexes passed no longer
exists.
"""
kwargs = {
'timeout_us': int(timeout * 1000000),
'interval_us': int(interval * 1000000)
}
ixlist = [N1qlIndex.from_any(x, self._cb.bucket) for x in indexes]
if watch_primary:
ixlist.append(
N1qlIndex.from_any(N1QL_PRIMARY_INDEX, self._cb.bucket))
return IxmgmtRequest(self._cb, 'watch', ixlist, **kwargs).execute() | python | def n1ql_index_watch(self, indexes,
timeout=30, interval=0.2, watch_primary=False):
"""
Await completion of index building
This method will wait up to `timeout` seconds for every index in
`indexes` to have been built. It will poll the cluster every
`interval` seconds.
:param list indexes: A list of indexes to check. This is returned by
:meth:`build_deferred_indexes`
:param float timeout: How long to wait for the indexes to become ready.
:param float interval: How often to poll the cluster.
:param bool watch_primary: Whether to also watch the primary index.
This parameter should only be used when manually constructing a
list of string indexes
:raise: :exc:`~.TimeoutError` if the timeout was reached before all
indexes were built
:raise: :exc:`~.NotFoundError` if one of the indexes passed no longer
exists.
"""
kwargs = {
'timeout_us': int(timeout * 1000000),
'interval_us': int(interval * 1000000)
}
ixlist = [N1qlIndex.from_any(x, self._cb.bucket) for x in indexes]
if watch_primary:
ixlist.append(
N1qlIndex.from_any(N1QL_PRIMARY_INDEX, self._cb.bucket))
return IxmgmtRequest(self._cb, 'watch', ixlist, **kwargs).execute() | [
"def",
"n1ql_index_watch",
"(",
"self",
",",
"indexes",
",",
"timeout",
"=",
"30",
",",
"interval",
"=",
"0.2",
",",
"watch_primary",
"=",
"False",
")",
":",
"kwargs",
"=",
"{",
"'timeout_us'",
":",
"int",
"(",
"timeout",
"*",
"1000000",
")",
",",
"'interval_us'",
":",
"int",
"(",
"interval",
"*",
"1000000",
")",
"}",
"ixlist",
"=",
"[",
"N1qlIndex",
".",
"from_any",
"(",
"x",
",",
"self",
".",
"_cb",
".",
"bucket",
")",
"for",
"x",
"in",
"indexes",
"]",
"if",
"watch_primary",
":",
"ixlist",
".",
"append",
"(",
"N1qlIndex",
".",
"from_any",
"(",
"N1QL_PRIMARY_INDEX",
",",
"self",
".",
"_cb",
".",
"bucket",
")",
")",
"return",
"IxmgmtRequest",
"(",
"self",
".",
"_cb",
",",
"'watch'",
",",
"ixlist",
",",
"*",
"*",
"kwargs",
")",
".",
"execute",
"(",
")"
] | Await completion of index building
This method will wait up to `timeout` seconds for every index in
`indexes` to have been built. It will poll the cluster every
`interval` seconds.
:param list indexes: A list of indexes to check. This is returned by
:meth:`build_deferred_indexes`
:param float timeout: How long to wait for the indexes to become ready.
:param float interval: How often to poll the cluster.
:param bool watch_primary: Whether to also watch the primary index.
This parameter should only be used when manually constructing a
list of string indexes
:raise: :exc:`~.TimeoutError` if the timeout was reached before all
indexes were built
:raise: :exc:`~.NotFoundError` if one of the indexes passed no longer
exists. | [
"Await",
"completion",
"of",
"index",
"building"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/bucketmanager.py#L499-L528 | train |
couchbase/couchbase-python-client | couchbase/views/params.py | QueryBase._set_range_common | def _set_range_common(self, k_sugar, k_start, k_end, value):
"""
Checks to see if the client-side convenience key is present, and if so
converts the sugar convenience key into its real server-side
equivalents.
:param string k_sugar: The client-side convenience key
:param string k_start: The server-side key specifying the beginning of
the range
:param string k_end: The server-side key specifying the end of the
range
"""
if not isinstance(value, (list, tuple, _Unspec)):
raise ArgumentError.pyexc(
"Range specification for {0} must be a list, tuple or UNSPEC"
.format(k_sugar))
if self._user_options.get(k_start, UNSPEC) is not UNSPEC or (
self._user_options.get(k_end, UNSPEC) is not UNSPEC):
raise ArgumentError.pyexc(
"Cannot specify {0} with either {1} or {2}"
.format(k_sugar, k_start, k_end))
if not value:
self._set_common(k_start, UNSPEC, set_user=False)
self._set_common(k_end, UNSPEC, set_user=False)
self._user_options[k_sugar] = UNSPEC
return
if len(value) not in (1, 2):
raise ArgumentError.pyexc("Range specification "
"must have one or two elements",
value)
value = value[::]
if len(value) == 1:
value.append(UNSPEC)
for p, ix in ((k_start, 0), (k_end, 1)):
self._set_common(p, value[ix], set_user=False)
self._user_options[k_sugar] = value | python | def _set_range_common(self, k_sugar, k_start, k_end, value):
"""
Checks to see if the client-side convenience key is present, and if so
converts the sugar convenience key into its real server-side
equivalents.
:param string k_sugar: The client-side convenience key
:param string k_start: The server-side key specifying the beginning of
the range
:param string k_end: The server-side key specifying the end of the
range
"""
if not isinstance(value, (list, tuple, _Unspec)):
raise ArgumentError.pyexc(
"Range specification for {0} must be a list, tuple or UNSPEC"
.format(k_sugar))
if self._user_options.get(k_start, UNSPEC) is not UNSPEC or (
self._user_options.get(k_end, UNSPEC) is not UNSPEC):
raise ArgumentError.pyexc(
"Cannot specify {0} with either {1} or {2}"
.format(k_sugar, k_start, k_end))
if not value:
self._set_common(k_start, UNSPEC, set_user=False)
self._set_common(k_end, UNSPEC, set_user=False)
self._user_options[k_sugar] = UNSPEC
return
if len(value) not in (1, 2):
raise ArgumentError.pyexc("Range specification "
"must have one or two elements",
value)
value = value[::]
if len(value) == 1:
value.append(UNSPEC)
for p, ix in ((k_start, 0), (k_end, 1)):
self._set_common(p, value[ix], set_user=False)
self._user_options[k_sugar] = value | [
"def",
"_set_range_common",
"(",
"self",
",",
"k_sugar",
",",
"k_start",
",",
"k_end",
",",
"value",
")",
":",
"if",
"not",
"isinstance",
"(",
"value",
",",
"(",
"list",
",",
"tuple",
",",
"_Unspec",
")",
")",
":",
"raise",
"ArgumentError",
".",
"pyexc",
"(",
"\"Range specification for {0} must be a list, tuple or UNSPEC\"",
".",
"format",
"(",
"k_sugar",
")",
")",
"if",
"self",
".",
"_user_options",
".",
"get",
"(",
"k_start",
",",
"UNSPEC",
")",
"is",
"not",
"UNSPEC",
"or",
"(",
"self",
".",
"_user_options",
".",
"get",
"(",
"k_end",
",",
"UNSPEC",
")",
"is",
"not",
"UNSPEC",
")",
":",
"raise",
"ArgumentError",
".",
"pyexc",
"(",
"\"Cannot specify {0} with either {1} or {2}\"",
".",
"format",
"(",
"k_sugar",
",",
"k_start",
",",
"k_end",
")",
")",
"if",
"not",
"value",
":",
"self",
".",
"_set_common",
"(",
"k_start",
",",
"UNSPEC",
",",
"set_user",
"=",
"False",
")",
"self",
".",
"_set_common",
"(",
"k_end",
",",
"UNSPEC",
",",
"set_user",
"=",
"False",
")",
"self",
".",
"_user_options",
"[",
"k_sugar",
"]",
"=",
"UNSPEC",
"return",
"if",
"len",
"(",
"value",
")",
"not",
"in",
"(",
"1",
",",
"2",
")",
":",
"raise",
"ArgumentError",
".",
"pyexc",
"(",
"\"Range specification \"",
"\"must have one or two elements\"",
",",
"value",
")",
"value",
"=",
"value",
"[",
":",
":",
"]",
"if",
"len",
"(",
"value",
")",
"==",
"1",
":",
"value",
".",
"append",
"(",
"UNSPEC",
")",
"for",
"p",
",",
"ix",
"in",
"(",
"(",
"k_start",
",",
"0",
")",
",",
"(",
"k_end",
",",
"1",
")",
")",
":",
"self",
".",
"_set_common",
"(",
"p",
",",
"value",
"[",
"ix",
"]",
",",
"set_user",
"=",
"False",
")",
"self",
".",
"_user_options",
"[",
"k_sugar",
"]",
"=",
"value"
] | Checks to see if the client-side convenience key is present, and if so
converts the sugar convenience key into its real server-side
equivalents.
:param string k_sugar: The client-side convenience key
:param string k_start: The server-side key specifying the beginning of
the range
:param string k_end: The server-side key specifying the end of the
range | [
"Checks",
"to",
"see",
"if",
"the",
"client",
"-",
"side",
"convenience",
"key",
"is",
"present",
"and",
"if",
"so",
"converts",
"the",
"sugar",
"convenience",
"key",
"into",
"its",
"real",
"server",
"-",
"side",
"equivalents",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L276-L319 | train |
couchbase/couchbase-python-client | couchbase/views/params.py | QueryBase.update | def update(self, copy=False, **params):
"""
Chained assignment operator.
This may be used to quickly assign extra parameters to the
:class:`Query` object.
Example::
q = Query(reduce=True, full_sec=True)
# Someplace later
v = View(design, view, query=q.update(mapkey_range=["foo"]))
Its primary use is to easily modify the query object (in-place).
:param boolean copy:
If set to true, the original object is copied before new attributes
are added to it
:param params: Extra arguments. These must be valid query options.
:return: A :class:`Query` object. If ``copy`` was set to true, this
will be a new instance, otherwise it is the same instance on which
this method was called
"""
if copy:
self = deepcopy(self)
for k, v in params.items():
if not hasattr(self, k):
if not self.unrecognized_ok:
raise ArgumentError.pyexc("Unknown option", k)
self._set_common(k, v)
else:
setattr(self, k, v)
return self | python | def update(self, copy=False, **params):
"""
Chained assignment operator.
This may be used to quickly assign extra parameters to the
:class:`Query` object.
Example::
q = Query(reduce=True, full_sec=True)
# Someplace later
v = View(design, view, query=q.update(mapkey_range=["foo"]))
Its primary use is to easily modify the query object (in-place).
:param boolean copy:
If set to true, the original object is copied before new attributes
are added to it
:param params: Extra arguments. These must be valid query options.
:return: A :class:`Query` object. If ``copy`` was set to true, this
will be a new instance, otherwise it is the same instance on which
this method was called
"""
if copy:
self = deepcopy(self)
for k, v in params.items():
if not hasattr(self, k):
if not self.unrecognized_ok:
raise ArgumentError.pyexc("Unknown option", k)
self._set_common(k, v)
else:
setattr(self, k, v)
return self | [
"def",
"update",
"(",
"self",
",",
"copy",
"=",
"False",
",",
"*",
"*",
"params",
")",
":",
"if",
"copy",
":",
"self",
"=",
"deepcopy",
"(",
"self",
")",
"for",
"k",
",",
"v",
"in",
"params",
".",
"items",
"(",
")",
":",
"if",
"not",
"hasattr",
"(",
"self",
",",
"k",
")",
":",
"if",
"not",
"self",
".",
"unrecognized_ok",
":",
"raise",
"ArgumentError",
".",
"pyexc",
"(",
"\"Unknown option\"",
",",
"k",
")",
"self",
".",
"_set_common",
"(",
"k",
",",
"v",
")",
"else",
":",
"setattr",
"(",
"self",
",",
"k",
",",
"v",
")",
"return",
"self"
] | Chained assignment operator.
This may be used to quickly assign extra parameters to the
:class:`Query` object.
Example::
q = Query(reduce=True, full_sec=True)
# Someplace later
v = View(design, view, query=q.update(mapkey_range=["foo"]))
Its primary use is to easily modify the query object (in-place).
:param boolean copy:
If set to true, the original object is copied before new attributes
are added to it
:param params: Extra arguments. These must be valid query options.
:return: A :class:`Query` object. If ``copy`` was set to true, this
will be a new instance, otherwise it is the same instance on which
this method was called | [
"Chained",
"assignment",
"operator",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L362-L401 | train |
couchbase/couchbase-python-client | couchbase/views/params.py | QueryBase.from_any | def from_any(cls, params, **ctor_opts):
"""
Creates a new Query object from input.
:param params: Parameter to convert to query
:type params: dict, string, or :class:`Query`
If ``params`` is a :class:`Query` object already, a deep copy is made
and a new :class:`Query` object is returned.
If ``params`` is a string, then a :class:`Query` object is contructed
from it. The string itself is not parsed, but rather prepended to
any additional parameters (defined via the object's methods)
with an additional ``&`` characted.
If ``params`` is a dictionary, it is passed to the :class:`Query`
constructor.
:return: a new :class:`Query` object
:raise: :exc:`ArgumentError` if the input is none of the acceptable
types mentioned above. Also raises any exceptions possibly thrown
by the constructor.
"""
if isinstance(params, cls):
return deepcopy(params)
elif isinstance(params, dict):
ctor_opts.update(**params)
if cls is QueryBase:
if ('bbox' in params or 'start_range' in params or
'end_range' in params):
return SpatialQuery(**ctor_opts)
else:
return ViewQuery(**ctor_opts)
elif isinstance(params, basestring):
ret = cls()
ret._base_str = params
return ret
else:
raise ArgumentError.pyexc("Params must be Query, dict, or string") | python | def from_any(cls, params, **ctor_opts):
"""
Creates a new Query object from input.
:param params: Parameter to convert to query
:type params: dict, string, or :class:`Query`
If ``params`` is a :class:`Query` object already, a deep copy is made
and a new :class:`Query` object is returned.
If ``params`` is a string, then a :class:`Query` object is contructed
from it. The string itself is not parsed, but rather prepended to
any additional parameters (defined via the object's methods)
with an additional ``&`` characted.
If ``params`` is a dictionary, it is passed to the :class:`Query`
constructor.
:return: a new :class:`Query` object
:raise: :exc:`ArgumentError` if the input is none of the acceptable
types mentioned above. Also raises any exceptions possibly thrown
by the constructor.
"""
if isinstance(params, cls):
return deepcopy(params)
elif isinstance(params, dict):
ctor_opts.update(**params)
if cls is QueryBase:
if ('bbox' in params or 'start_range' in params or
'end_range' in params):
return SpatialQuery(**ctor_opts)
else:
return ViewQuery(**ctor_opts)
elif isinstance(params, basestring):
ret = cls()
ret._base_str = params
return ret
else:
raise ArgumentError.pyexc("Params must be Query, dict, or string") | [
"def",
"from_any",
"(",
"cls",
",",
"params",
",",
"*",
"*",
"ctor_opts",
")",
":",
"if",
"isinstance",
"(",
"params",
",",
"cls",
")",
":",
"return",
"deepcopy",
"(",
"params",
")",
"elif",
"isinstance",
"(",
"params",
",",
"dict",
")",
":",
"ctor_opts",
".",
"update",
"(",
"*",
"*",
"params",
")",
"if",
"cls",
"is",
"QueryBase",
":",
"if",
"(",
"'bbox'",
"in",
"params",
"or",
"'start_range'",
"in",
"params",
"or",
"'end_range'",
"in",
"params",
")",
":",
"return",
"SpatialQuery",
"(",
"*",
"*",
"ctor_opts",
")",
"else",
":",
"return",
"ViewQuery",
"(",
"*",
"*",
"ctor_opts",
")",
"elif",
"isinstance",
"(",
"params",
",",
"basestring",
")",
":",
"ret",
"=",
"cls",
"(",
")",
"ret",
".",
"_base_str",
"=",
"params",
"return",
"ret",
"else",
":",
"raise",
"ArgumentError",
".",
"pyexc",
"(",
"\"Params must be Query, dict, or string\"",
")"
] | Creates a new Query object from input.
:param params: Parameter to convert to query
:type params: dict, string, or :class:`Query`
If ``params`` is a :class:`Query` object already, a deep copy is made
and a new :class:`Query` object is returned.
If ``params`` is a string, then a :class:`Query` object is contructed
from it. The string itself is not parsed, but rather prepended to
any additional parameters (defined via the object's methods)
with an additional ``&`` characted.
If ``params`` is a dictionary, it is passed to the :class:`Query`
constructor.
:return: a new :class:`Query` object
:raise: :exc:`ArgumentError` if the input is none of the acceptable
types mentioned above. Also raises any exceptions possibly thrown
by the constructor. | [
"Creates",
"a",
"new",
"Query",
"object",
"from",
"input",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L404-L446 | train |
couchbase/couchbase-python-client | couchbase/views/params.py | QueryBase.encoded | def encoded(self):
"""
Returns an encoded form of the query
"""
if not self._encoded:
self._encoded = self._encode()
if self._base_str:
return '&'.join((self._base_str, self._encoded))
else:
return self._encoded | python | def encoded(self):
"""
Returns an encoded form of the query
"""
if not self._encoded:
self._encoded = self._encode()
if self._base_str:
return '&'.join((self._base_str, self._encoded))
else:
return self._encoded | [
"def",
"encoded",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_encoded",
":",
"self",
".",
"_encoded",
"=",
"self",
".",
"_encode",
"(",
")",
"if",
"self",
".",
"_base_str",
":",
"return",
"'&'",
".",
"join",
"(",
"(",
"self",
".",
"_base_str",
",",
"self",
".",
"_encoded",
")",
")",
"else",
":",
"return",
"self",
".",
"_encoded"
] | Returns an encoded form of the query | [
"Returns",
"an",
"encoded",
"form",
"of",
"the",
"query"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/views/params.py#L475-L486 | train |
couchbase/couchbase-python-client | txcouchbase/bucket.py | RawBucket.registerDeferred | def registerDeferred(self, event, d):
"""
Register a defer to be fired at the firing of a specific event.
:param string event: Currently supported values are `connect`. Another
value may be `_dtor` which will register an event to fire when this
object has been completely destroyed.
:param event: The defered to fire when the event succeeds or failes
:type event: :class:`Deferred`
If this event has already fired, the deferred will be triggered
asynchronously.
Example::
def on_connect(*args):
print("I'm connected")
def on_connect_err(*args):
print("Connection failed")
d = Deferred()
cb.registerDeferred('connect', d)
d.addCallback(on_connect)
d.addErrback(on_connect_err)
:raise: :exc:`ValueError` if the event name is unrecognized
"""
try:
self._evq[event].schedule(d)
except KeyError:
raise ValueError("No such event type", event) | python | def registerDeferred(self, event, d):
"""
Register a defer to be fired at the firing of a specific event.
:param string event: Currently supported values are `connect`. Another
value may be `_dtor` which will register an event to fire when this
object has been completely destroyed.
:param event: The defered to fire when the event succeeds or failes
:type event: :class:`Deferred`
If this event has already fired, the deferred will be triggered
asynchronously.
Example::
def on_connect(*args):
print("I'm connected")
def on_connect_err(*args):
print("Connection failed")
d = Deferred()
cb.registerDeferred('connect', d)
d.addCallback(on_connect)
d.addErrback(on_connect_err)
:raise: :exc:`ValueError` if the event name is unrecognized
"""
try:
self._evq[event].schedule(d)
except KeyError:
raise ValueError("No such event type", event) | [
"def",
"registerDeferred",
"(",
"self",
",",
"event",
",",
"d",
")",
":",
"try",
":",
"self",
".",
"_evq",
"[",
"event",
"]",
".",
"schedule",
"(",
"d",
")",
"except",
"KeyError",
":",
"raise",
"ValueError",
"(",
"\"No such event type\"",
",",
"event",
")"
] | Register a defer to be fired at the firing of a specific event.
:param string event: Currently supported values are `connect`. Another
value may be `_dtor` which will register an event to fire when this
object has been completely destroyed.
:param event: The defered to fire when the event succeeds or failes
:type event: :class:`Deferred`
If this event has already fired, the deferred will be triggered
asynchronously.
Example::
def on_connect(*args):
print("I'm connected")
def on_connect_err(*args):
print("Connection failed")
d = Deferred()
cb.registerDeferred('connect', d)
d.addCallback(on_connect)
d.addErrback(on_connect_err)
:raise: :exc:`ValueError` if the event name is unrecognized | [
"Register",
"a",
"defer",
"to",
"be",
"fired",
"at",
"the",
"firing",
"of",
"a",
"specific",
"event",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L149-L180 | train |
couchbase/couchbase-python-client | txcouchbase/bucket.py | RawBucket.queryEx | def queryEx(self, viewcls, *args, **kwargs):
"""
Query a view, with the ``viewcls`` instance receiving events
of the query as they arrive.
:param type viewcls: A class (derived from :class:`AsyncViewBase`)
to instantiate
Other arguments are passed to the standard `query` method.
This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query`
method, except it automatically schedules operations if the connection
has not yet been negotiated.
"""
kwargs['itercls'] = viewcls
o = super(AsyncBucket, self).query(*args, **kwargs)
if not self.connected:
self.connect().addCallback(lambda x: o.start())
else:
o.start()
return o | python | def queryEx(self, viewcls, *args, **kwargs):
"""
Query a view, with the ``viewcls`` instance receiving events
of the query as they arrive.
:param type viewcls: A class (derived from :class:`AsyncViewBase`)
to instantiate
Other arguments are passed to the standard `query` method.
This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query`
method, except it automatically schedules operations if the connection
has not yet been negotiated.
"""
kwargs['itercls'] = viewcls
o = super(AsyncBucket, self).query(*args, **kwargs)
if not self.connected:
self.connect().addCallback(lambda x: o.start())
else:
o.start()
return o | [
"def",
"queryEx",
"(",
"self",
",",
"viewcls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'itercls'",
"]",
"=",
"viewcls",
"o",
"=",
"super",
"(",
"AsyncBucket",
",",
"self",
")",
".",
"query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"connect",
"(",
")",
".",
"addCallback",
"(",
"lambda",
"x",
":",
"o",
".",
"start",
"(",
")",
")",
"else",
":",
"o",
".",
"start",
"(",
")",
"return",
"o"
] | Query a view, with the ``viewcls`` instance receiving events
of the query as they arrive.
:param type viewcls: A class (derived from :class:`AsyncViewBase`)
to instantiate
Other arguments are passed to the standard `query` method.
This functions exactly like the :meth:`~couchbase.asynchronous.AsyncBucket.query`
method, except it automatically schedules operations if the connection
has not yet been negotiated. | [
"Query",
"a",
"view",
"with",
"the",
"viewcls",
"instance",
"receiving",
"events",
"of",
"the",
"query",
"as",
"they",
"arrive",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L239-L261 | train |
couchbase/couchbase-python-client | txcouchbase/bucket.py | RawBucket.n1qlQueryEx | def n1qlQueryEx(self, cls, *args, **kwargs):
"""
Execute a N1QL statement providing a custom handler for rows.
This method allows you to define your own subclass (of
:class:`~AsyncN1QLRequest`) which can handle rows as they are
received from the network.
:param cls: The subclass (not instance) to use
:param args: Positional arguments for the class constructor
:param kwargs: Keyword arguments for the class constructor
.. seealso:: :meth:`queryEx`, around which this method wraps
"""
kwargs['itercls'] = cls
o = super(AsyncBucket, self).n1ql_query(*args, **kwargs)
if not self.connected:
self.connect().addCallback(lambda x: o.start())
else:
o.start()
return o | python | def n1qlQueryEx(self, cls, *args, **kwargs):
"""
Execute a N1QL statement providing a custom handler for rows.
This method allows you to define your own subclass (of
:class:`~AsyncN1QLRequest`) which can handle rows as they are
received from the network.
:param cls: The subclass (not instance) to use
:param args: Positional arguments for the class constructor
:param kwargs: Keyword arguments for the class constructor
.. seealso:: :meth:`queryEx`, around which this method wraps
"""
kwargs['itercls'] = cls
o = super(AsyncBucket, self).n1ql_query(*args, **kwargs)
if not self.connected:
self.connect().addCallback(lambda x: o.start())
else:
o.start()
return o | [
"def",
"n1qlQueryEx",
"(",
"self",
",",
"cls",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'itercls'",
"]",
"=",
"cls",
"o",
"=",
"super",
"(",
"AsyncBucket",
",",
"self",
")",
".",
"n1ql_query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"if",
"not",
"self",
".",
"connected",
":",
"self",
".",
"connect",
"(",
")",
".",
"addCallback",
"(",
"lambda",
"x",
":",
"o",
".",
"start",
"(",
")",
")",
"else",
":",
"o",
".",
"start",
"(",
")",
"return",
"o"
] | Execute a N1QL statement providing a custom handler for rows.
This method allows you to define your own subclass (of
:class:`~AsyncN1QLRequest`) which can handle rows as they are
received from the network.
:param cls: The subclass (not instance) to use
:param args: Positional arguments for the class constructor
:param kwargs: Keyword arguments for the class constructor
.. seealso:: :meth:`queryEx`, around which this method wraps | [
"Execute",
"a",
"N1QL",
"statement",
"providing",
"a",
"custom",
"handler",
"for",
"rows",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L291-L311 | train |
couchbase/couchbase-python-client | txcouchbase/bucket.py | RawBucket.n1qlQueryAll | def n1qlQueryAll(self, *args, **kwargs):
"""
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query`
in its arguments.
Example::
def handler(req):
for row in req:
# ... handle row
d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`,
'Reno')
d.addCallback(handler)
:return: A :class:`Deferred`
.. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query`
"""
if not self.connected:
cb = lambda x: self.n1qlQueryAll(*args, **kwargs)
return self.connect().addCallback(cb)
kwargs['itercls'] = BatchedN1QLRequest
o = super(RawBucket, self).n1ql_query(*args, **kwargs)
o.start()
return o._getDeferred() | python | def n1qlQueryAll(self, *args, **kwargs):
"""
Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query`
in its arguments.
Example::
def handler(req):
for row in req:
# ... handle row
d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`,
'Reno')
d.addCallback(handler)
:return: A :class:`Deferred`
.. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query`
"""
if not self.connected:
cb = lambda x: self.n1qlQueryAll(*args, **kwargs)
return self.connect().addCallback(cb)
kwargs['itercls'] = BatchedN1QLRequest
o = super(RawBucket, self).n1ql_query(*args, **kwargs)
o.start()
return o._getDeferred() | [
"def",
"n1qlQueryAll",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"cb",
"=",
"lambda",
"x",
":",
"self",
".",
"n1qlQueryAll",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"connect",
"(",
")",
".",
"addCallback",
"(",
"cb",
")",
"kwargs",
"[",
"'itercls'",
"]",
"=",
"BatchedN1QLRequest",
"o",
"=",
"super",
"(",
"RawBucket",
",",
"self",
")",
".",
"n1ql_query",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"o",
".",
"start",
"(",
")",
"return",
"o",
".",
"_getDeferred",
"(",
")"
] | Execute a N1QL query, retrieving all rows.
This method returns a :class:`Deferred` object which is executed
with a :class:`~.N1QLRequest` object. The object may be iterated
over to yield the rows in the result set.
This method is similar to :meth:`~couchbase.bucket.Bucket.n1ql_query`
in its arguments.
Example::
def handler(req):
for row in req:
# ... handle row
d = cb.n1qlQueryAll('SELECT * from `travel-sample` WHERE city=$1`,
'Reno')
d.addCallback(handler)
:return: A :class:`Deferred`
.. seealso:: :meth:`~couchbase.bucket.Bucket.n1ql_query` | [
"Execute",
"a",
"N1QL",
"query",
"retrieving",
"all",
"rows",
"."
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L313-L345 | train |
couchbase/couchbase-python-client | txcouchbase/bucket.py | Bucket._wrap | def _wrap(self, meth, *args, **kwargs):
"""
Calls a given method with the appropriate arguments, or defers such
a call until the instance has been connected
"""
if not self.connected:
return self._connectSchedule(self._wrap, meth, *args, **kwargs)
opres = meth(self, *args, **kwargs)
return self.defer(opres) | python | def _wrap(self, meth, *args, **kwargs):
"""
Calls a given method with the appropriate arguments, or defers such
a call until the instance has been connected
"""
if not self.connected:
return self._connectSchedule(self._wrap, meth, *args, **kwargs)
opres = meth(self, *args, **kwargs)
return self.defer(opres) | [
"def",
"_wrap",
"(",
"self",
",",
"meth",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"connected",
":",
"return",
"self",
".",
"_connectSchedule",
"(",
"self",
".",
"_wrap",
",",
"meth",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"opres",
"=",
"meth",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"self",
".",
"defer",
"(",
"opres",
")"
] | Calls a given method with the appropriate arguments, or defers such
a call until the instance has been connected | [
"Calls",
"a",
"given",
"method",
"with",
"the",
"appropriate",
"arguments",
"or",
"defers",
"such",
"a",
"call",
"until",
"the",
"instance",
"has",
"been",
"connected"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/txcouchbase/bucket.py#L467-L476 | train |
couchbase/couchbase-python-client | couchbase/transcoder.py | get_decode_format | def get_decode_format(flags):
"""
Returns a tuple of format, recognized
"""
c_flags = flags & FMT_COMMON_MASK
l_flags = flags & FMT_LEGACY_MASK
if c_flags:
if c_flags not in COMMON_FORMATS:
return FMT_BYTES, False
else:
return COMMON2UNIFIED[c_flags], True
else:
if not l_flags in LEGACY_FORMATS:
return FMT_BYTES, False
else:
return LEGACY2UNIFIED[l_flags], True | python | def get_decode_format(flags):
"""
Returns a tuple of format, recognized
"""
c_flags = flags & FMT_COMMON_MASK
l_flags = flags & FMT_LEGACY_MASK
if c_flags:
if c_flags not in COMMON_FORMATS:
return FMT_BYTES, False
else:
return COMMON2UNIFIED[c_flags], True
else:
if not l_flags in LEGACY_FORMATS:
return FMT_BYTES, False
else:
return LEGACY2UNIFIED[l_flags], True | [
"def",
"get_decode_format",
"(",
"flags",
")",
":",
"c_flags",
"=",
"flags",
"&",
"FMT_COMMON_MASK",
"l_flags",
"=",
"flags",
"&",
"FMT_LEGACY_MASK",
"if",
"c_flags",
":",
"if",
"c_flags",
"not",
"in",
"COMMON_FORMATS",
":",
"return",
"FMT_BYTES",
",",
"False",
"else",
":",
"return",
"COMMON2UNIFIED",
"[",
"c_flags",
"]",
",",
"True",
"else",
":",
"if",
"not",
"l_flags",
"in",
"LEGACY_FORMATS",
":",
"return",
"FMT_BYTES",
",",
"False",
"else",
":",
"return",
"LEGACY2UNIFIED",
"[",
"l_flags",
"]",
",",
"True"
] | Returns a tuple of format, recognized | [
"Returns",
"a",
"tuple",
"of",
"format",
"recognized"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/transcoder.py#L43-L59 | train |
couchbase/couchbase-python-client | couchbase/admin.py | Admin.bucket_create | def bucket_create(self, name, bucket_type='couchbase',
bucket_password='', replicas=0, ram_quota=1024,
flush_enabled=False):
"""
Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bucket to create. This
can either be `couchbase` to create a couchbase style
bucket (which persists data and supports replication) or
`memcached` (which is memory-only and does not support
replication).
Since Couchbase version 5.0, you can also specify
`ephemeral`, which is a replicated bucket which does
not have strict disk persistence requirements
:param string bucket_password: The bucket password. This can be
empty to disable authentication. This can be changed later on
using :meth:`bucket_update`
:param int replicas: The number of replicas to use for this
bucket. The maximum number of replicas is currently 3.
This setting can be changed via :meth:`bucket_update`
:param int ram_quota:
The maximum amount of memory (per node) that this bucket
may use, in megabytes. The minimum for this value is 100.
This setting may be changed via :meth:`bucket_update`.
:param bool flush_enabled:
Whether the flush API is enabled. When the flush API is
enabled, any client connected to the bucket is able to
clear its contents. This may be useful in development but
not recommended in production. This setting may be changed
via :meth:`bucket_update`
:return: A :class:`~.HttpResult`
:raise: :exc:`~.HTTPError` if the bucket could not be created.
"""
params = {
'name': name,
'bucketType': bucket_type,
'authType': 'sasl',
'saslPassword': bucket_password if bucket_password else '',
'flushEnabled': int(flush_enabled),
'ramQuotaMB': ram_quota
}
if bucket_type in ('couchbase', 'membase', 'ephemeral'):
params['replicaNumber'] = replicas
return self.http_request(
path='/pools/default/buckets', method='POST',
content=self._mk_formstr(params),
content_type='application/x-www-form-urlencoded') | python | def bucket_create(self, name, bucket_type='couchbase',
bucket_password='', replicas=0, ram_quota=1024,
flush_enabled=False):
"""
Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bucket to create. This
can either be `couchbase` to create a couchbase style
bucket (which persists data and supports replication) or
`memcached` (which is memory-only and does not support
replication).
Since Couchbase version 5.0, you can also specify
`ephemeral`, which is a replicated bucket which does
not have strict disk persistence requirements
:param string bucket_password: The bucket password. This can be
empty to disable authentication. This can be changed later on
using :meth:`bucket_update`
:param int replicas: The number of replicas to use for this
bucket. The maximum number of replicas is currently 3.
This setting can be changed via :meth:`bucket_update`
:param int ram_quota:
The maximum amount of memory (per node) that this bucket
may use, in megabytes. The minimum for this value is 100.
This setting may be changed via :meth:`bucket_update`.
:param bool flush_enabled:
Whether the flush API is enabled. When the flush API is
enabled, any client connected to the bucket is able to
clear its contents. This may be useful in development but
not recommended in production. This setting may be changed
via :meth:`bucket_update`
:return: A :class:`~.HttpResult`
:raise: :exc:`~.HTTPError` if the bucket could not be created.
"""
params = {
'name': name,
'bucketType': bucket_type,
'authType': 'sasl',
'saslPassword': bucket_password if bucket_password else '',
'flushEnabled': int(flush_enabled),
'ramQuotaMB': ram_quota
}
if bucket_type in ('couchbase', 'membase', 'ephemeral'):
params['replicaNumber'] = replicas
return self.http_request(
path='/pools/default/buckets', method='POST',
content=self._mk_formstr(params),
content_type='application/x-www-form-urlencoded') | [
"def",
"bucket_create",
"(",
"self",
",",
"name",
",",
"bucket_type",
"=",
"'couchbase'",
",",
"bucket_password",
"=",
"''",
",",
"replicas",
"=",
"0",
",",
"ram_quota",
"=",
"1024",
",",
"flush_enabled",
"=",
"False",
")",
":",
"params",
"=",
"{",
"'name'",
":",
"name",
",",
"'bucketType'",
":",
"bucket_type",
",",
"'authType'",
":",
"'sasl'",
",",
"'saslPassword'",
":",
"bucket_password",
"if",
"bucket_password",
"else",
"''",
",",
"'flushEnabled'",
":",
"int",
"(",
"flush_enabled",
")",
",",
"'ramQuotaMB'",
":",
"ram_quota",
"}",
"if",
"bucket_type",
"in",
"(",
"'couchbase'",
",",
"'membase'",
",",
"'ephemeral'",
")",
":",
"params",
"[",
"'replicaNumber'",
"]",
"=",
"replicas",
"return",
"self",
".",
"http_request",
"(",
"path",
"=",
"'/pools/default/buckets'",
",",
"method",
"=",
"'POST'",
",",
"content",
"=",
"self",
".",
"_mk_formstr",
"(",
"params",
")",
",",
"content_type",
"=",
"'application/x-www-form-urlencoded'",
")"
] | Create a new bucket
:param string name: The name of the bucket to create
:param string bucket_type: The type of bucket to create. This
can either be `couchbase` to create a couchbase style
bucket (which persists data and supports replication) or
`memcached` (which is memory-only and does not support
replication).
Since Couchbase version 5.0, you can also specify
`ephemeral`, which is a replicated bucket which does
not have strict disk persistence requirements
:param string bucket_password: The bucket password. This can be
empty to disable authentication. This can be changed later on
using :meth:`bucket_update`
:param int replicas: The number of replicas to use for this
bucket. The maximum number of replicas is currently 3.
This setting can be changed via :meth:`bucket_update`
:param int ram_quota:
The maximum amount of memory (per node) that this bucket
may use, in megabytes. The minimum for this value is 100.
This setting may be changed via :meth:`bucket_update`.
:param bool flush_enabled:
Whether the flush API is enabled. When the flush API is
enabled, any client connected to the bucket is able to
clear its contents. This may be useful in development but
not recommended in production. This setting may be changed
via :meth:`bucket_update`
:return: A :class:`~.HttpResult`
:raise: :exc:`~.HTTPError` if the bucket could not be created. | [
"Create",
"a",
"new",
"bucket"
] | a7bada167785bf79a29c39f820d932a433a6a535 | https://github.com/couchbase/couchbase-python-client/blob/a7bada167785bf79a29c39f820d932a433a6a535/couchbase/admin.py#L162-L210 | train |