repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1
value | code stringlengths 75 19.8k | code_tokens listlengths 20 707 | docstring stringlengths 3 17.3k | docstring_tokens listlengths 3 222 | sha stringlengths 40 40 | url stringlengths 87 242 | partition stringclasses 1
value | idx int64 0 252k |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_NDEF.text | def text(self, encoding = 'UTF-8', language = 'en'):
"""
Configure parameters for NDEF type TEXT.
@param encoding: The encoding used. Should be either 'UTF-8' or 'UTF16'.
@param language: ISO/IANA language code (see RFC 3066).
"""
self.ndef_type = _NDEF_TEXT_TYPE
self.ndef_text_lang = language
self.ndef_text_enc = encoding
return self | python | def text(self, encoding = 'UTF-8', language = 'en'):
"""
Configure parameters for NDEF type TEXT.
@param encoding: The encoding used. Should be either 'UTF-8' or 'UTF16'.
@param language: ISO/IANA language code (see RFC 3066).
"""
self.ndef_type = _NDEF_TEXT_TYPE
self.ndef_text_lang = language
self.ndef_text_enc = encoding
return self | [
"def",
"text",
"(",
"self",
",",
"encoding",
"=",
"'UTF-8'",
",",
"language",
"=",
"'en'",
")",
":",
"self",
".",
"ndef_type",
"=",
"_NDEF_TEXT_TYPE",
"self",
".",
"ndef_text_lang",
"=",
"language",
"self",
".",
"ndef_text_enc",
"=",
"encoding",
"return",
... | Configure parameters for NDEF type TEXT.
@param encoding: The encoding used. Should be either 'UTF-8' or 'UTF16'.
@param language: ISO/IANA language code (see RFC 3066). | [
"Configure",
"parameters",
"for",
"NDEF",
"type",
"TEXT",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L190-L200 | train | 199,100 |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_NDEF.type | def type(self, url = False, text = False, other = None):
"""
Change the NDEF type.
"""
if (url, text, other) == (True, False, None):
self.ndef_type = _NDEF_URI_TYPE
elif (url, text, other) == (False, True, None):
self.ndef_type = _NDEF_TEXT_TYPE
elif (url, text, type(other)) == (False, False, int):
self.ndef_type = other
else:
raise YubiKeyNEO_USBHIDError("Bad or conflicting NDEF type specified")
return self | python | def type(self, url = False, text = False, other = None):
"""
Change the NDEF type.
"""
if (url, text, other) == (True, False, None):
self.ndef_type = _NDEF_URI_TYPE
elif (url, text, other) == (False, True, None):
self.ndef_type = _NDEF_TEXT_TYPE
elif (url, text, type(other)) == (False, False, int):
self.ndef_type = other
else:
raise YubiKeyNEO_USBHIDError("Bad or conflicting NDEF type specified")
return self | [
"def",
"type",
"(",
"self",
",",
"url",
"=",
"False",
",",
"text",
"=",
"False",
",",
"other",
"=",
"None",
")",
":",
"if",
"(",
"url",
",",
"text",
",",
"other",
")",
"==",
"(",
"True",
",",
"False",
",",
"None",
")",
":",
"self",
".",
"ndef... | Change the NDEF type. | [
"Change",
"the",
"NDEF",
"type",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L202-L214 | train | 199,101 |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_NDEF._encode_ndef_uri_type | def _encode_ndef_uri_type(self, data):
"""
Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used.
"""
t = 0x0
for (code, prefix) in uri_identifiers:
if data[:len(prefix)].decode('latin-1').lower() == prefix:
t = code
data = data[len(prefix):]
break
data = yubico_util.chr_byte(t) + data
return data | python | def _encode_ndef_uri_type(self, data):
"""
Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used.
"""
t = 0x0
for (code, prefix) in uri_identifiers:
if data[:len(prefix)].decode('latin-1').lower() == prefix:
t = code
data = data[len(prefix):]
break
data = yubico_util.chr_byte(t) + data
return data | [
"def",
"_encode_ndef_uri_type",
"(",
"self",
",",
"data",
")",
":",
"t",
"=",
"0x0",
"for",
"(",
"code",
",",
"prefix",
")",
"in",
"uri_identifiers",
":",
"if",
"data",
"[",
":",
"len",
"(",
"prefix",
")",
"]",
".",
"decode",
"(",
"'latin-1'",
")",
... | Implement NDEF URI Identifier Code.
This is a small hack to replace some well known prefixes (such as http://)
with a one byte code. If the prefix is not known, 0x00 is used. | [
"Implement",
"NDEF",
"URI",
"Identifier",
"Code",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L253-L267 | train | 199,102 |
Yubico/python-yubico | yubico/yubikey_neo_usb_hid.py | YubiKeyNEO_NDEF._encode_ndef_text_params | def _encode_ndef_text_params(self, data):
"""
Prepend language and enconding information to data, according to
nfcforum-ts-rtd-text-1-0.pdf
"""
status = len(self.ndef_text_lang)
if self.ndef_text_enc == 'UTF16':
status = status & 0b10000000
return yubico_util.chr_byte(status) + self.ndef_text_lang + data | python | def _encode_ndef_text_params(self, data):
"""
Prepend language and enconding information to data, according to
nfcforum-ts-rtd-text-1-0.pdf
"""
status = len(self.ndef_text_lang)
if self.ndef_text_enc == 'UTF16':
status = status & 0b10000000
return yubico_util.chr_byte(status) + self.ndef_text_lang + data | [
"def",
"_encode_ndef_text_params",
"(",
"self",
",",
"data",
")",
":",
"status",
"=",
"len",
"(",
"self",
".",
"ndef_text_lang",
")",
"if",
"self",
".",
"ndef_text_enc",
"==",
"'UTF16'",
":",
"status",
"=",
"status",
"&",
"0b10000000",
"return",
"yubico_util... | Prepend language and enconding information to data, according to
nfcforum-ts-rtd-text-1-0.pdf | [
"Prepend",
"language",
"and",
"enconding",
"information",
"to",
"data",
"according",
"to",
"nfcforum",
"-",
"ts",
"-",
"rtd",
"-",
"text",
"-",
"1",
"-",
"0",
".",
"pdf"
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey_neo_usb_hid.py#L269-L277 | train | 199,103 |
Yubico/python-yubico | yubico/yubikey.py | find_key | def find_key(debug=False, skip=0):
"""
Locate a connected YubiKey. Throws an exception if none is found.
This function is supposed to be possible to extend if any other YubiKeys
appear in the future.
Attributes :
skip -- number of YubiKeys to skip
debug -- True or False
"""
try:
hid_device = YubiKeyHIDDevice(debug, skip)
yk_version = hid_device.status().ykver()
if (2, 1, 4) <= yk_version <= (2, 1, 9):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
if yk_version < (3, 0, 0):
return YubiKeyUSBHID(debug, skip, hid_device)
if yk_version < (4, 0, 0):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
return YubiKey4_USBHID(debug, skip, hid_device)
except YubiKeyUSBHIDError as inst:
if 'No USB YubiKey found' in str(inst):
# generalize this error
raise YubiKeyError('No YubiKey found')
else:
raise | python | def find_key(debug=False, skip=0):
"""
Locate a connected YubiKey. Throws an exception if none is found.
This function is supposed to be possible to extend if any other YubiKeys
appear in the future.
Attributes :
skip -- number of YubiKeys to skip
debug -- True or False
"""
try:
hid_device = YubiKeyHIDDevice(debug, skip)
yk_version = hid_device.status().ykver()
if (2, 1, 4) <= yk_version <= (2, 1, 9):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
if yk_version < (3, 0, 0):
return YubiKeyUSBHID(debug, skip, hid_device)
if yk_version < (4, 0, 0):
return YubiKeyNEO_USBHID(debug, skip, hid_device)
return YubiKey4_USBHID(debug, skip, hid_device)
except YubiKeyUSBHIDError as inst:
if 'No USB YubiKey found' in str(inst):
# generalize this error
raise YubiKeyError('No YubiKey found')
else:
raise | [
"def",
"find_key",
"(",
"debug",
"=",
"False",
",",
"skip",
"=",
"0",
")",
":",
"try",
":",
"hid_device",
"=",
"YubiKeyHIDDevice",
"(",
"debug",
",",
"skip",
")",
"yk_version",
"=",
"hid_device",
".",
"status",
"(",
")",
".",
"ykver",
"(",
")",
"if",... | Locate a connected YubiKey. Throws an exception if none is found.
This function is supposed to be possible to extend if any other YubiKeys
appear in the future.
Attributes :
skip -- number of YubiKeys to skip
debug -- True or False | [
"Locate",
"a",
"connected",
"YubiKey",
".",
"Throws",
"an",
"exception",
"if",
"none",
"is",
"found",
"."
] | a72e8eddb90da6ee96e29f60912ca1f2872c9aea | https://github.com/Yubico/python-yubico/blob/a72e8eddb90da6ee96e29f60912ca1f2872c9aea/yubico/yubikey.py#L41-L67 | train | 199,104 |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/pypi.py | norm_package_version | def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.join(v for v in version if v.strip())
else:
version = ''
return version | python | def norm_package_version(version):
"""Normalize a version by removing extra spaces and parentheses."""
if version:
version = ','.join(v.strip() for v in version.split(',')).strip()
if version.startswith('(') and version.endswith(')'):
version = version[1:-1]
version = ''.join(v for v in version if v.strip())
else:
version = ''
return version | [
"def",
"norm_package_version",
"(",
"version",
")",
":",
"if",
"version",
":",
"version",
"=",
"','",
".",
"join",
"(",
"v",
".",
"strip",
"(",
")",
"for",
"v",
"in",
"version",
".",
"split",
"(",
"','",
")",
")",
".",
"strip",
"(",
")",
"if",
"v... | Normalize a version by removing extra spaces and parentheses. | [
"Normalize",
"a",
"version",
"by",
"removing",
"extra",
"spaces",
"and",
"parentheses",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/pypi.py#L41-L53 | train | 199,105 |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/pypi.py | split_spec | def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts."""
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end | python | def split_spec(spec, sep):
"""Split a spec by separator and return stripped start and end parts."""
parts = spec.rsplit(sep, 1)
spec_start = parts[0].strip()
spec_end = ''
if len(parts) == 2:
spec_end = parts[-1].strip()
return spec_start, spec_end | [
"def",
"split_spec",
"(",
"spec",
",",
"sep",
")",
":",
"parts",
"=",
"spec",
".",
"rsplit",
"(",
"sep",
",",
"1",
")",
"spec_start",
"=",
"parts",
"[",
"0",
"]",
".",
"strip",
"(",
")",
"spec_end",
"=",
"''",
"if",
"len",
"(",
"parts",
")",
"=... | Split a spec by separator and return stripped start and end parts. | [
"Split",
"a",
"spec",
"by",
"separator",
"and",
"return",
"stripped",
"start",
"and",
"end",
"parts",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/pypi.py#L56-L63 | train | 199,106 |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/pypi.py | parse_specification | def parse_specification(spec):
"""
Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no errors are raised.
Example
-------
spec = 'requests[security, tests] >=3.3.0 ; foo >= 2.7 or bar == 1'
('requests', ['security', 'pyfoo'], '>=3.3.0', 'foo >= 2.7 or bar == 1', '')
"""
name, extras, const = spec, [], ''
# Remove excess whitespace
spec = ' '.join(p for p in spec.split(' ') if p).strip()
# Extract marker (Assumes that there can only be one ';' inside the spec)
spec, marker = split_spec(spec, ';')
# Extract url (Assumes that there can only be one '@' inside the spec)
spec, url = split_spec(spec, '@')
# Find name, extras and constraints
r = PARTIAL_PYPI_SPEC_PATTERN.match(spec)
if r:
# Normalize name
name = r.group('name')
# Clean extras
extras = r.group('extras')
extras = [e.strip() for e in extras.split(',') if e] if extras else []
# Clean constraints
const = r.group('constraints')
const = ''.join(c for c in const.split(' ') if c).strip()
if const.startswith('(') and const.endswith(')'):
# Remove parens
const = const[1:-1]
return name, extras, const, marker, url | python | def parse_specification(spec):
"""
Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no errors are raised.
Example
-------
spec = 'requests[security, tests] >=3.3.0 ; foo >= 2.7 or bar == 1'
('requests', ['security', 'pyfoo'], '>=3.3.0', 'foo >= 2.7 or bar == 1', '')
"""
name, extras, const = spec, [], ''
# Remove excess whitespace
spec = ' '.join(p for p in spec.split(' ') if p).strip()
# Extract marker (Assumes that there can only be one ';' inside the spec)
spec, marker = split_spec(spec, ';')
# Extract url (Assumes that there can only be one '@' inside the spec)
spec, url = split_spec(spec, '@')
# Find name, extras and constraints
r = PARTIAL_PYPI_SPEC_PATTERN.match(spec)
if r:
# Normalize name
name = r.group('name')
# Clean extras
extras = r.group('extras')
extras = [e.strip() for e in extras.split(',') if e] if extras else []
# Clean constraints
const = r.group('constraints')
const = ''.join(c for c in const.split(' ') if c).strip()
if const.startswith('(') and const.endswith(')'):
# Remove parens
const = const[1:-1]
return name, extras, const, marker, url | [
"def",
"parse_specification",
"(",
"spec",
")",
":",
"name",
",",
"extras",
",",
"const",
"=",
"spec",
",",
"[",
"]",
",",
"''",
"# Remove excess whitespace",
"spec",
"=",
"' '",
".",
"join",
"(",
"p",
"for",
"p",
"in",
"spec",
".",
"split",
"(",
"' ... | Parse a requirement from a python distribution metadata and return a
tuple with name, extras, constraints, marker and url components.
This method does not enforce strict specifications but extracts the
information which is assumed to be *correct*. As such no errors are raised.
Example
-------
spec = 'requests[security, tests] >=3.3.0 ; foo >= 2.7 or bar == 1'
('requests', ['security', 'pyfoo'], '>=3.3.0', 'foo >= 2.7 or bar == 1', '') | [
"Parse",
"a",
"requirement",
"from",
"a",
"python",
"distribution",
"metadata",
"and",
"return",
"a",
"tuple",
"with",
"name",
"extras",
"constraints",
"marker",
"and",
"url",
"components",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/pypi.py#L66-L108 | train | 199,107 |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/pypi.py | get_header_description | def get_header_description(filedata):
"""Get description from metadata file and remove any empty lines at end."""
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))
payload = filedata.get_payload()
lines = payload.split('\n')
while True:
if lines and lines[-1] == '':
lines.pop()
else:
break
return '\n'.join(lines) | python | def get_header_description(filedata):
"""Get description from metadata file and remove any empty lines at end."""
python_version = sys.version_info.major
if python_version == 3:
filedata = Parser().parsestr(filedata)
else:
filedata = Parser().parsestr(filedata.encode("UTF-8", "replace"))
payload = filedata.get_payload()
lines = payload.split('\n')
while True:
if lines and lines[-1] == '':
lines.pop()
else:
break
return '\n'.join(lines) | [
"def",
"get_header_description",
"(",
"filedata",
")",
":",
"python_version",
"=",
"sys",
".",
"version_info",
".",
"major",
"if",
"python_version",
"==",
"3",
":",
"filedata",
"=",
"Parser",
"(",
")",
".",
"parsestr",
"(",
"filedata",
")",
"else",
":",
"f... | Get description from metadata file and remove any empty lines at end. | [
"Get",
"description",
"from",
"metadata",
"file",
"and",
"remove",
"any",
"empty",
"lines",
"at",
"end",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/pypi.py#L111-L126 | train | 199,108 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.check_server | def check_server(self):
"""
Checks if the server is reachable and throws
and exception if it isn't
"""
msg = 'API server not found. Please check your API url configuration.'
try:
response = self.session.head(self.domain)
except Exception as e:
raise_from(errors.ServerError(msg), e)
try:
self._check_response(response)
except errors.NotFound as e:
raise raise_from(errors.ServerError(msg), e) | python | def check_server(self):
"""
Checks if the server is reachable and throws
and exception if it isn't
"""
msg = 'API server not found. Please check your API url configuration.'
try:
response = self.session.head(self.domain)
except Exception as e:
raise_from(errors.ServerError(msg), e)
try:
self._check_response(response)
except errors.NotFound as e:
raise raise_from(errors.ServerError(msg), e) | [
"def",
"check_server",
"(",
"self",
")",
":",
"msg",
"=",
"'API server not found. Please check your API url configuration.'",
"try",
":",
"response",
"=",
"self",
".",
"session",
".",
"head",
"(",
"self",
".",
"domain",
")",
"except",
"Exception",
"as",
"e",
":"... | Checks if the server is reachable and throws
and exception if it isn't | [
"Checks",
"if",
"the",
"server",
"is",
"reachable",
"and",
"throws",
"and",
"exception",
"if",
"it",
"isn",
"t"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L70-L85 | train | 199,109 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar._authenticate | def _authenticate(self,
auth,
application,
application_url=None,
for_user=None,
scopes=None,
created_with=None,
max_age=None,
strength='strong',
fail_if_already_exists=False,
hostname=platform.node()):
'''
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens.
'''
url = '%s/authentications' % (self.domain)
payload = {"scopes": scopes, "note": application, "note_url": application_url,
'hostname': hostname,
'user': for_user,
'max-age': max_age,
'created_with': None,
'strength': strength,
'fail-if-exists': fail_if_already_exists}
data, headers = jencode(payload)
res = self.session.post(url, auth=auth, data=data, headers=headers)
self._check_response(res)
res = res.json()
token = res['token']
self.session.headers.update({'Authorization': 'token %s' % (token)})
return token | python | def _authenticate(self,
auth,
application,
application_url=None,
for_user=None,
scopes=None,
created_with=None,
max_age=None,
strength='strong',
fail_if_already_exists=False,
hostname=platform.node()):
'''
Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens.
'''
url = '%s/authentications' % (self.domain)
payload = {"scopes": scopes, "note": application, "note_url": application_url,
'hostname': hostname,
'user': for_user,
'max-age': max_age,
'created_with': None,
'strength': strength,
'fail-if-exists': fail_if_already_exists}
data, headers = jencode(payload)
res = self.session.post(url, auth=auth, data=data, headers=headers)
self._check_response(res)
res = res.json()
token = res['token']
self.session.headers.update({'Authorization': 'token %s' % (token)})
return token | [
"def",
"_authenticate",
"(",
"self",
",",
"auth",
",",
"application",
",",
"application_url",
"=",
"None",
",",
"for_user",
"=",
"None",
",",
"scopes",
"=",
"None",
",",
"created_with",
"=",
"None",
",",
"max_age",
"=",
"None",
",",
"strength",
"=",
"'st... | Use basic authentication to create an authentication token using the interface below.
With this technique, a username and password need not be stored permanently, and the user can
revoke access at any time.
:param username: The users name
:param password: The users password
:param application: The application that is requesting access
:param application_url: The application's home page
:param scopes: Scopes let you specify exactly what type of access you need. Scopes limit access for the tokens. | [
"Use",
"basic",
"authentication",
"to",
"create",
"an",
"authentication",
"token",
"using",
"the",
"interface",
"below",
".",
"With",
"this",
"technique",
"a",
"username",
"and",
"password",
"need",
"not",
"be",
"stored",
"permanently",
"and",
"the",
"user",
"... | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L113-L151 | train | 199,110 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.authentication | def authentication(self):
'''
Retrieve information on the current authentication token
'''
url = '%s/authentication' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() | python | def authentication(self):
'''
Retrieve information on the current authentication token
'''
url = '%s/authentication' % (self.domain)
res = self.session.get(url)
self._check_response(res)
return res.json() | [
"def",
"authentication",
"(",
"self",
")",
":",
"url",
"=",
"'%s/authentication'",
"%",
"(",
"self",
".",
"domain",
")",
"res",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"self",
".",
"_check_response",
"(",
"res",
")",
"return",
"res",
... | Retrieve information on the current authentication token | [
"Retrieve",
"information",
"on",
"the",
"current",
"authentication",
"token"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L159-L166 | train | 199,111 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.remove_authentication | def remove_authentication(self, auth_name=None, organization=None):
"""
Remove the current authentication or the one given by `auth_name`
"""
if auth_name:
if organization:
url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name)
else:
url = '%s/authentications/name/%s' % (self.domain, auth_name)
else:
url = '%s/authentications' % (self.domain,)
res = self.session.delete(url)
self._check_response(res, [201]) | python | def remove_authentication(self, auth_name=None, organization=None):
"""
Remove the current authentication or the one given by `auth_name`
"""
if auth_name:
if organization:
url = '%s/authentications/org/%s/name/%s' % (self.domain, organization, auth_name)
else:
url = '%s/authentications/name/%s' % (self.domain, auth_name)
else:
url = '%s/authentications' % (self.domain,)
res = self.session.delete(url)
self._check_response(res, [201]) | [
"def",
"remove_authentication",
"(",
"self",
",",
"auth_name",
"=",
"None",
",",
"organization",
"=",
"None",
")",
":",
"if",
"auth_name",
":",
"if",
"organization",
":",
"url",
"=",
"'%s/authentications/org/%s/name/%s'",
"%",
"(",
"self",
".",
"domain",
",",
... | Remove the current authentication or the one given by `auth_name` | [
"Remove",
"the",
"current",
"authentication",
"or",
"the",
"one",
"given",
"by",
"auth_name"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L178-L191 | train | 199,112 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.user_packages | def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public')
'''
if login:
url = '{0}/packages/{1}'.format(self.domain, login)
else:
url = '{0}/packages'.format(self.domain)
arguments = collections.OrderedDict()
if platform:
arguments['platform'] = platform
if package_type:
arguments['package_type'] = package_type
if type_:
arguments['type'] = type_
if access:
arguments['access'] = access
res = self.session.get(url, params=arguments)
self._check_response(res)
return res.json() | python | def user_packages(
self,
login=None,
platform=None,
package_type=None,
type_=None,
access=None):
'''
Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public')
'''
if login:
url = '{0}/packages/{1}'.format(self.domain, login)
else:
url = '{0}/packages'.format(self.domain)
arguments = collections.OrderedDict()
if platform:
arguments['platform'] = platform
if package_type:
arguments['package_type'] = package_type
if type_:
arguments['type'] = type_
if access:
arguments['access'] = access
res = self.session.get(url, params=arguments)
self._check_response(res)
return res.json() | [
"def",
"user_packages",
"(",
"self",
",",
"login",
"=",
"None",
",",
"platform",
"=",
"None",
",",
"package_type",
"=",
"None",
",",
"type_",
"=",
"None",
",",
"access",
"=",
"None",
")",
":",
"if",
"login",
":",
"url",
"=",
"'{0}/packages/{1}'",
".",
... | Returns a list of packages for a given user and optionally filter
by `platform`, `package_type` and `type_`.
:param login: (optional) the login name of the user or None. If login
is None this method will return the packages for the
authenticated user.
:param platform: only find packages that include files for this platform.
(e.g. 'linux-64', 'osx-64', 'win-32')
:param package_type: only find packages that have this kind of file
(e.g. 'env', 'conda', 'pypi')
:param type_: only find packages that have this conda `type`
(i.e. 'app')
:param access: only find packages that have this access level
(e.g. 'private', 'authenticated', 'public') | [
"Returns",
"a",
"list",
"of",
"packages",
"for",
"a",
"given",
"user",
"and",
"optionally",
"filter",
"by",
"platform",
"package_type",
"and",
"type_",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L249-L291 | train | 199,113 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.package | def package(self, login, package_name):
'''
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
return res.json() | python | def package(self, login, package_name):
'''
Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
res = self.session.get(url)
self._check_response(res)
return res.json() | [
"def",
"package",
"(",
"self",
",",
"login",
",",
"package_name",
")",
":",
"url",
"=",
"'%s/package/%s/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"login",
",",
"package_name",
")",
"res",
"=",
"self",
".",
"session",
".",
"get",
"(",
"url",
")",
"s... | Get information about a specific package
:param login: the login of the package owner
:param package_name: the name of the package | [
"Get",
"information",
"about",
"a",
"specific",
"package"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L293-L303 | train | 199,114 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.add_package | def add_package(self, login, package_name,
summary=None,
license=None,
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None):
'''
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
attrs = attrs or {}
attrs['summary'] = summary
attrs['package_types'] = [package_type]
attrs['license'] = {
'name': license,
'url': license_url,
'family': license_family,
}
payload = dict(public=bool(public),
publish=False,
public_attrs=dict(attrs or {})
)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | python | def add_package(self, login, package_name,
summary=None,
license=None,
public=True,
license_url=None,
license_family=None,
attrs=None,
package_type=None):
'''
Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package
'''
url = '%s/package/%s/%s' % (self.domain, login, package_name)
attrs = attrs or {}
attrs['summary'] = summary
attrs['package_types'] = [package_type]
attrs['license'] = {
'name': license,
'url': license_url,
'family': license_family,
}
payload = dict(public=bool(public),
publish=False,
public_attrs=dict(attrs or {})
)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | [
"def",
"add_package",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"summary",
"=",
"None",
",",
"license",
"=",
"None",
",",
"public",
"=",
"True",
",",
"license_url",
"=",
"None",
",",
"license_family",
"=",
"None",
",",
"attrs",
"=",
"None",
... | Add a new package to a users account
:param login: the login of the package owner
:param package_name: the name of the package to be created
:param package_type: A type identifier for the package (eg. 'pypi' or 'conda', etc.)
:param summary: A short summary about the package
:param license: the name of the package license
:param license_url: the url of the package license
:param public: if true then the package will be hosted publicly
:param attrs: A dictionary of extra attributes for this package | [
"Add",
"a",
"new",
"package",
"to",
"a",
"users",
"account"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L334-L373 | train | 199,115 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.release | def release(self, login, package_name, version):
'''
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
res = self.session.get(url)
self._check_response(res)
return res.json() | python | def release(self, login, package_name, version):
'''
Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
res = self.session.get(url)
self._check_response(res)
return res.json() | [
"def",
"release",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"version",
")",
":",
"url",
"=",
"'%s/release/%s/%s/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"login",
",",
"package_name",
",",
"version",
")",
"res",
"=",
"self",
".",
"session",
... | Get information about a specific release
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package | [
"Get",
"information",
"about",
"a",
"specific",
"release"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L383-L394 | train | 199,116 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.remove_release | def remove_release(self, username, package_name, version):
'''
remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, username, package_name, version)
res = self.session.delete(url)
self._check_response(res, [201])
return | python | def remove_release(self, username, package_name, version):
'''
remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package
'''
url = '%s/release/%s/%s/%s' % (self.domain, username, package_name, version)
res = self.session.delete(url)
self._check_response(res, [201])
return | [
"def",
"remove_release",
"(",
"self",
",",
"username",
",",
"package_name",
",",
"version",
")",
":",
"url",
"=",
"'%s/release/%s/%s/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"username",
",",
"package_name",
",",
"version",
")",
"res",
"=",
"self",
".",
... | remove a release and all files under it
:param username: the login of the package owner
:param package_name: the name of the package
:param version: the name of the package | [
"remove",
"a",
"release",
"and",
"all",
"files",
"under",
"it"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L396-L407 | train | 199,117 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.add_release | def add_release(self, login, package_name, version, requirements, announce, release_attrs):
'''
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announcement that will be posted to all package watchers
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
if not release_attrs:
release_attrs = {}
payload = {
'requirements': requirements,
'announce': announce,
'description': None, # Will be updated with the one on release_attrs
}
payload.update(release_attrs)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | python | def add_release(self, login, package_name, version, requirements, announce, release_attrs):
'''
Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announcement that will be posted to all package watchers
'''
url = '%s/release/%s/%s/%s' % (self.domain, login, package_name, version)
if not release_attrs:
release_attrs = {}
payload = {
'requirements': requirements,
'announce': announce,
'description': None, # Will be updated with the one on release_attrs
}
payload.update(release_attrs)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | [
"def",
"add_release",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"version",
",",
"requirements",
",",
"announce",
",",
"release_attrs",
")",
":",
"url",
"=",
"'%s/release/%s/%s/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"login",
",",
"package_name... | Add a new release to a package.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param requirements: A dict of requirements TODO: describe
:param announce: An announcement that will be posted to all package watchers | [
"Add",
"a",
"new",
"release",
"to",
"a",
"package",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L409-L435 | train | 199,118 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.download | def download(self, login, package_name, release, basename, md5=None):
'''
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None
'''
url = '%s/download/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
if md5:
headers = {'ETag':md5, }
else:
headers = {}
res = self.session.get(url, headers=headers, allow_redirects=False)
self._check_response(res, allowed=[200, 302, 304])
if res.status_code == 200:
# We received the content directly from anaconda.org
return res
elif res.status_code == 304:
# The content has not changed
return None
elif res.status_code == 302:
# Download from s3:
# We need to create a new request (without using session) to avoid
# sending the custom headers set on our session to S3 (which causes
# a failure).
res2 = requests.get(res.headers['location'], stream=True)
return res2 | python | def download(self, login, package_name, release, basename, md5=None):
'''
Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None
'''
url = '%s/download/%s/%s/%s/%s' % (self.domain, login, package_name, release, basename)
if md5:
headers = {'ETag':md5, }
else:
headers = {}
res = self.session.get(url, headers=headers, allow_redirects=False)
self._check_response(res, allowed=[200, 302, 304])
if res.status_code == 200:
# We received the content directly from anaconda.org
return res
elif res.status_code == 304:
# The content has not changed
return None
elif res.status_code == 302:
# Download from s3:
# We need to create a new request (without using session) to avoid
# sending the custom headers set on our session to S3 (which causes
# a failure).
res2 = requests.get(res.headers['location'], stream=True)
return res2 | [
"def",
"download",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"release",
",",
"basename",
",",
"md5",
"=",
"None",
")",
":",
"url",
"=",
"'%s/download/%s/%s/%s/%s'",
"%",
"(",
"self",
".",
"domain",
",",
"login",
",",
"package_name",
",",
"rele... | Download a package distribution
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param md5: (optional) an md5 hash of the download if given and the package has not changed
None will be returned
:returns: a file like object or None | [
"Download",
"a",
"package",
"distribution"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L459-L494 | train | 199,119 |
Anaconda-Platform/anaconda-client | binstar_client/__init__.py | Binstar.upload | def upload(self, login, package_name, release, basename, fd, distribution_type,
description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None):
'''
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc
:param description: (optional) a short description about the file
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx')
'''
url = '%s/stage/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
if attrs is None:
attrs = {}
if not isinstance(attrs, dict):
raise TypeError('argument attrs must be a dictionary')
payload = dict(distribution_type=distribution_type, description=description, attrs=attrs,
dependencies=dependencies, channels=channels)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
obj = res.json()
s3url = obj['post_url']
s3data = obj['form_data']
if md5 is None:
_hexmd5, b64md5, size = compute_hash(fd, size=size)
elif size is None:
spos = fd.tell()
fd.seek(0, os.SEEK_END)
size = fd.tell() - spos
fd.seek(spos)
s3data['Content-Length'] = size
s3data['Content-MD5'] = b64md5
data_stream, headers = stream_multipart(s3data, files={'file':(basename, fd)},
callback=callback)
request_method = self.session if s3url.startswith(self.domain) else requests
s3res = request_method.post(
s3url, data=data_stream,
verify=self.session.verify, timeout=10 * 60 * 60,
headers=headers
)
if s3res.status_code != 201:
logger.info(s3res.text)
logger.info('')
logger.info('')
raise errors.BinstarError('Error uploading package', s3res.status_code)
url = '%s/commit/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
payload = dict(dist_id=obj['dist_id'])
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | python | def upload(self, login, package_name, release, basename, fd, distribution_type,
description='', md5=None, size=None, dependencies=None, attrs=None, channels=('main',), callback=None):
'''
Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc
:param description: (optional) a short description about the file
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx')
'''
url = '%s/stage/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
if attrs is None:
attrs = {}
if not isinstance(attrs, dict):
raise TypeError('argument attrs must be a dictionary')
payload = dict(distribution_type=distribution_type, description=description, attrs=attrs,
dependencies=dependencies, channels=channels)
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
obj = res.json()
s3url = obj['post_url']
s3data = obj['form_data']
if md5 is None:
_hexmd5, b64md5, size = compute_hash(fd, size=size)
elif size is None:
spos = fd.tell()
fd.seek(0, os.SEEK_END)
size = fd.tell() - spos
fd.seek(spos)
s3data['Content-Length'] = size
s3data['Content-MD5'] = b64md5
data_stream, headers = stream_multipart(s3data, files={'file':(basename, fd)},
callback=callback)
request_method = self.session if s3url.startswith(self.domain) else requests
s3res = request_method.post(
s3url, data=data_stream,
verify=self.session.verify, timeout=10 * 60 * 60,
headers=headers
)
if s3res.status_code != 201:
logger.info(s3res.text)
logger.info('')
logger.info('')
raise errors.BinstarError('Error uploading package', s3res.status_code)
url = '%s/commit/%s/%s/%s/%s' % (self.domain, login, package_name, release, quote(basename))
payload = dict(dist_id=obj['dist_id'])
data, headers = jencode(payload)
res = self.session.post(url, data=data, headers=headers)
self._check_response(res)
return res.json() | [
"def",
"upload",
"(",
"self",
",",
"login",
",",
"package_name",
",",
"release",
",",
"basename",
",",
"fd",
",",
"distribution_type",
",",
"description",
"=",
"''",
",",
"md5",
"=",
"None",
",",
"size",
"=",
"None",
",",
"dependencies",
"=",
"None",
"... | Upload a new distribution to a package release.
:param login: the login of the package owner
:param package_name: the name of the package
:param version: the version string of the release
:param basename: the basename of the distribution to download
:param fd: a file like object to upload
:param distribution_type: pypi or conda or ipynb, etc
:param description: (optional) a short description about the file
:param attrs: any extra attributes about the file (eg. build=1, pyversion='2.7', os='osx') | [
"Upload",
"a",
"new",
"distribution",
"to",
"a",
"package",
"release",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/__init__.py#L497-L562 | train | 199,120 |
Anaconda-Platform/anaconda-client | binstar_client/inspect_package/conda.py | transform_conda_deps | def transform_conda_deps(deps):
"""
Format dependencies into a common binstar format
"""
depends = []
for dep in deps:
dep = dep.strip()
name_spec = dep.split(' ', 1)
if len(name_spec) == 1:
name, = name_spec
depends.append({'name':name, 'specs': []})
elif len(name_spec) == 2:
name, spec = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [[op, spec]]})
elif len(name_spec) == 3:
name, spec, build_str = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [['==', '%s+%s' % (spec, build_str)]]})
return {'depends': depends} | python | def transform_conda_deps(deps):
"""
Format dependencies into a common binstar format
"""
depends = []
for dep in deps:
dep = dep.strip()
name_spec = dep.split(' ', 1)
if len(name_spec) == 1:
name, = name_spec
depends.append({'name':name, 'specs': []})
elif len(name_spec) == 2:
name, spec = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [[op, spec]]})
elif len(name_spec) == 3:
name, spec, build_str = name_spec
if spec.endswith('*'): # Star does nothing in semver
spec = spec[:-1]
match = specs_re.match(spec)
if match:
op, spec = match.groups()
else:
op = '=='
depends.append({'name':name, 'specs': [['==', '%s+%s' % (spec, build_str)]]})
return {'depends': depends} | [
"def",
"transform_conda_deps",
"(",
"deps",
")",
":",
"depends",
"=",
"[",
"]",
"for",
"dep",
"in",
"deps",
":",
"dep",
"=",
"dep",
".",
"strip",
"(",
")",
"name_spec",
"=",
"dep",
".",
"split",
"(",
"' '",
",",
"1",
")",
"if",
"len",
"(",
"name_... | Format dependencies into a common binstar format | [
"Format",
"dependencies",
"into",
"a",
"common",
"binstar",
"format"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/inspect_package/conda.py#L20-L56 | train | 199,121 |
Anaconda-Platform/anaconda-client | binstar_client/scripts/cli.py | file_or_token | def file_or_token(value):
"""
If value is a file path and the file exists its contents are stripped and returned,
otherwise value is returned.
"""
if isfile(value):
with open(value) as fd:
return fd.read().strip()
if any(char in value for char in '/\\.'):
# This chars will never be in a token value, but may be in a path
# The error message will be handled by the parser
raise ValueError()
return value | python | def file_or_token(value):
"""
If value is a file path and the file exists its contents are stripped and returned,
otherwise value is returned.
"""
if isfile(value):
with open(value) as fd:
return fd.read().strip()
if any(char in value for char in '/\\.'):
# This chars will never be in a token value, but may be in a path
# The error message will be handled by the parser
raise ValueError()
return value | [
"def",
"file_or_token",
"(",
"value",
")",
":",
"if",
"isfile",
"(",
"value",
")",
":",
"with",
"open",
"(",
"value",
")",
"as",
"fd",
":",
"return",
"fd",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
"if",
"any",
"(",
"char",
"in",
"value",
... | If value is a file path and the file exists its contents are stripped and returned,
otherwise value is returned. | [
"If",
"value",
"is",
"a",
"file",
"path",
"and",
"the",
"file",
"exists",
"its",
"contents",
"are",
"stripped",
"and",
"returned",
"otherwise",
"value",
"is",
"returned",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/scripts/cli.py#L29-L43 | train | 199,122 |
Anaconda-Platform/anaconda-client | binstar_client/utils/config.py | get_server_api | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
if token:
logger.debug("Using token from command line args")
elif 'BINSTAR_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable BINSTAR_API_TOKEN")
token = os.environ['BINSTAR_API_TOKEN']
elif 'ANACONDA_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable ANACONDA_API_TOKEN")
token = os.environ['ANACONDA_API_TOKEN']
else:
token = load_token(url)
verify = config.get('ssl_verify', config.get('verify_ssl', True))
return cls(token, domain=url, verify=verify, **kwargs) | python | def get_server_api(token=None, site=None, cls=None, config=None, **kwargs):
"""
Get the anaconda server api class
"""
if not cls:
from binstar_client import Binstar
cls = Binstar
config = config if config is not None else get_config(site=site)
url = config.get('url', DEFAULT_URL)
logger.info("Using Anaconda API: %s", url)
if token:
logger.debug("Using token from command line args")
elif 'BINSTAR_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable BINSTAR_API_TOKEN")
token = os.environ['BINSTAR_API_TOKEN']
elif 'ANACONDA_API_TOKEN' in os.environ:
logger.debug("Using token from environment variable ANACONDA_API_TOKEN")
token = os.environ['ANACONDA_API_TOKEN']
else:
token = load_token(url)
verify = config.get('ssl_verify', config.get('verify_ssl', True))
return cls(token, domain=url, verify=verify, **kwargs) | [
"def",
"get_server_api",
"(",
"token",
"=",
"None",
",",
"site",
"=",
"None",
",",
"cls",
"=",
"None",
",",
"config",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"cls",
":",
"from",
"binstar_client",
"import",
"Binstar",
"cls",
"=",
... | Get the anaconda server api class | [
"Get",
"the",
"anaconda",
"server",
"api",
"class"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/config.py#L101-L128 | train | 199,123 |
Anaconda-Platform/anaconda-client | binstar_client/utils/conda.py | get_conda_root | def get_conda_root():
"""Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation
"""
try:
# Fast-path
# We're in the root environment
conda_root = _import_conda_root()
except ImportError:
# We're not in the root environment.
envs_dir = dirname(CONDA_PREFIX)
if basename(envs_dir) == 'envs':
# We're in a named environment: `conda create -n <name>`
conda_root = dirname(envs_dir)
else:
# We're in an isolated environment: `conda create -p <path>`
# The only way we can find out is by calling conda.
conda_root = _conda_root_from_conda_info()
return conda_root | python | def get_conda_root():
"""Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation
"""
try:
# Fast-path
# We're in the root environment
conda_root = _import_conda_root()
except ImportError:
# We're not in the root environment.
envs_dir = dirname(CONDA_PREFIX)
if basename(envs_dir) == 'envs':
# We're in a named environment: `conda create -n <name>`
conda_root = dirname(envs_dir)
else:
# We're in an isolated environment: `conda create -p <path>`
# The only way we can find out is by calling conda.
conda_root = _conda_root_from_conda_info()
return conda_root | [
"def",
"get_conda_root",
"(",
")",
":",
"try",
":",
"# Fast-path",
"# We're in the root environment",
"conda_root",
"=",
"_import_conda_root",
"(",
")",
"except",
"ImportError",
":",
"# We're not in the root environment.",
"envs_dir",
"=",
"dirname",
"(",
"CONDA_PREFIX",
... | Get the PREFIX of the conda installation.
Returns:
str: the ROOT_PREFIX of the conda installation | [
"Get",
"the",
"PREFIX",
"of",
"the",
"conda",
"installation",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/conda.py#L43-L64 | train | 199,124 |
Anaconda-Platform/anaconda-client | binstar_client/utils/notebook/downloader.py | Downloader.download | def download(self, dist):
"""
Download file into location.
"""
filename = dist['basename']
requests_handle = self.aserver_api.download(
self.username, self.notebook, dist['version'], filename
)
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
with open(os.path.join(self.output, filename), 'wb') as fdout:
for chunk in requests_handle.iter_content(4096):
fdout.write(chunk) | python | def download(self, dist):
"""
Download file into location.
"""
filename = dist['basename']
requests_handle = self.aserver_api.download(
self.username, self.notebook, dist['version'], filename
)
if not os.path.exists(os.path.dirname(filename)):
try:
os.makedirs(os.path.dirname(filename))
except OSError:
pass
with open(os.path.join(self.output, filename), 'wb') as fdout:
for chunk in requests_handle.iter_content(4096):
fdout.write(chunk) | [
"def",
"download",
"(",
"self",
",",
"dist",
")",
":",
"filename",
"=",
"dist",
"[",
"'basename'",
"]",
"requests_handle",
"=",
"self",
".",
"aserver_api",
".",
"download",
"(",
"self",
".",
"username",
",",
"self",
".",
"notebook",
",",
"dist",
"[",
"... | Download file into location. | [
"Download",
"file",
"into",
"location",
"."
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/notebook/downloader.py#L55-L72 | train | 199,125 |
Anaconda-Platform/anaconda-client | binstar_client/utils/notebook/downloader.py | Downloader.ensure_output | def ensure_output(self):
"""
Ensure output's directory exists
"""
if not os.path.exists(self.output):
os.makedirs(self.output) | python | def ensure_output(self):
"""
Ensure output's directory exists
"""
if not os.path.exists(self.output):
os.makedirs(self.output) | [
"def",
"ensure_output",
"(",
"self",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"output",
")",
":",
"os",
".",
"makedirs",
"(",
"self",
".",
"output",
")"
] | Ensure output's directory exists | [
"Ensure",
"output",
"s",
"directory",
"exists"
] | b276f0572744c73c184a8b43a897cfa7fc1dc523 | https://github.com/Anaconda-Platform/anaconda-client/blob/b276f0572744c73c184a8b43a897cfa7fc1dc523/binstar_client/utils/notebook/downloader.py#L83-L88 | train | 199,126 |
hMatoba/Piexif | piexif/_common.py | merge_segments | def merge_segments(segments, exif=b""):
"""Merges Exif with APP0 and APP1 manipulations.
"""
if segments[1][0:2] == b"\xff\xe0" and \
segments[2][0:2] == b"\xff\xe1" and \
segments[2][4:10] == b"Exif\x00\x00":
if exif:
segments[2] = exif
segments.pop(1)
elif exif is None:
segments.pop(2)
else:
segments.pop(1)
elif segments[1][0:2] == b"\xff\xe0":
if exif:
segments[1] = exif
elif segments[1][0:2] == b"\xff\xe1" and \
segments[1][4:10] == b"Exif\x00\x00":
if exif:
segments[1] = exif
elif exif is None:
segments.pop(1)
else:
if exif:
segments.insert(1, exif)
return b"".join(segments) | python | def merge_segments(segments, exif=b""):
"""Merges Exif with APP0 and APP1 manipulations.
"""
if segments[1][0:2] == b"\xff\xe0" and \
segments[2][0:2] == b"\xff\xe1" and \
segments[2][4:10] == b"Exif\x00\x00":
if exif:
segments[2] = exif
segments.pop(1)
elif exif is None:
segments.pop(2)
else:
segments.pop(1)
elif segments[1][0:2] == b"\xff\xe0":
if exif:
segments[1] = exif
elif segments[1][0:2] == b"\xff\xe1" and \
segments[1][4:10] == b"Exif\x00\x00":
if exif:
segments[1] = exif
elif exif is None:
segments.pop(1)
else:
if exif:
segments.insert(1, exif)
return b"".join(segments) | [
"def",
"merge_segments",
"(",
"segments",
",",
"exif",
"=",
"b\"\"",
")",
":",
"if",
"segments",
"[",
"1",
"]",
"[",
"0",
":",
"2",
"]",
"==",
"b\"\\xff\\xe0\"",
"and",
"segments",
"[",
"2",
"]",
"[",
"0",
":",
"2",
"]",
"==",
"b\"\\xff\\xe1\"",
"a... | Merges Exif with APP0 and APP1 manipulations. | [
"Merges",
"Exif",
"with",
"APP0",
"and",
"APP1",
"manipulations",
"."
] | afd0d232cf05cf530423f4b2a82ab291f150601a | https://github.com/hMatoba/Piexif/blob/afd0d232cf05cf530423f4b2a82ab291f150601a/piexif/_common.py#L69-L94 | train | 199,127 |
hMatoba/Piexif | piexif/helper.py | UserComment.load | def load(cls, data):
"""
Convert "UserComment" value in exif format to str.
:param bytes data: "UserComment" value from exif
:return: u"foobar"
:rtype: str(Unicode)
:raises: ValueError if the data does not conform to the EXIF specification,
or the encoding is unsupported.
"""
if len(data) < cls._PREFIX_SIZE:
raise ValueError('not enough data to decode UserComment')
prefix = data[:cls._PREFIX_SIZE]
body = data[cls._PREFIX_SIZE:]
if prefix == cls._UNDEFINED_PREFIX:
raise ValueError('prefix is UNDEFINED, unable to decode UserComment')
try:
encoding = {
cls._ASCII_PREFIX: cls.ASCII, cls._JIS_PREFIX: cls._JIS, cls._UNICODE_PREFIX: cls._UNICODE,
}[prefix]
except KeyError:
raise ValueError('unable to determine appropriate encoding')
return body.decode(encoding, errors='replace') | python | def load(cls, data):
"""
Convert "UserComment" value in exif format to str.
:param bytes data: "UserComment" value from exif
:return: u"foobar"
:rtype: str(Unicode)
:raises: ValueError if the data does not conform to the EXIF specification,
or the encoding is unsupported.
"""
if len(data) < cls._PREFIX_SIZE:
raise ValueError('not enough data to decode UserComment')
prefix = data[:cls._PREFIX_SIZE]
body = data[cls._PREFIX_SIZE:]
if prefix == cls._UNDEFINED_PREFIX:
raise ValueError('prefix is UNDEFINED, unable to decode UserComment')
try:
encoding = {
cls._ASCII_PREFIX: cls.ASCII, cls._JIS_PREFIX: cls._JIS, cls._UNICODE_PREFIX: cls._UNICODE,
}[prefix]
except KeyError:
raise ValueError('unable to determine appropriate encoding')
return body.decode(encoding, errors='replace') | [
"def",
"load",
"(",
"cls",
",",
"data",
")",
":",
"if",
"len",
"(",
"data",
")",
"<",
"cls",
".",
"_PREFIX_SIZE",
":",
"raise",
"ValueError",
"(",
"'not enough data to decode UserComment'",
")",
"prefix",
"=",
"data",
"[",
":",
"cls",
".",
"_PREFIX_SIZE",
... | Convert "UserComment" value in exif format to str.
:param bytes data: "UserComment" value from exif
:return: u"foobar"
:rtype: str(Unicode)
:raises: ValueError if the data does not conform to the EXIF specification,
or the encoding is unsupported. | [
"Convert",
"UserComment",
"value",
"in",
"exif",
"format",
"to",
"str",
"."
] | afd0d232cf05cf530423f4b2a82ab291f150601a | https://github.com/hMatoba/Piexif/blob/afd0d232cf05cf530423f4b2a82ab291f150601a/piexif/helper.py#L27-L49 | train | 199,128 |
hMatoba/Piexif | piexif/helper.py | UserComment.dump | def dump(cls, data, encoding="ascii"):
"""
Convert str to appropriate format for "UserComment".
:param data: Like u"foobar"
:param str encoding: "ascii", "jis", or "unicode"
:return: b"ASCII\x00\x00\x00foobar"
:rtype: bytes
:raises: ValueError if the encoding is unsupported.
"""
if encoding not in cls.ENCODINGS:
raise ValueError('encoding {!r} must be one of {!r}'.format(encoding, cls.ENCODINGS))
prefix = {cls.ASCII: cls._ASCII_PREFIX, cls.JIS: cls._JIS_PREFIX, cls.UNICODE: cls._UNICODE_PREFIX}[encoding]
internal_encoding = {cls.UNICODE: cls._UNICODE, cls.JIS: cls._JIS}.get(encoding, encoding)
return prefix + data.encode(internal_encoding, errors='replace') | python | def dump(cls, data, encoding="ascii"):
"""
Convert str to appropriate format for "UserComment".
:param data: Like u"foobar"
:param str encoding: "ascii", "jis", or "unicode"
:return: b"ASCII\x00\x00\x00foobar"
:rtype: bytes
:raises: ValueError if the encoding is unsupported.
"""
if encoding not in cls.ENCODINGS:
raise ValueError('encoding {!r} must be one of {!r}'.format(encoding, cls.ENCODINGS))
prefix = {cls.ASCII: cls._ASCII_PREFIX, cls.JIS: cls._JIS_PREFIX, cls.UNICODE: cls._UNICODE_PREFIX}[encoding]
internal_encoding = {cls.UNICODE: cls._UNICODE, cls.JIS: cls._JIS}.get(encoding, encoding)
return prefix + data.encode(internal_encoding, errors='replace') | [
"def",
"dump",
"(",
"cls",
",",
"data",
",",
"encoding",
"=",
"\"ascii\"",
")",
":",
"if",
"encoding",
"not",
"in",
"cls",
".",
"ENCODINGS",
":",
"raise",
"ValueError",
"(",
"'encoding {!r} must be one of {!r}'",
".",
"format",
"(",
"encoding",
",",
"cls",
... | Convert str to appropriate format for "UserComment".
:param data: Like u"foobar"
:param str encoding: "ascii", "jis", or "unicode"
:return: b"ASCII\x00\x00\x00foobar"
:rtype: bytes
:raises: ValueError if the encoding is unsupported. | [
"Convert",
"str",
"to",
"appropriate",
"format",
"for",
"UserComment",
"."
] | afd0d232cf05cf530423f4b2a82ab291f150601a | https://github.com/hMatoba/Piexif/blob/afd0d232cf05cf530423f4b2a82ab291f150601a/piexif/helper.py#L52-L66 | train | 199,129 |
svenkreiss/pysparkling | pysparkling/fileio/fs/__init__.py | get_fs | def get_fs(path):
"""Find the file system implementation for this path."""
scheme = ''
if '://' in path:
scheme = path.partition('://')[0]
for schemes, fs_class in FILE_EXTENSIONS:
if scheme in schemes:
return fs_class
return FileSystem | python | def get_fs(path):
"""Find the file system implementation for this path."""
scheme = ''
if '://' in path:
scheme = path.partition('://')[0]
for schemes, fs_class in FILE_EXTENSIONS:
if scheme in schemes:
return fs_class
return FileSystem | [
"def",
"get_fs",
"(",
"path",
")",
":",
"scheme",
"=",
"''",
"if",
"'://'",
"in",
"path",
":",
"scheme",
"=",
"path",
".",
"partition",
"(",
"'://'",
")",
"[",
"0",
"]",
"for",
"schemes",
",",
"fs_class",
"in",
"FILE_EXTENSIONS",
":",
"if",
"scheme",... | Find the file system implementation for this path. | [
"Find",
"the",
"file",
"system",
"implementation",
"for",
"this",
"path",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/fileio/fs/__init__.py#L23-L33 | train | 199,130 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.awaitTermination | def awaitTermination(self, timeout=None):
"""Wait for context to stop.
:param float timeout: in seconds
"""
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop)
IOLoop.current().start()
IOLoop.clear_current() | python | def awaitTermination(self, timeout=None):
"""Wait for context to stop.
:param float timeout: in seconds
"""
if timeout is not None:
IOLoop.current().call_later(timeout, self.stop)
IOLoop.current().start()
IOLoop.clear_current() | [
"def",
"awaitTermination",
"(",
"self",
",",
"timeout",
"=",
"None",
")",
":",
"if",
"timeout",
"is",
"not",
"None",
":",
"IOLoop",
".",
"current",
"(",
")",
".",
"call_later",
"(",
"timeout",
",",
"self",
".",
"stop",
")",
"IOLoop",
".",
"current",
... | Wait for context to stop.
:param float timeout: in seconds | [
"Wait",
"for",
"context",
"to",
"stop",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L58-L68 | train | 199,131 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.binaryRecordsStream | def binaryRecordsStream(self, directory, recordLength=None,
process_all=False):
"""Monitor a directory and process all binary files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param recordLength: None, int or struct format string
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
Only ``int`` ``recordLength`` are supported in PySpark API.
The ``process_all`` parameter does not exist in the PySpark API.
"""
deserializer = FileBinaryStreamDeserializer(self._context,
recordLength)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | python | def binaryRecordsStream(self, directory, recordLength=None,
process_all=False):
"""Monitor a directory and process all binary files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param recordLength: None, int or struct format string
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
Only ``int`` ``recordLength`` are supported in PySpark API.
The ``process_all`` parameter does not exist in the PySpark API.
"""
deserializer = FileBinaryStreamDeserializer(self._context,
recordLength)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | [
"def",
"binaryRecordsStream",
"(",
"self",
",",
"directory",
",",
"recordLength",
"=",
"None",
",",
"process_all",
"=",
"False",
")",
":",
"deserializer",
"=",
"FileBinaryStreamDeserializer",
"(",
"self",
".",
"_context",
",",
"recordLength",
")",
"file_stream",
... | Monitor a directory and process all binary files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param recordLength: None, int or struct format string
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
Only ``int`` ``recordLength`` are supported in PySpark API.
The ``process_all`` parameter does not exist in the PySpark API. | [
"Monitor",
"a",
"directory",
"and",
"process",
"all",
"binary",
"files",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L74-L93 | train | 199,132 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.queueStream | def queueStream(self, rdds, oneAtATime=True, default=None):
"""Create stream iterable over RDDs.
:param rdds: Iterable over RDDs or lists.
:param oneAtATime: Process one at a time or all.
:param default: If no more RDDs in ``rdds``, return this. Can be None.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
[7]
Example testing the default value:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2]], default=['placeholder'])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
['placeholder']
"""
deserializer = QueueStreamDeserializer(self._context)
if default is not None:
default = deserializer(default)
if Queue is False:
log.error('Run "pip install tornado" to install tornado.')
q = Queue()
for i in rdds:
q.put(i)
qstream = QueueStream(q, oneAtATime, default)
return DStream(qstream, self, deserializer) | python | def queueStream(self, rdds, oneAtATime=True, default=None):
"""Create stream iterable over RDDs.
:param rdds: Iterable over RDDs or lists.
:param oneAtATime: Process one at a time or all.
:param default: If no more RDDs in ``rdds``, return this. Can be None.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
[7]
Example testing the default value:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2]], default=['placeholder'])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
['placeholder']
"""
deserializer = QueueStreamDeserializer(self._context)
if default is not None:
default = deserializer(default)
if Queue is False:
log.error('Run "pip install tornado" to install tornado.')
q = Queue()
for i in rdds:
q.put(i)
qstream = QueueStream(q, oneAtATime, default)
return DStream(qstream, self, deserializer) | [
"def",
"queueStream",
"(",
"self",
",",
"rdds",
",",
"oneAtATime",
"=",
"True",
",",
"default",
"=",
"None",
")",
":",
"deserializer",
"=",
"QueueStreamDeserializer",
"(",
"self",
".",
"_context",
")",
"if",
"default",
"is",
"not",
"None",
":",
"default",
... | Create stream iterable over RDDs.
:param rdds: Iterable over RDDs or lists.
:param oneAtATime: Process one at a time or all.
:param default: If no more RDDs in ``rdds``, return this. Can be None.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
[7]
Example testing the default value:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2]], default=['placeholder'])
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[4]
[2]
['placeholder'] | [
"Create",
"stream",
"iterable",
"over",
"RDDs",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L95-L149 | train | 199,133 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.socketBinaryStream | def socketBinaryStream(self, hostname, port, length):
"""Create a TCP socket server for binary input.
.. warning::
This is not part of the PySpark API.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:param length:
Message length. Length in bytes or a format string for
``struct.unpack()``.
For variable length messages where the message length is sent right
before the message itself, ``length`` is
a format string that can be passed to ``struct.unpack()``.
For example, use ``length='<I'`` for a little-endian
(standard on x86) 32-bit unsigned int.
:rtype: DStream
"""
deserializer = TCPDeserializer(self._context)
tcp_binary_stream = TCPBinaryStream(length)
tcp_binary_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_binary_stream.stop)
return DStream(tcp_binary_stream, self, deserializer) | python | def socketBinaryStream(self, hostname, port, length):
"""Create a TCP socket server for binary input.
.. warning::
This is not part of the PySpark API.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:param length:
Message length. Length in bytes or a format string for
``struct.unpack()``.
For variable length messages where the message length is sent right
before the message itself, ``length`` is
a format string that can be passed to ``struct.unpack()``.
For example, use ``length='<I'`` for a little-endian
(standard on x86) 32-bit unsigned int.
:rtype: DStream
"""
deserializer = TCPDeserializer(self._context)
tcp_binary_stream = TCPBinaryStream(length)
tcp_binary_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_binary_stream.stop)
return DStream(tcp_binary_stream, self, deserializer) | [
"def",
"socketBinaryStream",
"(",
"self",
",",
"hostname",
",",
"port",
",",
"length",
")",
":",
"deserializer",
"=",
"TCPDeserializer",
"(",
"self",
".",
"_context",
")",
"tcp_binary_stream",
"=",
"TCPBinaryStream",
"(",
"length",
")",
"tcp_binary_stream",
".",... | Create a TCP socket server for binary input.
.. warning::
This is not part of the PySpark API.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:param length:
Message length. Length in bytes or a format string for
``struct.unpack()``.
For variable length messages where the message length is sent right
before the message itself, ``length`` is
a format string that can be passed to ``struct.unpack()``.
For example, use ``length='<I'`` for a little-endian
(standard on x86) 32-bit unsigned int.
:rtype: DStream | [
"Create",
"a",
"TCP",
"socket",
"server",
"for",
"binary",
"input",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L154-L177 | train | 199,134 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.socketTextStream | def socketTextStream(self, hostname, port):
"""Create a TCP socket server.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:rtype: DStream
"""
deserializer = TCPDeserializer(self._context)
tcp_text_stream = TCPTextStream()
tcp_text_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_text_stream.stop)
return DStream(tcp_text_stream, self, deserializer) | python | def socketTextStream(self, hostname, port):
"""Create a TCP socket server.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:rtype: DStream
"""
deserializer = TCPDeserializer(self._context)
tcp_text_stream = TCPTextStream()
tcp_text_stream.listen(port, hostname)
self._on_stop_cb.append(tcp_text_stream.stop)
return DStream(tcp_text_stream, self, deserializer) | [
"def",
"socketTextStream",
"(",
"self",
",",
"hostname",
",",
"port",
")",
":",
"deserializer",
"=",
"TCPDeserializer",
"(",
"self",
".",
"_context",
")",
"tcp_text_stream",
"=",
"TCPTextStream",
"(",
")",
"tcp_text_stream",
".",
"listen",
"(",
"port",
",",
... | Create a TCP socket server.
:param string hostname: Hostname of TCP server.
:param int port: Port of TCP server.
:rtype: DStream | [
"Create",
"a",
"TCP",
"socket",
"server",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L179-L190 | train | 199,135 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.start | def start(self):
"""Start processing streams."""
def cb():
time_ = time.time()
log.debug('Step {}'.format(time_))
# run a step on all streams
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)
self._pcb.start()
self._on_stop_cb.append(self._pcb.stop)
StreamingContext._activeContext = self | python | def start(self):
"""Start processing streams."""
def cb():
time_ = time.time()
log.debug('Step {}'.format(time_))
# run a step on all streams
for d in self._dstreams:
d._step(time_)
self._pcb = PeriodicCallback(cb, self.batch_duration * 1000.0)
self._pcb.start()
self._on_stop_cb.append(self._pcb.stop)
StreamingContext._activeContext = self | [
"def",
"start",
"(",
"self",
")",
":",
"def",
"cb",
"(",
")",
":",
"time_",
"=",
"time",
".",
"time",
"(",
")",
"log",
".",
"debug",
"(",
"'Step {}'",
".",
"format",
"(",
"time_",
")",
")",
"# run a step on all streams",
"for",
"d",
"in",
"self",
"... | Start processing streams. | [
"Start",
"processing",
"streams",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L192-L206 | train | 199,136 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.stop | def stop(self, stopSparkContext=True, stopGraceFully=False):
"""Stop processing streams.
:param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED)
:param stopGracefully: stop gracefully (NOT IMPLEMENTED)
"""
while self._on_stop_cb:
cb = self._on_stop_cb.pop()
log.debug('calling on_stop_cb {}'.format(cb))
cb()
IOLoop.current().stop()
StreamingContext._activeContext = None | python | def stop(self, stopSparkContext=True, stopGraceFully=False):
"""Stop processing streams.
:param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED)
:param stopGracefully: stop gracefully (NOT IMPLEMENTED)
"""
while self._on_stop_cb:
cb = self._on_stop_cb.pop()
log.debug('calling on_stop_cb {}'.format(cb))
cb()
IOLoop.current().stop()
StreamingContext._activeContext = None | [
"def",
"stop",
"(",
"self",
",",
"stopSparkContext",
"=",
"True",
",",
"stopGraceFully",
"=",
"False",
")",
":",
"while",
"self",
".",
"_on_stop_cb",
":",
"cb",
"=",
"self",
".",
"_on_stop_cb",
".",
"pop",
"(",
")",
"log",
".",
"debug",
"(",
"'calling ... | Stop processing streams.
:param stopSparkContext: stop the SparkContext (NOT IMPLEMENTED)
:param stopGracefully: stop gracefully (NOT IMPLEMENTED) | [
"Stop",
"processing",
"streams",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L208-L221 | train | 199,137 |
svenkreiss/pysparkling | pysparkling/streaming/context.py | StreamingContext.textFileStream | def textFileStream(self, directory, process_all=False):
"""Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
The ``process_all`` parameter does not exist in the PySpark API.
"""
deserializer = FileTextStreamDeserializer(self._context)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | python | def textFileStream(self, directory, process_all=False):
"""Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
The ``process_all`` parameter does not exist in the PySpark API.
"""
deserializer = FileTextStreamDeserializer(self._context)
file_stream = FileStream(directory, process_all)
self._on_stop_cb.append(file_stream.stop)
return DStream(file_stream, self, deserializer) | [
"def",
"textFileStream",
"(",
"self",
",",
"directory",
",",
"process_all",
"=",
"False",
")",
":",
"deserializer",
"=",
"FileTextStreamDeserializer",
"(",
"self",
".",
"_context",
")",
"file_stream",
"=",
"FileStream",
"(",
"directory",
",",
"process_all",
")",... | Monitor a directory and process all text files.
File names starting with ``.`` are ignored.
:param string directory: a path
:param bool process_all: whether to process pre-existing files
:rtype: DStream
.. warning::
The ``process_all`` parameter does not exist in the PySpark API. | [
"Monitor",
"a",
"directory",
"and",
"process",
"all",
"text",
"files",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/context.py#L223-L238 | train | 199,138 |
svenkreiss/pysparkling | pysparkling/fileio/codec/__init__.py | get_codec | def get_codec(path):
"""Find the codec implementation for this path."""
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in FILE_ENDINGS:
if any(path.endswith(e) for e in endings):
log.debug('Using {0} codec: {1}'.format(endings, path))
return codec_class
return NoCodec | python | def get_codec(path):
"""Find the codec implementation for this path."""
if '.' not in path or path.rfind('/') > path.rfind('.'):
return Codec
for endings, codec_class in FILE_ENDINGS:
if any(path.endswith(e) for e in endings):
log.debug('Using {0} codec: {1}'.format(endings, path))
return codec_class
return NoCodec | [
"def",
"get_codec",
"(",
"path",
")",
":",
"if",
"'.'",
"not",
"in",
"path",
"or",
"path",
".",
"rfind",
"(",
"'/'",
")",
">",
"path",
".",
"rfind",
"(",
"'.'",
")",
":",
"return",
"Codec",
"for",
"endings",
",",
"codec_class",
"in",
"FILE_ENDINGS",
... | Find the codec implementation for this path. | [
"Find",
"the",
"codec",
"implementation",
"for",
"this",
"path",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/fileio/codec/__init__.py#L31-L41 | train | 199,139 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.count | def count(self):
"""Count elements per RDD.
Creates a new RDD stream where each RDD has a single entry that
is the count of the elements.
:rtype: DStream
"""
return (
self
.mapPartitions(lambda p: [sum(1 for _ in p)])
.reduce(operator.add)
) | python | def count(self):
"""Count elements per RDD.
Creates a new RDD stream where each RDD has a single entry that
is the count of the elements.
:rtype: DStream
"""
return (
self
.mapPartitions(lambda p: [sum(1 for _ in p)])
.reduce(operator.add)
) | [
"def",
"count",
"(",
"self",
")",
":",
"return",
"(",
"self",
".",
"mapPartitions",
"(",
"lambda",
"p",
":",
"[",
"sum",
"(",
"1",
"for",
"_",
"in",
"p",
")",
"]",
")",
".",
"reduce",
"(",
"operator",
".",
"add",
")",
")"
] | Count elements per RDD.
Creates a new RDD stream where each RDD has a single entry that
is the count of the elements.
:rtype: DStream | [
"Count",
"elements",
"per",
"RDD",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L80-L92 | train | 199,140 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.countByValue | def countByValue(self):
"""Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[1, 1, 5, 5, 5, 2]])
... .countByValue()
... .foreachRDD(lambda rdd: print(sorted(rdd.collect())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.15)
[(1, 2), (2, 1), (5, 3)]
"""
return self.transform(
lambda rdd: self._context._context.parallelize(
rdd.countByValue().items())) | python | def countByValue(self):
"""Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[1, 1, 5, 5, 5, 2]])
... .countByValue()
... .foreachRDD(lambda rdd: print(sorted(rdd.collect())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.15)
[(1, 2), (2, 1), (5, 3)]
"""
return self.transform(
lambda rdd: self._context._context.parallelize(
rdd.countByValue().items())) | [
"def",
"countByValue",
"(",
"self",
")",
":",
"return",
"self",
".",
"transform",
"(",
"lambda",
"rdd",
":",
"self",
".",
"_context",
".",
"_context",
".",
"parallelize",
"(",
"rdd",
".",
"countByValue",
"(",
")",
".",
"items",
"(",
")",
")",
")"
] | Apply countByValue to every RDD.abs
:rtype: DStream
.. warning::
Implemented as a local operation.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[1, 1, 5, 5, 5, 2]])
... .countByValue()
... .foreachRDD(lambda rdd: print(sorted(rdd.collect())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.15)
[(1, 2), (2, 1), (5, 3)] | [
"Apply",
"countByValue",
"to",
"every",
"RDD",
".",
"abs"
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L94-L120 | train | 199,141 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.flatMap | def flatMap(self, f, preservesPartitioning=False):
"""Apply function f and flatten.
:param f: mapping function
:rtype: DStream
"""
return self.mapPartitions(
lambda p: (e for pp in p for e in f(pp)),
preservesPartitioning,
) | python | def flatMap(self, f, preservesPartitioning=False):
"""Apply function f and flatten.
:param f: mapping function
:rtype: DStream
"""
return self.mapPartitions(
lambda p: (e for pp in p for e in f(pp)),
preservesPartitioning,
) | [
"def",
"flatMap",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"return",
"self",
".",
"mapPartitions",
"(",
"lambda",
"p",
":",
"(",
"e",
"for",
"pp",
"in",
"p",
"for",
"e",
"in",
"f",
"(",
"pp",
")",
")",
",",
"pr... | Apply function f and flatten.
:param f: mapping function
:rtype: DStream | [
"Apply",
"function",
"f",
"and",
"flatten",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L157-L166 | train | 199,142 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.map | def map(self, f, preservesPartitioning=False):
"""Apply function f
:param f: mapping function
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .map(lambda e: e + 1)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[5]
[3]
[8]
"""
return (
self
.mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | python | def map(self, f, preservesPartitioning=False):
"""Apply function f
:param f: mapping function
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .map(lambda e: e + 1)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[5]
[3]
[8]
"""
return (
self
.mapPartitions(lambda p: (f(e) for e in p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | [
"def",
"map",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"return",
"(",
"self",
".",
"mapPartitions",
"(",
"lambda",
"p",
":",
"(",
"f",
"(",
"e",
")",
"for",
"e",
"in",
"p",
")",
",",
"preservesPartitioning",
")",
... | Apply function f
:param f: mapping function
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([[4], [2], [7]])
... .map(lambda e: e + 1)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[5]
[3]
[8] | [
"Apply",
"function",
"f"
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L279-L308 | train | 199,143 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.mapPartitions | def mapPartitions(self, f, preservesPartitioning=False):
"""Map partitions.
:param f: mapping function
:rtype: DStream
"""
return (
self
.mapPartitionsWithIndex(lambda i, p: f(p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | python | def mapPartitions(self, f, preservesPartitioning=False):
"""Map partitions.
:param f: mapping function
:rtype: DStream
"""
return (
self
.mapPartitionsWithIndex(lambda i, p: f(p), preservesPartitioning)
.transform(lambda rdd:
rdd.setName('{}:{}'.format(rdd.prev.name(), f)))
) | [
"def",
"mapPartitions",
"(",
"self",
",",
"f",
",",
"preservesPartitioning",
"=",
"False",
")",
":",
"return",
"(",
"self",
".",
"mapPartitionsWithIndex",
"(",
"lambda",
"i",
",",
"p",
":",
"f",
"(",
"p",
")",
",",
"preservesPartitioning",
")",
".",
"tra... | Map partitions.
:param f: mapping function
:rtype: DStream | [
"Map",
"partitions",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L310-L321 | train | 199,144 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.pprint | def pprint(self, num=10):
"""Print the first ``num`` elements of each RDD.
:param int num: Set number of elements to be printed.
"""
def pprint_map(time_, rdd):
print('>>> Time: {}'.format(time_))
data = rdd.take(num + 1)
for d in data[:num]:
py_pprint.pprint(d)
if len(data) > num:
print('...')
print('')
self.foreachRDD(pprint_map) | python | def pprint(self, num=10):
"""Print the first ``num`` elements of each RDD.
:param int num: Set number of elements to be printed.
"""
def pprint_map(time_, rdd):
print('>>> Time: {}'.format(time_))
data = rdd.take(num + 1)
for d in data[:num]:
py_pprint.pprint(d)
if len(data) > num:
print('...')
print('')
self.foreachRDD(pprint_map) | [
"def",
"pprint",
"(",
"self",
",",
"num",
"=",
"10",
")",
":",
"def",
"pprint_map",
"(",
"time_",
",",
"rdd",
")",
":",
"print",
"(",
"'>>> Time: {}'",
".",
"format",
"(",
"time_",
")",
")",
"data",
"=",
"rdd",
".",
"take",
"(",
"num",
"+",
"1",
... | Print the first ``num`` elements of each RDD.
:param int num: Set number of elements to be printed. | [
"Print",
"the",
"first",
"num",
"elements",
"of",
"each",
"RDD",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L361-L376 | train | 199,145 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.reduce | def reduce(self, func):
"""Return a new DStream where each RDD was reduced with ``func``.
:rtype: DStream
"""
# avoid RDD.reduce() which does not return an RDD
return self.transform(
lambda rdd: (
rdd
.map(lambda i: (None, i))
.reduceByKey(func)
.map(lambda none_i: none_i[1])
)
) | python | def reduce(self, func):
"""Return a new DStream where each RDD was reduced with ``func``.
:rtype: DStream
"""
# avoid RDD.reduce() which does not return an RDD
return self.transform(
lambda rdd: (
rdd
.map(lambda i: (None, i))
.reduceByKey(func)
.map(lambda none_i: none_i[1])
)
) | [
"def",
"reduce",
"(",
"self",
",",
"func",
")",
":",
"# avoid RDD.reduce() which does not return an RDD",
"return",
"self",
".",
"transform",
"(",
"lambda",
"rdd",
":",
"(",
"rdd",
".",
"map",
"(",
"lambda",
"i",
":",
"(",
"None",
",",
"i",
")",
")",
"."... | Return a new DStream where each RDD was reduced with ``func``.
:rtype: DStream | [
"Return",
"a",
"new",
"DStream",
"where",
"each",
"RDD",
"was",
"reduced",
"with",
"func",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L378-L392 | train | 199,146 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.reduceByKey | def reduceByKey(self, func, numPartitions=None):
"""Apply reduceByKey to every RDD.
:param func: reduce function to apply
:param int numPartitions: number of partitions
:rtype: DStream
"""
return self.transform(lambda rdd: rdd.reduceByKey(func)) | python | def reduceByKey(self, func, numPartitions=None):
"""Apply reduceByKey to every RDD.
:param func: reduce function to apply
:param int numPartitions: number of partitions
:rtype: DStream
"""
return self.transform(lambda rdd: rdd.reduceByKey(func)) | [
"def",
"reduceByKey",
"(",
"self",
",",
"func",
",",
"numPartitions",
"=",
"None",
")",
":",
"return",
"self",
".",
"transform",
"(",
"lambda",
"rdd",
":",
"rdd",
".",
"reduceByKey",
"(",
"func",
")",
")"
] | Apply reduceByKey to every RDD.
:param func: reduce function to apply
:param int numPartitions: number of partitions
:rtype: DStream | [
"Apply",
"reduceByKey",
"to",
"every",
"RDD",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L394-L401 | train | 199,147 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.repartition | def repartition(self, numPartitions):
"""Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['hello', 'world']])
... .repartition(2)
... .foreachRDD(lambda rdd: print(len(rdd.partitions())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.25)
2
0
"""
return self.transform(
lambda rdd: (rdd.repartition(numPartitions)
if not isinstance(rdd, EmptyRDD) else rdd)
) | python | def repartition(self, numPartitions):
"""Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['hello', 'world']])
... .repartition(2)
... .foreachRDD(lambda rdd: print(len(rdd.partitions())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.25)
2
0
"""
return self.transform(
lambda rdd: (rdd.repartition(numPartitions)
if not isinstance(rdd, EmptyRDD) else rdd)
) | [
"def",
"repartition",
"(",
"self",
",",
"numPartitions",
")",
":",
"return",
"self",
".",
"transform",
"(",
"lambda",
"rdd",
":",
"(",
"rdd",
".",
"repartition",
"(",
"numPartitions",
")",
"if",
"not",
"isinstance",
"(",
"rdd",
",",
"EmptyRDD",
")",
"els... | Repartition every RDD.
:rtype: DStream
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> (
... ssc
... .queueStream([['hello', 'world']])
... .repartition(2)
... .foreachRDD(lambda rdd: print(len(rdd.partitions())))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.25)
2
0 | [
"Repartition",
"every",
"RDD",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L403-L429 | train | 199,148 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.slice | def slice(self, begin, end):
"""Filter RDDs to between begin and end.
:param datetime.datetime|int begin: datetiem or unix timestamp
:param datetime.datetime|int end: datetiem or unix timestamp
:rtype: DStream
"""
return self.transform(lambda time_, rdd:
rdd if begin <= time_ <= end
else EmptyRDD(self._context._context)) | python | def slice(self, begin, end):
"""Filter RDDs to between begin and end.
:param datetime.datetime|int begin: datetiem or unix timestamp
:param datetime.datetime|int end: datetiem or unix timestamp
:rtype: DStream
"""
return self.transform(lambda time_, rdd:
rdd if begin <= time_ <= end
else EmptyRDD(self._context._context)) | [
"def",
"slice",
"(",
"self",
",",
"begin",
",",
"end",
")",
":",
"return",
"self",
".",
"transform",
"(",
"lambda",
"time_",
",",
"rdd",
":",
"rdd",
"if",
"begin",
"<=",
"time_",
"<=",
"end",
"else",
"EmptyRDD",
"(",
"self",
".",
"_context",
".",
"... | Filter RDDs to between begin and end.
:param datetime.datetime|int begin: datetiem or unix timestamp
:param datetime.datetime|int end: datetiem or unix timestamp
:rtype: DStream | [
"Filter",
"RDDs",
"to",
"between",
"begin",
"and",
"end",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L486-L495 | train | 199,149 |
svenkreiss/pysparkling | pysparkling/streaming/dstream.py | DStream.union | def union(self, other):
"""Union of two DStreams.
:param DStream other: Another DStream.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> odd = ssc.queueStream([[1], [3], [5]])
>>> even = ssc.queueStream([[2], [4], [6]])
>>> (
... odd.union(even)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[1, 2]
[3, 4]
[5, 6]
"""
def union_rdds(rdd_a, rdd_b):
return self._context._context.union((rdd_a, rdd_b))
return self.transformWith(union_rdds, other) | python | def union(self, other):
"""Union of two DStreams.
:param DStream other: Another DStream.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> odd = ssc.queueStream([[1], [3], [5]])
>>> even = ssc.queueStream([[2], [4], [6]])
>>> (
... odd.union(even)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[1, 2]
[3, 4]
[5, 6]
"""
def union_rdds(rdd_a, rdd_b):
return self._context._context.union((rdd_a, rdd_b))
return self.transformWith(union_rdds, other) | [
"def",
"union",
"(",
"self",
",",
"other",
")",
":",
"def",
"union_rdds",
"(",
"rdd_a",
",",
"rdd_b",
")",
":",
"return",
"self",
".",
"_context",
".",
"_context",
".",
"union",
"(",
"(",
"rdd_a",
",",
"rdd_b",
")",
")",
"return",
"self",
".",
"tra... | Union of two DStreams.
:param DStream other: Another DStream.
Example:
>>> import pysparkling
>>> sc = pysparkling.Context()
>>> ssc = pysparkling.streaming.StreamingContext(sc, 0.1)
>>> odd = ssc.queueStream([[1], [3], [5]])
>>> even = ssc.queueStream([[2], [4], [6]])
>>> (
... odd.union(even)
... .foreachRDD(lambda rdd: print(rdd.collect()))
... )
>>> ssc.start()
>>> ssc.awaitTermination(0.35)
[1, 2]
[3, 4]
[5, 6] | [
"Union",
"of",
"two",
"DStreams",
"."
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/streaming/dstream.py#L524-L550 | train | 199,150 |
svenkreiss/pysparkling | pysparkling/fileio/file.py | File.resolve_filenames | def resolve_filenames(all_expr):
"""resolve expression for a filename
:param all_expr:
A comma separated list of expressions. The expressions can contain
the wildcard characters ``*`` and ``?``. It also resolves Spark
datasets to the paths of the individual partitions
(i.e. ``my_data`` gets resolved to
``[my_data/part-00000, my_data/part-00001]``).
:returns: A list of file names.
:rtype: list
"""
files = []
for expr in all_expr.split(','):
expr = expr.strip()
files += fs.get_fs(expr).resolve_filenames(expr)
log.debug('Filenames: {0}'.format(files))
return files | python | def resolve_filenames(all_expr):
"""resolve expression for a filename
:param all_expr:
A comma separated list of expressions. The expressions can contain
the wildcard characters ``*`` and ``?``. It also resolves Spark
datasets to the paths of the individual partitions
(i.e. ``my_data`` gets resolved to
``[my_data/part-00000, my_data/part-00001]``).
:returns: A list of file names.
:rtype: list
"""
files = []
for expr in all_expr.split(','):
expr = expr.strip()
files += fs.get_fs(expr).resolve_filenames(expr)
log.debug('Filenames: {0}'.format(files))
return files | [
"def",
"resolve_filenames",
"(",
"all_expr",
")",
":",
"files",
"=",
"[",
"]",
"for",
"expr",
"in",
"all_expr",
".",
"split",
"(",
"','",
")",
":",
"expr",
"=",
"expr",
".",
"strip",
"(",
")",
"files",
"+=",
"fs",
".",
"get_fs",
"(",
"expr",
")",
... | resolve expression for a filename
:param all_expr:
A comma separated list of expressions. The expressions can contain
the wildcard characters ``*`` and ``?``. It also resolves Spark
datasets to the paths of the individual partitions
(i.e. ``my_data`` gets resolved to
``[my_data/part-00000, my_data/part-00001]``).
:returns: A list of file names.
:rtype: list | [
"resolve",
"expression",
"for",
"a",
"filename"
] | 596d0ef2793100f7115efe228ff9bfc17beaa08d | https://github.com/svenkreiss/pysparkling/blob/596d0ef2793100f7115efe228ff9bfc17beaa08d/pysparkling/fileio/file.py#L24-L42 | train | 199,151 |
emirozer/fake2db | fake2db/mongodb_handler.py | Fake2dbMongodbHandler.database_caller_creator | def database_caller_creator(self, host, port, name=None):
'''creates a mongodb database
returns the related connection object
which will be later used to spawn the cursor
'''
client = pymongo.MongoClient(host, port)
if name:
db = client[name]
else:
db = client['mongodb_' + str_generator(self)]
return db | python | def database_caller_creator(self, host, port, name=None):
'''creates a mongodb database
returns the related connection object
which will be later used to spawn the cursor
'''
client = pymongo.MongoClient(host, port)
if name:
db = client[name]
else:
db = client['mongodb_' + str_generator(self)]
return db | [
"def",
"database_caller_creator",
"(",
"self",
",",
"host",
",",
"port",
",",
"name",
"=",
"None",
")",
":",
"client",
"=",
"pymongo",
".",
"MongoClient",
"(",
"host",
",",
"port",
")",
"if",
"name",
":",
"db",
"=",
"client",
"[",
"name",
"]",
"else"... | creates a mongodb database
returns the related connection object
which will be later used to spawn the cursor | [
"creates",
"a",
"mongodb",
"database",
"returns",
"the",
"related",
"connection",
"object",
"which",
"will",
"be",
"later",
"used",
"to",
"spawn",
"the",
"cursor"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/mongodb_handler.py#L57-L70 | train | 199,152 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.database_caller_creator | def database_caller_creator(self, host, port, name=None):
'''creates a redis connection object
which will be later used to modify the db
'''
name = name or 0
client = redis.StrictRedis(host=host, port=port, db=name)
pipe = client.pipeline(transaction=False)
return client, pipe | python | def database_caller_creator(self, host, port, name=None):
'''creates a redis connection object
which will be later used to modify the db
'''
name = name or 0
client = redis.StrictRedis(host=host, port=port, db=name)
pipe = client.pipeline(transaction=False)
return client, pipe | [
"def",
"database_caller_creator",
"(",
"self",
",",
"host",
",",
"port",
",",
"name",
"=",
"None",
")",
":",
"name",
"=",
"name",
"or",
"0",
"client",
"=",
"redis",
".",
"StrictRedis",
"(",
"host",
"=",
"host",
",",
"port",
"=",
"port",
",",
"db",
... | creates a redis connection object
which will be later used to modify the db | [
"creates",
"a",
"redis",
"connection",
"object",
"which",
"will",
"be",
"later",
"used",
"to",
"modify",
"the",
"db"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L57-L65 | train | 199,153 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.data_filler_simple_registration | def data_filler_simple_registration(self, number_of_rows, pipe):
'''creates keys with simple regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('simple_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False)
})
pipe.execute()
logger.warning('simple_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_simple_registration(self, number_of_rows, pipe):
'''creates keys with simple regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('simple_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False)
})
pipe.execute()
logger.warning('simple_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_simple_registration",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'simple_registration:%s'",
"%",
"i",
",",
"{",
"'id'",
... | creates keys with simple regis. information | [
"creates",
"keys",
"with",
"simple",
"regis",
".",
"information"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L67-L82 | train | 199,154 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.data_filler_detailed_registration | def data_filler_detailed_registration(self, number_of_rows, pipe):
'''creates keys with detailed regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('detailed_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False),
'lastname': self.faker.last_name(),
'name': self.faker.first_name(),
'address': self.faker.address(),
'phone': self.faker.phone_number()
})
pipe.execute()
logger.warning('detailed_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_detailed_registration(self, number_of_rows, pipe):
'''creates keys with detailed regis. information
'''
try:
for i in range(number_of_rows):
pipe.hmset('detailed_registration:%s' % i, {
'id': rnd_id_generator(self),
'email': self.faker.safe_email(),
'password': self.faker.md5(raw_output=False),
'lastname': self.faker.last_name(),
'name': self.faker.first_name(),
'address': self.faker.address(),
'phone': self.faker.phone_number()
})
pipe.execute()
logger.warning('detailed_registration Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_detailed_registration",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'detailed_registration:%s'",
"%",
"i",
",",
"{",
"'id'"... | creates keys with detailed regis. information | [
"creates",
"keys",
"with",
"detailed",
"regis",
".",
"information"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L84-L103 | train | 199,155 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.data_filler_user_agent | def data_filler_user_agent(self, number_of_rows, pipe):
'''creates keys with user agent data
'''
try:
for i in range(number_of_rows):
pipe.hmset('user_agent:%s' % i, {
'id': rnd_id_generator(self),
'ip': self.faker.ipv4(),
'countrycode': self.faker.country_code(),
'useragent': self.faker.user_agent()
})
pipe.execute()
logger.warning('user_agent Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_user_agent(self, number_of_rows, pipe):
'''creates keys with user agent data
'''
try:
for i in range(number_of_rows):
pipe.hmset('user_agent:%s' % i, {
'id': rnd_id_generator(self),
'ip': self.faker.ipv4(),
'countrycode': self.faker.country_code(),
'useragent': self.faker.user_agent()
})
pipe.execute()
logger.warning('user_agent Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_user_agent",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'user_agent:%s'",
"%",
"i",
",",
"{",
"'id'",
":",
"rnd_id_gen... | creates keys with user agent data | [
"creates",
"keys",
"with",
"user",
"agent",
"data"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L105-L121 | train | 199,156 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.data_filler_company | def data_filler_company(self, number_of_rows, pipe):
'''creates keys with company data
'''
try:
for i in range(number_of_rows):
pipe.hmset('company:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.company(),
'date': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.company_email(),
'domain': self.faker.safe_email(),
'city': self.faker.city()
})
pipe.execute()
logger.warning('companies Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_company(self, number_of_rows, pipe):
'''creates keys with company data
'''
try:
for i in range(number_of_rows):
pipe.hmset('company:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.company(),
'date': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.company_email(),
'domain': self.faker.safe_email(),
'city': self.faker.city()
})
pipe.execute()
logger.warning('companies Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_company",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'company:%s'",
"%",
"i",
",",
"{",
"'id'",
":",
"rnd_id_generator... | creates keys with company data | [
"creates",
"keys",
"with",
"company",
"data"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L123-L141 | train | 199,157 |
emirozer/fake2db | fake2db/redis_handler.py | Fake2dbRedisHandler.data_filler_customer | def data_filler_customer(self, number_of_rows, pipe):
'''creates keys with customer data
'''
try:
for i in range(number_of_rows):
pipe.hmset('customer:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.first_name(),
'lastname': self.faker.last_name(),
'address': self.faker.address(),
'country': self.faker.country(),
'city': self.faker.city(),
'registry_date': self.faker.date(pattern="%d-%m-%Y"),
'birthdate': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.safe_email(),
'phone_number': self.faker.phone_number(),
'locale': self.faker.locale()
})
pipe.execute()
logger.warning('customer Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_customer(self, number_of_rows, pipe):
'''creates keys with customer data
'''
try:
for i in range(number_of_rows):
pipe.hmset('customer:%s' % i, {
'id': rnd_id_generator(self),
'name': self.faker.first_name(),
'lastname': self.faker.last_name(),
'address': self.faker.address(),
'country': self.faker.country(),
'city': self.faker.city(),
'registry_date': self.faker.date(pattern="%d-%m-%Y"),
'birthdate': self.faker.date(pattern="%d-%m-%Y"),
'email': self.faker.safe_email(),
'phone_number': self.faker.phone_number(),
'locale': self.faker.locale()
})
pipe.execute()
logger.warning('customer Commits are successful after write job!', extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_customer",
"(",
"self",
",",
"number_of_rows",
",",
"pipe",
")",
":",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"number_of_rows",
")",
":",
"pipe",
".",
"hmset",
"(",
"'customer:%s'",
"%",
"i",
",",
"{",
"'id'",
":",
"rnd_id_generat... | creates keys with customer data | [
"creates",
"keys",
"with",
"customer",
"data"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/redis_handler.py#L143-L166 | train | 199,158 |
emirozer/fake2db | fake2db/postgresql_handler.py | Fake2dbPostgresqlHandler.database_caller_creator | def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None):
'''creates a postgresql db
returns the related connection object
which will be later used to spawn the cursor
'''
cursor = None
conn = None
if name:
dbname = name
else:
dbname = 'postgresql_' + str_generator(self).lower()
try:
# createdb
conn = psycopg2.connect(
user=username, password=password, host=host, port=port)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute('CREATE DATABASE %s;' % dbname)
cur.close()
conn.close()
# reconnect to the new database
conn = psycopg2.connect(user=username, password=password,
host=host, port=port, database=dbname)
cursor = conn.cursor()
logger.warning('Database created and opened succesfully: %s' % dbname, extra=d)
except Exception as err:
logger.error(err, extra=d)
raise
if custom:
self.custom_db_creator(number_of_rows, cursor, conn, custom)
cursor.close()
conn.close()
sys.exit(0)
return cursor, conn | python | def database_caller_creator(self, number_of_rows, username, password, host, port, name=None, custom=None):
'''creates a postgresql db
returns the related connection object
which will be later used to spawn the cursor
'''
cursor = None
conn = None
if name:
dbname = name
else:
dbname = 'postgresql_' + str_generator(self).lower()
try:
# createdb
conn = psycopg2.connect(
user=username, password=password, host=host, port=port)
conn.set_isolation_level(ISOLATION_LEVEL_AUTOCOMMIT)
cur = conn.cursor()
cur.execute('CREATE DATABASE %s;' % dbname)
cur.close()
conn.close()
# reconnect to the new database
conn = psycopg2.connect(user=username, password=password,
host=host, port=port, database=dbname)
cursor = conn.cursor()
logger.warning('Database created and opened succesfully: %s' % dbname, extra=d)
except Exception as err:
logger.error(err, extra=d)
raise
if custom:
self.custom_db_creator(number_of_rows, cursor, conn, custom)
cursor.close()
conn.close()
sys.exit(0)
return cursor, conn | [
"def",
"database_caller_creator",
"(",
"self",
",",
"number_of_rows",
",",
"username",
",",
"password",
",",
"host",
",",
"port",
",",
"name",
"=",
"None",
",",
"custom",
"=",
"None",
")",
":",
"cursor",
"=",
"None",
"conn",
"=",
"None",
"if",
"name",
... | creates a postgresql db
returns the related connection object
which will be later used to spawn the cursor | [
"creates",
"a",
"postgresql",
"db",
"returns",
"the",
"related",
"connection",
"object",
"which",
"will",
"be",
"later",
"used",
"to",
"spawn",
"the",
"cursor"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/postgresql_handler.py#L28-L64 | train | 199,159 |
emirozer/fake2db | fake2db/mysql_handler.py | Fake2dbMySqlHandler.data_filler_customer | def data_filler_customer(self, number_of_rows, cursor, conn):
'''creates and fills the table with customer
'''
customer_data = []
try:
for i in range(0, number_of_rows):
customer_data.append((
rnd_id_generator(self), self.faker.first_name(), self.faker.last_name(), self.faker.address(),
self.faker.country(), self.faker.city(), self.faker.date(pattern="%d-%m-%Y"),
self.faker.date(pattern="%d-%m-%Y"), self.faker.safe_email(), self.faker.phone_number(),
self.faker.locale()))
customer_payload = ("INSERT INTO customer "
"(id, name, lastname, address, country, city, registry_date, birthdate, email, "
"phone_number, locale)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
cursor.executemany(customer_payload, customer_data)
conn.commit()
logger.warning('detailed_registration Commits are successful after write job!', extra=extra_information)
except Exception as e:
logger.error(e, extra=extra_information) | python | def data_filler_customer(self, number_of_rows, cursor, conn):
'''creates and fills the table with customer
'''
customer_data = []
try:
for i in range(0, number_of_rows):
customer_data.append((
rnd_id_generator(self), self.faker.first_name(), self.faker.last_name(), self.faker.address(),
self.faker.country(), self.faker.city(), self.faker.date(pattern="%d-%m-%Y"),
self.faker.date(pattern="%d-%m-%Y"), self.faker.safe_email(), self.faker.phone_number(),
self.faker.locale()))
customer_payload = ("INSERT INTO customer "
"(id, name, lastname, address, country, city, registry_date, birthdate, email, "
"phone_number, locale)"
"VALUES (%s, %s, %s, %s, %s, %s, %s, %s, %s, %s, %s)")
cursor.executemany(customer_payload, customer_data)
conn.commit()
logger.warning('detailed_registration Commits are successful after write job!', extra=extra_information)
except Exception as e:
logger.error(e, extra=extra_information) | [
"def",
"data_filler_customer",
"(",
"self",
",",
"number_of_rows",
",",
"cursor",
",",
"conn",
")",
":",
"customer_data",
"=",
"[",
"]",
"try",
":",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_rows",
")",
":",
"customer_data",
".",
"append",
"("... | creates and fills the table with customer | [
"creates",
"and",
"fills",
"the",
"table",
"with",
"customer"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/mysql_handler.py#L278-L300 | train | 199,160 |
emirozer/fake2db | fake2db/fake2db.py | _mysqld_process_checkpoint | def _mysqld_process_checkpoint():
'''this helper method checks if
mysql server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep mysqld", shell=True)
except Exception:
logger.warning(
'Your mysql server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("mysqld", close_fds=True, shell=True)
time.sleep(3) | python | def _mysqld_process_checkpoint():
'''this helper method checks if
mysql server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep mysqld", shell=True)
except Exception:
logger.warning(
'Your mysql server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("mysqld", close_fds=True, shell=True)
time.sleep(3) | [
"def",
"_mysqld_process_checkpoint",
"(",
")",
":",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"\"pgrep mysqld\"",
",",
"shell",
"=",
"True",
")",
"except",
"Exception",
":",
"logger",
".",
"warning",
"(",
"'Your mysql server is offline, fake2db will try to l... | this helper method checks if
mysql server is available in the sys
if not fires up one | [
"this",
"helper",
"method",
"checks",
"if",
"mysql",
"server",
"is",
"available",
"in",
"the",
"sys",
"if",
"not",
"fires",
"up",
"one"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/fake2db.py#L20-L34 | train | 199,161 |
emirozer/fake2db | fake2db/fake2db.py | _redis_process_checkpoint | def _redis_process_checkpoint(host, port):
'''this helper method checks if
redis server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep redis", shell=True)
except Exception:
logger.warning(
'Your redis server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("redis-server --bind %s --port %s" % (host, port),
close_fds=True,
shell=True)
time.sleep(3) | python | def _redis_process_checkpoint(host, port):
'''this helper method checks if
redis server is available in the sys
if not fires up one
'''
try:
subprocess.check_output("pgrep redis", shell=True)
except Exception:
logger.warning(
'Your redis server is offline, fake2db will try to launch it now!',
extra=extra_information)
# close_fds = True argument is the flag that is responsible
# for Popen to launch the process completely independent
subprocess.Popen("redis-server --bind %s --port %s" % (host, port),
close_fds=True,
shell=True)
time.sleep(3) | [
"def",
"_redis_process_checkpoint",
"(",
"host",
",",
"port",
")",
":",
"try",
":",
"subprocess",
".",
"check_output",
"(",
"\"pgrep redis\"",
",",
"shell",
"=",
"True",
")",
"except",
"Exception",
":",
"logger",
".",
"warning",
"(",
"'Your redis server is offli... | this helper method checks if
redis server is available in the sys
if not fires up one | [
"this",
"helper",
"method",
"checks",
"if",
"redis",
"server",
"is",
"available",
"in",
"the",
"sys",
"if",
"not",
"fires",
"up",
"one"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/fake2db.py#L70-L86 | train | 199,162 |
emirozer/fake2db | fake2db/sqlite_handler.py | Fake2dbSqliteHandler.database_caller_creator | def database_caller_creator(self, name=None):
'''creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor
'''
try:
if name:
database = name + '.db'
else:
database = 'sqlite_' + str_generator(self) + '.db'
conn = sqlite3.connect(database)
logger.warning('Database created and opened succesfully: %s' % database, extra=d)
except Exception:
logger.error('Failed to connect or create database / sqlite3', extra=d)
raise DbConnException
return conn | python | def database_caller_creator(self, name=None):
'''creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor
'''
try:
if name:
database = name + '.db'
else:
database = 'sqlite_' + str_generator(self) + '.db'
conn = sqlite3.connect(database)
logger.warning('Database created and opened succesfully: %s' % database, extra=d)
except Exception:
logger.error('Failed to connect or create database / sqlite3', extra=d)
raise DbConnException
return conn | [
"def",
"database_caller_creator",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"try",
":",
"if",
"name",
":",
"database",
"=",
"name",
"+",
"'.db'",
"else",
":",
"database",
"=",
"'sqlite_'",
"+",
"str_generator",
"(",
"self",
")",
"+",
"'.db'",
"c... | creates a sqlite3 db
returns the related connection object
which will be later used to spawn the cursor | [
"creates",
"a",
"sqlite3",
"db",
"returns",
"the",
"related",
"connection",
"object",
"which",
"will",
"be",
"later",
"used",
"to",
"spawn",
"the",
"cursor"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/sqlite_handler.py#L73-L91 | train | 199,163 |
emirozer/fake2db | fake2db/couchdb_handler.py | Fake2dbCouchdbHandler.database_caller_creator | def database_caller_creator(self, name=None):
'''creates a couchdb database
returns the related connection object
which will be later used to spawn the cursor
'''
couch = couchdb.Server()
if name:
db = couch.create(name)
else:
n = 'couchdb_' + lower_str_generator(self)
db = couch.create(n)
logger.warning('couchdb database created with the name: %s', n,
extra=d)
return db | python | def database_caller_creator(self, name=None):
'''creates a couchdb database
returns the related connection object
which will be later used to spawn the cursor
'''
couch = couchdb.Server()
if name:
db = couch.create(name)
else:
n = 'couchdb_' + lower_str_generator(self)
db = couch.create(n)
logger.warning('couchdb database created with the name: %s', n,
extra=d)
return db | [
"def",
"database_caller_creator",
"(",
"self",
",",
"name",
"=",
"None",
")",
":",
"couch",
"=",
"couchdb",
".",
"Server",
"(",
")",
"if",
"name",
":",
"db",
"=",
"couch",
".",
"create",
"(",
"name",
")",
"else",
":",
"n",
"=",
"'couchdb_'",
"+",
"... | creates a couchdb database
returns the related connection object
which will be later used to spawn the cursor | [
"creates",
"a",
"couchdb",
"database",
"returns",
"the",
"related",
"connection",
"object",
"which",
"will",
"be",
"later",
"used",
"to",
"spawn",
"the",
"cursor"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/couchdb_handler.py#L29-L45 | train | 199,164 |
emirozer/fake2db | fake2db/couchdb_handler.py | Fake2dbCouchdbHandler.data_filler_detailed_registration | def data_filler_detailed_registration(self, number_of_rows, db):
'''creates and fills the table with detailed regis. information
'''
try:
detailed_registration = db
data_list = list()
for i in range(0, number_of_rows):
post_det_reg = {
"id": rnd_id_generator(self),
"email": self.faker.safe_email(),
"password": self.faker.md5(raw_output=False),
"lastname": self.faker.last_name(),
"name": self.faker.first_name(),
"adress": self.faker.address(),
"phone": self.faker.phone_number()
}
detailed_registration.save(post_det_reg)
logger.warning(
'detailed_registration Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_detailed_registration(self, number_of_rows, db):
'''creates and fills the table with detailed regis. information
'''
try:
detailed_registration = db
data_list = list()
for i in range(0, number_of_rows):
post_det_reg = {
"id": rnd_id_generator(self),
"email": self.faker.safe_email(),
"password": self.faker.md5(raw_output=False),
"lastname": self.faker.last_name(),
"name": self.faker.first_name(),
"adress": self.faker.address(),
"phone": self.faker.phone_number()
}
detailed_registration.save(post_det_reg)
logger.warning(
'detailed_registration Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_detailed_registration",
"(",
"self",
",",
"number_of_rows",
",",
"db",
")",
":",
"try",
":",
"detailed_registration",
"=",
"db",
"data_list",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_rows",
")",
":",
"... | creates and fills the table with detailed regis. information | [
"creates",
"and",
"fills",
"the",
"table",
"with",
"detailed",
"regis",
".",
"information"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/couchdb_handler.py#L95-L119 | train | 199,165 |
emirozer/fake2db | fake2db/couchdb_handler.py | Fake2dbCouchdbHandler.data_filler_customer | def data_filler_customer(self, number_of_rows, db):
'''creates and fills the table with customer data
'''
try:
customer = db
data_list = list()
for i in range(0, number_of_rows):
post_cus_reg = {
"id": rnd_id_generator(self),
"name": self.faker.first_name(),
"lastname": self.faker.last_name(),
"address": self.faker.address(),
"country": self.faker.country(),
"city": self.faker.city(),
"registry_date": self.faker.date(pattern="%d-%m-%Y"),
"birthdate": self.faker.date(pattern="%d-%m-%Y"),
"email": self.faker.safe_email(),
"phone_number": self.faker.phone_number(),
"locale": self.faker.locale()
}
customer.save(post_cus_reg)
logger.warning('customer Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) | python | def data_filler_customer(self, number_of_rows, db):
'''creates and fills the table with customer data
'''
try:
customer = db
data_list = list()
for i in range(0, number_of_rows):
post_cus_reg = {
"id": rnd_id_generator(self),
"name": self.faker.first_name(),
"lastname": self.faker.last_name(),
"address": self.faker.address(),
"country": self.faker.country(),
"city": self.faker.city(),
"registry_date": self.faker.date(pattern="%d-%m-%Y"),
"birthdate": self.faker.date(pattern="%d-%m-%Y"),
"email": self.faker.safe_email(),
"phone_number": self.faker.phone_number(),
"locale": self.faker.locale()
}
customer.save(post_cus_reg)
logger.warning('customer Commits are successful after write job!',
extra=d)
except Exception as e:
logger.error(e, extra=d) | [
"def",
"data_filler_customer",
"(",
"self",
",",
"number_of_rows",
",",
"db",
")",
":",
"try",
":",
"customer",
"=",
"db",
"data_list",
"=",
"list",
"(",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"number_of_rows",
")",
":",
"post_cus_reg",
"=",
"{... | creates and fills the table with customer data | [
"creates",
"and",
"fills",
"the",
"table",
"with",
"customer",
"data"
] | 568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c | https://github.com/emirozer/fake2db/blob/568cf42afb3ac10fc15c4faaa1cdb84fc1f4946c/fake2db/couchdb_handler.py#L166-L192 | train | 199,166 |
erikrose/parsimonious | parsimonious/nodes.py | NodeVisitor.visit | def visit(self, node):
"""Walk a parse tree, transforming it into another representation.
Recursively descend a parse tree, dispatching to the method named after
the rule in the :class:`~parsimonious.grammar.Grammar` that produced
each node. If, for example, a rule was... ::
bold = '<b>'
...the ``visit_bold()`` method would be called. It is your
responsibility to subclass :class:`NodeVisitor` and implement those
methods.
"""
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where in the tree it failed if it blows
# up.
try:
return method(node, [self.visit(n) for n in node])
except (VisitationError, UndefinedLabel):
# Don't catch and re-wrap already-wrapped exceptions.
raise
except self.unwrapped_exceptions:
raise
except Exception:
# Catch any exception, and tack on a parse tree so it's easier to
# see where it went wrong.
exc_class, exc, tb = exc_info()
reraise(VisitationError, VisitationError(exc, exc_class, node), tb) | python | def visit(self, node):
"""Walk a parse tree, transforming it into another representation.
Recursively descend a parse tree, dispatching to the method named after
the rule in the :class:`~parsimonious.grammar.Grammar` that produced
each node. If, for example, a rule was... ::
bold = '<b>'
...the ``visit_bold()`` method would be called. It is your
responsibility to subclass :class:`NodeVisitor` and implement those
methods.
"""
method = getattr(self, 'visit_' + node.expr_name, self.generic_visit)
# Call that method, and show where in the tree it failed if it blows
# up.
try:
return method(node, [self.visit(n) for n in node])
except (VisitationError, UndefinedLabel):
# Don't catch and re-wrap already-wrapped exceptions.
raise
except self.unwrapped_exceptions:
raise
except Exception:
# Catch any exception, and tack on a parse tree so it's easier to
# see where it went wrong.
exc_class, exc, tb = exc_info()
reraise(VisitationError, VisitationError(exc, exc_class, node), tb) | [
"def",
"visit",
"(",
"self",
",",
"node",
")",
":",
"method",
"=",
"getattr",
"(",
"self",
",",
"'visit_'",
"+",
"node",
".",
"expr_name",
",",
"self",
".",
"generic_visit",
")",
"# Call that method, and show where in the tree it failed if it blows",
"# up.",
"try... | Walk a parse tree, transforming it into another representation.
Recursively descend a parse tree, dispatching to the method named after
the rule in the :class:`~parsimonious.grammar.Grammar` that produced
each node. If, for example, a rule was... ::
bold = '<b>'
...the ``visit_bold()`` method would be called. It is your
responsibility to subclass :class:`NodeVisitor` and implement those
methods. | [
"Walk",
"a",
"parse",
"tree",
"transforming",
"it",
"into",
"another",
"representation",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/nodes.py#L198-L227 | train | 199,167 |
erikrose/parsimonious | parsimonious/nodes.py | NodeVisitor._parse_or_match | def _parse_or_match(self, text, pos, method_name):
"""Execute a parse or match on the default grammar, followed by a
visitation.
Raise RuntimeError if there is no default grammar specified.
"""
if not self.grammar:
raise RuntimeError(
"The {cls}.{method}() shortcut won't work because {cls} was "
"never associated with a specific " "grammar. Fill out its "
"`grammar` attribute, and try again.".format(
cls=self.__class__.__name__,
method=method_name))
return self.visit(getattr(self.grammar, method_name)(text, pos=pos)) | python | def _parse_or_match(self, text, pos, method_name):
"""Execute a parse or match on the default grammar, followed by a
visitation.
Raise RuntimeError if there is no default grammar specified.
"""
if not self.grammar:
raise RuntimeError(
"The {cls}.{method}() shortcut won't work because {cls} was "
"never associated with a specific " "grammar. Fill out its "
"`grammar` attribute, and try again.".format(
cls=self.__class__.__name__,
method=method_name))
return self.visit(getattr(self.grammar, method_name)(text, pos=pos)) | [
"def",
"_parse_or_match",
"(",
"self",
",",
"text",
",",
"pos",
",",
"method_name",
")",
":",
"if",
"not",
"self",
".",
"grammar",
":",
"raise",
"RuntimeError",
"(",
"\"The {cls}.{method}() shortcut won't work because {cls} was \"",
"\"never associated with a specific \""... | Execute a parse or match on the default grammar, followed by a
visitation.
Raise RuntimeError if there is no default grammar specified. | [
"Execute",
"a",
"parse",
"or",
"match",
"on",
"the",
"default",
"grammar",
"followed",
"by",
"a",
"visitation",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/nodes.py#L275-L289 | train | 199,168 |
erikrose/parsimonious | parsimonious/grammar.py | BootstrappingGrammar._expressions_from_rules | def _expressions_from_rules(self, rule_syntax, custom_rules):
"""Return the rules for parsing the grammar definition syntax.
Return a 2-tuple: a dict of rule names pointing to their expressions,
and then the top-level expression for the first rule.
"""
# Hard-code enough of the rules to parse the grammar that describes the
# grammar description language, to bootstrap:
comment = Regex(r'#[^\r\n]*', name='comment')
meaninglessness = OneOf(Regex(r'\s+'), comment, name='meaninglessness')
_ = ZeroOrMore(meaninglessness, name='_')
equals = Sequence(Literal('='), _, name='equals')
label = Sequence(Regex(r'[a-zA-Z_][a-zA-Z_0-9]*'), _, name='label')
reference = Sequence(label, Not(equals), name='reference')
quantifier = Sequence(Regex(r'[*+?]'), _, name='quantifier')
# This pattern supports empty literals. TODO: A problem?
spaceless_literal = Regex(r'u?r?"[^"\\]*(?:\\.[^"\\]*)*"',
ignore_case=True,
dot_all=True,
name='spaceless_literal')
literal = Sequence(spaceless_literal, _, name='literal')
regex = Sequence(Literal('~'),
literal,
Regex('[ilmsuxa]*', ignore_case=True),
_,
name='regex')
atom = OneOf(reference, literal, regex, name='atom')
quantified = Sequence(atom, quantifier, name='quantified')
term = OneOf(quantified, atom, name='term')
not_term = Sequence(Literal('!'), term, _, name='not_term')
term.members = (not_term,) + term.members
sequence = Sequence(term, OneOrMore(term), name='sequence')
or_term = Sequence(Literal('/'), _, term, name='or_term')
ored = Sequence(term, OneOrMore(or_term), name='ored')
expression = OneOf(ored, sequence, term, name='expression')
rule = Sequence(label, equals, expression, name='rule')
rules = Sequence(_, OneOrMore(rule), name='rules')
# Use those hard-coded rules to parse the (more extensive) rule syntax.
# (For example, unless I start using parentheses in the rule language
# definition itself, I should never have to hard-code expressions for
# those above.)
rule_tree = rules.parse(rule_syntax)
# Turn the parse tree into a map of expressions:
return RuleVisitor().visit(rule_tree) | python | def _expressions_from_rules(self, rule_syntax, custom_rules):
"""Return the rules for parsing the grammar definition syntax.
Return a 2-tuple: a dict of rule names pointing to their expressions,
and then the top-level expression for the first rule.
"""
# Hard-code enough of the rules to parse the grammar that describes the
# grammar description language, to bootstrap:
comment = Regex(r'#[^\r\n]*', name='comment')
meaninglessness = OneOf(Regex(r'\s+'), comment, name='meaninglessness')
_ = ZeroOrMore(meaninglessness, name='_')
equals = Sequence(Literal('='), _, name='equals')
label = Sequence(Regex(r'[a-zA-Z_][a-zA-Z_0-9]*'), _, name='label')
reference = Sequence(label, Not(equals), name='reference')
quantifier = Sequence(Regex(r'[*+?]'), _, name='quantifier')
# This pattern supports empty literals. TODO: A problem?
spaceless_literal = Regex(r'u?r?"[^"\\]*(?:\\.[^"\\]*)*"',
ignore_case=True,
dot_all=True,
name='spaceless_literal')
literal = Sequence(spaceless_literal, _, name='literal')
regex = Sequence(Literal('~'),
literal,
Regex('[ilmsuxa]*', ignore_case=True),
_,
name='regex')
atom = OneOf(reference, literal, regex, name='atom')
quantified = Sequence(atom, quantifier, name='quantified')
term = OneOf(quantified, atom, name='term')
not_term = Sequence(Literal('!'), term, _, name='not_term')
term.members = (not_term,) + term.members
sequence = Sequence(term, OneOrMore(term), name='sequence')
or_term = Sequence(Literal('/'), _, term, name='or_term')
ored = Sequence(term, OneOrMore(or_term), name='ored')
expression = OneOf(ored, sequence, term, name='expression')
rule = Sequence(label, equals, expression, name='rule')
rules = Sequence(_, OneOrMore(rule), name='rules')
# Use those hard-coded rules to parse the (more extensive) rule syntax.
# (For example, unless I start using parentheses in the rule language
# definition itself, I should never have to hard-code expressions for
# those above.)
rule_tree = rules.parse(rule_syntax)
# Turn the parse tree into a map of expressions:
return RuleVisitor().visit(rule_tree) | [
"def",
"_expressions_from_rules",
"(",
"self",
",",
"rule_syntax",
",",
"custom_rules",
")",
":",
"# Hard-code enough of the rules to parse the grammar that describes the",
"# grammar description language, to bootstrap:",
"comment",
"=",
"Regex",
"(",
"r'#[^\\r\\n]*'",
",",
"name... | Return the rules for parsing the grammar definition syntax.
Return a 2-tuple: a dict of rule names pointing to their expressions,
and then the top-level expression for the first rule. | [
"Return",
"the",
"rules",
"for",
"parsing",
"the",
"grammar",
"definition",
"syntax",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/grammar.py#L169-L218 | train | 199,169 |
erikrose/parsimonious | parsimonious/grammar.py | RuleVisitor.visit_parenthesized | def visit_parenthesized(self, node, parenthesized):
"""Treat a parenthesized subexpression as just its contents.
Its position in the tree suffices to maintain its grouping semantics.
"""
left_paren, _, expression, right_paren, _ = parenthesized
return expression | python | def visit_parenthesized(self, node, parenthesized):
"""Treat a parenthesized subexpression as just its contents.
Its position in the tree suffices to maintain its grouping semantics.
"""
left_paren, _, expression, right_paren, _ = parenthesized
return expression | [
"def",
"visit_parenthesized",
"(",
"self",
",",
"node",
",",
"parenthesized",
")",
":",
"left_paren",
",",
"_",
",",
"expression",
",",
"right_paren",
",",
"_",
"=",
"parenthesized",
"return",
"expression"
] | Treat a parenthesized subexpression as just its contents.
Its position in the tree suffices to maintain its grouping semantics. | [
"Treat",
"a",
"parenthesized",
"subexpression",
"as",
"just",
"its",
"contents",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/grammar.py#L295-L302 | train | 199,170 |
erikrose/parsimonious | parsimonious/grammar.py | RuleVisitor.visit_rule | def visit_rule(self, node, rule):
"""Assign a name to the Expression and return it."""
label, equals, expression = rule
expression.name = label # Assign a name to the expr.
return expression | python | def visit_rule(self, node, rule):
"""Assign a name to the Expression and return it."""
label, equals, expression = rule
expression.name = label # Assign a name to the expr.
return expression | [
"def",
"visit_rule",
"(",
"self",
",",
"node",
",",
"rule",
")",
":",
"label",
",",
"equals",
",",
"expression",
"=",
"rule",
"expression",
".",
"name",
"=",
"label",
"# Assign a name to the expr.",
"return",
"expression"
] | Assign a name to the Expression and return it. | [
"Assign",
"a",
"name",
"to",
"the",
"Expression",
"and",
"return",
"it",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/grammar.py#L321-L325 | train | 199,171 |
erikrose/parsimonious | parsimonious/grammar.py | RuleVisitor.visit_regex | def visit_regex(self, node, regex):
"""Return a ``Regex`` expression."""
tilde, literal, flags, _ = regex
flags = flags.text.upper()
pattern = literal.literal # Pull the string back out of the Literal
# object.
return Regex(pattern, ignore_case='I' in flags,
locale='L' in flags,
multiline='M' in flags,
dot_all='S' in flags,
unicode='U' in flags,
verbose='X' in flags,
ascii='A' in flags) | python | def visit_regex(self, node, regex):
"""Return a ``Regex`` expression."""
tilde, literal, flags, _ = regex
flags = flags.text.upper()
pattern = literal.literal # Pull the string back out of the Literal
# object.
return Regex(pattern, ignore_case='I' in flags,
locale='L' in flags,
multiline='M' in flags,
dot_all='S' in flags,
unicode='U' in flags,
verbose='X' in flags,
ascii='A' in flags) | [
"def",
"visit_regex",
"(",
"self",
",",
"node",
",",
"regex",
")",
":",
"tilde",
",",
"literal",
",",
"flags",
",",
"_",
"=",
"regex",
"flags",
"=",
"flags",
".",
"text",
".",
"upper",
"(",
")",
"pattern",
"=",
"literal",
".",
"literal",
"# Pull the ... | Return a ``Regex`` expression. | [
"Return",
"a",
"Regex",
"expression",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/grammar.py#L360-L372 | train | 199,172 |
erikrose/parsimonious | parsimonious/grammar.py | RuleVisitor._resolve_refs | def _resolve_refs(self, rule_map, expr, done):
"""Return an expression with all its lazy references recursively
resolved.
Resolve any lazy references in the expression ``expr``, recursing into
all subexpressions.
:arg done: The set of Expressions that have already been or are
currently being resolved, to ward off redundant work and prevent
infinite recursion for circular refs
"""
if isinstance(expr, LazyReference):
label = text_type(expr)
try:
reffed_expr = rule_map[label]
except KeyError:
raise UndefinedLabel(expr)
return self._resolve_refs(rule_map, reffed_expr, done)
else:
if getattr(expr, 'members', ()) and expr not in done:
# Prevents infinite recursion for circular refs. At worst, one
# of `expr.members` can refer back to `expr`, but it can't go
# any farther.
done.add(expr)
expr.members = tuple(self._resolve_refs(rule_map, member, done)
for member in expr.members)
return expr | python | def _resolve_refs(self, rule_map, expr, done):
"""Return an expression with all its lazy references recursively
resolved.
Resolve any lazy references in the expression ``expr``, recursing into
all subexpressions.
:arg done: The set of Expressions that have already been or are
currently being resolved, to ward off redundant work and prevent
infinite recursion for circular refs
"""
if isinstance(expr, LazyReference):
label = text_type(expr)
try:
reffed_expr = rule_map[label]
except KeyError:
raise UndefinedLabel(expr)
return self._resolve_refs(rule_map, reffed_expr, done)
else:
if getattr(expr, 'members', ()) and expr not in done:
# Prevents infinite recursion for circular refs. At worst, one
# of `expr.members` can refer back to `expr`, but it can't go
# any farther.
done.add(expr)
expr.members = tuple(self._resolve_refs(rule_map, member, done)
for member in expr.members)
return expr | [
"def",
"_resolve_refs",
"(",
"self",
",",
"rule_map",
",",
"expr",
",",
"done",
")",
":",
"if",
"isinstance",
"(",
"expr",
",",
"LazyReference",
")",
":",
"label",
"=",
"text_type",
"(",
"expr",
")",
"try",
":",
"reffed_expr",
"=",
"rule_map",
"[",
"la... | Return an expression with all its lazy references recursively
resolved.
Resolve any lazy references in the expression ``expr``, recursing into
all subexpressions.
:arg done: The set of Expressions that have already been or are
currently being resolved, to ward off redundant work and prevent
infinite recursion for circular refs | [
"Return",
"an",
"expression",
"with",
"all",
"its",
"lazy",
"references",
"recursively",
"resolved",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/grammar.py#L399-L426 | train | 199,173 |
erikrose/parsimonious | parsimonious/expressions.py | expression | def expression(callable, rule_name, grammar):
"""Turn a plain callable into an Expression.
The callable can be of this simple form::
def foo(text, pos):
'''If this custom expression matches starting at text[pos], return
the index where it stops matching. Otherwise, return None.'''
if the expression matched:
return end_pos
If there child nodes to return, return a tuple::
return end_pos, children
If the expression doesn't match at the given ``pos`` at all... ::
return None
If your callable needs to make sub-calls to other rules in the grammar or
do error reporting, it can take this form, gaining additional arguments::
def foo(text, pos, cache, error, grammar):
# Call out to other rules:
node = grammar['another_rule'].match_core(text, pos, cache, error)
...
# Return values as above.
The return value of the callable, if an int or a tuple, will be
automatically transmuted into a :class:`~parsimonious.Node`. If it returns
a Node-like class directly, it will be passed through unchanged.
:arg rule_name: The rule name to attach to the resulting
:class:`~parsimonious.Expression`
:arg grammar: The :class:`~parsimonious.Grammar` this expression will be a
part of, to make delegating to other rules possible
"""
num_args = len(getargspec(callable).args)
if num_args == 2:
is_simple = True
elif num_args == 5:
is_simple = False
else:
raise RuntimeError("Custom rule functions must take either 2 or 5 "
"arguments, not %s." % num_args)
class AdHocExpression(Expression):
def _uncached_match(self, text, pos, cache, error):
result = (callable(text, pos) if is_simple else
callable(text, pos, cache, error, grammar))
if isinstance(result, integer_types):
end, children = result, None
elif isinstance(result, tuple):
end, children = result
else:
# Node or None
return result
return Node(self, text, pos, end, children=children)
def _as_rhs(self):
return '{custom function "%s"}' % callable.__name__
return AdHocExpression(name=rule_name) | python | def expression(callable, rule_name, grammar):
"""Turn a plain callable into an Expression.
The callable can be of this simple form::
def foo(text, pos):
'''If this custom expression matches starting at text[pos], return
the index where it stops matching. Otherwise, return None.'''
if the expression matched:
return end_pos
If there child nodes to return, return a tuple::
return end_pos, children
If the expression doesn't match at the given ``pos`` at all... ::
return None
If your callable needs to make sub-calls to other rules in the grammar or
do error reporting, it can take this form, gaining additional arguments::
def foo(text, pos, cache, error, grammar):
# Call out to other rules:
node = grammar['another_rule'].match_core(text, pos, cache, error)
...
# Return values as above.
The return value of the callable, if an int or a tuple, will be
automatically transmuted into a :class:`~parsimonious.Node`. If it returns
a Node-like class directly, it will be passed through unchanged.
:arg rule_name: The rule name to attach to the resulting
:class:`~parsimonious.Expression`
:arg grammar: The :class:`~parsimonious.Grammar` this expression will be a
part of, to make delegating to other rules possible
"""
num_args = len(getargspec(callable).args)
if num_args == 2:
is_simple = True
elif num_args == 5:
is_simple = False
else:
raise RuntimeError("Custom rule functions must take either 2 or 5 "
"arguments, not %s." % num_args)
class AdHocExpression(Expression):
def _uncached_match(self, text, pos, cache, error):
result = (callable(text, pos) if is_simple else
callable(text, pos, cache, error, grammar))
if isinstance(result, integer_types):
end, children = result, None
elif isinstance(result, tuple):
end, children = result
else:
# Node or None
return result
return Node(self, text, pos, end, children=children)
def _as_rhs(self):
return '{custom function "%s"}' % callable.__name__
return AdHocExpression(name=rule_name) | [
"def",
"expression",
"(",
"callable",
",",
"rule_name",
",",
"grammar",
")",
":",
"num_args",
"=",
"len",
"(",
"getargspec",
"(",
"callable",
")",
".",
"args",
")",
"if",
"num_args",
"==",
"2",
":",
"is_simple",
"=",
"True",
"elif",
"num_args",
"==",
"... | Turn a plain callable into an Expression.
The callable can be of this simple form::
def foo(text, pos):
'''If this custom expression matches starting at text[pos], return
the index where it stops matching. Otherwise, return None.'''
if the expression matched:
return end_pos
If there child nodes to return, return a tuple::
return end_pos, children
If the expression doesn't match at the given ``pos`` at all... ::
return None
If your callable needs to make sub-calls to other rules in the grammar or
do error reporting, it can take this form, gaining additional arguments::
def foo(text, pos, cache, error, grammar):
# Call out to other rules:
node = grammar['another_rule'].match_core(text, pos, cache, error)
...
# Return values as above.
The return value of the callable, if an int or a tuple, will be
automatically transmuted into a :class:`~parsimonious.Node`. If it returns
a Node-like class directly, it will be passed through unchanged.
:arg rule_name: The rule name to attach to the resulting
:class:`~parsimonious.Expression`
:arg grammar: The :class:`~parsimonious.Grammar` this expression will be a
part of, to make delegating to other rules possible | [
"Turn",
"a",
"plain",
"callable",
"into",
"an",
"Expression",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/expressions.py#L22-L86 | train | 199,174 |
erikrose/parsimonious | parsimonious/expressions.py | Regex._uncached_match | def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match."""
m = self.re.match(text, pos)
if m is not None:
span = m.span()
node = RegexNode(self, text, pos, pos + span[1] - span[0])
node.match = m # TODO: A terrible idea for cache size?
return node | python | def _uncached_match(self, text, pos, cache, error):
"""Return length of match, ``None`` if no match."""
m = self.re.match(text, pos)
if m is not None:
span = m.span()
node = RegexNode(self, text, pos, pos + span[1] - span[0])
node.match = m # TODO: A terrible idea for cache size?
return node | [
"def",
"_uncached_match",
"(",
"self",
",",
"text",
",",
"pos",
",",
"cache",
",",
"error",
")",
":",
"m",
"=",
"self",
".",
"re",
".",
"match",
"(",
"text",
",",
"pos",
")",
"if",
"m",
"is",
"not",
"None",
":",
"span",
"=",
"m",
".",
"span",
... | Return length of match, ``None`` if no match. | [
"Return",
"length",
"of",
"match",
"None",
"if",
"no",
"match",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/expressions.py#L278-L285 | train | 199,175 |
erikrose/parsimonious | parsimonious/expressions.py | Regex._regex_flags_from_bits | def _regex_flags_from_bits(self, bits):
"""Return the textual equivalent of numerically encoded regex flags."""
flags = 'ilmsuxa'
return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1)) | python | def _regex_flags_from_bits(self, bits):
"""Return the textual equivalent of numerically encoded regex flags."""
flags = 'ilmsuxa'
return ''.join(flags[i - 1] if (1 << i) & bits else '' for i in range(1, len(flags) + 1)) | [
"def",
"_regex_flags_from_bits",
"(",
"self",
",",
"bits",
")",
":",
"flags",
"=",
"'ilmsuxa'",
"return",
"''",
".",
"join",
"(",
"flags",
"[",
"i",
"-",
"1",
"]",
"if",
"(",
"1",
"<<",
"i",
")",
"&",
"bits",
"else",
"''",
"for",
"i",
"in",
"rang... | Return the textual equivalent of numerically encoded regex flags. | [
"Return",
"the",
"textual",
"equivalent",
"of",
"numerically",
"encoded",
"regex",
"flags",
"."
] | 12263be5ceca89344905c2c3eb9ac5a603e976e1 | https://github.com/erikrose/parsimonious/blob/12263be5ceca89344905c2c3eb9ac5a603e976e1/parsimonious/expressions.py#L287-L290 | train | 199,176 |
jarrekk/imgkit | imgkit/imgkit.py | IMGKit._gegetate_args | def _gegetate_args(self, options):
"""
Generator of args parts based on options specification.
"""
for optkey, optval in self._normalize_options(options):
yield optkey
if isinstance(optval, (list, tuple)):
assert len(optval) == 2 and optval[0] and optval[
1], 'Option value can only be either a string or a (tuple, list) of 2 items'
yield optval[0]
yield optval[1]
else:
yield optval | python | def _gegetate_args(self, options):
"""
Generator of args parts based on options specification.
"""
for optkey, optval in self._normalize_options(options):
yield optkey
if isinstance(optval, (list, tuple)):
assert len(optval) == 2 and optval[0] and optval[
1], 'Option value can only be either a string or a (tuple, list) of 2 items'
yield optval[0]
yield optval[1]
else:
yield optval | [
"def",
"_gegetate_args",
"(",
"self",
",",
"options",
")",
":",
"for",
"optkey",
",",
"optval",
"in",
"self",
".",
"_normalize_options",
"(",
"options",
")",
":",
"yield",
"optkey",
"if",
"isinstance",
"(",
"optval",
",",
"(",
"list",
",",
"tuple",
")",
... | Generator of args parts based on options specification. | [
"Generator",
"of",
"args",
"parts",
"based",
"on",
"options",
"specification",
"."
] | 763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16 | https://github.com/jarrekk/imgkit/blob/763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16/imgkit/imgkit.py#L55-L68 | train | 199,177 |
jarrekk/imgkit | imgkit/imgkit.py | IMGKit._find_options_in_meta | def _find_options_in_meta(self, content):
"""Reads 'content' and extracts options encoded in HTML meta tags
:param content: str or file-like object - contains HTML to parse
returns:
dict: {config option: value}
"""
if (isinstance(content, io.IOBase)
or content.__class__.__name__ == 'StreamReaderWriter'):
content = content.read()
found = {}
for x in re.findall('<meta [^>]*>', content):
if re.search('name=["\']%s' % self.config.meta_tag_prefix, x):
name = re.findall('name=["\']%s([^"\']*)' %
self.config.meta_tag_prefix, x)[0]
found[name] = re.findall('content=["\']([^"\']*)', x)[0]
return found | python | def _find_options_in_meta(self, content):
"""Reads 'content' and extracts options encoded in HTML meta tags
:param content: str or file-like object - contains HTML to parse
returns:
dict: {config option: value}
"""
if (isinstance(content, io.IOBase)
or content.__class__.__name__ == 'StreamReaderWriter'):
content = content.read()
found = {}
for x in re.findall('<meta [^>]*>', content):
if re.search('name=["\']%s' % self.config.meta_tag_prefix, x):
name = re.findall('name=["\']%s([^"\']*)' %
self.config.meta_tag_prefix, x)[0]
found[name] = re.findall('content=["\']([^"\']*)', x)[0]
return found | [
"def",
"_find_options_in_meta",
"(",
"self",
",",
"content",
")",
":",
"if",
"(",
"isinstance",
"(",
"content",
",",
"io",
".",
"IOBase",
")",
"or",
"content",
".",
"__class__",
".",
"__name__",
"==",
"'StreamReaderWriter'",
")",
":",
"content",
"=",
"cont... | Reads 'content' and extracts options encoded in HTML meta tags
:param content: str or file-like object - contains HTML to parse
returns:
dict: {config option: value} | [
"Reads",
"content",
"and",
"extracts",
"options",
"encoded",
"in",
"HTML",
"meta",
"tags"
] | 763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16 | https://github.com/jarrekk/imgkit/blob/763296cc2e81b16b9c3ebd2cd4355ddd02d5ab16/imgkit/imgkit.py#L187-L207 | train | 199,178 |
James1345/django-rest-knox | knox/auth.py | TokenAuthentication.authenticate_credentials | def authenticate_credentials(self, token):
'''
Due to the random nature of hashing a salted value, this must inspect
each auth_token individually to find the correct one.
Tokens that have expired will be deleted and skipped
'''
msg = _('Invalid token.')
token = token.decode("utf-8")
for auth_token in AuthToken.objects.filter(
token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
if self._cleanup_token(auth_token):
continue
try:
digest = hash_token(token, auth_token.salt)
except (TypeError, binascii.Error):
raise exceptions.AuthenticationFailed(msg)
if compare_digest(digest, auth_token.digest):
if knox_settings.AUTO_REFRESH and auth_token.expiry:
self.renew_token(auth_token)
return self.validate_user(auth_token)
raise exceptions.AuthenticationFailed(msg) | python | def authenticate_credentials(self, token):
'''
Due to the random nature of hashing a salted value, this must inspect
each auth_token individually to find the correct one.
Tokens that have expired will be deleted and skipped
'''
msg = _('Invalid token.')
token = token.decode("utf-8")
for auth_token in AuthToken.objects.filter(
token_key=token[:CONSTANTS.TOKEN_KEY_LENGTH]):
if self._cleanup_token(auth_token):
continue
try:
digest = hash_token(token, auth_token.salt)
except (TypeError, binascii.Error):
raise exceptions.AuthenticationFailed(msg)
if compare_digest(digest, auth_token.digest):
if knox_settings.AUTO_REFRESH and auth_token.expiry:
self.renew_token(auth_token)
return self.validate_user(auth_token)
raise exceptions.AuthenticationFailed(msg) | [
"def",
"authenticate_credentials",
"(",
"self",
",",
"token",
")",
":",
"msg",
"=",
"_",
"(",
"'Invalid token.'",
")",
"token",
"=",
"token",
".",
"decode",
"(",
"\"utf-8\"",
")",
"for",
"auth_token",
"in",
"AuthToken",
".",
"objects",
".",
"filter",
"(",
... | Due to the random nature of hashing a salted value, this must inspect
each auth_token individually to find the correct one.
Tokens that have expired will be deleted and skipped | [
"Due",
"to",
"the",
"random",
"nature",
"of",
"hashing",
"a",
"salted",
"value",
"this",
"must",
"inspect",
"each",
"auth_token",
"individually",
"to",
"find",
"the",
"correct",
"one",
"."
] | 05f218f1922999d1be76753076cf8af78f134e02 | https://github.com/James1345/django-rest-knox/blob/05f218f1922999d1be76753076cf8af78f134e02/knox/auth.py#L56-L78 | train | 199,179 |
James1345/django-rest-knox | knox/crypto.py | hash_token | def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode() | python | def hash_token(token, salt):
'''
Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised
'''
digest = hashes.Hash(sha(), backend=default_backend())
digest.update(binascii.unhexlify(token))
digest.update(binascii.unhexlify(salt))
return binascii.hexlify(digest.finalize()).decode() | [
"def",
"hash_token",
"(",
"token",
",",
"salt",
")",
":",
"digest",
"=",
"hashes",
".",
"Hash",
"(",
"sha",
"(",
")",
",",
"backend",
"=",
"default_backend",
"(",
")",
")",
"digest",
".",
"update",
"(",
"binascii",
".",
"unhexlify",
"(",
"token",
")"... | Calculates the hash of a token and salt.
input is unhexlified
token and salt must contain an even number of hex digits or
a binascii.Error exception will be raised | [
"Calculates",
"the",
"hash",
"of",
"a",
"token",
"and",
"salt",
".",
"input",
"is",
"unhexlified"
] | 05f218f1922999d1be76753076cf8af78f134e02 | https://github.com/James1345/django-rest-knox/blob/05f218f1922999d1be76753076cf8af78f134e02/knox/crypto.py#L23-L34 | train | 199,180 |
vmagamedov/grpclib | grpclib/health/service.py | Health.Check | async def Check(self, stream):
"""Implements synchronous periodic checks"""
request = await stream.recv_message()
checks = self._checks.get(request.service)
if checks is None:
await stream.send_trailing_metadata(status=Status.NOT_FOUND)
elif len(checks) == 0:
await stream.send_message(HealthCheckResponse(
status=HealthCheckResponse.SERVING,
))
else:
for check in checks:
await check.__check__()
await stream.send_message(HealthCheckResponse(
status=_status(checks),
)) | python | async def Check(self, stream):
"""Implements synchronous periodic checks"""
request = await stream.recv_message()
checks = self._checks.get(request.service)
if checks is None:
await stream.send_trailing_metadata(status=Status.NOT_FOUND)
elif len(checks) == 0:
await stream.send_message(HealthCheckResponse(
status=HealthCheckResponse.SERVING,
))
else:
for check in checks:
await check.__check__()
await stream.send_message(HealthCheckResponse(
status=_status(checks),
)) | [
"async",
"def",
"Check",
"(",
"self",
",",
"stream",
")",
":",
"request",
"=",
"await",
"stream",
".",
"recv_message",
"(",
")",
"checks",
"=",
"self",
".",
"_checks",
".",
"get",
"(",
"request",
".",
"service",
")",
"if",
"checks",
"is",
"None",
":"... | Implements synchronous periodic checks | [
"Implements",
"synchronous",
"periodic",
"checks"
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/health/service.py#L73-L88 | train | 199,181 |
vmagamedov/grpclib | grpclib/health/check.py | ServiceStatus.set | def set(self, value: Optional[bool]):
"""Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
"""
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all watchers that this check was changed
for event in self._events:
event.set() | python | def set(self, value: Optional[bool]):
"""Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown)
"""
prev_value = self._value
self._value = value
if self._value != prev_value:
# notify all watchers that this check was changed
for event in self._events:
event.set() | [
"def",
"set",
"(",
"self",
",",
"value",
":",
"Optional",
"[",
"bool",
"]",
")",
":",
"prev_value",
"=",
"self",
".",
"_value",
"self",
".",
"_value",
"=",
"value",
"if",
"self",
".",
"_value",
"!=",
"prev_value",
":",
"# notify all watchers that this chec... | Sets current status of a check
:param value: ``True`` (healthy), ``False`` (unhealthy), or ``None``
(unknown) | [
"Sets",
"current",
"status",
"of",
"a",
"check"
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/health/check.py#L169-L180 | train | 199,182 |
vmagamedov/grpclib | grpclib/utils.py | graceful_exit | def graceful_exit(servers, *, loop,
signals=frozenset({signal.SIGINT, signal.SIGTERM})):
"""Utility context-manager to help properly shutdown server in response to
the OS signals
By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals.
There are two stages:
1. first received signal closes servers
2. subsequent signals raise ``SystemExit`` exception
Example:
.. code-block:: python3
async def main(...):
...
with graceful_exit([server], loop=loop):
await server.start(host, port)
print('Serving on {}:{}'.format(host, port))
await server.wait_closed()
print('Server closed')
First stage calls ``server.close()`` and ``await server.wait_closed()``
should complete successfully without errors. If server wasn't started yet,
second stage runs to prevent server start.
Second stage raises ``SystemExit`` exception, but you will receive
``asyncio.CancelledError`` in your ``async def main()`` coroutine. You
can use ``try..finally`` constructs and context-managers to properly handle
this error.
This context-manager is designed to work in cooperation with
:py:func:`python:asyncio.run` function:
.. code-block:: python3
if __name__ == '__main__':
asyncio.run(main())
:param servers: list of servers
:param loop: asyncio-compatible event loop
:param signals: set of the OS signals to handle
"""
signals = set(signals)
flag = []
for sig_num in signals:
loop.add_signal_handler(sig_num, _exit_handler, sig_num, servers, flag)
try:
yield
finally:
for sig_num in signals:
loop.remove_signal_handler(sig_num) | python | def graceful_exit(servers, *, loop,
signals=frozenset({signal.SIGINT, signal.SIGTERM})):
"""Utility context-manager to help properly shutdown server in response to
the OS signals
By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals.
There are two stages:
1. first received signal closes servers
2. subsequent signals raise ``SystemExit`` exception
Example:
.. code-block:: python3
async def main(...):
...
with graceful_exit([server], loop=loop):
await server.start(host, port)
print('Serving on {}:{}'.format(host, port))
await server.wait_closed()
print('Server closed')
First stage calls ``server.close()`` and ``await server.wait_closed()``
should complete successfully without errors. If server wasn't started yet,
second stage runs to prevent server start.
Second stage raises ``SystemExit`` exception, but you will receive
``asyncio.CancelledError`` in your ``async def main()`` coroutine. You
can use ``try..finally`` constructs and context-managers to properly handle
this error.
This context-manager is designed to work in cooperation with
:py:func:`python:asyncio.run` function:
.. code-block:: python3
if __name__ == '__main__':
asyncio.run(main())
:param servers: list of servers
:param loop: asyncio-compatible event loop
:param signals: set of the OS signals to handle
"""
signals = set(signals)
flag = []
for sig_num in signals:
loop.add_signal_handler(sig_num, _exit_handler, sig_num, servers, flag)
try:
yield
finally:
for sig_num in signals:
loop.remove_signal_handler(sig_num) | [
"def",
"graceful_exit",
"(",
"servers",
",",
"*",
",",
"loop",
",",
"signals",
"=",
"frozenset",
"(",
"{",
"signal",
".",
"SIGINT",
",",
"signal",
".",
"SIGTERM",
"}",
")",
")",
":",
"signals",
"=",
"set",
"(",
"signals",
")",
"flag",
"=",
"[",
"]"... | Utility context-manager to help properly shutdown server in response to
the OS signals
By default this context-manager handles ``SIGINT`` and ``SIGTERM`` signals.
There are two stages:
1. first received signal closes servers
2. subsequent signals raise ``SystemExit`` exception
Example:
.. code-block:: python3
async def main(...):
...
with graceful_exit([server], loop=loop):
await server.start(host, port)
print('Serving on {}:{}'.format(host, port))
await server.wait_closed()
print('Server closed')
First stage calls ``server.close()`` and ``await server.wait_closed()``
should complete successfully without errors. If server wasn't started yet,
second stage runs to prevent server start.
Second stage raises ``SystemExit`` exception, but you will receive
``asyncio.CancelledError`` in your ``async def main()`` coroutine. You
can use ``try..finally`` constructs and context-managers to properly handle
this error.
This context-manager is designed to work in cooperation with
:py:func:`python:asyncio.run` function:
.. code-block:: python3
if __name__ == '__main__':
asyncio.run(main())
:param servers: list of servers
:param loop: asyncio-compatible event loop
:param signals: set of the OS signals to handle | [
"Utility",
"context",
"-",
"manager",
"to",
"help",
"properly",
"shutdown",
"server",
"in",
"response",
"to",
"the",
"OS",
"signals"
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/utils.py#L134-L187 | train | 199,183 |
vmagamedov/grpclib | grpclib/server.py | Stream.recv_message | async def recv_message(self):
"""Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns None. To simplify your code
in this case, :py:class:`Stream` class implements async iteration
protocol, so you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so server will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message
"""
message = await recv_message(self._stream, self._codec, self._recv_type)
message, = await self._dispatch.recv_message(message)
return message | python | async def recv_message(self):
"""Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns None. To simplify your code
in this case, :py:class:`Stream` class implements async iteration
protocol, so you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so server will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message
"""
message = await recv_message(self._stream, self._codec, self._recv_type)
message, = await self._dispatch.recv_message(message)
return message | [
"async",
"def",
"recv_message",
"(",
"self",
")",
":",
"message",
"=",
"await",
"recv_message",
"(",
"self",
".",
"_stream",
",",
"self",
".",
"_codec",
",",
"self",
".",
"_recv_type",
")",
"message",
",",
"=",
"await",
"self",
".",
"_dispatch",
".",
"... | Coroutine to receive incoming message from the client.
If client sends UNARY request, then you can call this coroutine
only once. If client sends STREAM request, then you should call this
coroutine several times, until it returns None. To simplify your code
in this case, :py:class:`Stream` class implements async iteration
protocol, so you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so server will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message | [
"Coroutine",
"to",
"receive",
"incoming",
"message",
"from",
"the",
"client",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L70-L97 | train | 199,184 |
vmagamedov/grpclib | grpclib/server.py | Stream.send_initial_metadata | async def send_initial_metadata(self, *, metadata=None):
"""Coroutine to send headers with initial metadata to the client.
In gRPC you can send initial metadata as soon as possible, because
gRPC doesn't use `:status` pseudo header to indicate success or failure
of the current request. gRPC uses trailers for this purpose, and
trailers are sent during :py:meth:`send_trailing_metadata` call, which
should be called in the end.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
:param metadata: custom initial metadata, dict or list of pairs
"""
if self._send_initial_metadata_done:
raise ProtocolError('Initial metadata was already sent')
headers = [
(':status', '200'),
('content-type', self._content_type),
]
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_initial_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers)
self._send_initial_metadata_done = True | python | async def send_initial_metadata(self, *, metadata=None):
"""Coroutine to send headers with initial metadata to the client.
In gRPC you can send initial metadata as soon as possible, because
gRPC doesn't use `:status` pseudo header to indicate success or failure
of the current request. gRPC uses trailers for this purpose, and
trailers are sent during :py:meth:`send_trailing_metadata` call, which
should be called in the end.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
:param metadata: custom initial metadata, dict or list of pairs
"""
if self._send_initial_metadata_done:
raise ProtocolError('Initial metadata was already sent')
headers = [
(':status', '200'),
('content-type', self._content_type),
]
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_initial_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers)
self._send_initial_metadata_done = True | [
"async",
"def",
"send_initial_metadata",
"(",
"self",
",",
"*",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"self",
".",
"_send_initial_metadata_done",
":",
"raise",
"ProtocolError",
"(",
"'Initial metadata was already sent'",
")",
"headers",
"=",
"[",
"(",
"'... | Coroutine to send headers with initial metadata to the client.
In gRPC you can send initial metadata as soon as possible, because
gRPC doesn't use `:status` pseudo header to indicate success or failure
of the current request. gRPC uses trailers for this purpose, and
trailers are sent during :py:meth:`send_trailing_metadata` call, which
should be called in the end.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
:param metadata: custom initial metadata, dict or list of pairs | [
"Coroutine",
"to",
"send",
"headers",
"with",
"initial",
"metadata",
"to",
"the",
"client",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L99-L126 | train | 199,185 |
vmagamedov/grpclib | grpclib/server.py | Stream.send_message | async def send_message(self, message, **kwargs):
"""Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:param message: message object
"""
if 'end' in kwargs:
warnings.warn('"end" argument is deprecated, use '
'"stream.send_trailing_metadata" explicitly',
stacklevel=2)
end = kwargs.pop('end', False)
assert not kwargs, kwargs
if not self._send_initial_metadata_done:
await self.send_initial_metadata()
if not self._cardinality.server_streaming:
if self._send_message_count:
raise ProtocolError('Server should send exactly one message '
'in response')
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message, self._send_type)
self._send_message_count += 1
if end:
await self.send_trailing_metadata() | python | async def send_message(self, message, **kwargs):
"""Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:param message: message object
"""
if 'end' in kwargs:
warnings.warn('"end" argument is deprecated, use '
'"stream.send_trailing_metadata" explicitly',
stacklevel=2)
end = kwargs.pop('end', False)
assert not kwargs, kwargs
if not self._send_initial_metadata_done:
await self.send_initial_metadata()
if not self._cardinality.server_streaming:
if self._send_message_count:
raise ProtocolError('Server should send exactly one message '
'in response')
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message, self._send_type)
self._send_message_count += 1
if end:
await self.send_trailing_metadata() | [
"async",
"def",
"send_message",
"(",
"self",
",",
"message",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"'end'",
"in",
"kwargs",
":",
"warnings",
".",
"warn",
"(",
"'\"end\" argument is deprecated, use '",
"'\"stream.send_trailing_metadata\" explicitly'",
",",
"stackl... | Coroutine to send message to the client.
If server sends UNARY response, then you should call this coroutine only
once. If server sends STREAM response, then you can call this coroutine
as many times as you need.
:param message: message object | [
"Coroutine",
"to",
"send",
"message",
"to",
"the",
"client",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L128-L158 | train | 199,186 |
vmagamedov/grpclib | grpclib/server.py | Stream.send_trailing_metadata | async def send_trailing_metadata(self, *, status=Status.OK,
status_message=None, metadata=None):
"""Coroutine to send trailers with trailing metadata to the client.
This coroutine allows sending trailers-only responses, in case of some
failure conditions during handling current request, i.e. when
``status is not OK``.
.. note:: This coroutine will be called implicitly at exit from
request handler, with appropriate status code, if not called
explicitly during handler execution.
:param status: resulting status of this coroutine call
:param status_message: description for a status
:param metadata: custom trailing metadata, dict or list of pairs
"""
if self._send_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already sent')
if (
not self._cardinality.server_streaming
and not self._send_message_count
and status is Status.OK
):
raise ProtocolError('Unary response with OK status requires '
'a single message to be sent')
if self._send_initial_metadata_done:
headers = []
else:
# trailers-only response
headers = [(':status', '200')]
headers.append(('grpc-status', str(status.value)))
if status_message is not None:
headers.append(('grpc-message',
encode_grpc_message(status_message)))
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_trailing_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers, end_stream=True)
self._send_trailing_metadata_done = True
if status != Status.OK and self._stream.closable:
self._stream.reset_nowait() | python | async def send_trailing_metadata(self, *, status=Status.OK,
status_message=None, metadata=None):
"""Coroutine to send trailers with trailing metadata to the client.
This coroutine allows sending trailers-only responses, in case of some
failure conditions during handling current request, i.e. when
``status is not OK``.
.. note:: This coroutine will be called implicitly at exit from
request handler, with appropriate status code, if not called
explicitly during handler execution.
:param status: resulting status of this coroutine call
:param status_message: description for a status
:param metadata: custom trailing metadata, dict or list of pairs
"""
if self._send_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already sent')
if (
not self._cardinality.server_streaming
and not self._send_message_count
and status is Status.OK
):
raise ProtocolError('Unary response with OK status requires '
'a single message to be sent')
if self._send_initial_metadata_done:
headers = []
else:
# trailers-only response
headers = [(':status', '200')]
headers.append(('grpc-status', str(status.value)))
if status_message is not None:
headers.append(('grpc-message',
encode_grpc_message(status_message)))
metadata = MultiDict(metadata or ())
metadata, = await self._dispatch.send_trailing_metadata(metadata)
headers.extend(encode_metadata(metadata))
await self._stream.send_headers(headers, end_stream=True)
self._send_trailing_metadata_done = True
if status != Status.OK and self._stream.closable:
self._stream.reset_nowait() | [
"async",
"def",
"send_trailing_metadata",
"(",
"self",
",",
"*",
",",
"status",
"=",
"Status",
".",
"OK",
",",
"status_message",
"=",
"None",
",",
"metadata",
"=",
"None",
")",
":",
"if",
"self",
".",
"_send_trailing_metadata_done",
":",
"raise",
"ProtocolEr... | Coroutine to send trailers with trailing metadata to the client.
This coroutine allows sending trailers-only responses, in case of some
failure conditions during handling current request, i.e. when
``status is not OK``.
.. note:: This coroutine will be called implicitly at exit from
request handler, with appropriate status code, if not called
explicitly during handler execution.
:param status: resulting status of this coroutine call
:param status_message: description for a status
:param metadata: custom trailing metadata, dict or list of pairs | [
"Coroutine",
"to",
"send",
"trailers",
"with",
"trailing",
"metadata",
"to",
"the",
"client",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L160-L206 | train | 199,187 |
vmagamedov/grpclib | grpclib/server.py | Server.start | async def start(self, host=None, port=None, *, path=None,
family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
sock=None, backlog=100, ssl=None, reuse_address=None,
reuse_port=None):
"""Coroutine to start the server.
:param host: can be a string, containing IPv4/v6 address or domain name.
If host is None, server will be bound to all available interfaces.
:param port: port number.
:param path: UNIX domain socket path. If specified, host and port should
be omitted (must be None).
:param family: can be set to either :py:data:`python:socket.AF_INET` or
:py:data:`python:socket.AF_INET6` to force the socket to use IPv4 or
IPv6. If not set it will be determined from host.
:param flags: is a bitmask for
:py:meth:`~python:asyncio.AbstractEventLoop.getaddrinfo`.
:param sock: sock can optionally be specified in order to use a
preexisting socket object. If specified, host and port should be
omitted (must be None).
:param backlog: is the maximum number of queued connections passed to
listen().
:param ssl: can be set to an :py:class:`~python:ssl.SSLContext`
to enable SSL over the accepted connections.
:param reuse_address: tells the kernel to reuse a local socket in
TIME_WAIT state, without waiting for its natural timeout to expire.
:param reuse_port: tells the kernel to allow this endpoint to be bound
to the same port as other existing endpoints are bound to,
so long as they all set this flag when being created.
"""
if path is not None and (host is not None or port is not None):
raise ValueError("The 'path' parameter can not be used with the "
"'host' or 'port' parameters.")
if self._server is not None:
raise RuntimeError('Server is already started')
if path is not None:
self._server = await self._loop.create_unix_server(
self._protocol_factory, path, sock=sock, backlog=backlog,
ssl=ssl
)
else:
self._server = await self._loop.create_server(
self._protocol_factory, host, port,
family=family, flags=flags, sock=sock, backlog=backlog, ssl=ssl,
reuse_address=reuse_address, reuse_port=reuse_port
) | python | async def start(self, host=None, port=None, *, path=None,
family=socket.AF_UNSPEC, flags=socket.AI_PASSIVE,
sock=None, backlog=100, ssl=None, reuse_address=None,
reuse_port=None):
"""Coroutine to start the server.
:param host: can be a string, containing IPv4/v6 address or domain name.
If host is None, server will be bound to all available interfaces.
:param port: port number.
:param path: UNIX domain socket path. If specified, host and port should
be omitted (must be None).
:param family: can be set to either :py:data:`python:socket.AF_INET` or
:py:data:`python:socket.AF_INET6` to force the socket to use IPv4 or
IPv6. If not set it will be determined from host.
:param flags: is a bitmask for
:py:meth:`~python:asyncio.AbstractEventLoop.getaddrinfo`.
:param sock: sock can optionally be specified in order to use a
preexisting socket object. If specified, host and port should be
omitted (must be None).
:param backlog: is the maximum number of queued connections passed to
listen().
:param ssl: can be set to an :py:class:`~python:ssl.SSLContext`
to enable SSL over the accepted connections.
:param reuse_address: tells the kernel to reuse a local socket in
TIME_WAIT state, without waiting for its natural timeout to expire.
:param reuse_port: tells the kernel to allow this endpoint to be bound
to the same port as other existing endpoints are bound to,
so long as they all set this flag when being created.
"""
if path is not None and (host is not None or port is not None):
raise ValueError("The 'path' parameter can not be used with the "
"'host' or 'port' parameters.")
if self._server is not None:
raise RuntimeError('Server is already started')
if path is not None:
self._server = await self._loop.create_unix_server(
self._protocol_factory, path, sock=sock, backlog=backlog,
ssl=ssl
)
else:
self._server = await self._loop.create_server(
self._protocol_factory, host, port,
family=family, flags=flags, sock=sock, backlog=backlog, ssl=ssl,
reuse_address=reuse_address, reuse_port=reuse_port
) | [
"async",
"def",
"start",
"(",
"self",
",",
"host",
"=",
"None",
",",
"port",
"=",
"None",
",",
"*",
",",
"path",
"=",
"None",
",",
"family",
"=",
"socket",
".",
"AF_UNSPEC",
",",
"flags",
"=",
"socket",
".",
"AI_PASSIVE",
",",
"sock",
"=",
"None",
... | Coroutine to start the server.
:param host: can be a string, containing IPv4/v6 address or domain name.
If host is None, server will be bound to all available interfaces.
:param port: port number.
:param path: UNIX domain socket path. If specified, host and port should
be omitted (must be None).
:param family: can be set to either :py:data:`python:socket.AF_INET` or
:py:data:`python:socket.AF_INET6` to force the socket to use IPv4 or
IPv6. If not set it will be determined from host.
:param flags: is a bitmask for
:py:meth:`~python:asyncio.AbstractEventLoop.getaddrinfo`.
:param sock: sock can optionally be specified in order to use a
preexisting socket object. If specified, host and port should be
omitted (must be None).
:param backlog: is the maximum number of queued connections passed to
listen().
:param ssl: can be set to an :py:class:`~python:ssl.SSLContext`
to enable SSL over the accepted connections.
:param reuse_address: tells the kernel to reuse a local socket in
TIME_WAIT state, without waiting for its natural timeout to expire.
:param reuse_port: tells the kernel to allow this endpoint to be bound
to the same port as other existing endpoints are bound to,
so long as they all set this flag when being created. | [
"Coroutine",
"to",
"start",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L473-L529 | train | 199,188 |
vmagamedov/grpclib | grpclib/server.py | Server.close | def close(self):
"""Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly.
"""
if self._server is None:
raise RuntimeError('Server is not started')
self._server.close()
for handler in self._handlers:
handler.close() | python | def close(self):
"""Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly.
"""
if self._server is None:
raise RuntimeError('Server is not started')
self._server.close()
for handler in self._handlers:
handler.close() | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Server is not started'",
")",
"self",
".",
"_server",
".",
"close",
"(",
")",
"for",
"handler",
"in",
"self",
".",
"_handlers",
":",
... | Stops accepting new connections, cancels all currently running
requests. Request handlers are able to handle `CancelledError` and
exit properly. | [
"Stops",
"accepting",
"new",
"connections",
"cancels",
"all",
"currently",
"running",
"requests",
".",
"Request",
"handlers",
"are",
"able",
"to",
"handle",
"CancelledError",
"and",
"exit",
"properly",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L531-L540 | train | 199,189 |
vmagamedov/grpclib | grpclib/server.py | Server.wait_closed | async def wait_closed(self):
"""Coroutine to wait until all existing request handlers will exit
properly.
"""
if self._server is None:
raise RuntimeError('Server is not started')
await self._server.wait_closed()
if self._handlers:
await asyncio.wait({h.wait_closed() for h in self._handlers},
loop=self._loop) | python | async def wait_closed(self):
"""Coroutine to wait until all existing request handlers will exit
properly.
"""
if self._server is None:
raise RuntimeError('Server is not started')
await self._server.wait_closed()
if self._handlers:
await asyncio.wait({h.wait_closed() for h in self._handlers},
loop=self._loop) | [
"async",
"def",
"wait_closed",
"(",
"self",
")",
":",
"if",
"self",
".",
"_server",
"is",
"None",
":",
"raise",
"RuntimeError",
"(",
"'Server is not started'",
")",
"await",
"self",
".",
"_server",
".",
"wait_closed",
"(",
")",
"if",
"self",
".",
"_handler... | Coroutine to wait until all existing request handlers will exit
properly. | [
"Coroutine",
"to",
"wait",
"until",
"all",
"existing",
"request",
"handlers",
"will",
"exit",
"properly",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/server.py#L542-L551 | train | 199,190 |
vmagamedov/grpclib | grpclib/client.py | Stream.send_request | async def send_request(self):
"""Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
"""
if self._send_request_done:
raise ProtocolError('Request is already sent')
with self._wrapper:
protocol = await self._channel.__connect__()
stream = protocol.processor.connection\
.create_stream(wrapper=self._wrapper)
headers = [
(':method', 'POST'),
(':scheme', self._channel._scheme),
(':path', self._method_name),
(':authority', self._channel._authority),
]
if self._deadline is not None:
timeout = self._deadline.time_remaining()
headers.append(('grpc-timeout', encode_timeout(timeout)))
content_type = (GRPC_CONTENT_TYPE
+ '+' + self._codec.__content_subtype__)
headers.extend((
('te', 'trailers'),
('content-type', content_type),
('user-agent', USER_AGENT),
))
metadata, = await self._dispatch.send_request(
self._metadata,
method_name=self._method_name,
deadline=self._deadline,
content_type=content_type,
)
headers.extend(encode_metadata(metadata))
release_stream = await stream.send_request(
headers, _processor=protocol.processor,
)
self._stream = stream
self._release_stream = release_stream
self._send_request_done = True | python | async def send_request(self):
"""Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly.
"""
if self._send_request_done:
raise ProtocolError('Request is already sent')
with self._wrapper:
protocol = await self._channel.__connect__()
stream = protocol.processor.connection\
.create_stream(wrapper=self._wrapper)
headers = [
(':method', 'POST'),
(':scheme', self._channel._scheme),
(':path', self._method_name),
(':authority', self._channel._authority),
]
if self._deadline is not None:
timeout = self._deadline.time_remaining()
headers.append(('grpc-timeout', encode_timeout(timeout)))
content_type = (GRPC_CONTENT_TYPE
+ '+' + self._codec.__content_subtype__)
headers.extend((
('te', 'trailers'),
('content-type', content_type),
('user-agent', USER_AGENT),
))
metadata, = await self._dispatch.send_request(
self._metadata,
method_name=self._method_name,
deadline=self._deadline,
content_type=content_type,
)
headers.extend(encode_metadata(metadata))
release_stream = await stream.send_request(
headers, _processor=protocol.processor,
)
self._stream = stream
self._release_stream = release_stream
self._send_request_done = True | [
"async",
"def",
"send_request",
"(",
"self",
")",
":",
"if",
"self",
".",
"_send_request_done",
":",
"raise",
"ProtocolError",
"(",
"'Request is already sent'",
")",
"with",
"self",
".",
"_wrapper",
":",
"protocol",
"=",
"await",
"self",
".",
"_channel",
".",
... | Coroutine to send request headers with metadata to the server.
New HTTP/2 stream will be created during this coroutine call.
.. note:: This coroutine will be called implicitly during first
:py:meth:`send_message` coroutine call, if not called before
explicitly. | [
"Coroutine",
"to",
"send",
"request",
"headers",
"with",
"metadata",
"to",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L120-L165 | train | 199,191 |
vmagamedov/grpclib | grpclib/client.py | Stream.send_message | async def send_message(self, message, *, end=False):
"""Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:: It is important to finally end stream from the client-side
when you finished sending messages.
You can do this in two ways:
- specify ``end=True`` argument while sending last message - and last
DATA frame will include END_STREAM flag;
- call :py:meth:`end` coroutine after sending last message - and extra
HEADERS frame with END_STREAM flag will be sent.
First approach is preferred, because it doesn't require sending
additional HTTP/2 frame.
"""
if not self._send_request_done:
await self.send_request()
if end and self._end_done:
raise ProtocolError('Stream was already ended')
with self._wrapper:
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message,
self._send_type, end=end)
self._send_message_count += 1
if end:
self._end_done = True | python | async def send_message(self, message, *, end=False):
"""Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:: It is important to finally end stream from the client-side
when you finished sending messages.
You can do this in two ways:
- specify ``end=True`` argument while sending last message - and last
DATA frame will include END_STREAM flag;
- call :py:meth:`end` coroutine after sending last message - and extra
HEADERS frame with END_STREAM flag will be sent.
First approach is preferred, because it doesn't require sending
additional HTTP/2 frame.
"""
if not self._send_request_done:
await self.send_request()
if end and self._end_done:
raise ProtocolError('Stream was already ended')
with self._wrapper:
message, = await self._dispatch.send_message(message)
await send_message(self._stream, self._codec, message,
self._send_type, end=end)
self._send_message_count += 1
if end:
self._end_done = True | [
"async",
"def",
"send_message",
"(",
"self",
",",
"message",
",",
"*",
",",
"end",
"=",
"False",
")",
":",
"if",
"not",
"self",
".",
"_send_request_done",
":",
"await",
"self",
".",
"send_request",
"(",
")",
"if",
"end",
"and",
"self",
".",
"_end_done"... | Coroutine to send message to the server.
If client sends UNARY request, then you should call this coroutine only
once. If client sends STREAM request, then you can call this coroutine
as many times as you need.
.. warning:: It is important to finally end stream from the client-side
when you finished sending messages.
You can do this in two ways:
- specify ``end=True`` argument while sending last message - and last
DATA frame will include END_STREAM flag;
- call :py:meth:`end` coroutine after sending last message - and extra
HEADERS frame with END_STREAM flag will be sent.
First approach is preferred, because it doesn't require sending
additional HTTP/2 frame. | [
"Coroutine",
"to",
"send",
"message",
"to",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L167-L199 | train | 199,192 |
vmagamedov/grpclib | grpclib/client.py | Stream.end | async def end(self):
"""Coroutine to end stream from the client-side.
It should be used to finally end stream from the client-side when we're
finished sending messages to the server and stream wasn't closed with
last DATA frame. See :py:meth:`send_message` for more details.
HTTP/2 stream will have half-closed (local) state after this coroutine
call.
"""
if self._end_done:
raise ProtocolError('Stream was already ended')
if (
not self._cardinality.client_streaming
and not self._send_message_count
):
raise ProtocolError('Unary request requires a single message '
'to be sent')
await self._stream.end()
self._end_done = True | python | async def end(self):
"""Coroutine to end stream from the client-side.
It should be used to finally end stream from the client-side when we're
finished sending messages to the server and stream wasn't closed with
last DATA frame. See :py:meth:`send_message` for more details.
HTTP/2 stream will have half-closed (local) state after this coroutine
call.
"""
if self._end_done:
raise ProtocolError('Stream was already ended')
if (
not self._cardinality.client_streaming
and not self._send_message_count
):
raise ProtocolError('Unary request requires a single message '
'to be sent')
await self._stream.end()
self._end_done = True | [
"async",
"def",
"end",
"(",
"self",
")",
":",
"if",
"self",
".",
"_end_done",
":",
"raise",
"ProtocolError",
"(",
"'Stream was already ended'",
")",
"if",
"(",
"not",
"self",
".",
"_cardinality",
".",
"client_streaming",
"and",
"not",
"self",
".",
"_send_mes... | Coroutine to end stream from the client-side.
It should be used to finally end stream from the client-side when we're
finished sending messages to the server and stream wasn't closed with
last DATA frame. See :py:meth:`send_message` for more details.
HTTP/2 stream will have half-closed (local) state after this coroutine
call. | [
"Coroutine",
"to",
"end",
"stream",
"from",
"the",
"client",
"-",
"side",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L201-L222 | train | 199,193 |
vmagamedov/grpclib | grpclib/client.py | Stream.recv_initial_metadata | async def recv_initial_metadata(self):
"""Coroutine to wait for headers with initial metadata from the server.
.. note:: This coroutine will be called implicitly during first
:py:meth:`recv_message` coroutine call, if not called before
explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers-only
response.
When this coroutine finishes, you can access received initial metadata
by using :py:attr:`initial_metadata` attribute.
"""
if not self._send_request_done:
raise ProtocolError('Request was not sent yet')
if self._recv_initial_metadata_done:
raise ProtocolError('Initial metadata was already received')
try:
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_initial_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_initial_metadata(metadata)
self.initial_metadata = metadata
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
content_type = headers_map.get('content-type')
if content_type is None:
raise GRPCError(Status.UNKNOWN,
'Missing content-type header')
base_content_type, _, sub_type = content_type.partition('+')
sub_type = sub_type or ProtoCodec.__content_subtype__
if (
base_content_type != GRPC_CONTENT_TYPE
or sub_type != self._codec.__content_subtype__
):
raise GRPCError(Status.UNKNOWN,
'Invalid content-type: {!r}'
.format(content_type))
except StreamTerminatedError:
# Server can send RST_STREAM frame right after sending trailers-only
# response, so we have to check received headers and probably raise
# more descriptive error
headers = self._stream.recv_headers_nowait()
if headers is None:
raise
else:
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
# If there are no errors in the headers, just reraise original
# StreamTerminatedError
raise | python | async def recv_initial_metadata(self):
"""Coroutine to wait for headers with initial metadata from the server.
.. note:: This coroutine will be called implicitly during first
:py:meth:`recv_message` coroutine call, if not called before
explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers-only
response.
When this coroutine finishes, you can access received initial metadata
by using :py:attr:`initial_metadata` attribute.
"""
if not self._send_request_done:
raise ProtocolError('Request was not sent yet')
if self._recv_initial_metadata_done:
raise ProtocolError('Initial metadata was already received')
try:
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_initial_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_initial_metadata(metadata)
self.initial_metadata = metadata
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
content_type = headers_map.get('content-type')
if content_type is None:
raise GRPCError(Status.UNKNOWN,
'Missing content-type header')
base_content_type, _, sub_type = content_type.partition('+')
sub_type = sub_type or ProtoCodec.__content_subtype__
if (
base_content_type != GRPC_CONTENT_TYPE
or sub_type != self._codec.__content_subtype__
):
raise GRPCError(Status.UNKNOWN,
'Invalid content-type: {!r}'
.format(content_type))
except StreamTerminatedError:
# Server can send RST_STREAM frame right after sending trailers-only
# response, so we have to check received headers and probably raise
# more descriptive error
headers = self._stream.recv_headers_nowait()
if headers is None:
raise
else:
headers_map = dict(headers)
self._raise_for_status(headers_map)
self._raise_for_grpc_status(headers_map, optional=True)
# If there are no errors in the headers, just reraise original
# StreamTerminatedError
raise | [
"async",
"def",
"recv_initial_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_send_request_done",
":",
"raise",
"ProtocolError",
"(",
"'Request was not sent yet'",
")",
"if",
"self",
".",
"_recv_initial_metadata_done",
":",
"raise",
"ProtocolError",
"(... | Coroutine to wait for headers with initial metadata from the server.
.. note:: This coroutine will be called implicitly during first
:py:meth:`recv_message` coroutine call, if not called before
explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers-only
response.
When this coroutine finishes, you can access received initial metadata
by using :py:attr:`initial_metadata` attribute. | [
"Coroutine",
"to",
"wait",
"for",
"headers",
"with",
"initial",
"metadata",
"from",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L252-L312 | train | 199,194 |
vmagamedov/grpclib | grpclib/client.py | Stream.recv_message | async def recv_message(self):
"""Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns None. To simplify you code in
this case, :py:class:`Stream` implements async iterations protocol, so
you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so client will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message
"""
# TODO: check that messages were sent for non-stream-stream requests
if not self._recv_initial_metadata_done:
await self.recv_initial_metadata()
with self._wrapper:
message = await recv_message(self._stream, self._codec,
self._recv_type)
self._recv_message_count += 1
message, = await self._dispatch.recv_message(message)
return message | python | async def recv_message(self):
"""Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns None. To simplify you code in
this case, :py:class:`Stream` implements async iterations protocol, so
you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so client will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message
"""
# TODO: check that messages were sent for non-stream-stream requests
if not self._recv_initial_metadata_done:
await self.recv_initial_metadata()
with self._wrapper:
message = await recv_message(self._stream, self._codec,
self._recv_type)
self._recv_message_count += 1
message, = await self._dispatch.recv_message(message)
return message | [
"async",
"def",
"recv_message",
"(",
"self",
")",
":",
"# TODO: check that messages were sent for non-stream-stream requests",
"if",
"not",
"self",
".",
"_recv_initial_metadata_done",
":",
"await",
"self",
".",
"recv_initial_metadata",
"(",
")",
"with",
"self",
".",
"_w... | Coroutine to receive incoming message from the server.
If server sends UNARY response, then you can call this coroutine only
once. If server sends STREAM response, then you should call this
coroutine several times, until it returns None. To simplify you code in
this case, :py:class:`Stream` implements async iterations protocol, so
you can use it like this:
.. code-block:: python3
async for massage in stream:
do_smth_with(message)
or even like this:
.. code-block:: python3
messages = [msg async for msg in stream]
HTTP/2 has flow control mechanism, so client will acknowledge received
DATA frames as a message only after user consumes this coroutine.
:returns: message | [
"Coroutine",
"to",
"receive",
"incoming",
"message",
"from",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L314-L348 | train | 199,195 |
vmagamedov/grpclib | grpclib/client.py | Stream.recv_trailing_metadata | async def recv_trailing_metadata(self):
"""Coroutine to wait for trailers with trailing metadata from the
server.
.. note:: This coroutine will be called implicitly at exit from
this call (context manager's exit), if not called before explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers.
When this coroutine finishes, you can access received trailing metadata
by using :py:attr:`trailing_metadata` attribute.
"""
if not self._end_done:
raise ProtocolError('Outgoing stream was not ended')
if (
not self._cardinality.server_streaming
and not self._recv_message_count
):
raise ProtocolError('No messages were received before waiting '
'for trailing metadata')
if self._recv_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already received')
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_trailing_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_trailing_metadata(metadata)
self.trailing_metadata = metadata
self._raise_for_grpc_status(dict(headers)) | python | async def recv_trailing_metadata(self):
"""Coroutine to wait for trailers with trailing metadata from the
server.
.. note:: This coroutine will be called implicitly at exit from
this call (context manager's exit), if not called before explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers.
When this coroutine finishes, you can access received trailing metadata
by using :py:attr:`trailing_metadata` attribute.
"""
if not self._end_done:
raise ProtocolError('Outgoing stream was not ended')
if (
not self._cardinality.server_streaming
and not self._recv_message_count
):
raise ProtocolError('No messages were received before waiting '
'for trailing metadata')
if self._recv_trailing_metadata_done:
raise ProtocolError('Trailing metadata was already received')
with self._wrapper:
headers = await self._stream.recv_headers()
self._recv_trailing_metadata_done = True
metadata = decode_metadata(headers)
metadata, = await self._dispatch.recv_trailing_metadata(metadata)
self.trailing_metadata = metadata
self._raise_for_grpc_status(dict(headers)) | [
"async",
"def",
"recv_trailing_metadata",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_end_done",
":",
"raise",
"ProtocolError",
"(",
"'Outgoing stream was not ended'",
")",
"if",
"(",
"not",
"self",
".",
"_cardinality",
".",
"server_streaming",
"and",
"no... | Coroutine to wait for trailers with trailing metadata from the
server.
.. note:: This coroutine will be called implicitly at exit from
this call (context manager's exit), if not called before explicitly.
May raise :py:class:`~grpclib.exceptions.GRPCError` if server returned
non-:py:attr:`Status.OK <grpclib.const.Status.OK>` in trailers.
When this coroutine finishes, you can access received trailing metadata
by using :py:attr:`trailing_metadata` attribute. | [
"Coroutine",
"to",
"wait",
"for",
"trailers",
"with",
"trailing",
"metadata",
"from",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L350-L384 | train | 199,196 |
vmagamedov/grpclib | grpclib/client.py | Channel.close | def close(self):
"""Closes connection to the server.
"""
if self._protocol is not None:
self._protocol.processor.close()
del self._protocol | python | def close(self):
"""Closes connection to the server.
"""
if self._protocol is not None:
self._protocol.processor.close()
del self._protocol | [
"def",
"close",
"(",
"self",
")",
":",
"if",
"self",
".",
"_protocol",
"is",
"not",
"None",
":",
"self",
".",
"_protocol",
".",
"processor",
".",
"close",
"(",
")",
"del",
"self",
".",
"_protocol"
] | Closes connection to the server. | [
"Closes",
"connection",
"to",
"the",
"server",
"."
] | e4a0af8d2802297586cf8d67d2d3e65f31c09dae | https://github.com/vmagamedov/grpclib/blob/e4a0af8d2802297586cf8d67d2d3e65f31c09dae/grpclib/client.py#L557-L562 | train | 199,197 |
NiklasRosenstein/pydoc-markdown | pydocmd/__main__.py | read_config | def read_config():
"""
Reads and preprocesses the pydoc-markdown configuration file.
"""
with open(PYDOCMD_CONFIG) as fp:
config = yaml.load(fp)
return default_config(config) | python | def read_config():
"""
Reads and preprocesses the pydoc-markdown configuration file.
"""
with open(PYDOCMD_CONFIG) as fp:
config = yaml.load(fp)
return default_config(config) | [
"def",
"read_config",
"(",
")",
":",
"with",
"open",
"(",
"PYDOCMD_CONFIG",
")",
"as",
"fp",
":",
"config",
"=",
"yaml",
".",
"load",
"(",
"fp",
")",
"return",
"default_config",
"(",
"config",
")"
] | Reads and preprocesses the pydoc-markdown configuration file. | [
"Reads",
"and",
"preprocesses",
"the",
"pydoc",
"-",
"markdown",
"configuration",
"file",
"."
] | e7e93b2bf7f7535e0de4cd275058fc9865dff21b | https://github.com/NiklasRosenstein/pydoc-markdown/blob/e7e93b2bf7f7535e0de4cd275058fc9865dff21b/pydocmd/__main__.py#L41-L48 | train | 199,198 |
NiklasRosenstein/pydoc-markdown | pydocmd/__main__.py | write_temp_mkdocs_config | def write_temp_mkdocs_config(inconf):
"""
Generates a configuration for MkDocs on-the-fly from the pydoc-markdown
configuration and makes sure it gets removed when this program exists.
"""
ignored_keys = ('gens_dir', 'pages', 'headers', 'generate', 'loader',
'preprocessor', 'additional_search_paths')
config = {key: value for key, value in inconf.items() if key not in ignored_keys}
config['docs_dir'] = inconf['gens_dir']
if 'pages' in inconf:
config['nav'] = inconf['pages']
with open('mkdocs.yml', 'w') as fp:
yaml.dump(config, fp)
atexit.register(lambda: os.remove('mkdocs.yml')) | python | def write_temp_mkdocs_config(inconf):
"""
Generates a configuration for MkDocs on-the-fly from the pydoc-markdown
configuration and makes sure it gets removed when this program exists.
"""
ignored_keys = ('gens_dir', 'pages', 'headers', 'generate', 'loader',
'preprocessor', 'additional_search_paths')
config = {key: value for key, value in inconf.items() if key not in ignored_keys}
config['docs_dir'] = inconf['gens_dir']
if 'pages' in inconf:
config['nav'] = inconf['pages']
with open('mkdocs.yml', 'w') as fp:
yaml.dump(config, fp)
atexit.register(lambda: os.remove('mkdocs.yml')) | [
"def",
"write_temp_mkdocs_config",
"(",
"inconf",
")",
":",
"ignored_keys",
"=",
"(",
"'gens_dir'",
",",
"'pages'",
",",
"'headers'",
",",
"'generate'",
",",
"'loader'",
",",
"'preprocessor'",
",",
"'additional_search_paths'",
")",
"config",
"=",
"{",
"key",
":"... | Generates a configuration for MkDocs on-the-fly from the pydoc-markdown
configuration and makes sure it gets removed when this program exists. | [
"Generates",
"a",
"configuration",
"for",
"MkDocs",
"on",
"-",
"the",
"-",
"fly",
"from",
"the",
"pydoc",
"-",
"markdown",
"configuration",
"and",
"makes",
"sure",
"it",
"gets",
"removed",
"when",
"this",
"program",
"exists",
"."
] | e7e93b2bf7f7535e0de4cd275058fc9865dff21b | https://github.com/NiklasRosenstein/pydoc-markdown/blob/e7e93b2bf7f7535e0de4cd275058fc9865dff21b/pydocmd/__main__.py#L67-L83 | train | 199,199 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.