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 |
|---|---|---|---|---|---|---|---|---|---|---|---|---|
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.applicable_file_flags | def applicable_file_flags(self):
"""
Return the applicable file flags attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.APPLICABLE_FILE_FLAGS) | python | def applicable_file_flags(self):
"""
Return the applicable file flags attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.APPLICABLE_FILE_FLAGS) | [
"def",
"applicable_file_flags",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"APPLICABLE_FILE_FLAGS",
")"
] | Return the applicable file flags attribute of the BFD file being
processed. | [
"Return",
"the",
"applicable",
"file",
"flags",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L524-L534 | train | 238,600 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.my_archieve | def my_archieve(self):
"""Return the my archieve attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.MY_ARCHIEVE) | python | def my_archieve(self):
"""Return the my archieve attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.MY_ARCHIEVE) | [
"def",
"my_archieve",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"MY_ARCHIEVE",
")"
] | Return the my archieve attribute of the BFD file being processed. | [
"Return",
"the",
"my",
"archieve",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L537-L542 | train | 238,601 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.has_map | def has_map(self):
"""Return the has map attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.HAS_MAP) | python | def has_map(self):
"""Return the has map attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.HAS_MAP) | [
"def",
"has_map",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"HAS_MAP",
")"
] | Return the has map attribute of the BFD file being processed. | [
"Return",
"the",
"has",
"map",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L545-L550 | train | 238,602 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.is_thin_archieve | def is_thin_archieve(self):
"""
Return the is thin archieve attribute of the BFD file being processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.IS_THIN_ARCHIEVE) | python | def is_thin_archieve(self):
"""
Return the is thin archieve attribute of the BFD file being processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.IS_THIN_ARCHIEVE) | [
"def",
"is_thin_archieve",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"IS_THIN_ARCHIEVE",
")"
] | Return the is thin archieve attribute of the BFD file being processed. | [
"Return",
"the",
"is",
"thin",
"archieve",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L553-L561 | train | 238,603 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.has_gap_in_elf_shndx | def has_gap_in_elf_shndx(self):
"""Return the has gap in elf shndx attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.HAS_GAP_IN_ELF_SHNDX) | python | def has_gap_in_elf_shndx(self):
"""Return the has gap in elf shndx attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.HAS_GAP_IN_ELF_SHNDX) | [
"def",
"has_gap_in_elf_shndx",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"HAS_GAP_IN_ELF_SHNDX",
")"
] | Return the has gap in elf shndx attribute of the BFD file being
processed. | [
"Return",
"the",
"has",
"gap",
"in",
"elf",
"shndx",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L564-L572 | train | 238,604 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.valid_reloction_types | def valid_reloction_types(self):
"""Return the valid_reloc_types attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.VALID_RELOC_TYPES) | python | def valid_reloction_types(self):
"""Return the valid_reloc_types attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.VALID_RELOC_TYPES) | [
"def",
"valid_reloction_types",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"VALID_RELOC_TYPES",
")"
] | Return the valid_reloc_types attribute of the BFD file being processed. | [
"Return",
"the",
"valid_reloc_types",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L575-L581 | train | 238,605 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.user_data | def user_data(self):
"""Return the usrdata attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.USRDATA) | python | def user_data(self):
"""Return the usrdata attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.USRDATA) | [
"def",
"user_data",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"USRDATA",
")"
] | Return the usrdata attribute of the BFD file being processed. | [
"Return",
"the",
"usrdata",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L584-L589 | train | 238,606 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.start_address | def start_address(self):
"""Return the start address attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.START_ADDRESS) | python | def start_address(self):
"""Return the start address attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.START_ADDRESS) | [
"def",
"start_address",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"START_ADDRESS",
")"
] | Return the start address attribute of the BFD file being processed. | [
"Return",
"the",
"start",
"address",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L592-L597 | train | 238,607 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.symbols_count | def symbols_count(self):
"""Return the symcount attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.SYMCOUNT) | python | def symbols_count(self):
"""Return the symcount attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.SYMCOUNT) | [
"def",
"symbols_count",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"SYMCOUNT",
")"
] | Return the symcount attribute of the BFD file being processed. | [
"Return",
"the",
"symcount",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L630-L635 | train | 238,608 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.out_symbols | def out_symbols(self):
"""Return the out symbols attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.OUTSYMBOLS) | python | def out_symbols(self):
"""Return the out symbols attribute of the BFD file being processed."""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.OUTSYMBOLS) | [
"def",
"out_symbols",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"OUTSYMBOLS",
")"
] | Return the out symbols attribute of the BFD file being processed. | [
"Return",
"the",
"out",
"symbols",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L638-L643 | train | 238,609 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.sections_count | def sections_count(self):
"""Return the sections_count attribute of the BFD file being processed."""
# This should match the 'sections' attribute length so instead should
# use :
#
# len(bfd.sections)
#
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.COUNT_SECTIONS) | python | def sections_count(self):
"""Return the sections_count attribute of the BFD file being processed."""
# This should match the 'sections' attribute length so instead should
# use :
#
# len(bfd.sections)
#
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(self._ptr, BfdAttributes.COUNT_SECTIONS) | [
"def",
"sections_count",
"(",
"self",
")",
":",
"# This should match the 'sections' attribute length so instead should",
"# use :",
"#",
"# len(bfd.sections)",
"#",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"COUNT_SECTIONS",
")"
] | Return the sections_count attribute of the BFD file being processed. | [
"Return",
"the",
"sections_count",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L646-L656 | train | 238,610 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.dynamic_symbols_count | def dynamic_symbols_count(self):
"""Return the dynamic symbols count attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.DYNAMIC_SYMCOUNT) | python | def dynamic_symbols_count(self):
"""Return the dynamic symbols count attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.DYNAMIC_SYMCOUNT) | [
"def",
"dynamic_symbols_count",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"DYNAMIC_SYMCOUNT",
")"
] | Return the dynamic symbols count attribute of the BFD file being
processed. | [
"Return",
"the",
"dynamic",
"symbols",
"count",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L659-L668 | train | 238,611 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.symbol_leading_char | def symbol_leading_char(self):
"""Return the symbol leading char attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.SYMBOL_LEADING_CHAR) | python | def symbol_leading_char(self):
"""Return the symbol leading char attribute of the BFD file being
processed.
"""
if not self._ptr:
raise BfdException("BFD not initialized")
return _bfd.get_bfd_attribute(
self._ptr, BfdAttributes.SYMBOL_LEADING_CHAR) | [
"def",
"symbol_leading_char",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"return",
"_bfd",
".",
"get_bfd_attribute",
"(",
"self",
".",
"_ptr",
",",
"BfdAttributes",
".",
"SYMBOL_LEADING_CHAR",
")"
] | Return the symbol leading char attribute of the BFD file being
processed. | [
"Return",
"the",
"symbol",
"leading",
"char",
"attribute",
"of",
"the",
"BFD",
"file",
"being",
"processed",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L671-L680 | train | 238,612 |
Groundworkstech/pybfd | pybfd/bfd.py | Bfd.arch_size | def arch_size(self):
"""Return the architecure size in bits."""
if not self._ptr:
raise BfdException("BFD not initialized")
try:
return _bfd.get_arch_size(self._ptr)
except Exception, err:
raise BfdException("Unable to determine architeure size.") | python | def arch_size(self):
"""Return the architecure size in bits."""
if not self._ptr:
raise BfdException("BFD not initialized")
try:
return _bfd.get_arch_size(self._ptr)
except Exception, err:
raise BfdException("Unable to determine architeure size.") | [
"def",
"arch_size",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_ptr",
":",
"raise",
"BfdException",
"(",
"\"BFD not initialized\"",
")",
"try",
":",
"return",
"_bfd",
".",
"get_arch_size",
"(",
"self",
".",
"_ptr",
")",
"except",
"Exception",
",",
"err",
":",
"raise",
"BfdException",
"(",
"\"Unable to determine architeure size.\"",
")"
] | Return the architecure size in bits. | [
"Return",
"the",
"architecure",
"size",
"in",
"bits",
"."
] | 9e722435929b4ad52212043a6f1e9e9ce60b5d72 | https://github.com/Groundworkstech/pybfd/blob/9e722435929b4ad52212043a6f1e9e9ce60b5d72/pybfd/bfd.py#L697-L705 | train | 238,613 |
getsenic/nuimo-linux-python | nuimo/nuimo.py | Controller.display_matrix | def display_matrix(self, matrix, interval=2.0, brightness=1.0, fading=False, ignore_duplicates=False):
"""
Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed
"""
self._matrix_writer.write(
matrix=matrix,
interval=interval,
brightness=brightness,
fading=fading,
ignore_duplicates=ignore_duplicates
) | python | def display_matrix(self, matrix, interval=2.0, brightness=1.0, fading=False, ignore_duplicates=False):
"""
Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed
"""
self._matrix_writer.write(
matrix=matrix,
interval=interval,
brightness=brightness,
fading=fading,
ignore_duplicates=ignore_duplicates
) | [
"def",
"display_matrix",
"(",
"self",
",",
"matrix",
",",
"interval",
"=",
"2.0",
",",
"brightness",
"=",
"1.0",
",",
"fading",
"=",
"False",
",",
"ignore_duplicates",
"=",
"False",
")",
":",
"self",
".",
"_matrix_writer",
".",
"write",
"(",
"matrix",
"=",
"matrix",
",",
"interval",
"=",
"interval",
",",
"brightness",
"=",
"brightness",
",",
"fading",
"=",
"fading",
",",
"ignore_duplicates",
"=",
"ignore_duplicates",
")"
] | Displays an LED matrix on Nuimo's LED matrix display.
:param matrix: the matrix to display
:param interval: interval in seconds until the matrix disappears again
:param brightness: led brightness between 0..1
:param fading: if True, the previous matrix fades into the new matrix
:param ignore_duplicates: if True, the matrix is not sent again if already being displayed | [
"Displays",
"an",
"LED",
"matrix",
"on",
"Nuimo",
"s",
"LED",
"matrix",
"display",
"."
] | 1918e6e51ad6569eb134904e891122479fafa2d6 | https://github.com/getsenic/nuimo-linux-python/blob/1918e6e51ad6569eb134904e891122479fafa2d6/nuimo/nuimo.py#L208-L224 | train | 238,614 |
secynic/ipwhois | ipwhois/net.py | Net.get_asn_origin_whois | def get_asn_origin_whois(self, asn_registry='radb', asn=None,
retry_count=3, server=None, port=43):
"""
The function for retrieving CIDR info for an ASN via whois.
Args:
asn_registry (:obj:`str`): The source to run the query against
(asn.ASN_ORIGIN_WHOIS).
asn (:obj:`str`): The AS number (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
server (:obj:`str`): An optional server to connect to.
port (:obj:`int`): The network port to connect on. Defaults to 43.
Returns:
str: The raw ASN origin whois data.
Raises:
WhoisLookupError: The ASN origin whois lookup failed.
WhoisRateLimitError: The ASN origin Whois request rate limited and
retries were exhausted.
"""
try:
if server is None:
server = ASN_ORIGIN_WHOIS[asn_registry]['server']
# Create the connection for the whois query.
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.settimeout(self.timeout)
log.debug('ASN origin WHOIS query for {0} at {1}:{2}'.format(
asn, server, port))
conn.connect((server, port))
# Prep the query.
query = ' -i origin {0}{1}'.format(asn, '\r\n')
# Query the whois server, and store the results.
conn.send(query.encode())
response = ''
while True:
d = conn.recv(4096).decode()
response += d
if not d:
break
conn.close()
# TODO: this was taken from get_whois(). Need to test rate limiting
if 'Query rate limit exceeded' in response: # pragma: no cover
if retry_count > 0:
log.debug('ASN origin WHOIS query rate limit exceeded. '
'Waiting...')
sleep(1)
return self.get_asn_origin_whois(
asn_registry=asn_registry, asn=asn,
retry_count=retry_count-1,
server=server, port=port
)
else:
raise WhoisRateLimitError(
'ASN origin Whois lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(asn))
elif ('error 501' in response or 'error 230' in response
): # pragma: no cover
log.debug('ASN origin WHOIS query error: {0}'.format(response))
raise ValueError
return str(response)
except (socket.timeout, socket.error) as e:
log.debug('ASN origin WHOIS query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('ASN origin WHOIS query retrying (count: {0})'
''.format(str(retry_count)))
return self.get_asn_origin_whois(
asn_registry=asn_registry, asn=asn,
retry_count=retry_count-1, server=server, port=port
)
else:
raise WhoisLookupError(
'ASN origin WHOIS lookup failed for {0}.'.format(asn)
)
except WhoisRateLimitError: # pragma: no cover
raise
except: # pragma: no cover
raise WhoisLookupError(
'ASN origin WHOIS lookup failed for {0}.'.format(asn)
) | python | def get_asn_origin_whois(self, asn_registry='radb', asn=None,
retry_count=3, server=None, port=43):
"""
The function for retrieving CIDR info for an ASN via whois.
Args:
asn_registry (:obj:`str`): The source to run the query against
(asn.ASN_ORIGIN_WHOIS).
asn (:obj:`str`): The AS number (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
server (:obj:`str`): An optional server to connect to.
port (:obj:`int`): The network port to connect on. Defaults to 43.
Returns:
str: The raw ASN origin whois data.
Raises:
WhoisLookupError: The ASN origin whois lookup failed.
WhoisRateLimitError: The ASN origin Whois request rate limited and
retries were exhausted.
"""
try:
if server is None:
server = ASN_ORIGIN_WHOIS[asn_registry]['server']
# Create the connection for the whois query.
conn = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
conn.settimeout(self.timeout)
log.debug('ASN origin WHOIS query for {0} at {1}:{2}'.format(
asn, server, port))
conn.connect((server, port))
# Prep the query.
query = ' -i origin {0}{1}'.format(asn, '\r\n')
# Query the whois server, and store the results.
conn.send(query.encode())
response = ''
while True:
d = conn.recv(4096).decode()
response += d
if not d:
break
conn.close()
# TODO: this was taken from get_whois(). Need to test rate limiting
if 'Query rate limit exceeded' in response: # pragma: no cover
if retry_count > 0:
log.debug('ASN origin WHOIS query rate limit exceeded. '
'Waiting...')
sleep(1)
return self.get_asn_origin_whois(
asn_registry=asn_registry, asn=asn,
retry_count=retry_count-1,
server=server, port=port
)
else:
raise WhoisRateLimitError(
'ASN origin Whois lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(asn))
elif ('error 501' in response or 'error 230' in response
): # pragma: no cover
log.debug('ASN origin WHOIS query error: {0}'.format(response))
raise ValueError
return str(response)
except (socket.timeout, socket.error) as e:
log.debug('ASN origin WHOIS query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('ASN origin WHOIS query retrying (count: {0})'
''.format(str(retry_count)))
return self.get_asn_origin_whois(
asn_registry=asn_registry, asn=asn,
retry_count=retry_count-1, server=server, port=port
)
else:
raise WhoisLookupError(
'ASN origin WHOIS lookup failed for {0}.'.format(asn)
)
except WhoisRateLimitError: # pragma: no cover
raise
except: # pragma: no cover
raise WhoisLookupError(
'ASN origin WHOIS lookup failed for {0}.'.format(asn)
) | [
"def",
"get_asn_origin_whois",
"(",
"self",
",",
"asn_registry",
"=",
"'radb'",
",",
"asn",
"=",
"None",
",",
"retry_count",
"=",
"3",
",",
"server",
"=",
"None",
",",
"port",
"=",
"43",
")",
":",
"try",
":",
"if",
"server",
"is",
"None",
":",
"server",
"=",
"ASN_ORIGIN_WHOIS",
"[",
"asn_registry",
"]",
"[",
"'server'",
"]",
"# Create the connection for the whois query.",
"conn",
"=",
"socket",
".",
"socket",
"(",
"socket",
".",
"AF_INET",
",",
"socket",
".",
"SOCK_STREAM",
")",
"conn",
".",
"settimeout",
"(",
"self",
".",
"timeout",
")",
"log",
".",
"debug",
"(",
"'ASN origin WHOIS query for {0} at {1}:{2}'",
".",
"format",
"(",
"asn",
",",
"server",
",",
"port",
")",
")",
"conn",
".",
"connect",
"(",
"(",
"server",
",",
"port",
")",
")",
"# Prep the query.",
"query",
"=",
"' -i origin {0}{1}'",
".",
"format",
"(",
"asn",
",",
"'\\r\\n'",
")",
"# Query the whois server, and store the results.",
"conn",
".",
"send",
"(",
"query",
".",
"encode",
"(",
")",
")",
"response",
"=",
"''",
"while",
"True",
":",
"d",
"=",
"conn",
".",
"recv",
"(",
"4096",
")",
".",
"decode",
"(",
")",
"response",
"+=",
"d",
"if",
"not",
"d",
":",
"break",
"conn",
".",
"close",
"(",
")",
"# TODO: this was taken from get_whois(). Need to test rate limiting",
"if",
"'Query rate limit exceeded'",
"in",
"response",
":",
"# pragma: no cover",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'ASN origin WHOIS query rate limit exceeded. '",
"'Waiting...'",
")",
"sleep",
"(",
"1",
")",
"return",
"self",
".",
"get_asn_origin_whois",
"(",
"asn_registry",
"=",
"asn_registry",
",",
"asn",
"=",
"asn",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"server",
"=",
"server",
",",
"port",
"=",
"port",
")",
"else",
":",
"raise",
"WhoisRateLimitError",
"(",
"'ASN origin Whois lookup failed for {0}. Rate limit '",
"'exceeded, wait and try again (possibly a '",
"'temporary block).'",
".",
"format",
"(",
"asn",
")",
")",
"elif",
"(",
"'error 501'",
"in",
"response",
"or",
"'error 230'",
"in",
"response",
")",
":",
"# pragma: no cover",
"log",
".",
"debug",
"(",
"'ASN origin WHOIS query error: {0}'",
".",
"format",
"(",
"response",
")",
")",
"raise",
"ValueError",
"return",
"str",
"(",
"response",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'ASN origin WHOIS query socket error: {0}'",
".",
"format",
"(",
"e",
")",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'ASN origin WHOIS query retrying (count: {0})'",
"''",
".",
"format",
"(",
"str",
"(",
"retry_count",
")",
")",
")",
"return",
"self",
".",
"get_asn_origin_whois",
"(",
"asn_registry",
"=",
"asn_registry",
",",
"asn",
"=",
"asn",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"server",
"=",
"server",
",",
"port",
"=",
"port",
")",
"else",
":",
"raise",
"WhoisLookupError",
"(",
"'ASN origin WHOIS lookup failed for {0}.'",
".",
"format",
"(",
"asn",
")",
")",
"except",
"WhoisRateLimitError",
":",
"# pragma: no cover",
"raise",
"except",
":",
"# pragma: no cover",
"raise",
"WhoisLookupError",
"(",
"'ASN origin WHOIS lookup failed for {0}.'",
".",
"format",
"(",
"asn",
")",
")"
] | The function for retrieving CIDR info for an ASN via whois.
Args:
asn_registry (:obj:`str`): The source to run the query against
(asn.ASN_ORIGIN_WHOIS).
asn (:obj:`str`): The AS number (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
server (:obj:`str`): An optional server to connect to.
port (:obj:`int`): The network port to connect on. Defaults to 43.
Returns:
str: The raw ASN origin whois data.
Raises:
WhoisLookupError: The ASN origin whois lookup failed.
WhoisRateLimitError: The ASN origin Whois request rate limited and
retries were exhausted. | [
"The",
"function",
"for",
"retrieving",
"CIDR",
"info",
"for",
"an",
"ASN",
"via",
"whois",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/net.py#L431-L541 | train | 238,615 |
secynic/ipwhois | ipwhois/net.py | Net.get_http_json | def get_http_json(self, url=None, retry_count=3, rate_limit_timeout=120,
headers=None):
"""
The function for retrieving a json result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
rate_limit_timeout (:obj:`int`): The number of seconds to wait
before retrying when a rate limit notice is returned via
rdap+json or HTTP error 429. Defaults to 60.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'application/rdap+json'.
Returns:
dict: The data in json format.
Raises:
HTTPLookupError: The HTTP lookup failed.
HTTPRateLimitError: The HTTP request rate limited and retries
were exhausted.
"""
if headers is None:
headers = {'Accept': 'application/rdap+json'}
try:
# Create the connection for the whois query.
log.debug('HTTP query for {0} at {1}'.format(
self.address_str, url))
conn = Request(url, headers=headers)
data = self.opener.open(conn, timeout=self.timeout)
try:
d = json.loads(data.readall().decode('utf-8', 'ignore'))
except AttributeError: # pragma: no cover
d = json.loads(data.read().decode('utf-8', 'ignore'))
try:
# Tests written but commented out. I do not want to send a
# flood of requests on every test.
for tmp in d['notices']: # pragma: no cover
if tmp['title'] == 'Rate Limit Notice':
log.debug('RDAP query rate limit exceeded.')
if retry_count > 0:
log.debug('Waiting {0} seconds...'.format(
str(rate_limit_timeout)))
sleep(rate_limit_timeout)
return self.get_http_json(
url=url, retry_count=retry_count-1,
rate_limit_timeout=rate_limit_timeout,
headers=headers
)
else:
raise HTTPRateLimitError(
'HTTP lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(url))
except (KeyError, IndexError): # pragma: no cover
pass
return d
except HTTPError as e: # pragma: no cover
# RIPE is producing this HTTP error rather than a JSON error.
if e.code == 429:
log.debug('HTTP query rate limit exceeded.')
if retry_count > 0:
log.debug('Waiting {0} seconds...'.format(
str(rate_limit_timeout)))
sleep(rate_limit_timeout)
return self.get_http_json(
url=url, retry_count=retry_count - 1,
rate_limit_timeout=rate_limit_timeout,
headers=headers
)
else:
raise HTTPRateLimitError(
'HTTP lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(url))
else:
raise HTTPLookupError('HTTP lookup failed for {0} with error '
'code {1}.'.format(url, str(e.code)))
except (URLError, socket.timeout, socket.error) as e:
log.debug('HTTP query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('HTTP query retrying (count: {0})'.format(
str(retry_count)))
return self.get_http_json(
url=url, retry_count=retry_count-1,
rate_limit_timeout=rate_limit_timeout, headers=headers
)
else:
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(
url))
except (HTTPLookupError, HTTPRateLimitError) as e: # pragma: no cover
raise e
except: # pragma: no cover
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url)) | python | def get_http_json(self, url=None, retry_count=3, rate_limit_timeout=120,
headers=None):
"""
The function for retrieving a json result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
rate_limit_timeout (:obj:`int`): The number of seconds to wait
before retrying when a rate limit notice is returned via
rdap+json or HTTP error 429. Defaults to 60.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'application/rdap+json'.
Returns:
dict: The data in json format.
Raises:
HTTPLookupError: The HTTP lookup failed.
HTTPRateLimitError: The HTTP request rate limited and retries
were exhausted.
"""
if headers is None:
headers = {'Accept': 'application/rdap+json'}
try:
# Create the connection for the whois query.
log.debug('HTTP query for {0} at {1}'.format(
self.address_str, url))
conn = Request(url, headers=headers)
data = self.opener.open(conn, timeout=self.timeout)
try:
d = json.loads(data.readall().decode('utf-8', 'ignore'))
except AttributeError: # pragma: no cover
d = json.loads(data.read().decode('utf-8', 'ignore'))
try:
# Tests written but commented out. I do not want to send a
# flood of requests on every test.
for tmp in d['notices']: # pragma: no cover
if tmp['title'] == 'Rate Limit Notice':
log.debug('RDAP query rate limit exceeded.')
if retry_count > 0:
log.debug('Waiting {0} seconds...'.format(
str(rate_limit_timeout)))
sleep(rate_limit_timeout)
return self.get_http_json(
url=url, retry_count=retry_count-1,
rate_limit_timeout=rate_limit_timeout,
headers=headers
)
else:
raise HTTPRateLimitError(
'HTTP lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(url))
except (KeyError, IndexError): # pragma: no cover
pass
return d
except HTTPError as e: # pragma: no cover
# RIPE is producing this HTTP error rather than a JSON error.
if e.code == 429:
log.debug('HTTP query rate limit exceeded.')
if retry_count > 0:
log.debug('Waiting {0} seconds...'.format(
str(rate_limit_timeout)))
sleep(rate_limit_timeout)
return self.get_http_json(
url=url, retry_count=retry_count - 1,
rate_limit_timeout=rate_limit_timeout,
headers=headers
)
else:
raise HTTPRateLimitError(
'HTTP lookup failed for {0}. Rate limit '
'exceeded, wait and try again (possibly a '
'temporary block).'.format(url))
else:
raise HTTPLookupError('HTTP lookup failed for {0} with error '
'code {1}.'.format(url, str(e.code)))
except (URLError, socket.timeout, socket.error) as e:
log.debug('HTTP query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('HTTP query retrying (count: {0})'.format(
str(retry_count)))
return self.get_http_json(
url=url, retry_count=retry_count-1,
rate_limit_timeout=rate_limit_timeout, headers=headers
)
else:
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(
url))
except (HTTPLookupError, HTTPRateLimitError) as e: # pragma: no cover
raise e
except: # pragma: no cover
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url)) | [
"def",
"get_http_json",
"(",
"self",
",",
"url",
"=",
"None",
",",
"retry_count",
"=",
"3",
",",
"rate_limit_timeout",
"=",
"120",
",",
"headers",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"'Accept'",
":",
"'application/rdap+json'",
"}",
"try",
":",
"# Create the connection for the whois query.",
"log",
".",
"debug",
"(",
"'HTTP query for {0} at {1}'",
".",
"format",
"(",
"self",
".",
"address_str",
",",
"url",
")",
")",
"conn",
"=",
"Request",
"(",
"url",
",",
"headers",
"=",
"headers",
")",
"data",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"conn",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"try",
":",
"d",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"readall",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"d",
"=",
"json",
".",
"loads",
"(",
"data",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
",",
"'ignore'",
")",
")",
"try",
":",
"# Tests written but commented out. I do not want to send a",
"# flood of requests on every test.",
"for",
"tmp",
"in",
"d",
"[",
"'notices'",
"]",
":",
"# pragma: no cover",
"if",
"tmp",
"[",
"'title'",
"]",
"==",
"'Rate Limit Notice'",
":",
"log",
".",
"debug",
"(",
"'RDAP query rate limit exceeded.'",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'Waiting {0} seconds...'",
".",
"format",
"(",
"str",
"(",
"rate_limit_timeout",
")",
")",
")",
"sleep",
"(",
"rate_limit_timeout",
")",
"return",
"self",
".",
"get_http_json",
"(",
"url",
"=",
"url",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"rate_limit_timeout",
"=",
"rate_limit_timeout",
",",
"headers",
"=",
"headers",
")",
"else",
":",
"raise",
"HTTPRateLimitError",
"(",
"'HTTP lookup failed for {0}. Rate limit '",
"'exceeded, wait and try again (possibly a '",
"'temporary block).'",
".",
"format",
"(",
"url",
")",
")",
"except",
"(",
"KeyError",
",",
"IndexError",
")",
":",
"# pragma: no cover",
"pass",
"return",
"d",
"except",
"HTTPError",
"as",
"e",
":",
"# pragma: no cover",
"# RIPE is producing this HTTP error rather than a JSON error.",
"if",
"e",
".",
"code",
"==",
"429",
":",
"log",
".",
"debug",
"(",
"'HTTP query rate limit exceeded.'",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'Waiting {0} seconds...'",
".",
"format",
"(",
"str",
"(",
"rate_limit_timeout",
")",
")",
")",
"sleep",
"(",
"rate_limit_timeout",
")",
"return",
"self",
".",
"get_http_json",
"(",
"url",
"=",
"url",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"rate_limit_timeout",
"=",
"rate_limit_timeout",
",",
"headers",
"=",
"headers",
")",
"else",
":",
"raise",
"HTTPRateLimitError",
"(",
"'HTTP lookup failed for {0}. Rate limit '",
"'exceeded, wait and try again (possibly a '",
"'temporary block).'",
".",
"format",
"(",
"url",
")",
")",
"else",
":",
"raise",
"HTTPLookupError",
"(",
"'HTTP lookup failed for {0} with error '",
"'code {1}.'",
".",
"format",
"(",
"url",
",",
"str",
"(",
"e",
".",
"code",
")",
")",
")",
"except",
"(",
"URLError",
",",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'HTTP query socket error: {0}'",
".",
"format",
"(",
"e",
")",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'HTTP query retrying (count: {0})'",
".",
"format",
"(",
"str",
"(",
"retry_count",
")",
")",
")",
"return",
"self",
".",
"get_http_json",
"(",
"url",
"=",
"url",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"rate_limit_timeout",
"=",
"rate_limit_timeout",
",",
"headers",
"=",
"headers",
")",
"else",
":",
"raise",
"HTTPLookupError",
"(",
"'HTTP lookup failed for {0}.'",
".",
"format",
"(",
"url",
")",
")",
"except",
"(",
"HTTPLookupError",
",",
"HTTPRateLimitError",
")",
"as",
"e",
":",
"# pragma: no cover",
"raise",
"e",
"except",
":",
"# pragma: no cover",
"raise",
"HTTPLookupError",
"(",
"'HTTP lookup failed for {0}.'",
".",
"format",
"(",
"url",
")",
")"
] | The function for retrieving a json result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
rate_limit_timeout (:obj:`int`): The number of seconds to wait
before retrying when a rate limit notice is returned via
rdap+json or HTTP error 429. Defaults to 60.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'application/rdap+json'.
Returns:
dict: The data in json format.
Raises:
HTTPLookupError: The HTTP lookup failed.
HTTPRateLimitError: The HTTP request rate limited and retries
were exhausted. | [
"The",
"function",
"for",
"retrieving",
"a",
"json",
"result",
"via",
"HTTP",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/net.py#L672-L793 | train | 238,616 |
secynic/ipwhois | ipwhois/net.py | Net.get_host | def get_host(self, retry_count=3):
"""
The function for retrieving host information for an IP address.
Args:
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
Returns:
namedtuple:
:hostname (str): The hostname returned mapped to the given IP
address.
:aliaslist (list): Alternate names for the given IP address.
:ipaddrlist (list): IPv4/v6 addresses mapped to the same hostname.
Raises:
HostLookupError: The host lookup failed.
"""
try:
default_timeout_set = False
if not socket.getdefaulttimeout():
socket.setdefaulttimeout(self.timeout)
default_timeout_set = True
log.debug('Host query for {0}'.format(self.address_str))
ret = socket.gethostbyaddr(self.address_str)
if default_timeout_set: # pragma: no cover
socket.setdefaulttimeout(None)
results = namedtuple('get_host_results', 'hostname, aliaslist, '
'ipaddrlist')
return results(ret)
except (socket.timeout, socket.error) as e:
log.debug('Host query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('Host query retrying (count: {0})'.format(
str(retry_count)))
return self.get_host(retry_count - 1)
else:
raise HostLookupError(
'Host lookup failed for {0}.'.format(self.address_str)
)
except: # pragma: no cover
raise HostLookupError(
'Host lookup failed for {0}.'.format(self.address_str)
) | python | def get_host(self, retry_count=3):
"""
The function for retrieving host information for an IP address.
Args:
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
Returns:
namedtuple:
:hostname (str): The hostname returned mapped to the given IP
address.
:aliaslist (list): Alternate names for the given IP address.
:ipaddrlist (list): IPv4/v6 addresses mapped to the same hostname.
Raises:
HostLookupError: The host lookup failed.
"""
try:
default_timeout_set = False
if not socket.getdefaulttimeout():
socket.setdefaulttimeout(self.timeout)
default_timeout_set = True
log.debug('Host query for {0}'.format(self.address_str))
ret = socket.gethostbyaddr(self.address_str)
if default_timeout_set: # pragma: no cover
socket.setdefaulttimeout(None)
results = namedtuple('get_host_results', 'hostname, aliaslist, '
'ipaddrlist')
return results(ret)
except (socket.timeout, socket.error) as e:
log.debug('Host query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('Host query retrying (count: {0})'.format(
str(retry_count)))
return self.get_host(retry_count - 1)
else:
raise HostLookupError(
'Host lookup failed for {0}.'.format(self.address_str)
)
except: # pragma: no cover
raise HostLookupError(
'Host lookup failed for {0}.'.format(self.address_str)
) | [
"def",
"get_host",
"(",
"self",
",",
"retry_count",
"=",
"3",
")",
":",
"try",
":",
"default_timeout_set",
"=",
"False",
"if",
"not",
"socket",
".",
"getdefaulttimeout",
"(",
")",
":",
"socket",
".",
"setdefaulttimeout",
"(",
"self",
".",
"timeout",
")",
"default_timeout_set",
"=",
"True",
"log",
".",
"debug",
"(",
"'Host query for {0}'",
".",
"format",
"(",
"self",
".",
"address_str",
")",
")",
"ret",
"=",
"socket",
".",
"gethostbyaddr",
"(",
"self",
".",
"address_str",
")",
"if",
"default_timeout_set",
":",
"# pragma: no cover",
"socket",
".",
"setdefaulttimeout",
"(",
"None",
")",
"results",
"=",
"namedtuple",
"(",
"'get_host_results'",
",",
"'hostname, aliaslist, '",
"'ipaddrlist'",
")",
"return",
"results",
"(",
"ret",
")",
"except",
"(",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Host query socket error: {0}'",
".",
"format",
"(",
"e",
")",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'Host query retrying (count: {0})'",
".",
"format",
"(",
"str",
"(",
"retry_count",
")",
")",
")",
"return",
"self",
".",
"get_host",
"(",
"retry_count",
"-",
"1",
")",
"else",
":",
"raise",
"HostLookupError",
"(",
"'Host lookup failed for {0}.'",
".",
"format",
"(",
"self",
".",
"address_str",
")",
")",
"except",
":",
"# pragma: no cover",
"raise",
"HostLookupError",
"(",
"'Host lookup failed for {0}.'",
".",
"format",
"(",
"self",
".",
"address_str",
")",
")"
] | The function for retrieving host information for an IP address.
Args:
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
Returns:
namedtuple:
:hostname (str): The hostname returned mapped to the given IP
address.
:aliaslist (list): Alternate names for the given IP address.
:ipaddrlist (list): IPv4/v6 addresses mapped to the same hostname.
Raises:
HostLookupError: The host lookup failed. | [
"The",
"function",
"for",
"retrieving",
"host",
"information",
"for",
"an",
"IP",
"address",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/net.py#L795-L855 | train | 238,617 |
secynic/ipwhois | ipwhois/net.py | Net.get_http_raw | def get_http_raw(self, url=None, retry_count=3, headers=None,
request_type='GET', form_data=None):
"""
The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'text/html'.
request_type (:obj:`str`): Request type 'GET' or 'POST'. Defaults
to 'GET'.
form_data (:obj:`dict`): Optional form POST data.
Returns:
str: The raw data.
Raises:
HTTPLookupError: The HTTP lookup failed.
"""
if headers is None:
headers = {'Accept': 'text/html'}
enc_form_data = None
if form_data:
enc_form_data = urlencode(form_data)
try:
# Py 2 inspection will alert on the encoding arg, no harm done.
enc_form_data = bytes(enc_form_data, encoding='ascii')
except TypeError: # pragma: no cover
pass
try:
# Create the connection for the HTTP query.
log.debug('HTTP query for {0} at {1}'.format(
self.address_str, url))
try:
# Py 2 inspection alert bypassed by using kwargs dict.
conn = Request(url=url, data=enc_form_data, headers=headers,
**{'method': request_type})
except TypeError: # pragma: no cover
conn = Request(url=url, data=enc_form_data, headers=headers)
data = self.opener.open(conn, timeout=self.timeout)
try:
d = data.readall().decode('ascii', 'ignore')
except AttributeError: # pragma: no cover
d = data.read().decode('ascii', 'ignore')
return str(d)
except (URLError, socket.timeout, socket.error) as e:
log.debug('HTTP query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('HTTP query retrying (count: {0})'.format(
str(retry_count)))
return self.get_http_raw(
url=url, retry_count=retry_count - 1, headers=headers,
request_type=request_type, form_data=form_data
)
else:
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(
url))
except HTTPLookupError as e: # pragma: no cover
raise e
except Exception: # pragma: no cover
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url)) | python | def get_http_raw(self, url=None, retry_count=3, headers=None,
request_type='GET', form_data=None):
"""
The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'text/html'.
request_type (:obj:`str`): Request type 'GET' or 'POST'. Defaults
to 'GET'.
form_data (:obj:`dict`): Optional form POST data.
Returns:
str: The raw data.
Raises:
HTTPLookupError: The HTTP lookup failed.
"""
if headers is None:
headers = {'Accept': 'text/html'}
enc_form_data = None
if form_data:
enc_form_data = urlencode(form_data)
try:
# Py 2 inspection will alert on the encoding arg, no harm done.
enc_form_data = bytes(enc_form_data, encoding='ascii')
except TypeError: # pragma: no cover
pass
try:
# Create the connection for the HTTP query.
log.debug('HTTP query for {0} at {1}'.format(
self.address_str, url))
try:
# Py 2 inspection alert bypassed by using kwargs dict.
conn = Request(url=url, data=enc_form_data, headers=headers,
**{'method': request_type})
except TypeError: # pragma: no cover
conn = Request(url=url, data=enc_form_data, headers=headers)
data = self.opener.open(conn, timeout=self.timeout)
try:
d = data.readall().decode('ascii', 'ignore')
except AttributeError: # pragma: no cover
d = data.read().decode('ascii', 'ignore')
return str(d)
except (URLError, socket.timeout, socket.error) as e:
log.debug('HTTP query socket error: {0}'.format(e))
if retry_count > 0:
log.debug('HTTP query retrying (count: {0})'.format(
str(retry_count)))
return self.get_http_raw(
url=url, retry_count=retry_count - 1, headers=headers,
request_type=request_type, form_data=form_data
)
else:
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(
url))
except HTTPLookupError as e: # pragma: no cover
raise e
except Exception: # pragma: no cover
raise HTTPLookupError('HTTP lookup failed for {0}.'.format(url)) | [
"def",
"get_http_raw",
"(",
"self",
",",
"url",
"=",
"None",
",",
"retry_count",
"=",
"3",
",",
"headers",
"=",
"None",
",",
"request_type",
"=",
"'GET'",
",",
"form_data",
"=",
"None",
")",
":",
"if",
"headers",
"is",
"None",
":",
"headers",
"=",
"{",
"'Accept'",
":",
"'text/html'",
"}",
"enc_form_data",
"=",
"None",
"if",
"form_data",
":",
"enc_form_data",
"=",
"urlencode",
"(",
"form_data",
")",
"try",
":",
"# Py 2 inspection will alert on the encoding arg, no harm done.",
"enc_form_data",
"=",
"bytes",
"(",
"enc_form_data",
",",
"encoding",
"=",
"'ascii'",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"pass",
"try",
":",
"# Create the connection for the HTTP query.",
"log",
".",
"debug",
"(",
"'HTTP query for {0} at {1}'",
".",
"format",
"(",
"self",
".",
"address_str",
",",
"url",
")",
")",
"try",
":",
"# Py 2 inspection alert bypassed by using kwargs dict.",
"conn",
"=",
"Request",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"enc_form_data",
",",
"headers",
"=",
"headers",
",",
"*",
"*",
"{",
"'method'",
":",
"request_type",
"}",
")",
"except",
"TypeError",
":",
"# pragma: no cover",
"conn",
"=",
"Request",
"(",
"url",
"=",
"url",
",",
"data",
"=",
"enc_form_data",
",",
"headers",
"=",
"headers",
")",
"data",
"=",
"self",
".",
"opener",
".",
"open",
"(",
"conn",
",",
"timeout",
"=",
"self",
".",
"timeout",
")",
"try",
":",
"d",
"=",
"data",
".",
"readall",
"(",
")",
".",
"decode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"except",
"AttributeError",
":",
"# pragma: no cover",
"d",
"=",
"data",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'ascii'",
",",
"'ignore'",
")",
"return",
"str",
"(",
"d",
")",
"except",
"(",
"URLError",
",",
"socket",
".",
"timeout",
",",
"socket",
".",
"error",
")",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'HTTP query socket error: {0}'",
".",
"format",
"(",
"e",
")",
")",
"if",
"retry_count",
">",
"0",
":",
"log",
".",
"debug",
"(",
"'HTTP query retrying (count: {0})'",
".",
"format",
"(",
"str",
"(",
"retry_count",
")",
")",
")",
"return",
"self",
".",
"get_http_raw",
"(",
"url",
"=",
"url",
",",
"retry_count",
"=",
"retry_count",
"-",
"1",
",",
"headers",
"=",
"headers",
",",
"request_type",
"=",
"request_type",
",",
"form_data",
"=",
"form_data",
")",
"else",
":",
"raise",
"HTTPLookupError",
"(",
"'HTTP lookup failed for {0}.'",
".",
"format",
"(",
"url",
")",
")",
"except",
"HTTPLookupError",
"as",
"e",
":",
"# pragma: no cover",
"raise",
"e",
"except",
"Exception",
":",
"# pragma: no cover",
"raise",
"HTTPLookupError",
"(",
"'HTTP lookup failed for {0}.'",
".",
"format",
"(",
"url",
")",
")"
] | The function for retrieving a raw HTML result via HTTP.
Args:
url (:obj:`str`): The URL to retrieve (required).
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
headers (:obj:`dict`): The HTTP headers. The Accept header
defaults to 'text/html'.
request_type (:obj:`str`): Request type 'GET' or 'POST'. Defaults
to 'GET'.
form_data (:obj:`dict`): Optional form POST data.
Returns:
str: The raw data.
Raises:
HTTPLookupError: The HTTP lookup failed. | [
"The",
"function",
"for",
"retrieving",
"a",
"raw",
"HTML",
"result",
"via",
"HTTP",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/net.py#L857-L936 | train | 238,618 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | generate_output | def generate_output(line='0', short=None, name=None, value=None,
is_parent=False, colorize=True):
"""
The function for formatting CLI output results.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
short (:obj:`str`): The optional abbreviated name for a field.
See hr.py for values.
name (:obj:`str`): The optional name for a field. See hr.py for values.
value (:obj:`str`): The field data (required).
is_parent (:obj:`bool`): Set to True if the field value has sub-items
(dicts/lists). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI colors.
Defaults to True.
Returns:
str: The generated output.
"""
# TODO: so ugly
output = '{0}{1}{2}{3}{4}{5}{6}{7}\n'.format(
LINES['{0}{1}'.format(line, 'C' if colorize else '')] if (
line in LINES.keys()) else '',
COLOR_DEPTH[line] if (colorize and line in COLOR_DEPTH) else '',
ANSI['b'],
short if short is not None else (
name if (name is not None) else ''
),
'' if (name is None or short is None) else ' ({0})'.format(
name),
'' if (name is None and short is None) else ': ',
ANSI['end'] if colorize else '',
'' if is_parent else value
)
return output | python | def generate_output(line='0', short=None, name=None, value=None,
is_parent=False, colorize=True):
"""
The function for formatting CLI output results.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
short (:obj:`str`): The optional abbreviated name for a field.
See hr.py for values.
name (:obj:`str`): The optional name for a field. See hr.py for values.
value (:obj:`str`): The field data (required).
is_parent (:obj:`bool`): Set to True if the field value has sub-items
(dicts/lists). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI colors.
Defaults to True.
Returns:
str: The generated output.
"""
# TODO: so ugly
output = '{0}{1}{2}{3}{4}{5}{6}{7}\n'.format(
LINES['{0}{1}'.format(line, 'C' if colorize else '')] if (
line in LINES.keys()) else '',
COLOR_DEPTH[line] if (colorize and line in COLOR_DEPTH) else '',
ANSI['b'],
short if short is not None else (
name if (name is not None) else ''
),
'' if (name is None or short is None) else ' ({0})'.format(
name),
'' if (name is None and short is None) else ': ',
ANSI['end'] if colorize else '',
'' if is_parent else value
)
return output | [
"def",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"None",
",",
"name",
"=",
"None",
",",
"value",
"=",
"None",
",",
"is_parent",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"# TODO: so ugly",
"output",
"=",
"'{0}{1}{2}{3}{4}{5}{6}{7}\\n'",
".",
"format",
"(",
"LINES",
"[",
"'{0}{1}'",
".",
"format",
"(",
"line",
",",
"'C'",
"if",
"colorize",
"else",
"''",
")",
"]",
"if",
"(",
"line",
"in",
"LINES",
".",
"keys",
"(",
")",
")",
"else",
"''",
",",
"COLOR_DEPTH",
"[",
"line",
"]",
"if",
"(",
"colorize",
"and",
"line",
"in",
"COLOR_DEPTH",
")",
"else",
"''",
",",
"ANSI",
"[",
"'b'",
"]",
",",
"short",
"if",
"short",
"is",
"not",
"None",
"else",
"(",
"name",
"if",
"(",
"name",
"is",
"not",
"None",
")",
"else",
"''",
")",
",",
"''",
"if",
"(",
"name",
"is",
"None",
"or",
"short",
"is",
"None",
")",
"else",
"' ({0})'",
".",
"format",
"(",
"name",
")",
",",
"''",
"if",
"(",
"name",
"is",
"None",
"and",
"short",
"is",
"None",
")",
"else",
"': '",
",",
"ANSI",
"[",
"'end'",
"]",
"if",
"colorize",
"else",
"''",
",",
"''",
"if",
"is_parent",
"else",
"value",
")",
"return",
"output"
] | The function for formatting CLI output results.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
short (:obj:`str`): The optional abbreviated name for a field.
See hr.py for values.
name (:obj:`str`): The optional name for a field. See hr.py for values.
value (:obj:`str`): The field data (required).
is_parent (:obj:`bool`): Set to True if the field value has sub-items
(dicts/lists). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI colors.
Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"formatting",
"CLI",
"output",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L313-L350 | train | 238,619 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_header | def generate_output_header(self, query_type='RDAP'):
"""
The function for generating the CLI output header.
Args:
query_type (:obj:`str`): The IPWhois query type. Defaults to
'RDAP'.
Returns:
str: The generated output.
"""
output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format(
ANSI['ul'],
ANSI['b'],
query_type,
self.obj.address_str,
ANSI['end']
)
return output | python | def generate_output_header(self, query_type='RDAP'):
"""
The function for generating the CLI output header.
Args:
query_type (:obj:`str`): The IPWhois query type. Defaults to
'RDAP'.
Returns:
str: The generated output.
"""
output = '\n{0}{1}{2} query for {3}:{4}\n\n'.format(
ANSI['ul'],
ANSI['b'],
query_type,
self.obj.address_str,
ANSI['end']
)
return output | [
"def",
"generate_output_header",
"(",
"self",
",",
"query_type",
"=",
"'RDAP'",
")",
":",
"output",
"=",
"'\\n{0}{1}{2} query for {3}:{4}\\n\\n'",
".",
"format",
"(",
"ANSI",
"[",
"'ul'",
"]",
",",
"ANSI",
"[",
"'b'",
"]",
",",
"query_type",
",",
"self",
".",
"obj",
".",
"address_str",
",",
"ANSI",
"[",
"'end'",
"]",
")",
"return",
"output"
] | The function for generating the CLI output header.
Args:
query_type (:obj:`str`): The IPWhois query type. Defaults to
'RDAP'.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"the",
"CLI",
"output",
"header",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L406-L426 | train | 238,620 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_newline | def generate_output_newline(self, line='0', colorize=True):
"""
The function for generating a CLI output new line.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
return generate_output(
line=line,
is_parent=True,
colorize=colorize
) | python | def generate_output_newline(self, line='0', colorize=True):
"""
The function for generating a CLI output new line.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
return generate_output(
line=line,
is_parent=True,
colorize=colorize
) | [
"def",
"generate_output_newline",
"(",
"self",
",",
"line",
"=",
"'0'",
",",
"colorize",
"=",
"True",
")",
":",
"return",
"generate_output",
"(",
"line",
"=",
"line",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")"
] | The function for generating a CLI output new line.
Args:
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"a",
"CLI",
"output",
"new",
"line",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L428-L446 | train | 238,621 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_asn | def generate_output_asn(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output ASN results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
keys = {'asn', 'asn_cidr', 'asn_country_code', 'asn_date',
'asn_registry', 'asn_description'}.intersection(json_data)
output = ''
for key in keys:
output += generate_output(
line='0',
short=HR_ASN[key]['_short'] if hr else key,
name=HR_ASN[key]['_name'] if (hr and show_name) else None,
value=(json_data[key] if (
json_data[key] is not None and
len(json_data[key]) > 0 and
json_data[key] != 'NA') else 'None'),
colorize=colorize
)
return output | python | def generate_output_asn(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output ASN results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
keys = {'asn', 'asn_cidr', 'asn_country_code', 'asn_date',
'asn_registry', 'asn_description'}.intersection(json_data)
output = ''
for key in keys:
output += generate_output(
line='0',
short=HR_ASN[key]['_short'] if hr else key,
name=HR_ASN[key]['_name'] if (hr and show_name) else None,
value=(json_data[key] if (
json_data[key] is not None and
len(json_data[key]) > 0 and
json_data[key] != 'NA') else 'None'),
colorize=colorize
)
return output | [
"def",
"generate_output_asn",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"keys",
"=",
"{",
"'asn'",
",",
"'asn_cidr'",
",",
"'asn_country_code'",
",",
"'asn_date'",
",",
"'asn_registry'",
",",
"'asn_description'",
"}",
".",
"intersection",
"(",
"json_data",
")",
"output",
"=",
"''",
"for",
"key",
"in",
"keys",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"HR_ASN",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_ASN",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"(",
"json_data",
"[",
"key",
"]",
"if",
"(",
"json_data",
"[",
"key",
"]",
"is",
"not",
"None",
"and",
"len",
"(",
"json_data",
"[",
"key",
"]",
")",
">",
"0",
"and",
"json_data",
"[",
"key",
"]",
"!=",
"'NA'",
")",
"else",
"'None'",
")",
",",
"colorize",
"=",
"colorize",
")",
"return",
"output"
] | The function for generating CLI output ASN results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"ASN",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L448-L487 | train | 238,622 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_entities | def generate_output_entities(self, json_data=None, hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP entity results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = ''
short = HR_RDAP['entities']['_short'] if hr else 'entities'
name = HR_RDAP['entities']['_name'] if (hr and show_name) else None
output += generate_output(
line='0',
short=short,
name=name,
is_parent=False if (json_data is None or
json_data['entities'] is None) else True,
value='None' if (json_data is None or
json_data['entities'] is None) else None,
colorize=colorize
)
if json_data is not None:
for ent in json_data['entities']:
output += generate_output(
line='1',
value=ent,
colorize=colorize
)
return output | python | def generate_output_entities(self, json_data=None, hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP entity results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = ''
short = HR_RDAP['entities']['_short'] if hr else 'entities'
name = HR_RDAP['entities']['_name'] if (hr and show_name) else None
output += generate_output(
line='0',
short=short,
name=name,
is_parent=False if (json_data is None or
json_data['entities'] is None) else True,
value='None' if (json_data is None or
json_data['entities'] is None) else None,
colorize=colorize
)
if json_data is not None:
for ent in json_data['entities']:
output += generate_output(
line='1',
value=ent,
colorize=colorize
)
return output | [
"def",
"generate_output_entities",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"output",
"=",
"''",
"short",
"=",
"HR_RDAP",
"[",
"'entities'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'entities'",
"name",
"=",
"HR_RDAP",
"[",
"'entities'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"short",
",",
"name",
"=",
"name",
",",
"is_parent",
"=",
"False",
"if",
"(",
"json_data",
"is",
"None",
"or",
"json_data",
"[",
"'entities'",
"]",
"is",
"None",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"json_data",
"is",
"None",
"or",
"json_data",
"[",
"'entities'",
"]",
"is",
"None",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"if",
"json_data",
"is",
"not",
"None",
":",
"for",
"ent",
"in",
"json_data",
"[",
"'entities'",
"]",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'1'",
",",
"value",
"=",
"ent",
",",
"colorize",
"=",
"colorize",
")",
"return",
"output"
] | The function for generating CLI output RDAP entity results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"entity",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L489-L532 | train | 238,623 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_events | def generate_output_events(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP events results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
count = 0
for item in val:
try:
action = item['action']
except KeyError:
action = None
try:
timestamp = item['timestamp']
except KeyError:
timestamp = None
try:
actor = item['actor']
except KeyError:
actor = None
if count > 0:
output += generate_output(
line=str(int(line)+1),
is_parent=True,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['action'][
'_short'] if hr else 'action',
name=HR_RDAP_COMMON[key]['action'][
'_name'] if (hr and show_name) else None,
value=action,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['timestamp'][
'_short'] if hr else 'timestamp',
name=HR_RDAP_COMMON[key]['timestamp'][
'_name'] if (hr and show_name) else None,
value=timestamp,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['actor'][
'_short'] if hr else 'actor',
name=HR_RDAP_COMMON[key]['actor'][
'_name'] if (hr and show_name) else None,
value=actor,
colorize=colorize
)
count += 1
return output | python | def generate_output_events(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP events results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
count = 0
for item in val:
try:
action = item['action']
except KeyError:
action = None
try:
timestamp = item['timestamp']
except KeyError:
timestamp = None
try:
actor = item['actor']
except KeyError:
actor = None
if count > 0:
output += generate_output(
line=str(int(line)+1),
is_parent=True,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['action'][
'_short'] if hr else 'action',
name=HR_RDAP_COMMON[key]['action'][
'_name'] if (hr and show_name) else None,
value=action,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['timestamp'][
'_short'] if hr else 'timestamp',
name=HR_RDAP_COMMON[key]['timestamp'][
'_name'] if (hr and show_name) else None,
value=timestamp,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['actor'][
'_short'] if hr else 'actor',
name=HR_RDAP_COMMON[key]['actor'][
'_name'] if (hr and show_name) else None,
value=actor,
colorize=colorize
)
count += 1
return output | [
"def",
"generate_output_events",
"(",
"self",
",",
"source",
",",
"key",
",",
"val",
",",
"line",
"=",
"'2'",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"line",
",",
"short",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"False",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"if",
"val",
"is",
"not",
"None",
":",
"count",
"=",
"0",
"for",
"item",
"in",
"val",
":",
"try",
":",
"action",
"=",
"item",
"[",
"'action'",
"]",
"except",
"KeyError",
":",
"action",
"=",
"None",
"try",
":",
"timestamp",
"=",
"item",
"[",
"'timestamp'",
"]",
"except",
"KeyError",
":",
"timestamp",
"=",
"None",
"try",
":",
"actor",
"=",
"item",
"[",
"'actor'",
"]",
"except",
"KeyError",
":",
"actor",
"=",
"None",
"if",
"count",
">",
"0",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"short",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'action'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'action'",
",",
"name",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'action'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"action",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"short",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'timestamp'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'timestamp'",
",",
"name",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'timestamp'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"timestamp",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"short",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'actor'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'actor'",
",",
"name",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'actor'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"actor",
",",
"colorize",
"=",
"colorize",
")",
"count",
"+=",
"1",
"return",
"output"
] | The function for generating CLI output RDAP events results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"events",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L534-L628 | train | 238,624 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_list | def generate_output_list(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
for item in val:
output += generate_output(
line=str(int(line)+1),
value=item,
colorize=colorize
)
return output | python | def generate_output_list(self, source, key, val, line='2', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
for item in val:
output += generate_output(
line=str(int(line)+1),
value=item,
colorize=colorize
)
return output | [
"def",
"generate_output_list",
"(",
"self",
",",
"source",
",",
"key",
",",
"val",
",",
"line",
"=",
"'2'",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"line",
",",
"short",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"False",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"if",
"val",
"is",
"not",
"None",
":",
"for",
"item",
"in",
"val",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"value",
"=",
"item",
",",
"colorize",
"=",
"colorize",
")",
"return",
"output"
] | The function for generating CLI output RDAP list results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"list",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L630-L673 | train | 238,625 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_notices | def generate_output_notices(self, source, key, val, line='1', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP notices results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
count = 0
for item in val:
title = item['title']
description = item['description']
links = item['links']
if count > 0:
output += generate_output(
line=str(int(line)+1),
is_parent=True,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['title']['_short'] if hr else (
'title'),
name=HR_RDAP_COMMON[key]['title']['_name'] if (
hr and show_name) else None,
value=title,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['description'][
'_short'] if hr else 'description',
name=HR_RDAP_COMMON[key]['description'][
'_name'] if (hr and show_name) else None,
value=description.replace(
'\n',
'\n{0}'.format(generate_output(line='3'))
),
colorize=colorize
)
output += self.generate_output_list(
source=source,
key='links',
val=links,
line=str(int(line)+1),
hr=hr,
show_name=show_name,
colorize=colorize
)
count += 1
return output | python | def generate_output_notices(self, source, key, val, line='1', hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output RDAP notices results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
output = generate_output(
line=line,
short=HR_RDAP[source][key]['_short'] if hr else key,
name=HR_RDAP[source][key]['_name'] if (hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if val is not None:
count = 0
for item in val:
title = item['title']
description = item['description']
links = item['links']
if count > 0:
output += generate_output(
line=str(int(line)+1),
is_parent=True,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['title']['_short'] if hr else (
'title'),
name=HR_RDAP_COMMON[key]['title']['_name'] if (
hr and show_name) else None,
value=title,
colorize=colorize
)
output += generate_output(
line=str(int(line)+1),
short=HR_RDAP_COMMON[key]['description'][
'_short'] if hr else 'description',
name=HR_RDAP_COMMON[key]['description'][
'_name'] if (hr and show_name) else None,
value=description.replace(
'\n',
'\n{0}'.format(generate_output(line='3'))
),
colorize=colorize
)
output += self.generate_output_list(
source=source,
key='links',
val=links,
line=str(int(line)+1),
hr=hr,
show_name=show_name,
colorize=colorize
)
count += 1
return output | [
"def",
"generate_output_notices",
"(",
"self",
",",
"source",
",",
"key",
",",
"val",
",",
"line",
"=",
"'1'",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"line",
",",
"short",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_RDAP",
"[",
"source",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"False",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"if",
"val",
"is",
"not",
"None",
":",
"count",
"=",
"0",
"for",
"item",
"in",
"val",
":",
"title",
"=",
"item",
"[",
"'title'",
"]",
"description",
"=",
"item",
"[",
"'description'",
"]",
"links",
"=",
"item",
"[",
"'links'",
"]",
"if",
"count",
">",
"0",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"short",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'title'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"(",
"'title'",
")",
",",
"name",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'title'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"title",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"short",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'description'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'description'",
",",
"name",
"=",
"HR_RDAP_COMMON",
"[",
"key",
"]",
"[",
"'description'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"description",
".",
"replace",
"(",
"'\\n'",
",",
"'\\n{0}'",
".",
"format",
"(",
"generate_output",
"(",
"line",
"=",
"'3'",
")",
")",
")",
",",
"colorize",
"=",
"colorize",
")",
"output",
"+=",
"self",
".",
"generate_output_list",
"(",
"source",
"=",
"source",
",",
"key",
"=",
"'links'",
",",
"val",
"=",
"links",
",",
"line",
"=",
"str",
"(",
"int",
"(",
"line",
")",
"+",
"1",
")",
",",
"hr",
"=",
"hr",
",",
"show_name",
"=",
"show_name",
",",
"colorize",
"=",
"colorize",
")",
"count",
"+=",
"1",
"return",
"output"
] | The function for generating CLI output RDAP notices results.
Args:
source (:obj:`str`): The parent key 'network' or 'objects'
(required).
key (:obj:`str`): The event key 'events' or 'events_actor'
(required).
val (:obj:`dict`): The event dictionary (required).
line (:obj:`str`): The line number (0-4). Determines indentation.
Defaults to '0'.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"notices",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L675-L760 | train | 238,626 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_network | def generate_output_network(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_RDAP['network']['_short'] if hr else 'network',
name=HR_RDAP['network']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
for key, val in json_data['network'].items():
if key in ['links', 'status']:
output += self.generate_output_list(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key in ['notices', 'remarks']:
output += self.generate_output_notices(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key == 'events':
output += self.generate_output_events(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key not in ['raw']:
output += generate_output(
line='1',
short=HR_RDAP['network'][key]['_short'] if hr else key,
name=HR_RDAP['network'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
return output | python | def generate_output_network(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_RDAP['network']['_short'] if hr else 'network',
name=HR_RDAP['network']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
for key, val in json_data['network'].items():
if key in ['links', 'status']:
output += self.generate_output_list(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key in ['notices', 'remarks']:
output += self.generate_output_notices(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key == 'events':
output += self.generate_output_events(
source='network',
key=key,
val=val,
line='1',
hr=hr,
show_name=show_name,
colorize=colorize
)
elif key not in ['raw']:
output += generate_output(
line='1',
short=HR_RDAP['network'][key]['_short'] if hr else key,
name=HR_RDAP['network'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
return output | [
"def",
"generate_output_network",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"HR_RDAP",
"[",
"'network'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'network'",
",",
"name",
"=",
"HR_RDAP",
"[",
"'network'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"for",
"key",
",",
"val",
"in",
"json_data",
"[",
"'network'",
"]",
".",
"items",
"(",
")",
":",
"if",
"key",
"in",
"[",
"'links'",
",",
"'status'",
"]",
":",
"output",
"+=",
"self",
".",
"generate_output_list",
"(",
"source",
"=",
"'network'",
",",
"key",
"=",
"key",
",",
"val",
"=",
"val",
",",
"line",
"=",
"'1'",
",",
"hr",
"=",
"hr",
",",
"show_name",
"=",
"show_name",
",",
"colorize",
"=",
"colorize",
")",
"elif",
"key",
"in",
"[",
"'notices'",
",",
"'remarks'",
"]",
":",
"output",
"+=",
"self",
".",
"generate_output_notices",
"(",
"source",
"=",
"'network'",
",",
"key",
"=",
"key",
",",
"val",
"=",
"val",
",",
"line",
"=",
"'1'",
",",
"hr",
"=",
"hr",
",",
"show_name",
"=",
"show_name",
",",
"colorize",
"=",
"colorize",
")",
"elif",
"key",
"==",
"'events'",
":",
"output",
"+=",
"self",
".",
"generate_output_events",
"(",
"source",
"=",
"'network'",
",",
"key",
"=",
"key",
",",
"val",
"=",
"val",
",",
"line",
"=",
"'1'",
",",
"hr",
"=",
"hr",
",",
"show_name",
"=",
"show_name",
",",
"colorize",
"=",
"colorize",
")",
"elif",
"key",
"not",
"in",
"[",
"'raw'",
"]",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'1'",
",",
"short",
"=",
"HR_RDAP",
"[",
"'network'",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_RDAP",
"[",
"'network'",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"val",
",",
"colorize",
"=",
"colorize",
")",
"return",
"output"
] | The function for generating CLI output RDAP network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"RDAP",
"network",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L762-L840 | train | 238,627 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_whois_nets | def generate_output_whois_nets(self, json_data=None, hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output Legacy Whois networks results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_WHOIS['nets']['_short'] if hr else 'nets',
name=HR_WHOIS['nets']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
count = 0
for net in json_data['nets']:
if count > 0:
output += self.generate_output_newline(
line='1',
colorize=colorize
)
count += 1
output += generate_output(
line='1',
short=net['handle'],
is_parent=True,
colorize=colorize
)
for key, val in net.items():
if val and '\n' in val:
output += generate_output(
line='2',
short=HR_WHOIS['nets'][key]['_short'] if hr else key,
name=HR_WHOIS['nets'][key]['_name'] if (
hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
for v in val.split('\n'):
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
output += generate_output(
line='2',
short=HR_WHOIS['nets'][key]['_short'] if hr else key,
name=HR_WHOIS['nets'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
return output | python | def generate_output_whois_nets(self, json_data=None, hr=True,
show_name=False, colorize=True):
"""
The function for generating CLI output Legacy Whois networks results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_WHOIS['nets']['_short'] if hr else 'nets',
name=HR_WHOIS['nets']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
count = 0
for net in json_data['nets']:
if count > 0:
output += self.generate_output_newline(
line='1',
colorize=colorize
)
count += 1
output += generate_output(
line='1',
short=net['handle'],
is_parent=True,
colorize=colorize
)
for key, val in net.items():
if val and '\n' in val:
output += generate_output(
line='2',
short=HR_WHOIS['nets'][key]['_short'] if hr else key,
name=HR_WHOIS['nets'][key]['_name'] if (
hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
for v in val.split('\n'):
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
output += generate_output(
line='2',
short=HR_WHOIS['nets'][key]['_short'] if hr else key,
name=HR_WHOIS['nets'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
return output | [
"def",
"generate_output_whois_nets",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'nets'",
",",
"name",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"count",
"=",
"0",
"for",
"net",
"in",
"json_data",
"[",
"'nets'",
"]",
":",
"if",
"count",
">",
"0",
":",
"output",
"+=",
"self",
".",
"generate_output_newline",
"(",
"line",
"=",
"'1'",
",",
"colorize",
"=",
"colorize",
")",
"count",
"+=",
"1",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'1'",
",",
"short",
"=",
"net",
"[",
"'handle'",
"]",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"for",
"key",
",",
"val",
"in",
"net",
".",
"items",
"(",
")",
":",
"if",
"val",
"and",
"'\\n'",
"in",
"val",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'2'",
",",
"short",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"False",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"for",
"v",
"in",
"val",
".",
"split",
"(",
"'\\n'",
")",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'3'",
",",
"value",
"=",
"v",
",",
"colorize",
"=",
"colorize",
")",
"else",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'2'",
",",
"short",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"key",
",",
"name",
"=",
"HR_WHOIS",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"val",
",",
"colorize",
"=",
"colorize",
")",
"return",
"output"
] | The function for generating CLI output Legacy Whois networks results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"Legacy",
"Whois",
"networks",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L1085-L1164 | train | 238,628 |
secynic/ipwhois | ipwhois/scripts/ipwhois_cli.py | IPWhoisCLI.generate_output_nir | def generate_output_nir(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output NIR network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_WHOIS_NIR['nets']['_short'] if hr else 'nir_nets',
name=HR_WHOIS_NIR['nets']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
count = 0
if json_data['nir']:
for net in json_data['nir']['nets']:
if count > 0:
output += self.generate_output_newline(
line='1',
colorize=colorize
)
count += 1
output += generate_output(
line='1',
short=net['handle'],
is_parent=True,
colorize=colorize
)
for key, val in net.items():
if val and (isinstance(val, dict) or '\n' in val or
key == 'nameservers'):
output += generate_output(
line='2',
short=(
HR_WHOIS_NIR['nets'][key]['_short'] if (
hr) else key
),
name=HR_WHOIS_NIR['nets'][key]['_name'] if (
hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if key == 'contacts':
for k, v in val.items():
if v:
output += generate_output(
line='3',
is_parent=False if (
len(v) == 0) else True,
name=k,
colorize=colorize
)
for contact_key, contact_val in v.items():
if v is not None:
tmp_out = '{0}{1}{2}'.format(
contact_key,
': ',
contact_val
)
output += generate_output(
line='4',
value=tmp_out,
colorize=colorize
)
elif key == 'nameservers':
for v in val:
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
for v in val.split('\n'):
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
output += generate_output(
line='2',
short=(
HR_WHOIS_NIR['nets'][key]['_short'] if (
hr) else key
),
name=HR_WHOIS_NIR['nets'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
else:
output += 'None'
return output | python | def generate_output_nir(self, json_data=None, hr=True, show_name=False,
colorize=True):
"""
The function for generating CLI output NIR network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output.
"""
if json_data is None:
json_data = {}
output = generate_output(
line='0',
short=HR_WHOIS_NIR['nets']['_short'] if hr else 'nir_nets',
name=HR_WHOIS_NIR['nets']['_name'] if (hr and show_name) else None,
is_parent=True,
colorize=colorize
)
count = 0
if json_data['nir']:
for net in json_data['nir']['nets']:
if count > 0:
output += self.generate_output_newline(
line='1',
colorize=colorize
)
count += 1
output += generate_output(
line='1',
short=net['handle'],
is_parent=True,
colorize=colorize
)
for key, val in net.items():
if val and (isinstance(val, dict) or '\n' in val or
key == 'nameservers'):
output += generate_output(
line='2',
short=(
HR_WHOIS_NIR['nets'][key]['_short'] if (
hr) else key
),
name=HR_WHOIS_NIR['nets'][key]['_name'] if (
hr and show_name) else None,
is_parent=False if (val is None or
len(val) == 0) else True,
value='None' if (val is None or
len(val) == 0) else None,
colorize=colorize
)
if key == 'contacts':
for k, v in val.items():
if v:
output += generate_output(
line='3',
is_parent=False if (
len(v) == 0) else True,
name=k,
colorize=colorize
)
for contact_key, contact_val in v.items():
if v is not None:
tmp_out = '{0}{1}{2}'.format(
contact_key,
': ',
contact_val
)
output += generate_output(
line='4',
value=tmp_out,
colorize=colorize
)
elif key == 'nameservers':
for v in val:
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
for v in val.split('\n'):
output += generate_output(
line='3',
value=v,
colorize=colorize
)
else:
output += generate_output(
line='2',
short=(
HR_WHOIS_NIR['nets'][key]['_short'] if (
hr) else key
),
name=HR_WHOIS_NIR['nets'][key]['_name'] if (
hr and show_name) else None,
value=val,
colorize=colorize
)
else:
output += 'None'
return output | [
"def",
"generate_output_nir",
"(",
"self",
",",
"json_data",
"=",
"None",
",",
"hr",
"=",
"True",
",",
"show_name",
"=",
"False",
",",
"colorize",
"=",
"True",
")",
":",
"if",
"json_data",
"is",
"None",
":",
"json_data",
"=",
"{",
"}",
"output",
"=",
"generate_output",
"(",
"line",
"=",
"'0'",
",",
"short",
"=",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"'_short'",
"]",
"if",
"hr",
"else",
"'nir_nets'",
",",
"name",
"=",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"count",
"=",
"0",
"if",
"json_data",
"[",
"'nir'",
"]",
":",
"for",
"net",
"in",
"json_data",
"[",
"'nir'",
"]",
"[",
"'nets'",
"]",
":",
"if",
"count",
">",
"0",
":",
"output",
"+=",
"self",
".",
"generate_output_newline",
"(",
"line",
"=",
"'1'",
",",
"colorize",
"=",
"colorize",
")",
"count",
"+=",
"1",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'1'",
",",
"short",
"=",
"net",
"[",
"'handle'",
"]",
",",
"is_parent",
"=",
"True",
",",
"colorize",
"=",
"colorize",
")",
"for",
"key",
",",
"val",
"in",
"net",
".",
"items",
"(",
")",
":",
"if",
"val",
"and",
"(",
"isinstance",
"(",
"val",
",",
"dict",
")",
"or",
"'\\n'",
"in",
"val",
"or",
"key",
"==",
"'nameservers'",
")",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'2'",
",",
"short",
"=",
"(",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"(",
"hr",
")",
"else",
"key",
")",
",",
"name",
"=",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"is_parent",
"=",
"False",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"True",
",",
"value",
"=",
"'None'",
"if",
"(",
"val",
"is",
"None",
"or",
"len",
"(",
"val",
")",
"==",
"0",
")",
"else",
"None",
",",
"colorize",
"=",
"colorize",
")",
"if",
"key",
"==",
"'contacts'",
":",
"for",
"k",
",",
"v",
"in",
"val",
".",
"items",
"(",
")",
":",
"if",
"v",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'3'",
",",
"is_parent",
"=",
"False",
"if",
"(",
"len",
"(",
"v",
")",
"==",
"0",
")",
"else",
"True",
",",
"name",
"=",
"k",
",",
"colorize",
"=",
"colorize",
")",
"for",
"contact_key",
",",
"contact_val",
"in",
"v",
".",
"items",
"(",
")",
":",
"if",
"v",
"is",
"not",
"None",
":",
"tmp_out",
"=",
"'{0}{1}{2}'",
".",
"format",
"(",
"contact_key",
",",
"': '",
",",
"contact_val",
")",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'4'",
",",
"value",
"=",
"tmp_out",
",",
"colorize",
"=",
"colorize",
")",
"elif",
"key",
"==",
"'nameservers'",
":",
"for",
"v",
"in",
"val",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'3'",
",",
"value",
"=",
"v",
",",
"colorize",
"=",
"colorize",
")",
"else",
":",
"for",
"v",
"in",
"val",
".",
"split",
"(",
"'\\n'",
")",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'3'",
",",
"value",
"=",
"v",
",",
"colorize",
"=",
"colorize",
")",
"else",
":",
"output",
"+=",
"generate_output",
"(",
"line",
"=",
"'2'",
",",
"short",
"=",
"(",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_short'",
"]",
"if",
"(",
"hr",
")",
"else",
"key",
")",
",",
"name",
"=",
"HR_WHOIS_NIR",
"[",
"'nets'",
"]",
"[",
"key",
"]",
"[",
"'_name'",
"]",
"if",
"(",
"hr",
"and",
"show_name",
")",
"else",
"None",
",",
"value",
"=",
"val",
",",
"colorize",
"=",
"colorize",
")",
"else",
":",
"output",
"+=",
"'None'",
"return",
"output"
] | The function for generating CLI output NIR network results.
Args:
json_data (:obj:`dict`): The data to process. Defaults to None.
hr (:obj:`bool`): Enable human readable key translations. Defaults
to True.
show_name (:obj:`bool`): Show human readable name (default is to
only show short). Defaults to False.
colorize (:obj:`bool`): Colorize the console output with ANSI
colors. Defaults to True.
Returns:
str: The generated output. | [
"The",
"function",
"for",
"generating",
"CLI",
"output",
"NIR",
"network",
"results",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/scripts/ipwhois_cli.py#L1234-L1368 | train | 238,629 |
secynic/ipwhois | ipwhois/asn.py | IPASN.parse_fields_whois | def parse_fields_whois(self, response):
"""
The function for parsing ASN fields from a whois response.
Args:
response (:obj:`str`): The response from the ASN whois server.
Returns:
dict: The ASN lookup results
::
{
'asn' (str) - The Autonomous System Number
'asn_date' (str) - The ASN Allocation date
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (str) - The assigned ASN CIDR
'asn_country_code' (str) - The assigned ASN country code
'asn_description' (str) - The ASN description
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed.
"""
try:
temp = response.split('|')
# Parse out the ASN information.
ret = {'asn_registry': temp[4].strip(' \n')}
if ret['asn_registry'] not in self.rir_whois.keys():
raise ASNRegistryError(
'ASN registry {0} is not known.'.format(
ret['asn_registry'])
)
ret['asn'] = temp[0].strip(' \n')
ret['asn_cidr'] = temp[2].strip(' \n')
ret['asn_country_code'] = temp[3].strip(' \n').upper()
ret['asn_date'] = temp[5].strip(' \n')
ret['asn_description'] = temp[6].strip(' \n')
except ASNRegistryError:
raise
except Exception as e:
raise ASNParseError('Parsing failed for "{0}" with exception: {1}.'
''.format(response, e)[:100])
return ret | python | def parse_fields_whois(self, response):
"""
The function for parsing ASN fields from a whois response.
Args:
response (:obj:`str`): The response from the ASN whois server.
Returns:
dict: The ASN lookup results
::
{
'asn' (str) - The Autonomous System Number
'asn_date' (str) - The ASN Allocation date
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (str) - The assigned ASN CIDR
'asn_country_code' (str) - The assigned ASN country code
'asn_description' (str) - The ASN description
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed.
"""
try:
temp = response.split('|')
# Parse out the ASN information.
ret = {'asn_registry': temp[4].strip(' \n')}
if ret['asn_registry'] not in self.rir_whois.keys():
raise ASNRegistryError(
'ASN registry {0} is not known.'.format(
ret['asn_registry'])
)
ret['asn'] = temp[0].strip(' \n')
ret['asn_cidr'] = temp[2].strip(' \n')
ret['asn_country_code'] = temp[3].strip(' \n').upper()
ret['asn_date'] = temp[5].strip(' \n')
ret['asn_description'] = temp[6].strip(' \n')
except ASNRegistryError:
raise
except Exception as e:
raise ASNParseError('Parsing failed for "{0}" with exception: {1}.'
''.format(response, e)[:100])
return ret | [
"def",
"parse_fields_whois",
"(",
"self",
",",
"response",
")",
":",
"try",
":",
"temp",
"=",
"response",
".",
"split",
"(",
"'|'",
")",
"# Parse out the ASN information.",
"ret",
"=",
"{",
"'asn_registry'",
":",
"temp",
"[",
"4",
"]",
".",
"strip",
"(",
"' \\n'",
")",
"}",
"if",
"ret",
"[",
"'asn_registry'",
"]",
"not",
"in",
"self",
".",
"rir_whois",
".",
"keys",
"(",
")",
":",
"raise",
"ASNRegistryError",
"(",
"'ASN registry {0} is not known.'",
".",
"format",
"(",
"ret",
"[",
"'asn_registry'",
"]",
")",
")",
"ret",
"[",
"'asn'",
"]",
"=",
"temp",
"[",
"0",
"]",
".",
"strip",
"(",
"' \\n'",
")",
"ret",
"[",
"'asn_cidr'",
"]",
"=",
"temp",
"[",
"2",
"]",
".",
"strip",
"(",
"' \\n'",
")",
"ret",
"[",
"'asn_country_code'",
"]",
"=",
"temp",
"[",
"3",
"]",
".",
"strip",
"(",
"' \\n'",
")",
".",
"upper",
"(",
")",
"ret",
"[",
"'asn_date'",
"]",
"=",
"temp",
"[",
"5",
"]",
".",
"strip",
"(",
"' \\n'",
")",
"ret",
"[",
"'asn_description'",
"]",
"=",
"temp",
"[",
"6",
"]",
".",
"strip",
"(",
"' \\n'",
")",
"except",
"ASNRegistryError",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"raise",
"ASNParseError",
"(",
"'Parsing failed for \"{0}\" with exception: {1}.'",
"''",
".",
"format",
"(",
"response",
",",
"e",
")",
"[",
":",
"100",
"]",
")",
"return",
"ret"
] | The function for parsing ASN fields from a whois response.
Args:
response (:obj:`str`): The response from the ASN whois server.
Returns:
dict: The ASN lookup results
::
{
'asn' (str) - The Autonomous System Number
'asn_date' (str) - The ASN Allocation date
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (str) - The assigned ASN CIDR
'asn_country_code' (str) - The assigned ASN country code
'asn_description' (str) - The ASN description
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed. | [
"The",
"function",
"for",
"parsing",
"ASN",
"fields",
"from",
"a",
"whois",
"response",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/asn.py#L239-L294 | train | 238,630 |
secynic/ipwhois | ipwhois/asn.py | IPASN.parse_fields_http | def parse_fields_http(self, response, extra_org_map=None):
"""
The function for parsing ASN fields from a http response.
Args:
response (:obj:`str`): The response from the ASN http server.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP lookup) does not show an RIR as the org handle e.g., DNIC
(which is now the built in ORG_MAP) e.g., {'DNIC': 'arin'}.
Valid RIR values are (note the case-sensitive - this is meant
to match the REST result): 'ARIN', 'RIPE', 'apnic', 'lacnic',
'afrinic'. Defaults to None.
Returns:
dict: The ASN lookup results
::
{
'asn' (None) - Cannot retrieve with this method.
'asn_date' (None) - Cannot retrieve with this method.
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (None) - Cannot retrieve with this method.
'asn_country_code' (None) - Cannot retrieve with this
method.
'asn_description' (None) - Cannot retrieve with this
method.
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed.
"""
# Set the org_map. Map the orgRef handle to an RIR.
org_map = self.org_map.copy()
try:
org_map.update(extra_org_map)
except (TypeError, ValueError, IndexError, KeyError):
pass
try:
asn_data = {
'asn_registry': None,
'asn': None,
'asn_cidr': None,
'asn_country_code': None,
'asn_date': None,
'asn_description': None
}
try:
net_list = response['nets']['net']
if not isinstance(net_list, list):
net_list = [net_list]
except (KeyError, TypeError):
log.debug('No networks found')
net_list = []
for n in reversed(net_list):
try:
asn_data['asn_registry'] = (
org_map[n['orgRef']['@handle'].upper()]
)
except KeyError as e:
log.debug('Could not parse ASN registry via HTTP: '
'{0}'.format(str(e)))
continue
break
if not asn_data['asn_registry']:
log.debug('Could not parse ASN registry via HTTP')
raise ASNRegistryError('ASN registry lookup failed.')
except ASNRegistryError:
raise
except Exception as e: # pragma: no cover
raise ASNParseError('Parsing failed for "{0}" with exception: {1}.'
''.format(response, e)[:100])
return asn_data | python | def parse_fields_http(self, response, extra_org_map=None):
"""
The function for parsing ASN fields from a http response.
Args:
response (:obj:`str`): The response from the ASN http server.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP lookup) does not show an RIR as the org handle e.g., DNIC
(which is now the built in ORG_MAP) e.g., {'DNIC': 'arin'}.
Valid RIR values are (note the case-sensitive - this is meant
to match the REST result): 'ARIN', 'RIPE', 'apnic', 'lacnic',
'afrinic'. Defaults to None.
Returns:
dict: The ASN lookup results
::
{
'asn' (None) - Cannot retrieve with this method.
'asn_date' (None) - Cannot retrieve with this method.
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (None) - Cannot retrieve with this method.
'asn_country_code' (None) - Cannot retrieve with this
method.
'asn_description' (None) - Cannot retrieve with this
method.
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed.
"""
# Set the org_map. Map the orgRef handle to an RIR.
org_map = self.org_map.copy()
try:
org_map.update(extra_org_map)
except (TypeError, ValueError, IndexError, KeyError):
pass
try:
asn_data = {
'asn_registry': None,
'asn': None,
'asn_cidr': None,
'asn_country_code': None,
'asn_date': None,
'asn_description': None
}
try:
net_list = response['nets']['net']
if not isinstance(net_list, list):
net_list = [net_list]
except (KeyError, TypeError):
log.debug('No networks found')
net_list = []
for n in reversed(net_list):
try:
asn_data['asn_registry'] = (
org_map[n['orgRef']['@handle'].upper()]
)
except KeyError as e:
log.debug('Could not parse ASN registry via HTTP: '
'{0}'.format(str(e)))
continue
break
if not asn_data['asn_registry']:
log.debug('Could not parse ASN registry via HTTP')
raise ASNRegistryError('ASN registry lookup failed.')
except ASNRegistryError:
raise
except Exception as e: # pragma: no cover
raise ASNParseError('Parsing failed for "{0}" with exception: {1}.'
''.format(response, e)[:100])
return asn_data | [
"def",
"parse_fields_http",
"(",
"self",
",",
"response",
",",
"extra_org_map",
"=",
"None",
")",
":",
"# Set the org_map. Map the orgRef handle to an RIR.",
"org_map",
"=",
"self",
".",
"org_map",
".",
"copy",
"(",
")",
"try",
":",
"org_map",
".",
"update",
"(",
"extra_org_map",
")",
"except",
"(",
"TypeError",
",",
"ValueError",
",",
"IndexError",
",",
"KeyError",
")",
":",
"pass",
"try",
":",
"asn_data",
"=",
"{",
"'asn_registry'",
":",
"None",
",",
"'asn'",
":",
"None",
",",
"'asn_cidr'",
":",
"None",
",",
"'asn_country_code'",
":",
"None",
",",
"'asn_date'",
":",
"None",
",",
"'asn_description'",
":",
"None",
"}",
"try",
":",
"net_list",
"=",
"response",
"[",
"'nets'",
"]",
"[",
"'net'",
"]",
"if",
"not",
"isinstance",
"(",
"net_list",
",",
"list",
")",
":",
"net_list",
"=",
"[",
"net_list",
"]",
"except",
"(",
"KeyError",
",",
"TypeError",
")",
":",
"log",
".",
"debug",
"(",
"'No networks found'",
")",
"net_list",
"=",
"[",
"]",
"for",
"n",
"in",
"reversed",
"(",
"net_list",
")",
":",
"try",
":",
"asn_data",
"[",
"'asn_registry'",
"]",
"=",
"(",
"org_map",
"[",
"n",
"[",
"'orgRef'",
"]",
"[",
"'@handle'",
"]",
".",
"upper",
"(",
")",
"]",
")",
"except",
"KeyError",
"as",
"e",
":",
"log",
".",
"debug",
"(",
"'Could not parse ASN registry via HTTP: '",
"'{0}'",
".",
"format",
"(",
"str",
"(",
"e",
")",
")",
")",
"continue",
"break",
"if",
"not",
"asn_data",
"[",
"'asn_registry'",
"]",
":",
"log",
".",
"debug",
"(",
"'Could not parse ASN registry via HTTP'",
")",
"raise",
"ASNRegistryError",
"(",
"'ASN registry lookup failed.'",
")",
"except",
"ASNRegistryError",
":",
"raise",
"except",
"Exception",
"as",
"e",
":",
"# pragma: no cover",
"raise",
"ASNParseError",
"(",
"'Parsing failed for \"{0}\" with exception: {1}.'",
"''",
".",
"format",
"(",
"response",
",",
"e",
")",
"[",
":",
"100",
"]",
")",
"return",
"asn_data"
] | The function for parsing ASN fields from a http response.
Args:
response (:obj:`str`): The response from the ASN http server.
extra_org_map (:obj:`dict`): Dictionary mapping org handles to
RIRs. This is for limited cases where ARIN REST (ASN fallback
HTTP lookup) does not show an RIR as the org handle e.g., DNIC
(which is now the built in ORG_MAP) e.g., {'DNIC': 'arin'}.
Valid RIR values are (note the case-sensitive - this is meant
to match the REST result): 'ARIN', 'RIPE', 'apnic', 'lacnic',
'afrinic'. Defaults to None.
Returns:
dict: The ASN lookup results
::
{
'asn' (None) - Cannot retrieve with this method.
'asn_date' (None) - Cannot retrieve with this method.
'asn_registry' (str) - The assigned ASN registry
'asn_cidr' (None) - Cannot retrieve with this method.
'asn_country_code' (None) - Cannot retrieve with this
method.
'asn_description' (None) - Cannot retrieve with this
method.
}
Raises:
ASNRegistryError: The ASN registry is not known.
ASNParseError: ASN parsing failed. | [
"The",
"function",
"for",
"parsing",
"ASN",
"fields",
"from",
"a",
"http",
"response",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/asn.py#L306-L404 | train | 238,631 |
secynic/ipwhois | ipwhois/asn.py | ASNOrigin.get_nets_radb | def get_nets_radb(self, response, is_http=False):
"""
The function for parsing network blocks from ASN origin data.
Args:
response (:obj:`str`): The response from the RADB whois/http
server.
is_http (:obj:`bool`): If the query is RADB HTTP instead of whois,
set to True. Defaults to False.
Returns:
list: A list of network block dictionaries
::
[{
'cidr' (str) - The assigned CIDR
'start' (int) - The index for the start of the parsed
network block
'end' (int) - The index for the end of the parsed network
block
}]
"""
nets = []
if is_http:
regex = r'route(?:6)?:[^\S\n]+(?P<val>.+?)<br>'
else:
regex = r'^route(?:6)?:[^\S\n]+(?P<val>.+|.+)$'
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
regex,
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net['cidr'] = match.group(1).strip()
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError: # pragma: no cover
pass
return nets | python | def get_nets_radb(self, response, is_http=False):
"""
The function for parsing network blocks from ASN origin data.
Args:
response (:obj:`str`): The response from the RADB whois/http
server.
is_http (:obj:`bool`): If the query is RADB HTTP instead of whois,
set to True. Defaults to False.
Returns:
list: A list of network block dictionaries
::
[{
'cidr' (str) - The assigned CIDR
'start' (int) - The index for the start of the parsed
network block
'end' (int) - The index for the end of the parsed network
block
}]
"""
nets = []
if is_http:
regex = r'route(?:6)?:[^\S\n]+(?P<val>.+?)<br>'
else:
regex = r'^route(?:6)?:[^\S\n]+(?P<val>.+|.+)$'
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
regex,
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net['cidr'] = match.group(1).strip()
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError: # pragma: no cover
pass
return nets | [
"def",
"get_nets_radb",
"(",
"self",
",",
"response",
",",
"is_http",
"=",
"False",
")",
":",
"nets",
"=",
"[",
"]",
"if",
"is_http",
":",
"regex",
"=",
"r'route(?:6)?:[^\\S\\n]+(?P<val>.+?)<br>'",
"else",
":",
"regex",
"=",
"r'^route(?:6)?:[^\\S\\n]+(?P<val>.+|.+)$'",
"# Iterate through all of the networks found, storing the CIDR value",
"# and the start and end positions.",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"regex",
",",
"response",
",",
"re",
".",
"MULTILINE",
")",
":",
"try",
":",
"net",
"=",
"copy",
".",
"deepcopy",
"(",
"BASE_NET",
")",
"net",
"[",
"'cidr'",
"]",
"=",
"match",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"net",
"[",
"'start'",
"]",
"=",
"match",
".",
"start",
"(",
")",
"net",
"[",
"'end'",
"]",
"=",
"match",
".",
"end",
"(",
")",
"nets",
".",
"append",
"(",
"net",
")",
"except",
"ValueError",
":",
"# pragma: no cover",
"pass",
"return",
"nets"
] | The function for parsing network blocks from ASN origin data.
Args:
response (:obj:`str`): The response from the RADB whois/http
server.
is_http (:obj:`bool`): If the query is RADB HTTP instead of whois,
set to True. Defaults to False.
Returns:
list: A list of network block dictionaries
::
[{
'cidr' (str) - The assigned CIDR
'start' (int) - The index for the start of the parsed
network block
'end' (int) - The index for the end of the parsed network
block
}] | [
"The",
"function",
"for",
"parsing",
"network",
"blocks",
"from",
"ASN",
"origin",
"data",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/asn.py#L719-L770 | train | 238,632 |
secynic/ipwhois | ipwhois/nir.py | NIRWhois.get_nets_jpnic | def get_nets_jpnic(self, response):
"""
The function for parsing network blocks from jpnic whois data.
Args:
response (:obj:`str`): The response from the jpnic server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^.*?(\[Network Number\])[^\S\n]+.+?>(?P<val>.+?)</A>$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
tmp = ip_network(match.group(2))
try: # pragma: no cover
network_address = tmp.network_address
except AttributeError: # pragma: no cover
network_address = tmp.ip
pass
try: # pragma: no cover
broadcast_address = tmp.broadcast_address
except AttributeError: # pragma: no cover
broadcast_address = tmp.broadcast
pass
net['range'] = '{0} - {1}'.format(
network_address + 1, broadcast_address
)
cidr = ip_network(match.group(2).strip()).__str__()
net['cidr'] = cidr
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except (ValueError, TypeError):
pass
return nets | python | def get_nets_jpnic(self, response):
"""
The function for parsing network blocks from jpnic whois data.
Args:
response (:obj:`str`): The response from the jpnic server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^.*?(\[Network Number\])[^\S\n]+.+?>(?P<val>.+?)</A>$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
tmp = ip_network(match.group(2))
try: # pragma: no cover
network_address = tmp.network_address
except AttributeError: # pragma: no cover
network_address = tmp.ip
pass
try: # pragma: no cover
broadcast_address = tmp.broadcast_address
except AttributeError: # pragma: no cover
broadcast_address = tmp.broadcast
pass
net['range'] = '{0} - {1}'.format(
network_address + 1, broadcast_address
)
cidr = ip_network(match.group(2).strip()).__str__()
net['cidr'] = cidr
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except (ValueError, TypeError):
pass
return nets | [
"def",
"get_nets_jpnic",
"(",
"self",
",",
"response",
")",
":",
"nets",
"=",
"[",
"]",
"# Iterate through all of the networks found, storing the CIDR value",
"# and the start and end positions.",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'^.*?(\\[Network Number\\])[^\\S\\n]+.+?>(?P<val>.+?)</A>$'",
",",
"response",
",",
"re",
".",
"MULTILINE",
")",
":",
"try",
":",
"net",
"=",
"copy",
".",
"deepcopy",
"(",
"BASE_NET",
")",
"tmp",
"=",
"ip_network",
"(",
"match",
".",
"group",
"(",
"2",
")",
")",
"try",
":",
"# pragma: no cover",
"network_address",
"=",
"tmp",
".",
"network_address",
"except",
"AttributeError",
":",
"# pragma: no cover",
"network_address",
"=",
"tmp",
".",
"ip",
"pass",
"try",
":",
"# pragma: no cover",
"broadcast_address",
"=",
"tmp",
".",
"broadcast_address",
"except",
"AttributeError",
":",
"# pragma: no cover",
"broadcast_address",
"=",
"tmp",
".",
"broadcast",
"pass",
"net",
"[",
"'range'",
"]",
"=",
"'{0} - {1}'",
".",
"format",
"(",
"network_address",
"+",
"1",
",",
"broadcast_address",
")",
"cidr",
"=",
"ip_network",
"(",
"match",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
")",
".",
"__str__",
"(",
")",
"net",
"[",
"'cidr'",
"]",
"=",
"cidr",
"net",
"[",
"'start'",
"]",
"=",
"match",
".",
"start",
"(",
")",
"net",
"[",
"'end'",
"]",
"=",
"match",
".",
"end",
"(",
")",
"nets",
".",
"append",
"(",
"net",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"return",
"nets"
] | The function for parsing network blocks from jpnic whois data.
Args:
response (:obj:`str`): The response from the jpnic server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}] | [
"The",
"function",
"for",
"parsing",
"network",
"blocks",
"from",
"jpnic",
"whois",
"data",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/nir.py#L299-L360 | train | 238,633 |
secynic/ipwhois | ipwhois/nir.py | NIRWhois.get_contact | def get_contact(self, response=None, nir=None, handle=None,
retry_count=3, dt_format=None):
"""
The function for retrieving and parsing NIR whois data based on
NIR_WHOIS contact_fields.
Args:
response (:obj:`str`): Optional response object, this bypasses the
lookup.
nir (:obj:`str`): The NIR to query ('jpnic' or 'krnic'). Required
if response is None.
handle (:obj:`str`): For NIRs that have separate contact queries
(JPNIC), this is the contact handle to use in the query.
Defaults to None.
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
dt_format (:obj:`str`): The format of datetime fields if known.
Defaults to None.
Returns:
dict: Mapping of the fields provided in contact_fields, to their
parsed results.
"""
if response or nir == 'krnic':
contact_response = response
else:
# Retrieve the whois data.
contact_response = self._net.get_http_raw(
url=str(NIR_WHOIS[nir]['url']).format(handle),
retry_count=retry_count,
headers=NIR_WHOIS[nir]['request_headers'],
request_type=NIR_WHOIS[nir]['request_type']
)
return self.parse_fields(
response=contact_response,
fields_dict=NIR_WHOIS[nir]['contact_fields'],
dt_format=dt_format,
hourdelta=int(NIR_WHOIS[nir]['dt_hourdelta']),
is_contact=True
) | python | def get_contact(self, response=None, nir=None, handle=None,
retry_count=3, dt_format=None):
"""
The function for retrieving and parsing NIR whois data based on
NIR_WHOIS contact_fields.
Args:
response (:obj:`str`): Optional response object, this bypasses the
lookup.
nir (:obj:`str`): The NIR to query ('jpnic' or 'krnic'). Required
if response is None.
handle (:obj:`str`): For NIRs that have separate contact queries
(JPNIC), this is the contact handle to use in the query.
Defaults to None.
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
dt_format (:obj:`str`): The format of datetime fields if known.
Defaults to None.
Returns:
dict: Mapping of the fields provided in contact_fields, to their
parsed results.
"""
if response or nir == 'krnic':
contact_response = response
else:
# Retrieve the whois data.
contact_response = self._net.get_http_raw(
url=str(NIR_WHOIS[nir]['url']).format(handle),
retry_count=retry_count,
headers=NIR_WHOIS[nir]['request_headers'],
request_type=NIR_WHOIS[nir]['request_type']
)
return self.parse_fields(
response=contact_response,
fields_dict=NIR_WHOIS[nir]['contact_fields'],
dt_format=dt_format,
hourdelta=int(NIR_WHOIS[nir]['dt_hourdelta']),
is_contact=True
) | [
"def",
"get_contact",
"(",
"self",
",",
"response",
"=",
"None",
",",
"nir",
"=",
"None",
",",
"handle",
"=",
"None",
",",
"retry_count",
"=",
"3",
",",
"dt_format",
"=",
"None",
")",
":",
"if",
"response",
"or",
"nir",
"==",
"'krnic'",
":",
"contact_response",
"=",
"response",
"else",
":",
"# Retrieve the whois data.",
"contact_response",
"=",
"self",
".",
"_net",
".",
"get_http_raw",
"(",
"url",
"=",
"str",
"(",
"NIR_WHOIS",
"[",
"nir",
"]",
"[",
"'url'",
"]",
")",
".",
"format",
"(",
"handle",
")",
",",
"retry_count",
"=",
"retry_count",
",",
"headers",
"=",
"NIR_WHOIS",
"[",
"nir",
"]",
"[",
"'request_headers'",
"]",
",",
"request_type",
"=",
"NIR_WHOIS",
"[",
"nir",
"]",
"[",
"'request_type'",
"]",
")",
"return",
"self",
".",
"parse_fields",
"(",
"response",
"=",
"contact_response",
",",
"fields_dict",
"=",
"NIR_WHOIS",
"[",
"nir",
"]",
"[",
"'contact_fields'",
"]",
",",
"dt_format",
"=",
"dt_format",
",",
"hourdelta",
"=",
"int",
"(",
"NIR_WHOIS",
"[",
"nir",
"]",
"[",
"'dt_hourdelta'",
"]",
")",
",",
"is_contact",
"=",
"True",
")"
] | The function for retrieving and parsing NIR whois data based on
NIR_WHOIS contact_fields.
Args:
response (:obj:`str`): Optional response object, this bypasses the
lookup.
nir (:obj:`str`): The NIR to query ('jpnic' or 'krnic'). Required
if response is None.
handle (:obj:`str`): For NIRs that have separate contact queries
(JPNIC), this is the contact handle to use in the query.
Defaults to None.
retry_count (:obj:`int`): The number of times to retry in case
socket errors, timeouts, connection resets, etc. are
encountered. Defaults to 3.
dt_format (:obj:`str`): The format of datetime fields if known.
Defaults to None.
Returns:
dict: Mapping of the fields provided in contact_fields, to their
parsed results. | [
"The",
"function",
"for",
"retrieving",
"and",
"parsing",
"NIR",
"whois",
"data",
"based",
"on",
"NIR_WHOIS",
"contact_fields",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/nir.py#L447-L492 | train | 238,634 |
secynic/ipwhois | ipwhois/rdap.py | _RDAPContact._parse_address | def _parse_address(self, val):
"""
The function for parsing the vcard address.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (KeyError, ValueError, TypeError):
pass
try:
ret['value'] = val[1]['label']
except (KeyError, ValueError, TypeError):
ret['value'] = '\n'.join(val[3]).strip()
try:
self.vars['address'].append(ret)
except AttributeError:
self.vars['address'] = []
self.vars['address'].append(ret) | python | def _parse_address(self, val):
"""
The function for parsing the vcard address.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (KeyError, ValueError, TypeError):
pass
try:
ret['value'] = val[1]['label']
except (KeyError, ValueError, TypeError):
ret['value'] = '\n'.join(val[3]).strip()
try:
self.vars['address'].append(ret)
except AttributeError:
self.vars['address'] = []
self.vars['address'].append(ret) | [
"def",
"_parse_address",
"(",
"self",
",",
"val",
")",
":",
"ret",
"=",
"{",
"'type'",
":",
"None",
",",
"'value'",
":",
"None",
"}",
"try",
":",
"ret",
"[",
"'type'",
"]",
"=",
"val",
"[",
"1",
"]",
"[",
"'type'",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"try",
":",
"ret",
"[",
"'value'",
"]",
"=",
"val",
"[",
"1",
"]",
"[",
"'label'",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"ret",
"[",
"'value'",
"]",
"=",
"'\\n'",
".",
"join",
"(",
"val",
"[",
"3",
"]",
")",
".",
"strip",
"(",
")",
"try",
":",
"self",
".",
"vars",
"[",
"'address'",
"]",
".",
"append",
"(",
"ret",
")",
"except",
"AttributeError",
":",
"self",
".",
"vars",
"[",
"'address'",
"]",
"=",
"[",
"]",
"self",
".",
"vars",
"[",
"'address'",
"]",
".",
"append",
"(",
"ret",
")"
] | The function for parsing the vcard address.
Args:
val (:obj:`list`): The value to parse. | [
"The",
"function",
"for",
"parsing",
"the",
"vcard",
"address",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/rdap.py#L112-L148 | train | 238,635 |
secynic/ipwhois | ipwhois/rdap.py | _RDAPContact._parse_phone | def _parse_phone(self, val):
"""
The function for parsing the vcard phone numbers.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (IndexError, KeyError, ValueError, TypeError):
pass
ret['value'] = val[3].strip()
try:
self.vars['phone'].append(ret)
except AttributeError:
self.vars['phone'] = []
self.vars['phone'].append(ret) | python | def _parse_phone(self, val):
"""
The function for parsing the vcard phone numbers.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (IndexError, KeyError, ValueError, TypeError):
pass
ret['value'] = val[3].strip()
try:
self.vars['phone'].append(ret)
except AttributeError:
self.vars['phone'] = []
self.vars['phone'].append(ret) | [
"def",
"_parse_phone",
"(",
"self",
",",
"val",
")",
":",
"ret",
"=",
"{",
"'type'",
":",
"None",
",",
"'value'",
":",
"None",
"}",
"try",
":",
"ret",
"[",
"'type'",
"]",
"=",
"val",
"[",
"1",
"]",
"[",
"'type'",
"]",
"except",
"(",
"IndexError",
",",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"ret",
"[",
"'value'",
"]",
"=",
"val",
"[",
"3",
"]",
".",
"strip",
"(",
")",
"try",
":",
"self",
".",
"vars",
"[",
"'phone'",
"]",
".",
"append",
"(",
"ret",
")",
"except",
"AttributeError",
":",
"self",
".",
"vars",
"[",
"'phone'",
"]",
"=",
"[",
"]",
"self",
".",
"vars",
"[",
"'phone'",
"]",
".",
"append",
"(",
"ret",
")"
] | The function for parsing the vcard phone numbers.
Args:
val (:obj:`list`): The value to parse. | [
"The",
"function",
"for",
"parsing",
"the",
"vcard",
"phone",
"numbers",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/rdap.py#L150-L180 | train | 238,636 |
secynic/ipwhois | ipwhois/rdap.py | _RDAPContact._parse_email | def _parse_email(self, val):
"""
The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (KeyError, ValueError, TypeError):
pass
ret['value'] = val[3].strip()
try:
self.vars['email'].append(ret)
except AttributeError:
self.vars['email'] = []
self.vars['email'].append(ret) | python | def _parse_email(self, val):
"""
The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse.
"""
ret = {
'type': None,
'value': None
}
try:
ret['type'] = val[1]['type']
except (KeyError, ValueError, TypeError):
pass
ret['value'] = val[3].strip()
try:
self.vars['email'].append(ret)
except AttributeError:
self.vars['email'] = []
self.vars['email'].append(ret) | [
"def",
"_parse_email",
"(",
"self",
",",
"val",
")",
":",
"ret",
"=",
"{",
"'type'",
":",
"None",
",",
"'value'",
":",
"None",
"}",
"try",
":",
"ret",
"[",
"'type'",
"]",
"=",
"val",
"[",
"1",
"]",
"[",
"'type'",
"]",
"except",
"(",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"ret",
"[",
"'value'",
"]",
"=",
"val",
"[",
"3",
"]",
".",
"strip",
"(",
")",
"try",
":",
"self",
".",
"vars",
"[",
"'email'",
"]",
".",
"append",
"(",
"ret",
")",
"except",
"AttributeError",
":",
"self",
".",
"vars",
"[",
"'email'",
"]",
"=",
"[",
"]",
"self",
".",
"vars",
"[",
"'email'",
"]",
".",
"append",
"(",
"ret",
")"
] | The function for parsing the vcard email addresses.
Args:
val (:obj:`list`): The value to parse. | [
"The",
"function",
"for",
"parsing",
"the",
"vcard",
"email",
"addresses",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/rdap.py#L182-L212 | train | 238,637 |
secynic/ipwhois | ipwhois/rdap.py | _RDAPContact.parse | def parse(self):
"""
The function for parsing the vcard to the vars dictionary.
"""
keys = {
'fn': self._parse_name,
'kind': self._parse_kind,
'adr': self._parse_address,
'tel': self._parse_phone,
'email': self._parse_email,
'role': self._parse_role,
'title': self._parse_title
}
for val in self.vcard:
try:
parser = keys.get(val[0])
parser(val)
except (KeyError, ValueError, TypeError):
pass | python | def parse(self):
"""
The function for parsing the vcard to the vars dictionary.
"""
keys = {
'fn': self._parse_name,
'kind': self._parse_kind,
'adr': self._parse_address,
'tel': self._parse_phone,
'email': self._parse_email,
'role': self._parse_role,
'title': self._parse_title
}
for val in self.vcard:
try:
parser = keys.get(val[0])
parser(val)
except (KeyError, ValueError, TypeError):
pass | [
"def",
"parse",
"(",
"self",
")",
":",
"keys",
"=",
"{",
"'fn'",
":",
"self",
".",
"_parse_name",
",",
"'kind'",
":",
"self",
".",
"_parse_kind",
",",
"'adr'",
":",
"self",
".",
"_parse_address",
",",
"'tel'",
":",
"self",
".",
"_parse_phone",
",",
"'email'",
":",
"self",
".",
"_parse_email",
",",
"'role'",
":",
"self",
".",
"_parse_role",
",",
"'title'",
":",
"self",
".",
"_parse_title",
"}",
"for",
"val",
"in",
"self",
".",
"vcard",
":",
"try",
":",
"parser",
"=",
"keys",
".",
"get",
"(",
"val",
"[",
"0",
"]",
")",
"parser",
"(",
"val",
")",
"except",
"(",
"KeyError",
",",
"ValueError",
",",
"TypeError",
")",
":",
"pass"
] | The function for parsing the vcard to the vars dictionary. | [
"The",
"function",
"for",
"parsing",
"the",
"vcard",
"to",
"the",
"vars",
"dictionary",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/rdap.py#L234-L258 | train | 238,638 |
secynic/ipwhois | ipwhois/utils.py | ipv4_lstrip_zeros | def ipv4_lstrip_zeros(address):
"""
The function to strip leading zeros in each octet of an IPv4 address.
Args:
address (:obj:`str`): An IPv4 address.
Returns:
str: The modified IPv4 address.
"""
# Split the octets.
obj = address.strip().split('.')
for x, y in enumerate(obj):
# Strip leading zeros. Split / here in case CIDR is attached.
obj[x] = y.split('/')[0].lstrip('0')
if obj[x] in ['', None]:
obj[x] = '0'
return '.'.join(obj) | python | def ipv4_lstrip_zeros(address):
"""
The function to strip leading zeros in each octet of an IPv4 address.
Args:
address (:obj:`str`): An IPv4 address.
Returns:
str: The modified IPv4 address.
"""
# Split the octets.
obj = address.strip().split('.')
for x, y in enumerate(obj):
# Strip leading zeros. Split / here in case CIDR is attached.
obj[x] = y.split('/')[0].lstrip('0')
if obj[x] in ['', None]:
obj[x] = '0'
return '.'.join(obj) | [
"def",
"ipv4_lstrip_zeros",
"(",
"address",
")",
":",
"# Split the octets.",
"obj",
"=",
"address",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'.'",
")",
"for",
"x",
",",
"y",
"in",
"enumerate",
"(",
"obj",
")",
":",
"# Strip leading zeros. Split / here in case CIDR is attached.",
"obj",
"[",
"x",
"]",
"=",
"y",
".",
"split",
"(",
"'/'",
")",
"[",
"0",
"]",
".",
"lstrip",
"(",
"'0'",
")",
"if",
"obj",
"[",
"x",
"]",
"in",
"[",
"''",
",",
"None",
"]",
":",
"obj",
"[",
"x",
"]",
"=",
"'0'",
"return",
"'.'",
".",
"join",
"(",
"obj",
")"
] | The function to strip leading zeros in each octet of an IPv4 address.
Args:
address (:obj:`str`): An IPv4 address.
Returns:
str: The modified IPv4 address. | [
"The",
"function",
"to",
"strip",
"leading",
"zeros",
"in",
"each",
"octet",
"of",
"an",
"IPv4",
"address",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/utils.py#L117-L138 | train | 238,639 |
secynic/ipwhois | ipwhois/utils.py | get_countries | def get_countries(is_legacy_xml=False):
"""
The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country codes as the keys to the country names as
the values.
"""
# Initialize the countries dictionary.
countries = {}
# Set the data directory based on if the script is a frozen executable.
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
data_dir = path.dirname(sys.executable) # pragma: no cover
else:
data_dir = path.dirname(__file__)
if is_legacy_xml:
log.debug('Opening country code legacy XML: {0}'.format(
str(data_dir) + '/data/iso_3166-1_list_en.xml'))
# Create the country codes file object.
f = io.open(str(data_dir) + '/data/iso_3166-1_list_en.xml', 'r',
encoding='ISO-8859-1')
# Read the file.
data = f.read()
# Check if there is data.
if not data: # pragma: no cover
return {}
# Parse the data to get the DOM.
dom = parseString(data)
# Retrieve the country entries.
entries = dom.getElementsByTagName('ISO_3166-1_Entry')
# Iterate through the entries and add to the countries dictionary.
for entry in entries:
# Retrieve the country code and name from the DOM.
code = entry.getElementsByTagName(
'ISO_3166-1_Alpha-2_Code_element')[0].firstChild.data
name = entry.getElementsByTagName(
'ISO_3166-1_Country_name')[0].firstChild.data
# Add to the countries dictionary.
countries[code] = name.title()
else:
log.debug('Opening country code CSV: {0}'.format(
str(data_dir) + '/data/iso_3166-1_list_en.xml'))
# Create the country codes file object.
f = io.open(str(data_dir) + '/data/iso_3166-1.csv', 'r',
encoding='utf-8')
# Create csv reader object.
csv_reader = csv.reader(f, delimiter=',', quotechar='"')
# Iterate through the rows and add to the countries dictionary.
for row in csv_reader:
# Retrieve the country code and name columns.
code = row[0]
name = row[1]
# Add to the countries dictionary.
countries[code] = name
return countries | python | def get_countries(is_legacy_xml=False):
"""
The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country codes as the keys to the country names as
the values.
"""
# Initialize the countries dictionary.
countries = {}
# Set the data directory based on if the script is a frozen executable.
if sys.platform == 'win32' and getattr(sys, 'frozen', False):
data_dir = path.dirname(sys.executable) # pragma: no cover
else:
data_dir = path.dirname(__file__)
if is_legacy_xml:
log.debug('Opening country code legacy XML: {0}'.format(
str(data_dir) + '/data/iso_3166-1_list_en.xml'))
# Create the country codes file object.
f = io.open(str(data_dir) + '/data/iso_3166-1_list_en.xml', 'r',
encoding='ISO-8859-1')
# Read the file.
data = f.read()
# Check if there is data.
if not data: # pragma: no cover
return {}
# Parse the data to get the DOM.
dom = parseString(data)
# Retrieve the country entries.
entries = dom.getElementsByTagName('ISO_3166-1_Entry')
# Iterate through the entries and add to the countries dictionary.
for entry in entries:
# Retrieve the country code and name from the DOM.
code = entry.getElementsByTagName(
'ISO_3166-1_Alpha-2_Code_element')[0].firstChild.data
name = entry.getElementsByTagName(
'ISO_3166-1_Country_name')[0].firstChild.data
# Add to the countries dictionary.
countries[code] = name.title()
else:
log.debug('Opening country code CSV: {0}'.format(
str(data_dir) + '/data/iso_3166-1_list_en.xml'))
# Create the country codes file object.
f = io.open(str(data_dir) + '/data/iso_3166-1.csv', 'r',
encoding='utf-8')
# Create csv reader object.
csv_reader = csv.reader(f, delimiter=',', quotechar='"')
# Iterate through the rows and add to the countries dictionary.
for row in csv_reader:
# Retrieve the country code and name columns.
code = row[0]
name = row[1]
# Add to the countries dictionary.
countries[code] = name
return countries | [
"def",
"get_countries",
"(",
"is_legacy_xml",
"=",
"False",
")",
":",
"# Initialize the countries dictionary.",
"countries",
"=",
"{",
"}",
"# Set the data directory based on if the script is a frozen executable.",
"if",
"sys",
".",
"platform",
"==",
"'win32'",
"and",
"getattr",
"(",
"sys",
",",
"'frozen'",
",",
"False",
")",
":",
"data_dir",
"=",
"path",
".",
"dirname",
"(",
"sys",
".",
"executable",
")",
"# pragma: no cover",
"else",
":",
"data_dir",
"=",
"path",
".",
"dirname",
"(",
"__file__",
")",
"if",
"is_legacy_xml",
":",
"log",
".",
"debug",
"(",
"'Opening country code legacy XML: {0}'",
".",
"format",
"(",
"str",
"(",
"data_dir",
")",
"+",
"'/data/iso_3166-1_list_en.xml'",
")",
")",
"# Create the country codes file object.",
"f",
"=",
"io",
".",
"open",
"(",
"str",
"(",
"data_dir",
")",
"+",
"'/data/iso_3166-1_list_en.xml'",
",",
"'r'",
",",
"encoding",
"=",
"'ISO-8859-1'",
")",
"# Read the file.",
"data",
"=",
"f",
".",
"read",
"(",
")",
"# Check if there is data.",
"if",
"not",
"data",
":",
"# pragma: no cover",
"return",
"{",
"}",
"# Parse the data to get the DOM.",
"dom",
"=",
"parseString",
"(",
"data",
")",
"# Retrieve the country entries.",
"entries",
"=",
"dom",
".",
"getElementsByTagName",
"(",
"'ISO_3166-1_Entry'",
")",
"# Iterate through the entries and add to the countries dictionary.",
"for",
"entry",
"in",
"entries",
":",
"# Retrieve the country code and name from the DOM.",
"code",
"=",
"entry",
".",
"getElementsByTagName",
"(",
"'ISO_3166-1_Alpha-2_Code_element'",
")",
"[",
"0",
"]",
".",
"firstChild",
".",
"data",
"name",
"=",
"entry",
".",
"getElementsByTagName",
"(",
"'ISO_3166-1_Country_name'",
")",
"[",
"0",
"]",
".",
"firstChild",
".",
"data",
"# Add to the countries dictionary.",
"countries",
"[",
"code",
"]",
"=",
"name",
".",
"title",
"(",
")",
"else",
":",
"log",
".",
"debug",
"(",
"'Opening country code CSV: {0}'",
".",
"format",
"(",
"str",
"(",
"data_dir",
")",
"+",
"'/data/iso_3166-1_list_en.xml'",
")",
")",
"# Create the country codes file object.",
"f",
"=",
"io",
".",
"open",
"(",
"str",
"(",
"data_dir",
")",
"+",
"'/data/iso_3166-1.csv'",
",",
"'r'",
",",
"encoding",
"=",
"'utf-8'",
")",
"# Create csv reader object.",
"csv_reader",
"=",
"csv",
".",
"reader",
"(",
"f",
",",
"delimiter",
"=",
"','",
",",
"quotechar",
"=",
"'\"'",
")",
"# Iterate through the rows and add to the countries dictionary.",
"for",
"row",
"in",
"csv_reader",
":",
"# Retrieve the country code and name columns.",
"code",
"=",
"row",
"[",
"0",
"]",
"name",
"=",
"row",
"[",
"1",
"]",
"# Add to the countries dictionary.",
"countries",
"[",
"code",
"]",
"=",
"name",
"return",
"countries"
] | The function to generate a dictionary containing ISO_3166-1 country codes
to names.
Args:
is_legacy_xml (:obj:`bool`): Whether to use the older country code
list (iso_3166-1_list_en.xml).
Returns:
dict: A mapping of country codes as the keys to the country names as
the values. | [
"The",
"function",
"to",
"generate",
"a",
"dictionary",
"containing",
"ISO_3166",
"-",
"1",
"country",
"codes",
"to",
"names",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/utils.py#L178-L261 | train | 238,640 |
secynic/ipwhois | ipwhois/utils.py | unique_everseen | def unique_everseen(iterable, key=None):
"""
The generator to list unique elements, preserving the order. Remember all
elements ever seen. This was taken from the itertools recipes.
Args:
iterable (:obj:`iter`): An iterable to process.
key (:obj:`callable`): Optional function to run when checking
elements (e.g., str.lower)
Yields:
The next unique element found.
"""
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element | python | def unique_everseen(iterable, key=None):
"""
The generator to list unique elements, preserving the order. Remember all
elements ever seen. This was taken from the itertools recipes.
Args:
iterable (:obj:`iter`): An iterable to process.
key (:obj:`callable`): Optional function to run when checking
elements (e.g., str.lower)
Yields:
The next unique element found.
"""
seen = set()
seen_add = seen.add
if key is None:
for element in filterfalse(seen.__contains__, iterable):
seen_add(element)
yield element
else:
for element in iterable:
k = key(element)
if k not in seen:
seen_add(k)
yield element | [
"def",
"unique_everseen",
"(",
"iterable",
",",
"key",
"=",
"None",
")",
":",
"seen",
"=",
"set",
"(",
")",
"seen_add",
"=",
"seen",
".",
"add",
"if",
"key",
"is",
"None",
":",
"for",
"element",
"in",
"filterfalse",
"(",
"seen",
".",
"__contains__",
",",
"iterable",
")",
":",
"seen_add",
"(",
"element",
")",
"yield",
"element",
"else",
":",
"for",
"element",
"in",
"iterable",
":",
"k",
"=",
"key",
"(",
"element",
")",
"if",
"k",
"not",
"in",
"seen",
":",
"seen_add",
"(",
"k",
")",
"yield",
"element"
] | The generator to list unique elements, preserving the order. Remember all
elements ever seen. This was taken from the itertools recipes.
Args:
iterable (:obj:`iter`): An iterable to process.
key (:obj:`callable`): Optional function to run when checking
elements (e.g., str.lower)
Yields:
The next unique element found. | [
"The",
"generator",
"to",
"list",
"unique",
"elements",
"preserving",
"the",
"order",
".",
"Remember",
"all",
"elements",
"ever",
"seen",
".",
"This",
"was",
"taken",
"from",
"the",
"itertools",
"recipes",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/utils.py#L424-L457 | train | 238,641 |
secynic/ipwhois | ipwhois/whois.py | Whois.get_nets_arin | def get_nets_arin(self, response):
"""
The function for parsing network blocks from ARIN whois data.
Args:
response (:obj:`str`): The response from the ARIN whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Find the first NetRange value.
pattern = re.compile(
r'^NetRange:[^\S\n]+(.+)$',
re.MULTILINE
)
temp = pattern.search(response)
net_range = None
net_range_start = None
if temp is not None:
net_range = temp.group(1).strip()
net_range_start = temp.start()
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^CIDR:[^\S\n]+(.+?,[^\S\n].+|.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
if len(nets) > 0:
temp = pattern.search(response, match.start())
net_range = None
net_range_start = None
if temp is not None:
net_range = temp.group(1).strip()
net_range_start = temp.start()
if net_range is not None:
if net_range_start < match.start() or len(nets) > 0:
try:
net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
net['cidr'] = ', '.join(
[ip_network(c.strip()).__str__()
for c in match.group(1).split(', ')]
)
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError:
pass
return nets | python | def get_nets_arin(self, response):
"""
The function for parsing network blocks from ARIN whois data.
Args:
response (:obj:`str`): The response from the ARIN whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Find the first NetRange value.
pattern = re.compile(
r'^NetRange:[^\S\n]+(.+)$',
re.MULTILINE
)
temp = pattern.search(response)
net_range = None
net_range_start = None
if temp is not None:
net_range = temp.group(1).strip()
net_range_start = temp.start()
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^CIDR:[^\S\n]+(.+?,[^\S\n].+|.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
if len(nets) > 0:
temp = pattern.search(response, match.start())
net_range = None
net_range_start = None
if temp is not None:
net_range = temp.group(1).strip()
net_range_start = temp.start()
if net_range is not None:
if net_range_start < match.start() or len(nets) > 0:
try:
net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
net['cidr'] = ', '.join(
[ip_network(c.strip()).__str__()
for c in match.group(1).split(', ')]
)
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError:
pass
return nets | [
"def",
"get_nets_arin",
"(",
"self",
",",
"response",
")",
":",
"nets",
"=",
"[",
"]",
"# Find the first NetRange value.",
"pattern",
"=",
"re",
".",
"compile",
"(",
"r'^NetRange:[^\\S\\n]+(.+)$'",
",",
"re",
".",
"MULTILINE",
")",
"temp",
"=",
"pattern",
".",
"search",
"(",
"response",
")",
"net_range",
"=",
"None",
"net_range_start",
"=",
"None",
"if",
"temp",
"is",
"not",
"None",
":",
"net_range",
"=",
"temp",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"net_range_start",
"=",
"temp",
".",
"start",
"(",
")",
"# Iterate through all of the networks found, storing the CIDR value",
"# and the start and end positions.",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'^CIDR:[^\\S\\n]+(.+?,[^\\S\\n].+|.+)$'",
",",
"response",
",",
"re",
".",
"MULTILINE",
")",
":",
"try",
":",
"net",
"=",
"copy",
".",
"deepcopy",
"(",
"BASE_NET",
")",
"if",
"len",
"(",
"nets",
")",
">",
"0",
":",
"temp",
"=",
"pattern",
".",
"search",
"(",
"response",
",",
"match",
".",
"start",
"(",
")",
")",
"net_range",
"=",
"None",
"net_range_start",
"=",
"None",
"if",
"temp",
"is",
"not",
"None",
":",
"net_range",
"=",
"temp",
".",
"group",
"(",
"1",
")",
".",
"strip",
"(",
")",
"net_range_start",
"=",
"temp",
".",
"start",
"(",
")",
"if",
"net_range",
"is",
"not",
"None",
":",
"if",
"net_range_start",
"<",
"match",
".",
"start",
"(",
")",
"or",
"len",
"(",
"nets",
")",
">",
"0",
":",
"try",
":",
"net",
"[",
"'range'",
"]",
"=",
"'{0} - {1}'",
".",
"format",
"(",
"ip_network",
"(",
"net_range",
")",
"[",
"0",
"]",
".",
"__str__",
"(",
")",
",",
"ip_network",
"(",
"net_range",
")",
"[",
"-",
"1",
"]",
".",
"__str__",
"(",
")",
")",
"if",
"'/'",
"in",
"net_range",
"else",
"net_range",
"except",
"ValueError",
":",
"# pragma: no cover",
"net",
"[",
"'range'",
"]",
"=",
"net_range",
"net",
"[",
"'cidr'",
"]",
"=",
"', '",
".",
"join",
"(",
"[",
"ip_network",
"(",
"c",
".",
"strip",
"(",
")",
")",
".",
"__str__",
"(",
")",
"for",
"c",
"in",
"match",
".",
"group",
"(",
"1",
")",
".",
"split",
"(",
"', '",
")",
"]",
")",
"net",
"[",
"'start'",
"]",
"=",
"match",
".",
"start",
"(",
")",
"net",
"[",
"'end'",
"]",
"=",
"match",
".",
"end",
"(",
")",
"nets",
".",
"append",
"(",
"net",
")",
"except",
"ValueError",
":",
"pass",
"return",
"nets"
] | The function for parsing network blocks from ARIN whois data.
Args:
response (:obj:`str`): The response from the ARIN whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}] | [
"The",
"function",
"for",
"parsing",
"network",
"blocks",
"from",
"ARIN",
"whois",
"data",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/whois.py#L337-L416 | train | 238,642 |
secynic/ipwhois | ipwhois/whois.py | Whois.get_nets_lacnic | def get_nets_lacnic(self, response):
"""
The function for parsing network blocks from LACNIC whois data.
Args:
response (:obj:`str`): The response from the LACNIC whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^(inetnum|inet6num|route):[^\S\n]+(.+?,[^\S\n].+|.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net_range = match.group(2).strip()
try:
net['range'] = net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
temp = []
for addr in net_range.split(', '):
count = addr.count('.')
if count is not 0 and count < 4:
addr_split = addr.strip().split('/')
for i in range(count + 1, 4):
addr_split[0] += '.0'
addr = '/'.join(addr_split)
temp.append(ip_network(addr.strip()).__str__())
net['cidr'] = ', '.join(temp)
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError:
pass
return nets | python | def get_nets_lacnic(self, response):
"""
The function for parsing network blocks from LACNIC whois data.
Args:
response (:obj:`str`): The response from the LACNIC whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^(inetnum|inet6num|route):[^\S\n]+(.+?,[^\S\n].+|.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net_range = match.group(2).strip()
try:
net['range'] = net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
temp = []
for addr in net_range.split(', '):
count = addr.count('.')
if count is not 0 and count < 4:
addr_split = addr.strip().split('/')
for i in range(count + 1, 4):
addr_split[0] += '.0'
addr = '/'.join(addr_split)
temp.append(ip_network(addr.strip()).__str__())
net['cidr'] = ', '.join(temp)
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except ValueError:
pass
return nets | [
"def",
"get_nets_lacnic",
"(",
"self",
",",
"response",
")",
":",
"nets",
"=",
"[",
"]",
"# Iterate through all of the networks found, storing the CIDR value",
"# and the start and end positions.",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'^(inetnum|inet6num|route):[^\\S\\n]+(.+?,[^\\S\\n].+|.+)$'",
",",
"response",
",",
"re",
".",
"MULTILINE",
")",
":",
"try",
":",
"net",
"=",
"copy",
".",
"deepcopy",
"(",
"BASE_NET",
")",
"net_range",
"=",
"match",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
"try",
":",
"net",
"[",
"'range'",
"]",
"=",
"net",
"[",
"'range'",
"]",
"=",
"'{0} - {1}'",
".",
"format",
"(",
"ip_network",
"(",
"net_range",
")",
"[",
"0",
"]",
".",
"__str__",
"(",
")",
",",
"ip_network",
"(",
"net_range",
")",
"[",
"-",
"1",
"]",
".",
"__str__",
"(",
")",
")",
"if",
"'/'",
"in",
"net_range",
"else",
"net_range",
"except",
"ValueError",
":",
"# pragma: no cover",
"net",
"[",
"'range'",
"]",
"=",
"net_range",
"temp",
"=",
"[",
"]",
"for",
"addr",
"in",
"net_range",
".",
"split",
"(",
"', '",
")",
":",
"count",
"=",
"addr",
".",
"count",
"(",
"'.'",
")",
"if",
"count",
"is",
"not",
"0",
"and",
"count",
"<",
"4",
":",
"addr_split",
"=",
"addr",
".",
"strip",
"(",
")",
".",
"split",
"(",
"'/'",
")",
"for",
"i",
"in",
"range",
"(",
"count",
"+",
"1",
",",
"4",
")",
":",
"addr_split",
"[",
"0",
"]",
"+=",
"'.0'",
"addr",
"=",
"'/'",
".",
"join",
"(",
"addr_split",
")",
"temp",
".",
"append",
"(",
"ip_network",
"(",
"addr",
".",
"strip",
"(",
")",
")",
".",
"__str__",
"(",
")",
")",
"net",
"[",
"'cidr'",
"]",
"=",
"', '",
".",
"join",
"(",
"temp",
")",
"net",
"[",
"'start'",
"]",
"=",
"match",
".",
"start",
"(",
")",
"net",
"[",
"'end'",
"]",
"=",
"match",
".",
"end",
"(",
")",
"nets",
".",
"append",
"(",
"net",
")",
"except",
"ValueError",
":",
"pass",
"return",
"nets"
] | The function for parsing network blocks from LACNIC whois data.
Args:
response (:obj:`str`): The response from the LACNIC whois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}] | [
"The",
"function",
"for",
"parsing",
"network",
"blocks",
"from",
"LACNIC",
"whois",
"data",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/whois.py#L428-L496 | train | 238,643 |
secynic/ipwhois | ipwhois/whois.py | Whois.get_nets_other | def get_nets_other(self, response):
"""
The function for parsing network blocks from generic whois data.
Args:
response (:obj:`str`): The response from the whois/rwhois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^(inetnum|inet6num|route):[^\S\n]+((.+?)[^\S\n]-[^\S\n](.+)|'
'.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net_range = match.group(2).strip()
try:
net['range'] = net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
if match.group(3) and match.group(4):
addrs = []
addrs.extend(summarize_address_range(
ip_address(match.group(3).strip()),
ip_address(match.group(4).strip())))
cidr = ', '.join(
[i.__str__() for i in collapse_addresses(addrs)]
)
else:
cidr = ip_network(net_range).__str__()
net['cidr'] = cidr
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except (ValueError, TypeError):
pass
return nets | python | def get_nets_other(self, response):
"""
The function for parsing network blocks from generic whois data.
Args:
response (:obj:`str`): The response from the whois/rwhois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}]
"""
nets = []
# Iterate through all of the networks found, storing the CIDR value
# and the start and end positions.
for match in re.finditer(
r'^(inetnum|inet6num|route):[^\S\n]+((.+?)[^\S\n]-[^\S\n](.+)|'
'.+)$',
response,
re.MULTILINE
):
try:
net = copy.deepcopy(BASE_NET)
net_range = match.group(2).strip()
try:
net['range'] = net['range'] = '{0} - {1}'.format(
ip_network(net_range)[0].__str__(),
ip_network(net_range)[-1].__str__()
) if '/' in net_range else net_range
except ValueError: # pragma: no cover
net['range'] = net_range
if match.group(3) and match.group(4):
addrs = []
addrs.extend(summarize_address_range(
ip_address(match.group(3).strip()),
ip_address(match.group(4).strip())))
cidr = ', '.join(
[i.__str__() for i in collapse_addresses(addrs)]
)
else:
cidr = ip_network(net_range).__str__()
net['cidr'] = cidr
net['start'] = match.start()
net['end'] = match.end()
nets.append(net)
except (ValueError, TypeError):
pass
return nets | [
"def",
"get_nets_other",
"(",
"self",
",",
"response",
")",
":",
"nets",
"=",
"[",
"]",
"# Iterate through all of the networks found, storing the CIDR value",
"# and the start and end positions.",
"for",
"match",
"in",
"re",
".",
"finditer",
"(",
"r'^(inetnum|inet6num|route):[^\\S\\n]+((.+?)[^\\S\\n]-[^\\S\\n](.+)|'",
"'.+)$'",
",",
"response",
",",
"re",
".",
"MULTILINE",
")",
":",
"try",
":",
"net",
"=",
"copy",
".",
"deepcopy",
"(",
"BASE_NET",
")",
"net_range",
"=",
"match",
".",
"group",
"(",
"2",
")",
".",
"strip",
"(",
")",
"try",
":",
"net",
"[",
"'range'",
"]",
"=",
"net",
"[",
"'range'",
"]",
"=",
"'{0} - {1}'",
".",
"format",
"(",
"ip_network",
"(",
"net_range",
")",
"[",
"0",
"]",
".",
"__str__",
"(",
")",
",",
"ip_network",
"(",
"net_range",
")",
"[",
"-",
"1",
"]",
".",
"__str__",
"(",
")",
")",
"if",
"'/'",
"in",
"net_range",
"else",
"net_range",
"except",
"ValueError",
":",
"# pragma: no cover",
"net",
"[",
"'range'",
"]",
"=",
"net_range",
"if",
"match",
".",
"group",
"(",
"3",
")",
"and",
"match",
".",
"group",
"(",
"4",
")",
":",
"addrs",
"=",
"[",
"]",
"addrs",
".",
"extend",
"(",
"summarize_address_range",
"(",
"ip_address",
"(",
"match",
".",
"group",
"(",
"3",
")",
".",
"strip",
"(",
")",
")",
",",
"ip_address",
"(",
"match",
".",
"group",
"(",
"4",
")",
".",
"strip",
"(",
")",
")",
")",
")",
"cidr",
"=",
"', '",
".",
"join",
"(",
"[",
"i",
".",
"__str__",
"(",
")",
"for",
"i",
"in",
"collapse_addresses",
"(",
"addrs",
")",
"]",
")",
"else",
":",
"cidr",
"=",
"ip_network",
"(",
"net_range",
")",
".",
"__str__",
"(",
")",
"net",
"[",
"'cidr'",
"]",
"=",
"cidr",
"net",
"[",
"'start'",
"]",
"=",
"match",
".",
"start",
"(",
")",
"net",
"[",
"'end'",
"]",
"=",
"match",
".",
"end",
"(",
")",
"nets",
".",
"append",
"(",
"net",
")",
"except",
"(",
"ValueError",
",",
"TypeError",
")",
":",
"pass",
"return",
"nets"
] | The function for parsing network blocks from generic whois data.
Args:
response (:obj:`str`): The response from the whois/rwhois server.
Returns:
list of dict: Mapping of networks with start and end positions.
::
[{
'cidr' (str) - The network routing block
'start' (int) - The starting point of the network
'end' (int) - The endpoint point of the network
}] | [
"The",
"function",
"for",
"parsing",
"network",
"blocks",
"from",
"generic",
"whois",
"data",
"."
] | b5d634d36b0b942d538d38d77b3bdcd815f155a0 | https://github.com/secynic/ipwhois/blob/b5d634d36b0b942d538d38d77b3bdcd815f155a0/ipwhois/whois.py#L508-L578 | train | 238,644 |
klen/marshmallow-peewee | marshmallow_peewee/convert.py | ModelConverter.convert_default | def convert_default(self, field, **params):
"""Return raw field."""
for klass, ma_field in self.TYPE_MAPPING:
if isinstance(field, klass):
return ma_field(**params)
return fields.Raw(**params) | python | def convert_default(self, field, **params):
"""Return raw field."""
for klass, ma_field in self.TYPE_MAPPING:
if isinstance(field, klass):
return ma_field(**params)
return fields.Raw(**params) | [
"def",
"convert_default",
"(",
"self",
",",
"field",
",",
"*",
"*",
"params",
")",
":",
"for",
"klass",
",",
"ma_field",
"in",
"self",
".",
"TYPE_MAPPING",
":",
"if",
"isinstance",
"(",
"field",
",",
"klass",
")",
":",
"return",
"ma_field",
"(",
"*",
"*",
"params",
")",
"return",
"fields",
".",
"Raw",
"(",
"*",
"*",
"params",
")"
] | Return raw field. | [
"Return",
"raw",
"field",
"."
] | a5985daa4072605882a9c7c41d74881631943953 | https://github.com/klen/marshmallow-peewee/blob/a5985daa4072605882a9c7c41d74881631943953/marshmallow_peewee/convert.py#L78-L83 | train | 238,645 |
klen/marshmallow-peewee | marshmallow_peewee/schema.py | ModelSchema.make_instance | def make_instance(self, data):
"""Build object from data."""
if not self.opts.model:
return data
if self.instance is not None:
for key, value in data.items():
setattr(self.instance, key, value)
return self.instance
return self.opts.model(**data) | python | def make_instance(self, data):
"""Build object from data."""
if not self.opts.model:
return data
if self.instance is not None:
for key, value in data.items():
setattr(self.instance, key, value)
return self.instance
return self.opts.model(**data) | [
"def",
"make_instance",
"(",
"self",
",",
"data",
")",
":",
"if",
"not",
"self",
".",
"opts",
".",
"model",
":",
"return",
"data",
"if",
"self",
".",
"instance",
"is",
"not",
"None",
":",
"for",
"key",
",",
"value",
"in",
"data",
".",
"items",
"(",
")",
":",
"setattr",
"(",
"self",
".",
"instance",
",",
"key",
",",
"value",
")",
"return",
"self",
".",
"instance",
"return",
"self",
".",
"opts",
".",
"model",
"(",
"*",
"*",
"data",
")"
] | Build object from data. | [
"Build",
"object",
"from",
"data",
"."
] | a5985daa4072605882a9c7c41d74881631943953 | https://github.com/klen/marshmallow-peewee/blob/a5985daa4072605882a9c7c41d74881631943953/marshmallow_peewee/schema.py#L68-L78 | train | 238,646 |
tyarkoni/pliers | pliers/extractors/text.py | ComplexTextExtractor._extract | def _extract(self, stim):
''' Returns all words. '''
props = [(e.text, e.onset, e.duration) for e in stim.elements]
vals, onsets, durations = map(list, zip(*props))
return ExtractorResult(vals, stim, self, ['word'], onsets, durations) | python | def _extract(self, stim):
''' Returns all words. '''
props = [(e.text, e.onset, e.duration) for e in stim.elements]
vals, onsets, durations = map(list, zip(*props))
return ExtractorResult(vals, stim, self, ['word'], onsets, durations) | [
"def",
"_extract",
"(",
"self",
",",
"stim",
")",
":",
"props",
"=",
"[",
"(",
"e",
".",
"text",
",",
"e",
".",
"onset",
",",
"e",
".",
"duration",
")",
"for",
"e",
"in",
"stim",
".",
"elements",
"]",
"vals",
",",
"onsets",
",",
"durations",
"=",
"map",
"(",
"list",
",",
"zip",
"(",
"*",
"props",
")",
")",
"return",
"ExtractorResult",
"(",
"vals",
",",
"stim",
",",
"self",
",",
"[",
"'word'",
"]",
",",
"onsets",
",",
"durations",
")"
] | Returns all words. | [
"Returns",
"all",
"words",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/extractors/text.py#L44-L48 | train | 238,647 |
tyarkoni/pliers | pliers/stimuli/base.py | Stim.get_filename | def get_filename(self):
''' Return the source filename of the current Stim. '''
if self.filename is None or not os.path.exists(self.filename):
tf = tempfile.mktemp() + self._default_file_extension
self.save(tf)
yield tf
os.remove(tf)
else:
yield self.filename | python | def get_filename(self):
''' Return the source filename of the current Stim. '''
if self.filename is None or not os.path.exists(self.filename):
tf = tempfile.mktemp() + self._default_file_extension
self.save(tf)
yield tf
os.remove(tf)
else:
yield self.filename | [
"def",
"get_filename",
"(",
"self",
")",
":",
"if",
"self",
".",
"filename",
"is",
"None",
"or",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"self",
".",
"filename",
")",
":",
"tf",
"=",
"tempfile",
".",
"mktemp",
"(",
")",
"+",
"self",
".",
"_default_file_extension",
"self",
".",
"save",
"(",
"tf",
")",
"yield",
"tf",
"os",
".",
"remove",
"(",
"tf",
")",
"else",
":",
"yield",
"self",
".",
"filename"
] | Return the source filename of the current Stim. | [
"Return",
"the",
"source",
"filename",
"of",
"the",
"current",
"Stim",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/base.py#L55-L63 | train | 238,648 |
tyarkoni/pliers | pliers/stimuli/compound.py | CompoundStim.get_stim | def get_stim(self, type_, return_all=False):
''' Returns component elements of the specified type.
Args:
type_ (str or Stim class): the desired Stim subclass to return.
return_all (bool): when True, returns all elements that matched the
specified type as a list. When False (default), returns only
the first matching Stim.
Returns:
If return_all is True, a list of matching elements (or an empty
list if no elements match). If return_all is False, returns the
first matching Stim, or None if no elements match.
'''
if isinstance(type_, string_types):
type_ = _get_stim_class(type_)
matches = []
for s in self.elements:
if isinstance(s, type_):
if not return_all:
return s
matches.append(s)
if not matches:
return [] if return_all else None
return matches | python | def get_stim(self, type_, return_all=False):
''' Returns component elements of the specified type.
Args:
type_ (str or Stim class): the desired Stim subclass to return.
return_all (bool): when True, returns all elements that matched the
specified type as a list. When False (default), returns only
the first matching Stim.
Returns:
If return_all is True, a list of matching elements (or an empty
list if no elements match). If return_all is False, returns the
first matching Stim, or None if no elements match.
'''
if isinstance(type_, string_types):
type_ = _get_stim_class(type_)
matches = []
for s in self.elements:
if isinstance(s, type_):
if not return_all:
return s
matches.append(s)
if not matches:
return [] if return_all else None
return matches | [
"def",
"get_stim",
"(",
"self",
",",
"type_",
",",
"return_all",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"type_",
",",
"string_types",
")",
":",
"type_",
"=",
"_get_stim_class",
"(",
"type_",
")",
"matches",
"=",
"[",
"]",
"for",
"s",
"in",
"self",
".",
"elements",
":",
"if",
"isinstance",
"(",
"s",
",",
"type_",
")",
":",
"if",
"not",
"return_all",
":",
"return",
"s",
"matches",
".",
"append",
"(",
"s",
")",
"if",
"not",
"matches",
":",
"return",
"[",
"]",
"if",
"return_all",
"else",
"None",
"return",
"matches"
] | Returns component elements of the specified type.
Args:
type_ (str or Stim class): the desired Stim subclass to return.
return_all (bool): when True, returns all elements that matched the
specified type as a list. When False (default), returns only
the first matching Stim.
Returns:
If return_all is True, a list of matching elements (or an empty
list if no elements match). If return_all is False, returns the
first matching Stim, or None if no elements match. | [
"Returns",
"component",
"elements",
"of",
"the",
"specified",
"type",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/compound.py#L57-L81 | train | 238,649 |
tyarkoni/pliers | pliers/stimuli/compound.py | CompoundStim.has_types | def has_types(self, types, all_=True):
''' Check whether the current component list matches all Stim types
in the types argument.
Args:
types (Stim, list): a Stim class or iterable of Stim classes.
all_ (bool): if True, all input types must match; if False, at
least one input type must match.
Returns:
True if all passed types match at least one Stim in the component
list, otherwise False.
'''
func = all if all_ else any
return func([self.get_stim(t) for t in listify(types)]) | python | def has_types(self, types, all_=True):
''' Check whether the current component list matches all Stim types
in the types argument.
Args:
types (Stim, list): a Stim class or iterable of Stim classes.
all_ (bool): if True, all input types must match; if False, at
least one input type must match.
Returns:
True if all passed types match at least one Stim in the component
list, otherwise False.
'''
func = all if all_ else any
return func([self.get_stim(t) for t in listify(types)]) | [
"def",
"has_types",
"(",
"self",
",",
"types",
",",
"all_",
"=",
"True",
")",
":",
"func",
"=",
"all",
"if",
"all_",
"else",
"any",
"return",
"func",
"(",
"[",
"self",
".",
"get_stim",
"(",
"t",
")",
"for",
"t",
"in",
"listify",
"(",
"types",
")",
"]",
")"
] | Check whether the current component list matches all Stim types
in the types argument.
Args:
types (Stim, list): a Stim class or iterable of Stim classes.
all_ (bool): if True, all input types must match; if False, at
least one input type must match.
Returns:
True if all passed types match at least one Stim in the component
list, otherwise False. | [
"Check",
"whether",
"the",
"current",
"component",
"list",
"matches",
"all",
"Stim",
"types",
"in",
"the",
"types",
"argument",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/compound.py#L87-L101 | train | 238,650 |
tyarkoni/pliers | pliers/stimuli/audio.py | AudioStim.save | def save(self, path):
''' Save clip data to file.
Args:
path (str): Filename to save audio data to.
'''
self.clip.write_audiofile(path, fps=self.sampling_rate) | python | def save(self, path):
''' Save clip data to file.
Args:
path (str): Filename to save audio data to.
'''
self.clip.write_audiofile(path, fps=self.sampling_rate) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"self",
".",
"clip",
".",
"write_audiofile",
"(",
"path",
",",
"fps",
"=",
"self",
".",
"sampling_rate",
")"
] | Save clip data to file.
Args:
path (str): Filename to save audio data to. | [
"Save",
"clip",
"data",
"to",
"file",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/audio.py#L77-L83 | train | 238,651 |
tyarkoni/pliers | pliers/converters/base.py | get_converter | def get_converter(in_type, out_type, *args, **kwargs):
''' Scans the list of available Converters and returns an instantiation
of the first one whose input and output types match those passed in.
Args:
in_type (type): The type of input the converter must have.
out_type (type): The type of output the converter must have.
args, kwargs: Optional positional and keyword arguments to pass onto
matching Converter's initializer.
'''
convs = pliers.converters.__all__
# If config includes default converters for this combination, try them
# first
out_type = listify(out_type)[::-1]
default_convs = config.get_option('default_converters')
for ot in out_type:
conv_str = '%s->%s' % (in_type.__name__, ot.__name__)
if conv_str in default_convs:
convs = list(default_convs[conv_str]) + convs
for name in convs:
cls = getattr(pliers.converters, name)
if not issubclass(cls, Converter):
continue
available = cls.available if issubclass(
cls, EnvironmentKeyMixin) else True
if cls._input_type == in_type and cls._output_type in out_type \
and available:
conv = cls(*args, **kwargs)
return conv
return None | python | def get_converter(in_type, out_type, *args, **kwargs):
''' Scans the list of available Converters and returns an instantiation
of the first one whose input and output types match those passed in.
Args:
in_type (type): The type of input the converter must have.
out_type (type): The type of output the converter must have.
args, kwargs: Optional positional and keyword arguments to pass onto
matching Converter's initializer.
'''
convs = pliers.converters.__all__
# If config includes default converters for this combination, try them
# first
out_type = listify(out_type)[::-1]
default_convs = config.get_option('default_converters')
for ot in out_type:
conv_str = '%s->%s' % (in_type.__name__, ot.__name__)
if conv_str in default_convs:
convs = list(default_convs[conv_str]) + convs
for name in convs:
cls = getattr(pliers.converters, name)
if not issubclass(cls, Converter):
continue
available = cls.available if issubclass(
cls, EnvironmentKeyMixin) else True
if cls._input_type == in_type and cls._output_type in out_type \
and available:
conv = cls(*args, **kwargs)
return conv
return None | [
"def",
"get_converter",
"(",
"in_type",
",",
"out_type",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"convs",
"=",
"pliers",
".",
"converters",
".",
"__all__",
"# If config includes default converters for this combination, try them",
"# first",
"out_type",
"=",
"listify",
"(",
"out_type",
")",
"[",
":",
":",
"-",
"1",
"]",
"default_convs",
"=",
"config",
".",
"get_option",
"(",
"'default_converters'",
")",
"for",
"ot",
"in",
"out_type",
":",
"conv_str",
"=",
"'%s->%s'",
"%",
"(",
"in_type",
".",
"__name__",
",",
"ot",
".",
"__name__",
")",
"if",
"conv_str",
"in",
"default_convs",
":",
"convs",
"=",
"list",
"(",
"default_convs",
"[",
"conv_str",
"]",
")",
"+",
"convs",
"for",
"name",
"in",
"convs",
":",
"cls",
"=",
"getattr",
"(",
"pliers",
".",
"converters",
",",
"name",
")",
"if",
"not",
"issubclass",
"(",
"cls",
",",
"Converter",
")",
":",
"continue",
"available",
"=",
"cls",
".",
"available",
"if",
"issubclass",
"(",
"cls",
",",
"EnvironmentKeyMixin",
")",
"else",
"True",
"if",
"cls",
".",
"_input_type",
"==",
"in_type",
"and",
"cls",
".",
"_output_type",
"in",
"out_type",
"and",
"available",
":",
"conv",
"=",
"cls",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"return",
"conv",
"return",
"None"
] | Scans the list of available Converters and returns an instantiation
of the first one whose input and output types match those passed in.
Args:
in_type (type): The type of input the converter must have.
out_type (type): The type of output the converter must have.
args, kwargs: Optional positional and keyword arguments to pass onto
matching Converter's initializer. | [
"Scans",
"the",
"list",
"of",
"available",
"Converters",
"and",
"returns",
"an",
"instantiation",
"of",
"the",
"first",
"one",
"whose",
"input",
"and",
"output",
"types",
"match",
"those",
"passed",
"in",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/converters/base.py#L27-L61 | train | 238,652 |
tyarkoni/pliers | pliers/external/tensorflow/classify_image.py | create_graph | def create_graph():
"""Creates a graph from saved GraphDef file and returns a saver."""
# Creates graph from saved graph_def.pb.
with tf.gfile.FastGFile(os.path.join(
FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='') | python | def create_graph():
"""Creates a graph from saved GraphDef file and returns a saver."""
# Creates graph from saved graph_def.pb.
with tf.gfile.FastGFile(os.path.join(
FLAGS.model_dir, 'classify_image_graph_def.pb'), 'rb') as f:
graph_def = tf.GraphDef()
graph_def.ParseFromString(f.read())
_ = tf.import_graph_def(graph_def, name='') | [
"def",
"create_graph",
"(",
")",
":",
"# Creates graph from saved graph_def.pb.",
"with",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"os",
".",
"path",
".",
"join",
"(",
"FLAGS",
".",
"model_dir",
",",
"'classify_image_graph_def.pb'",
")",
",",
"'rb'",
")",
"as",
"f",
":",
"graph_def",
"=",
"tf",
".",
"GraphDef",
"(",
")",
"graph_def",
".",
"ParseFromString",
"(",
"f",
".",
"read",
"(",
")",
")",
"_",
"=",
"tf",
".",
"import_graph_def",
"(",
"graph_def",
",",
"name",
"=",
"''",
")"
] | Creates a graph from saved GraphDef file and returns a saver. | [
"Creates",
"a",
"graph",
"from",
"saved",
"GraphDef",
"file",
"and",
"returns",
"a",
"saver",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/external/tensorflow/classify_image.py#L120-L127 | train | 238,653 |
tyarkoni/pliers | pliers/external/tensorflow/classify_image.py | run_inference_on_image | def run_inference_on_image(image):
"""Runs inference on an image.
Args:
image: Image file name.
Returns:
Nothing
"""
if not tf.gfile.Exists(image):
tf.logging.fatal('File does not exist %s', image)
image_data = tf.gfile.FastGFile(image, 'rb').read()
# Creates graph from saved GraphDef.
create_graph()
with tf.Session() as sess:
# Some useful tensors:
# 'softmax:0': A tensor containing the normalized prediction across
# 1000 labels.
# 'pool_3:0': A tensor containing the next-to-last layer containing 2048
# float description of the image.
# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
# encoding of the image.
# Runs the softmax tensor by feeding the image_data as input to the graph.
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
predictions = sess.run(softmax_tensor,
{'DecodeJpeg/contents:0': image_data})
predictions = np.squeeze(predictions)
# Creates node ID --> English string lookup.
node_lookup = NodeLookup()
top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
for node_id in top_k:
human_string = node_lookup.id_to_string(node_id)
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score)) | python | def run_inference_on_image(image):
"""Runs inference on an image.
Args:
image: Image file name.
Returns:
Nothing
"""
if not tf.gfile.Exists(image):
tf.logging.fatal('File does not exist %s', image)
image_data = tf.gfile.FastGFile(image, 'rb').read()
# Creates graph from saved GraphDef.
create_graph()
with tf.Session() as sess:
# Some useful tensors:
# 'softmax:0': A tensor containing the normalized prediction across
# 1000 labels.
# 'pool_3:0': A tensor containing the next-to-last layer containing 2048
# float description of the image.
# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG
# encoding of the image.
# Runs the softmax tensor by feeding the image_data as input to the graph.
softmax_tensor = sess.graph.get_tensor_by_name('softmax:0')
predictions = sess.run(softmax_tensor,
{'DecodeJpeg/contents:0': image_data})
predictions = np.squeeze(predictions)
# Creates node ID --> English string lookup.
node_lookup = NodeLookup()
top_k = predictions.argsort()[-FLAGS.num_top_predictions:][::-1]
for node_id in top_k:
human_string = node_lookup.id_to_string(node_id)
score = predictions[node_id]
print('%s (score = %.5f)' % (human_string, score)) | [
"def",
"run_inference_on_image",
"(",
"image",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"image",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"image",
")",
"image_data",
"=",
"tf",
".",
"gfile",
".",
"FastGFile",
"(",
"image",
",",
"'rb'",
")",
".",
"read",
"(",
")",
"# Creates graph from saved GraphDef.",
"create_graph",
"(",
")",
"with",
"tf",
".",
"Session",
"(",
")",
"as",
"sess",
":",
"# Some useful tensors:",
"# 'softmax:0': A tensor containing the normalized prediction across",
"# 1000 labels.",
"# 'pool_3:0': A tensor containing the next-to-last layer containing 2048",
"# float description of the image.",
"# 'DecodeJpeg/contents:0': A tensor containing a string providing JPEG",
"# encoding of the image.",
"# Runs the softmax tensor by feeding the image_data as input to the graph.",
"softmax_tensor",
"=",
"sess",
".",
"graph",
".",
"get_tensor_by_name",
"(",
"'softmax:0'",
")",
"predictions",
"=",
"sess",
".",
"run",
"(",
"softmax_tensor",
",",
"{",
"'DecodeJpeg/contents:0'",
":",
"image_data",
"}",
")",
"predictions",
"=",
"np",
".",
"squeeze",
"(",
"predictions",
")",
"# Creates node ID --> English string lookup.",
"node_lookup",
"=",
"NodeLookup",
"(",
")",
"top_k",
"=",
"predictions",
".",
"argsort",
"(",
")",
"[",
"-",
"FLAGS",
".",
"num_top_predictions",
":",
"]",
"[",
":",
":",
"-",
"1",
"]",
"for",
"node_id",
"in",
"top_k",
":",
"human_string",
"=",
"node_lookup",
".",
"id_to_string",
"(",
"node_id",
")",
"score",
"=",
"predictions",
"[",
"node_id",
"]",
"print",
"(",
"'%s (score = %.5f)'",
"%",
"(",
"human_string",
",",
"score",
")",
")"
] | Runs inference on an image.
Args:
image: Image file name.
Returns:
Nothing | [
"Runs",
"inference",
"on",
"an",
"image",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/external/tensorflow/classify_image.py#L130-L167 | train | 238,654 |
tyarkoni/pliers | pliers/external/tensorflow/classify_image.py | NodeLookup.load | def load(self, label_lookup_path, uid_lookup_path):
"""Loads a human readable English name for each softmax node.
Args:
label_lookup_path: string UID to integer node ID.
uid_lookup_path: string UID to human-readable string.
Returns:
dict from integer node ID to human-readable string.
"""
if not tf.gfile.Exists(uid_lookup_path):
tf.logging.fatal('File does not exist %s', uid_lookup_path)
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
# Loads mapping from string UID to human-readable string
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
p = re.compile(r'[n\d]*[ \S,]*')
for line in proto_as_ascii_lines:
parsed_items = p.findall(line)
uid = parsed_items[0]
human_string = parsed_items[2]
uid_to_human[uid] = human_string
# Loads mapping from string UID to integer node ID.
node_id_to_uid = {}
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
for line in proto_as_ascii:
if line.startswith(' target_class:'):
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
target_class_string = line.split(': ')[1]
node_id_to_uid[target_class] = target_class_string[1:-2]
# Loads the final mapping of integer node ID to human-readable string
node_id_to_name = {}
for key, val in node_id_to_uid.items():
if val not in uid_to_human:
tf.logging.fatal('Failed to locate: %s', val)
name = uid_to_human[val]
node_id_to_name[key] = name
return node_id_to_name | python | def load(self, label_lookup_path, uid_lookup_path):
"""Loads a human readable English name for each softmax node.
Args:
label_lookup_path: string UID to integer node ID.
uid_lookup_path: string UID to human-readable string.
Returns:
dict from integer node ID to human-readable string.
"""
if not tf.gfile.Exists(uid_lookup_path):
tf.logging.fatal('File does not exist %s', uid_lookup_path)
if not tf.gfile.Exists(label_lookup_path):
tf.logging.fatal('File does not exist %s', label_lookup_path)
# Loads mapping from string UID to human-readable string
proto_as_ascii_lines = tf.gfile.GFile(uid_lookup_path).readlines()
uid_to_human = {}
p = re.compile(r'[n\d]*[ \S,]*')
for line in proto_as_ascii_lines:
parsed_items = p.findall(line)
uid = parsed_items[0]
human_string = parsed_items[2]
uid_to_human[uid] = human_string
# Loads mapping from string UID to integer node ID.
node_id_to_uid = {}
proto_as_ascii = tf.gfile.GFile(label_lookup_path).readlines()
for line in proto_as_ascii:
if line.startswith(' target_class:'):
target_class = int(line.split(': ')[1])
if line.startswith(' target_class_string:'):
target_class_string = line.split(': ')[1]
node_id_to_uid[target_class] = target_class_string[1:-2]
# Loads the final mapping of integer node ID to human-readable string
node_id_to_name = {}
for key, val in node_id_to_uid.items():
if val not in uid_to_human:
tf.logging.fatal('Failed to locate: %s', val)
name = uid_to_human[val]
node_id_to_name[key] = name
return node_id_to_name | [
"def",
"load",
"(",
"self",
",",
"label_lookup_path",
",",
"uid_lookup_path",
")",
":",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"uid_lookup_path",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"uid_lookup_path",
")",
"if",
"not",
"tf",
".",
"gfile",
".",
"Exists",
"(",
"label_lookup_path",
")",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'File does not exist %s'",
",",
"label_lookup_path",
")",
"# Loads mapping from string UID to human-readable string",
"proto_as_ascii_lines",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"uid_lookup_path",
")",
".",
"readlines",
"(",
")",
"uid_to_human",
"=",
"{",
"}",
"p",
"=",
"re",
".",
"compile",
"(",
"r'[n\\d]*[ \\S,]*'",
")",
"for",
"line",
"in",
"proto_as_ascii_lines",
":",
"parsed_items",
"=",
"p",
".",
"findall",
"(",
"line",
")",
"uid",
"=",
"parsed_items",
"[",
"0",
"]",
"human_string",
"=",
"parsed_items",
"[",
"2",
"]",
"uid_to_human",
"[",
"uid",
"]",
"=",
"human_string",
"# Loads mapping from string UID to integer node ID.",
"node_id_to_uid",
"=",
"{",
"}",
"proto_as_ascii",
"=",
"tf",
".",
"gfile",
".",
"GFile",
"(",
"label_lookup_path",
")",
".",
"readlines",
"(",
")",
"for",
"line",
"in",
"proto_as_ascii",
":",
"if",
"line",
".",
"startswith",
"(",
"' target_class:'",
")",
":",
"target_class",
"=",
"int",
"(",
"line",
".",
"split",
"(",
"': '",
")",
"[",
"1",
"]",
")",
"if",
"line",
".",
"startswith",
"(",
"' target_class_string:'",
")",
":",
"target_class_string",
"=",
"line",
".",
"split",
"(",
"': '",
")",
"[",
"1",
"]",
"node_id_to_uid",
"[",
"target_class",
"]",
"=",
"target_class_string",
"[",
"1",
":",
"-",
"2",
"]",
"# Loads the final mapping of integer node ID to human-readable string",
"node_id_to_name",
"=",
"{",
"}",
"for",
"key",
",",
"val",
"in",
"node_id_to_uid",
".",
"items",
"(",
")",
":",
"if",
"val",
"not",
"in",
"uid_to_human",
":",
"tf",
".",
"logging",
".",
"fatal",
"(",
"'Failed to locate: %s'",
",",
"val",
")",
"name",
"=",
"uid_to_human",
"[",
"val",
"]",
"node_id_to_name",
"[",
"key",
"]",
"=",
"name",
"return",
"node_id_to_name"
] | Loads a human readable English name for each softmax node.
Args:
label_lookup_path: string UID to integer node ID.
uid_lookup_path: string UID to human-readable string.
Returns:
dict from integer node ID to human-readable string. | [
"Loads",
"a",
"human",
"readable",
"English",
"name",
"for",
"each",
"softmax",
"node",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/external/tensorflow/classify_image.py#L69-L112 | train | 238,655 |
tyarkoni/pliers | pliers/datasets/text.py | fetch_dictionary | def fetch_dictionary(name, url=None, format=None, index=0, rename=None,
save=True, force_retrieve=False):
''' Retrieve a dictionary of text norms from the web or local storage.
Args:
name (str): The name of the dictionary. If no url is passed, this must
match either one of the keys in the predefined dictionary file (see
dictionaries.json), or the name assigned to a previous dictionary
retrieved from a specific URL.
url (str): The URL of dictionary file to retrieve. Optional if name
matches an existing dictionary.
format (str): One of 'csv', 'tsv', 'xls', or None. Used to read data
appropriately. Note that most forms of compression will be detected
and handled automatically, so the format string refers only to the
format of the decompressed file. When format is None, the format
will be inferred from the filename.
index (str, int): The name or numeric index of the column to used as
the dictionary index. Passed directly to pd.ix.
rename (dict): An optional dictionary passed to pd.rename(); can be
used to rename columns in the loaded dictionary. Note that the
locally-saved dictionary will retain the renamed columns.
save (bool): Whether or not to save the dictionary locally the first
time it is retrieved.
force_retrieve (bool): If True, remote dictionary will always be
downloaded, even if a local copy exists (and the local copy will
be overwritten).
Returns: A pandas DataFrame indexed by strings (typically words).
'''
file_path = os.path.join(_get_dictionary_path(), name + '.csv')
if not force_retrieve and os.path.exists(file_path):
df = pd.read_csv(file_path)
index = datasets[name].get('index', df.columns[index])
return df.set_index(index)
if name in datasets:
url = datasets[name]['url']
format = datasets[name].get('format', format)
index = datasets[name].get('index', index)
rename = datasets.get('rename', rename)
if url is None:
raise ValueError("Dataset '%s' not found in local storage or presets, "
"and no download URL provided." % name)
data = _download_dictionary(url, format=format, rename=rename)
if isinstance(index, int):
index = data.columns[index]
data = data.set_index(index)
if save:
file_path = os.path.join(_get_dictionary_path(), name + '.csv')
data.to_csv(file_path, encoding='utf-8')
return data | python | def fetch_dictionary(name, url=None, format=None, index=0, rename=None,
save=True, force_retrieve=False):
''' Retrieve a dictionary of text norms from the web or local storage.
Args:
name (str): The name of the dictionary. If no url is passed, this must
match either one of the keys in the predefined dictionary file (see
dictionaries.json), or the name assigned to a previous dictionary
retrieved from a specific URL.
url (str): The URL of dictionary file to retrieve. Optional if name
matches an existing dictionary.
format (str): One of 'csv', 'tsv', 'xls', or None. Used to read data
appropriately. Note that most forms of compression will be detected
and handled automatically, so the format string refers only to the
format of the decompressed file. When format is None, the format
will be inferred from the filename.
index (str, int): The name or numeric index of the column to used as
the dictionary index. Passed directly to pd.ix.
rename (dict): An optional dictionary passed to pd.rename(); can be
used to rename columns in the loaded dictionary. Note that the
locally-saved dictionary will retain the renamed columns.
save (bool): Whether or not to save the dictionary locally the first
time it is retrieved.
force_retrieve (bool): If True, remote dictionary will always be
downloaded, even if a local copy exists (and the local copy will
be overwritten).
Returns: A pandas DataFrame indexed by strings (typically words).
'''
file_path = os.path.join(_get_dictionary_path(), name + '.csv')
if not force_retrieve and os.path.exists(file_path):
df = pd.read_csv(file_path)
index = datasets[name].get('index', df.columns[index])
return df.set_index(index)
if name in datasets:
url = datasets[name]['url']
format = datasets[name].get('format', format)
index = datasets[name].get('index', index)
rename = datasets.get('rename', rename)
if url is None:
raise ValueError("Dataset '%s' not found in local storage or presets, "
"and no download URL provided." % name)
data = _download_dictionary(url, format=format, rename=rename)
if isinstance(index, int):
index = data.columns[index]
data = data.set_index(index)
if save:
file_path = os.path.join(_get_dictionary_path(), name + '.csv')
data.to_csv(file_path, encoding='utf-8')
return data | [
"def",
"fetch_dictionary",
"(",
"name",
",",
"url",
"=",
"None",
",",
"format",
"=",
"None",
",",
"index",
"=",
"0",
",",
"rename",
"=",
"None",
",",
"save",
"=",
"True",
",",
"force_retrieve",
"=",
"False",
")",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_get_dictionary_path",
"(",
")",
",",
"name",
"+",
"'.csv'",
")",
"if",
"not",
"force_retrieve",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"file_path",
")",
":",
"df",
"=",
"pd",
".",
"read_csv",
"(",
"file_path",
")",
"index",
"=",
"datasets",
"[",
"name",
"]",
".",
"get",
"(",
"'index'",
",",
"df",
".",
"columns",
"[",
"index",
"]",
")",
"return",
"df",
".",
"set_index",
"(",
"index",
")",
"if",
"name",
"in",
"datasets",
":",
"url",
"=",
"datasets",
"[",
"name",
"]",
"[",
"'url'",
"]",
"format",
"=",
"datasets",
"[",
"name",
"]",
".",
"get",
"(",
"'format'",
",",
"format",
")",
"index",
"=",
"datasets",
"[",
"name",
"]",
".",
"get",
"(",
"'index'",
",",
"index",
")",
"rename",
"=",
"datasets",
".",
"get",
"(",
"'rename'",
",",
"rename",
")",
"if",
"url",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"\"Dataset '%s' not found in local storage or presets, \"",
"\"and no download URL provided.\"",
"%",
"name",
")",
"data",
"=",
"_download_dictionary",
"(",
"url",
",",
"format",
"=",
"format",
",",
"rename",
"=",
"rename",
")",
"if",
"isinstance",
"(",
"index",
",",
"int",
")",
":",
"index",
"=",
"data",
".",
"columns",
"[",
"index",
"]",
"data",
"=",
"data",
".",
"set_index",
"(",
"index",
")",
"if",
"save",
":",
"file_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"_get_dictionary_path",
"(",
")",
",",
"name",
"+",
"'.csv'",
")",
"data",
".",
"to_csv",
"(",
"file_path",
",",
"encoding",
"=",
"'utf-8'",
")",
"return",
"data"
] | Retrieve a dictionary of text norms from the web or local storage.
Args:
name (str): The name of the dictionary. If no url is passed, this must
match either one of the keys in the predefined dictionary file (see
dictionaries.json), or the name assigned to a previous dictionary
retrieved from a specific URL.
url (str): The URL of dictionary file to retrieve. Optional if name
matches an existing dictionary.
format (str): One of 'csv', 'tsv', 'xls', or None. Used to read data
appropriately. Note that most forms of compression will be detected
and handled automatically, so the format string refers only to the
format of the decompressed file. When format is None, the format
will be inferred from the filename.
index (str, int): The name or numeric index of the column to used as
the dictionary index. Passed directly to pd.ix.
rename (dict): An optional dictionary passed to pd.rename(); can be
used to rename columns in the loaded dictionary. Note that the
locally-saved dictionary will retain the renamed columns.
save (bool): Whether or not to save the dictionary locally the first
time it is retrieved.
force_retrieve (bool): If True, remote dictionary will always be
downloaded, even if a local copy exists (and the local copy will
be overwritten).
Returns: A pandas DataFrame indexed by strings (typically words). | [
"Retrieve",
"a",
"dictionary",
"of",
"text",
"norms",
"from",
"the",
"web",
"or",
"local",
"storage",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/datasets/text.py#L57-L111 | train | 238,656 |
tyarkoni/pliers | pliers/extractors/api/google.py | GoogleVisionAPIFaceExtractor._to_df | def _to_df(self, result, handle_annotations=None):
'''
Converts a Google API Face JSON response into a Pandas Dataframe.
Args:
result (ExtractorResult): Result object from which to parse out a
Dataframe.
handle_annotations (str): How returned face annotations should be
handled in cases where there are multiple faces.
'first' indicates to only use the first face JSON object, all
other values will default to including every face.
'''
annotations = result._data
if handle_annotations == 'first':
annotations = [annotations[0]]
face_results = []
for i, annotation in enumerate(annotations):
data_dict = {}
for field, val in annotation.items():
if 'Confidence' in field:
data_dict['face_' + field] = val
elif 'oundingPoly' in field:
for j, vertex in enumerate(val['vertices']):
for dim in ['x', 'y']:
name = '%s_vertex%d_%s' % (field, j+1, dim)
val = vertex[dim] if dim in vertex else np.nan
data_dict[name] = val
elif field == 'landmarks':
for lm in val:
name = 'landmark_' + lm['type'] + '_%s'
lm_pos = {name %
k: v for (k, v) in lm['position'].items()}
data_dict.update(lm_pos)
else:
data_dict[field] = val
face_results.append(data_dict)
return pd.DataFrame(face_results) | python | def _to_df(self, result, handle_annotations=None):
'''
Converts a Google API Face JSON response into a Pandas Dataframe.
Args:
result (ExtractorResult): Result object from which to parse out a
Dataframe.
handle_annotations (str): How returned face annotations should be
handled in cases where there are multiple faces.
'first' indicates to only use the first face JSON object, all
other values will default to including every face.
'''
annotations = result._data
if handle_annotations == 'first':
annotations = [annotations[0]]
face_results = []
for i, annotation in enumerate(annotations):
data_dict = {}
for field, val in annotation.items():
if 'Confidence' in field:
data_dict['face_' + field] = val
elif 'oundingPoly' in field:
for j, vertex in enumerate(val['vertices']):
for dim in ['x', 'y']:
name = '%s_vertex%d_%s' % (field, j+1, dim)
val = vertex[dim] if dim in vertex else np.nan
data_dict[name] = val
elif field == 'landmarks':
for lm in val:
name = 'landmark_' + lm['type'] + '_%s'
lm_pos = {name %
k: v for (k, v) in lm['position'].items()}
data_dict.update(lm_pos)
else:
data_dict[field] = val
face_results.append(data_dict)
return pd.DataFrame(face_results) | [
"def",
"_to_df",
"(",
"self",
",",
"result",
",",
"handle_annotations",
"=",
"None",
")",
":",
"annotations",
"=",
"result",
".",
"_data",
"if",
"handle_annotations",
"==",
"'first'",
":",
"annotations",
"=",
"[",
"annotations",
"[",
"0",
"]",
"]",
"face_results",
"=",
"[",
"]",
"for",
"i",
",",
"annotation",
"in",
"enumerate",
"(",
"annotations",
")",
":",
"data_dict",
"=",
"{",
"}",
"for",
"field",
",",
"val",
"in",
"annotation",
".",
"items",
"(",
")",
":",
"if",
"'Confidence'",
"in",
"field",
":",
"data_dict",
"[",
"'face_'",
"+",
"field",
"]",
"=",
"val",
"elif",
"'oundingPoly'",
"in",
"field",
":",
"for",
"j",
",",
"vertex",
"in",
"enumerate",
"(",
"val",
"[",
"'vertices'",
"]",
")",
":",
"for",
"dim",
"in",
"[",
"'x'",
",",
"'y'",
"]",
":",
"name",
"=",
"'%s_vertex%d_%s'",
"%",
"(",
"field",
",",
"j",
"+",
"1",
",",
"dim",
")",
"val",
"=",
"vertex",
"[",
"dim",
"]",
"if",
"dim",
"in",
"vertex",
"else",
"np",
".",
"nan",
"data_dict",
"[",
"name",
"]",
"=",
"val",
"elif",
"field",
"==",
"'landmarks'",
":",
"for",
"lm",
"in",
"val",
":",
"name",
"=",
"'landmark_'",
"+",
"lm",
"[",
"'type'",
"]",
"+",
"'_%s'",
"lm_pos",
"=",
"{",
"name",
"%",
"k",
":",
"v",
"for",
"(",
"k",
",",
"v",
")",
"in",
"lm",
"[",
"'position'",
"]",
".",
"items",
"(",
")",
"}",
"data_dict",
".",
"update",
"(",
"lm_pos",
")",
"else",
":",
"data_dict",
"[",
"field",
"]",
"=",
"val",
"face_results",
".",
"append",
"(",
"data_dict",
")",
"return",
"pd",
".",
"DataFrame",
"(",
"face_results",
")"
] | Converts a Google API Face JSON response into a Pandas Dataframe.
Args:
result (ExtractorResult): Result object from which to parse out a
Dataframe.
handle_annotations (str): How returned face annotations should be
handled in cases where there are multiple faces.
'first' indicates to only use the first face JSON object, all
other values will default to including every face. | [
"Converts",
"a",
"Google",
"API",
"Face",
"JSON",
"response",
"into",
"a",
"Pandas",
"Dataframe",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/extractors/api/google.py#L50-L89 | train | 238,657 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | correlation_matrix | def correlation_matrix(df):
'''
Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
columns = df.columns.tolist()
corr = pd.DataFrame(
np.corrcoef(df, rowvar=0), columns=columns, index=columns)
return corr | python | def correlation_matrix(df):
'''
Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
columns = df.columns.tolist()
corr = pd.DataFrame(
np.corrcoef(df, rowvar=0), columns=columns, index=columns)
return corr | [
"def",
"correlation_matrix",
"(",
"df",
")",
":",
"columns",
"=",
"df",
".",
"columns",
".",
"tolist",
"(",
")",
"corr",
"=",
"pd",
".",
"DataFrame",
"(",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
",",
"columns",
"=",
"columns",
",",
"index",
"=",
"columns",
")",
"return",
"corr"
] | Returns a pandas DataFrame with the pair-wise correlations of the columns.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"DataFrame",
"with",
"the",
"pair",
"-",
"wise",
"correlations",
"of",
"the",
"columns",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L12-L22 | train | 238,658 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | eigenvalues | def eigenvalues(df):
'''
Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
eigvals = np.linalg.eigvals(corr)
return pd.Series(eigvals, df.columns, name='Eigenvalue') | python | def eigenvalues(df):
'''
Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
corr = np.corrcoef(df, rowvar=0)
eigvals = np.linalg.eigvals(corr)
return pd.Series(eigvals, df.columns, name='Eigenvalue') | [
"def",
"eigenvalues",
"(",
"df",
")",
":",
"corr",
"=",
"np",
".",
"corrcoef",
"(",
"df",
",",
"rowvar",
"=",
"0",
")",
"eigvals",
"=",
"np",
".",
"linalg",
".",
"eigvals",
"(",
"corr",
")",
"return",
"pd",
".",
"Series",
"(",
"eigvals",
",",
"df",
".",
"columns",
",",
"name",
"=",
"'Eigenvalue'",
")"
] | Returns a pandas Series with eigenvalues of the correlation matrix.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"Series",
"with",
"eigenvalues",
"of",
"the",
"correlation",
"matrix",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L25-L34 | train | 238,659 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | condition_indices | def condition_indices(df):
'''
Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
eigvals = eigenvalues(df)
cond_idx = np.sqrt(eigvals.max() / eigvals)
return pd.Series(cond_idx, df.columns, name='Condition index') | python | def condition_indices(df):
'''
Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on
'''
eigvals = eigenvalues(df)
cond_idx = np.sqrt(eigvals.max() / eigvals)
return pd.Series(cond_idx, df.columns, name='Condition index') | [
"def",
"condition_indices",
"(",
"df",
")",
":",
"eigvals",
"=",
"eigenvalues",
"(",
"df",
")",
"cond_idx",
"=",
"np",
".",
"sqrt",
"(",
"eigvals",
".",
"max",
"(",
")",
"/",
"eigvals",
")",
"return",
"pd",
".",
"Series",
"(",
"cond_idx",
",",
"df",
".",
"columns",
",",
"name",
"=",
"'Condition index'",
")"
] | Returns a pandas Series with condition indices of the df columns.
Args:
df: pandas DataFrame with columns to run diagnostics on | [
"Returns",
"a",
"pandas",
"Series",
"with",
"condition",
"indices",
"of",
"the",
"df",
"columns",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L37-L46 | train | 238,660 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | mahalanobis_distances | def mahalanobis_distances(df, axis=0):
'''
Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns
'''
df = df.transpose() if axis == 1 else df
means = df.mean()
try:
inv_cov = np.linalg.inv(df.cov())
except LinAlgError:
return pd.Series([np.NAN] * len(df.index), df.index,
name='Mahalanobis')
dists = []
for i, sample in df.iterrows():
dists.append(mahalanobis(sample, means, inv_cov))
return pd.Series(dists, df.index, name='Mahalanobis') | python | def mahalanobis_distances(df, axis=0):
'''
Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns
'''
df = df.transpose() if axis == 1 else df
means = df.mean()
try:
inv_cov = np.linalg.inv(df.cov())
except LinAlgError:
return pd.Series([np.NAN] * len(df.index), df.index,
name='Mahalanobis')
dists = []
for i, sample in df.iterrows():
dists.append(mahalanobis(sample, means, inv_cov))
return pd.Series(dists, df.index, name='Mahalanobis') | [
"def",
"mahalanobis_distances",
"(",
"df",
",",
"axis",
"=",
"0",
")",
":",
"df",
"=",
"df",
".",
"transpose",
"(",
")",
"if",
"axis",
"==",
"1",
"else",
"df",
"means",
"=",
"df",
".",
"mean",
"(",
")",
"try",
":",
"inv_cov",
"=",
"np",
".",
"linalg",
".",
"inv",
"(",
"df",
".",
"cov",
"(",
")",
")",
"except",
"LinAlgError",
":",
"return",
"pd",
".",
"Series",
"(",
"[",
"np",
".",
"NAN",
"]",
"*",
"len",
"(",
"df",
".",
"index",
")",
",",
"df",
".",
"index",
",",
"name",
"=",
"'Mahalanobis'",
")",
"dists",
"=",
"[",
"]",
"for",
"i",
",",
"sample",
"in",
"df",
".",
"iterrows",
"(",
")",
":",
"dists",
".",
"append",
"(",
"mahalanobis",
"(",
"sample",
",",
"means",
",",
"inv_cov",
")",
")",
"return",
"pd",
".",
"Series",
"(",
"dists",
",",
"df",
".",
"index",
",",
"name",
"=",
"'Mahalanobis'",
")"
] | Returns a pandas Series with Mahalanobis distances for each sample on the
axis.
Note: does not work well when # of observations < # of dimensions
Will either return NaN in answer
or (in the extreme case) fail with a Singular Matrix LinAlgError
Args:
df: pandas DataFrame with columns to run diagnostics on
axis: 0 to find outlier rows, 1 to find outlier columns | [
"Returns",
"a",
"pandas",
"Series",
"with",
"Mahalanobis",
"distances",
"for",
"each",
"sample",
"on",
"the",
"axis",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L63-L87 | train | 238,661 |
tyarkoni/pliers | pliers/diagnostics/diagnostics.py | Diagnostics.summary | def summary(self, stdout=True, plot=False):
'''
Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results
'''
if stdout:
print('Collinearity summary:')
print(pd.concat([self.results['Eigenvalues'],
self.results['ConditionIndices'],
self.results['VIFs'],
self.results['CorrelationMatrix']],
axis=1))
print('Outlier summary:')
print(self.results['RowMahalanobisDistances'])
print(self.results['ColumnMahalanobisDistances'])
print('Validity summary:')
print(self.results['Variances'])
if plot:
verify_dependencies('seaborn')
for key, result in self.results.items():
if key == 'CorrelationMatrix':
ax = plt.axes()
sns.heatmap(result, cmap='Blues', ax=ax)
ax.set_title(key)
sns.plt.show()
else:
result.plot(kind='bar', title=key)
plt.show() | python | def summary(self, stdout=True, plot=False):
'''
Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results
'''
if stdout:
print('Collinearity summary:')
print(pd.concat([self.results['Eigenvalues'],
self.results['ConditionIndices'],
self.results['VIFs'],
self.results['CorrelationMatrix']],
axis=1))
print('Outlier summary:')
print(self.results['RowMahalanobisDistances'])
print(self.results['ColumnMahalanobisDistances'])
print('Validity summary:')
print(self.results['Variances'])
if plot:
verify_dependencies('seaborn')
for key, result in self.results.items():
if key == 'CorrelationMatrix':
ax = plt.axes()
sns.heatmap(result, cmap='Blues', ax=ax)
ax.set_title(key)
sns.plt.show()
else:
result.plot(kind='bar', title=key)
plt.show() | [
"def",
"summary",
"(",
"self",
",",
"stdout",
"=",
"True",
",",
"plot",
"=",
"False",
")",
":",
"if",
"stdout",
":",
"print",
"(",
"'Collinearity summary:'",
")",
"print",
"(",
"pd",
".",
"concat",
"(",
"[",
"self",
".",
"results",
"[",
"'Eigenvalues'",
"]",
",",
"self",
".",
"results",
"[",
"'ConditionIndices'",
"]",
",",
"self",
".",
"results",
"[",
"'VIFs'",
"]",
",",
"self",
".",
"results",
"[",
"'CorrelationMatrix'",
"]",
"]",
",",
"axis",
"=",
"1",
")",
")",
"print",
"(",
"'Outlier summary:'",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'RowMahalanobisDistances'",
"]",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'ColumnMahalanobisDistances'",
"]",
")",
"print",
"(",
"'Validity summary:'",
")",
"print",
"(",
"self",
".",
"results",
"[",
"'Variances'",
"]",
")",
"if",
"plot",
":",
"verify_dependencies",
"(",
"'seaborn'",
")",
"for",
"key",
",",
"result",
"in",
"self",
".",
"results",
".",
"items",
"(",
")",
":",
"if",
"key",
"==",
"'CorrelationMatrix'",
":",
"ax",
"=",
"plt",
".",
"axes",
"(",
")",
"sns",
".",
"heatmap",
"(",
"result",
",",
"cmap",
"=",
"'Blues'",
",",
"ax",
"=",
"ax",
")",
"ax",
".",
"set_title",
"(",
"key",
")",
"sns",
".",
"plt",
".",
"show",
"(",
")",
"else",
":",
"result",
".",
"plot",
"(",
"kind",
"=",
"'bar'",
",",
"title",
"=",
"key",
")",
"plt",
".",
"show",
"(",
")"
] | Displays diagnostics to the user
Args:
stdout (bool): print results to the console
plot (bool): use Seaborn to plot results | [
"Displays",
"diagnostics",
"to",
"the",
"user"
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/diagnostics/diagnostics.py#L128-L161 | train | 238,662 |
tyarkoni/pliers | pliers/graph.py | Graph.add_nodes | def add_nodes(self, nodes, parent=None, mode='horizontal'):
''' Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list.
'''
for n in nodes:
node_args = self._parse_node_args(n)
if mode == 'horizontal':
self.add_node(parent=parent, **node_args)
elif mode == 'vertical':
parent = self.add_node(parent=parent, return_node=True,
**node_args)
else:
raise ValueError("Invalid mode for adding nodes to a graph:"
"%s" % mode) | python | def add_nodes(self, nodes, parent=None, mode='horizontal'):
''' Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list.
'''
for n in nodes:
node_args = self._parse_node_args(n)
if mode == 'horizontal':
self.add_node(parent=parent, **node_args)
elif mode == 'vertical':
parent = self.add_node(parent=parent, return_node=True,
**node_args)
else:
raise ValueError("Invalid mode for adding nodes to a graph:"
"%s" % mode) | [
"def",
"add_nodes",
"(",
"self",
",",
"nodes",
",",
"parent",
"=",
"None",
",",
"mode",
"=",
"'horizontal'",
")",
":",
"for",
"n",
"in",
"nodes",
":",
"node_args",
"=",
"self",
".",
"_parse_node_args",
"(",
"n",
")",
"if",
"mode",
"==",
"'horizontal'",
":",
"self",
".",
"add_node",
"(",
"parent",
"=",
"parent",
",",
"*",
"*",
"node_args",
")",
"elif",
"mode",
"==",
"'vertical'",
":",
"parent",
"=",
"self",
".",
"add_node",
"(",
"parent",
"=",
"parent",
",",
"return_node",
"=",
"True",
",",
"*",
"*",
"node_args",
")",
"else",
":",
"raise",
"ValueError",
"(",
"\"Invalid mode for adding nodes to a graph:\"",
"\"%s\"",
"%",
"mode",
")"
] | Adds one or more nodes to the current graph.
Args:
nodes (list): A list of nodes to add. Each element must be one of
the following:
* A dict containing keyword args to pass onto to the Node init.
* An iterable containing 1 - 3 elements. The first element is
mandatory, and specifies the Transformer at that node. The
second element (optional) is an iterable of child nodes
(specified in the same format). The third element
(optional) is a string giving the (unique) name of the
node.
* A Node instance.
* A Transformer instance.
parent (Node): Optional parent node (i.e., the node containing the
pliers Transformer from which the to-be-created nodes receive
their inputs).
mode (str): Indicates the direction with which to add the new nodes
* horizontal: the nodes should each be added as a child of the
'parent' argument (or a Graph root by default).
* vertical: the nodes should each be added in sequence with
the first node being the child of the 'parnet' argument
(a Graph root by default) and each subsequent node being
the child of the previous node in the list. | [
"Adds",
"one",
"or",
"more",
"nodes",
"to",
"the",
"current",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L107-L144 | train | 238,663 |
tyarkoni/pliers | pliers/graph.py | Graph.add_node | def add_node(self, transformer, name=None, children=None, parent=None,
parameters={}, return_node=False):
''' Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise.
'''
node = Node(transformer, name, **parameters)
self.nodes[node.id] = node
if parent is None:
self.roots.append(node)
else:
parent = self.nodes[parent.id]
parent.add_child(node)
if children is not None:
self.add_nodes(children, parent=node)
if return_node:
return node | python | def add_node(self, transformer, name=None, children=None, parent=None,
parameters={}, return_node=False):
''' Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise.
'''
node = Node(transformer, name, **parameters)
self.nodes[node.id] = node
if parent is None:
self.roots.append(node)
else:
parent = self.nodes[parent.id]
parent.add_child(node)
if children is not None:
self.add_nodes(children, parent=node)
if return_node:
return node | [
"def",
"add_node",
"(",
"self",
",",
"transformer",
",",
"name",
"=",
"None",
",",
"children",
"=",
"None",
",",
"parent",
"=",
"None",
",",
"parameters",
"=",
"{",
"}",
",",
"return_node",
"=",
"False",
")",
":",
"node",
"=",
"Node",
"(",
"transformer",
",",
"name",
",",
"*",
"*",
"parameters",
")",
"self",
".",
"nodes",
"[",
"node",
".",
"id",
"]",
"=",
"node",
"if",
"parent",
"is",
"None",
":",
"self",
".",
"roots",
".",
"append",
"(",
"node",
")",
"else",
":",
"parent",
"=",
"self",
".",
"nodes",
"[",
"parent",
".",
"id",
"]",
"parent",
".",
"add_child",
"(",
"node",
")",
"if",
"children",
"is",
"not",
"None",
":",
"self",
".",
"add_nodes",
"(",
"children",
",",
"parent",
"=",
"node",
")",
"if",
"return_node",
":",
"return",
"node"
] | Adds a node to the current graph.
Args:
transformer (str, Transformer): The pliers Transformer to use at
the to-be-added node. Either a case-insensitive string giving
the name of a Transformer class, or an initialized Transformer
instance.
name (str): Optional name to give this Node.
children (list): Optional list of child nodes (i.e., nodes to pass
the to-be-added node's Transformer output to).
parent (Node): Optional node from which the to-be-added Node
receives its input.
parameters (dict): Optional keyword arguments to pass onto the
Transformer initialized at this Node if a string is passed to
the 'transformer' argument. Ignored if an already-initialized
Transformer is passed.
return_node (bool): If True, returns the initialized Node instance.
Returns:
The initialized Node instance if return_node is True,
None otherwise. | [
"Adds",
"a",
"node",
"to",
"the",
"current",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L154-L192 | train | 238,664 |
tyarkoni/pliers | pliers/graph.py | Graph.run | def run(self, stim, merge=True, **merge_kwargs):
''' Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call.
'''
results = list(chain(*[self.run_node(n, stim) for n in self.roots]))
results = list(flatten(results))
self._results = results # For use in plotting
return merge_results(results, **merge_kwargs) if merge else results | python | def run(self, stim, merge=True, **merge_kwargs):
''' Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call.
'''
results = list(chain(*[self.run_node(n, stim) for n in self.roots]))
results = list(flatten(results))
self._results = results # For use in plotting
return merge_results(results, **merge_kwargs) if merge else results | [
"def",
"run",
"(",
"self",
",",
"stim",
",",
"merge",
"=",
"True",
",",
"*",
"*",
"merge_kwargs",
")",
":",
"results",
"=",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"run_node",
"(",
"n",
",",
"stim",
")",
"for",
"n",
"in",
"self",
".",
"roots",
"]",
")",
")",
"results",
"=",
"list",
"(",
"flatten",
"(",
"results",
")",
")",
"self",
".",
"_results",
"=",
"results",
"# For use in plotting",
"return",
"merge_results",
"(",
"results",
",",
"*",
"*",
"merge_kwargs",
")",
"if",
"merge",
"else",
"results"
] | Executes the graph by calling all Transformers in sequence.
Args:
stim (str, Stim, list): One or more valid inputs to any
Transformer's 'transform' call.
merge (bool): If True, all results are merged into a single pandas
DataFrame before being returned. If False, a list of
ExtractorResult objects is returned (one per Extractor/Stim
combination).
merge_kwargs: Optional keyword arguments to pass onto the
merge_results() call. | [
"Executes",
"the",
"graph",
"by",
"calling",
"all",
"Transformers",
"in",
"sequence",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L194-L210 | train | 238,665 |
tyarkoni/pliers | pliers/graph.py | Graph.run_node | def run_node(self, node, stim):
''' Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node.
'''
if isinstance(node, string_types):
node = self.nodes[node]
result = node.transformer.transform(stim)
if node.is_leaf():
return listify(result)
stim = result
# If result is a generator, the first child will destroy the
# iterable, so cache via list conversion
if len(node.children) > 1 and isgenerator(stim):
stim = list(stim)
return list(chain(*[self.run_node(c, stim) for c in node.children])) | python | def run_node(self, node, stim):
''' Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node.
'''
if isinstance(node, string_types):
node = self.nodes[node]
result = node.transformer.transform(stim)
if node.is_leaf():
return listify(result)
stim = result
# If result is a generator, the first child will destroy the
# iterable, so cache via list conversion
if len(node.children) > 1 and isgenerator(stim):
stim = list(stim)
return list(chain(*[self.run_node(c, stim) for c in node.children])) | [
"def",
"run_node",
"(",
"self",
",",
"node",
",",
"stim",
")",
":",
"if",
"isinstance",
"(",
"node",
",",
"string_types",
")",
":",
"node",
"=",
"self",
".",
"nodes",
"[",
"node",
"]",
"result",
"=",
"node",
".",
"transformer",
".",
"transform",
"(",
"stim",
")",
"if",
"node",
".",
"is_leaf",
"(",
")",
":",
"return",
"listify",
"(",
"result",
")",
"stim",
"=",
"result",
"# If result is a generator, the first child will destroy the",
"# iterable, so cache via list conversion",
"if",
"len",
"(",
"node",
".",
"children",
")",
">",
"1",
"and",
"isgenerator",
"(",
"stim",
")",
":",
"stim",
"=",
"list",
"(",
"stim",
")",
"return",
"list",
"(",
"chain",
"(",
"*",
"[",
"self",
".",
"run_node",
"(",
"c",
",",
"stim",
")",
"for",
"c",
"in",
"node",
".",
"children",
"]",
")",
")"
] | Executes the Transformer at a specific node.
Args:
node (str, Node): If a string, the name of the Node in the current
Graph. Otherwise the Node instance to execute.
stim (str, stim, list): Any valid input to the Transformer stored
at the target node. | [
"Executes",
"the",
"Transformer",
"at",
"a",
"specific",
"node",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L214-L235 | train | 238,666 |
tyarkoni/pliers | pliers/graph.py | Graph.draw | def draw(self, filename, color=True):
''' Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph.
'''
verify_dependencies(['pgv'])
if not hasattr(self, '_results'):
raise RuntimeError("Graph cannot be drawn before it is executed. "
"Try calling run() first.")
g = pgv.AGraph(directed=True)
g.node_attr['colorscheme'] = 'set312'
for elem in self._results:
if not hasattr(elem, 'history'):
continue
log = elem.history
while log:
# Configure nodes
source_from = log.parent[6] if log.parent else ''
s_node = hash((source_from, log[2]))
s_color = stim_list.index(log[2])
s_color = s_color % 12 + 1
t_node = hash((log[6], log[7]))
t_style = 'filled,' if color else ''
t_style += 'dotted' if log.implicit else ''
if log[6].endswith('Extractor'):
t_color = '#0082c8'
elif log[6].endswith('Filter'):
t_color = '#e6194b'
else:
t_color = '#3cb44b'
r_node = hash((log[6], log[5]))
r_color = stim_list.index(log[5])
r_color = r_color % 12 + 1
# Add nodes
if color:
g.add_node(s_node, label=log[2], shape='ellipse',
style='filled', fillcolor=s_color)
g.add_node(t_node, label=log[6], shape='box',
style=t_style, fillcolor=t_color)
g.add_node(r_node, label=log[5], shape='ellipse',
style='filled', fillcolor=r_color)
else:
g.add_node(s_node, label=log[2], shape='ellipse')
g.add_node(t_node, label=log[6], shape='box',
style=t_style)
g.add_node(r_node, label=log[5], shape='ellipse')
# Add edges
g.add_edge(s_node, t_node, style=t_style)
g.add_edge(t_node, r_node, style=t_style)
log = log.parent
g.draw(filename, prog='dot') | python | def draw(self, filename, color=True):
''' Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph.
'''
verify_dependencies(['pgv'])
if not hasattr(self, '_results'):
raise RuntimeError("Graph cannot be drawn before it is executed. "
"Try calling run() first.")
g = pgv.AGraph(directed=True)
g.node_attr['colorscheme'] = 'set312'
for elem in self._results:
if not hasattr(elem, 'history'):
continue
log = elem.history
while log:
# Configure nodes
source_from = log.parent[6] if log.parent else ''
s_node = hash((source_from, log[2]))
s_color = stim_list.index(log[2])
s_color = s_color % 12 + 1
t_node = hash((log[6], log[7]))
t_style = 'filled,' if color else ''
t_style += 'dotted' if log.implicit else ''
if log[6].endswith('Extractor'):
t_color = '#0082c8'
elif log[6].endswith('Filter'):
t_color = '#e6194b'
else:
t_color = '#3cb44b'
r_node = hash((log[6], log[5]))
r_color = stim_list.index(log[5])
r_color = r_color % 12 + 1
# Add nodes
if color:
g.add_node(s_node, label=log[2], shape='ellipse',
style='filled', fillcolor=s_color)
g.add_node(t_node, label=log[6], shape='box',
style=t_style, fillcolor=t_color)
g.add_node(r_node, label=log[5], shape='ellipse',
style='filled', fillcolor=r_color)
else:
g.add_node(s_node, label=log[2], shape='ellipse')
g.add_node(t_node, label=log[6], shape='box',
style=t_style)
g.add_node(r_node, label=log[5], shape='ellipse')
# Add edges
g.add_edge(s_node, t_node, style=t_style)
g.add_edge(t_node, r_node, style=t_style)
log = log.parent
g.draw(filename, prog='dot') | [
"def",
"draw",
"(",
"self",
",",
"filename",
",",
"color",
"=",
"True",
")",
":",
"verify_dependencies",
"(",
"[",
"'pgv'",
"]",
")",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'_results'",
")",
":",
"raise",
"RuntimeError",
"(",
"\"Graph cannot be drawn before it is executed. \"",
"\"Try calling run() first.\"",
")",
"g",
"=",
"pgv",
".",
"AGraph",
"(",
"directed",
"=",
"True",
")",
"g",
".",
"node_attr",
"[",
"'colorscheme'",
"]",
"=",
"'set312'",
"for",
"elem",
"in",
"self",
".",
"_results",
":",
"if",
"not",
"hasattr",
"(",
"elem",
",",
"'history'",
")",
":",
"continue",
"log",
"=",
"elem",
".",
"history",
"while",
"log",
":",
"# Configure nodes",
"source_from",
"=",
"log",
".",
"parent",
"[",
"6",
"]",
"if",
"log",
".",
"parent",
"else",
"''",
"s_node",
"=",
"hash",
"(",
"(",
"source_from",
",",
"log",
"[",
"2",
"]",
")",
")",
"s_color",
"=",
"stim_list",
".",
"index",
"(",
"log",
"[",
"2",
"]",
")",
"s_color",
"=",
"s_color",
"%",
"12",
"+",
"1",
"t_node",
"=",
"hash",
"(",
"(",
"log",
"[",
"6",
"]",
",",
"log",
"[",
"7",
"]",
")",
")",
"t_style",
"=",
"'filled,'",
"if",
"color",
"else",
"''",
"t_style",
"+=",
"'dotted'",
"if",
"log",
".",
"implicit",
"else",
"''",
"if",
"log",
"[",
"6",
"]",
".",
"endswith",
"(",
"'Extractor'",
")",
":",
"t_color",
"=",
"'#0082c8'",
"elif",
"log",
"[",
"6",
"]",
".",
"endswith",
"(",
"'Filter'",
")",
":",
"t_color",
"=",
"'#e6194b'",
"else",
":",
"t_color",
"=",
"'#3cb44b'",
"r_node",
"=",
"hash",
"(",
"(",
"log",
"[",
"6",
"]",
",",
"log",
"[",
"5",
"]",
")",
")",
"r_color",
"=",
"stim_list",
".",
"index",
"(",
"log",
"[",
"5",
"]",
")",
"r_color",
"=",
"r_color",
"%",
"12",
"+",
"1",
"# Add nodes",
"if",
"color",
":",
"g",
".",
"add_node",
"(",
"s_node",
",",
"label",
"=",
"log",
"[",
"2",
"]",
",",
"shape",
"=",
"'ellipse'",
",",
"style",
"=",
"'filled'",
",",
"fillcolor",
"=",
"s_color",
")",
"g",
".",
"add_node",
"(",
"t_node",
",",
"label",
"=",
"log",
"[",
"6",
"]",
",",
"shape",
"=",
"'box'",
",",
"style",
"=",
"t_style",
",",
"fillcolor",
"=",
"t_color",
")",
"g",
".",
"add_node",
"(",
"r_node",
",",
"label",
"=",
"log",
"[",
"5",
"]",
",",
"shape",
"=",
"'ellipse'",
",",
"style",
"=",
"'filled'",
",",
"fillcolor",
"=",
"r_color",
")",
"else",
":",
"g",
".",
"add_node",
"(",
"s_node",
",",
"label",
"=",
"log",
"[",
"2",
"]",
",",
"shape",
"=",
"'ellipse'",
")",
"g",
".",
"add_node",
"(",
"t_node",
",",
"label",
"=",
"log",
"[",
"6",
"]",
",",
"shape",
"=",
"'box'",
",",
"style",
"=",
"t_style",
")",
"g",
".",
"add_node",
"(",
"r_node",
",",
"label",
"=",
"log",
"[",
"5",
"]",
",",
"shape",
"=",
"'ellipse'",
")",
"# Add edges",
"g",
".",
"add_edge",
"(",
"s_node",
",",
"t_node",
",",
"style",
"=",
"t_style",
")",
"g",
".",
"add_edge",
"(",
"t_node",
",",
"r_node",
",",
"style",
"=",
"t_style",
")",
"log",
"=",
"log",
".",
"parent",
"g",
".",
"draw",
"(",
"filename",
",",
"prog",
"=",
"'dot'",
")"
] | Render a plot of the graph via pygraphviz.
Args:
filename (str): Path to save the generated image to.
color (bool): If True, will color graph nodes based on their type,
otherwise will draw a black-and-white graph. | [
"Render",
"a",
"plot",
"of",
"the",
"graph",
"via",
"pygraphviz",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L237-L298 | train | 238,667 |
tyarkoni/pliers | pliers/graph.py | Graph.to_json | def to_json(self):
''' Returns the JSON representation of this graph. '''
roots = []
for r in self.roots:
roots.append(r.to_json())
return {'roots': roots} | python | def to_json(self):
''' Returns the JSON representation of this graph. '''
roots = []
for r in self.roots:
roots.append(r.to_json())
return {'roots': roots} | [
"def",
"to_json",
"(",
"self",
")",
":",
"roots",
"=",
"[",
"]",
"for",
"r",
"in",
"self",
".",
"roots",
":",
"roots",
".",
"append",
"(",
"r",
".",
"to_json",
"(",
")",
")",
"return",
"{",
"'roots'",
":",
"roots",
"}"
] | Returns the JSON representation of this graph. | [
"Returns",
"the",
"JSON",
"representation",
"of",
"this",
"graph",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/graph.py#L300-L305 | train | 238,668 |
tyarkoni/pliers | pliers/utils/base.py | flatten | def flatten(l):
''' Flatten an iterable. '''
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, string_types):
for sub in flatten(el):
yield sub
else:
yield el | python | def flatten(l):
''' Flatten an iterable. '''
for el in l:
if isinstance(el, collections.Iterable) and not isinstance(el, string_types):
for sub in flatten(el):
yield sub
else:
yield el | [
"def",
"flatten",
"(",
"l",
")",
":",
"for",
"el",
"in",
"l",
":",
"if",
"isinstance",
"(",
"el",
",",
"collections",
".",
"Iterable",
")",
"and",
"not",
"isinstance",
"(",
"el",
",",
"string_types",
")",
":",
"for",
"sub",
"in",
"flatten",
"(",
"el",
")",
":",
"yield",
"sub",
"else",
":",
"yield",
"el"
] | Flatten an iterable. | [
"Flatten",
"an",
"iterable",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L20-L27 | train | 238,669 |
tyarkoni/pliers | pliers/utils/base.py | set_iterable_type | def set_iterable_type(obj):
''' Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. '''
if not isiterable(obj):
return obj
if config.get_option('use_generators'):
return obj if isgenerator(obj) else (i for i in obj)
else:
return [set_iterable_type(i) for i in obj] | python | def set_iterable_type(obj):
''' Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. '''
if not isiterable(obj):
return obj
if config.get_option('use_generators'):
return obj if isgenerator(obj) else (i for i in obj)
else:
return [set_iterable_type(i) for i in obj] | [
"def",
"set_iterable_type",
"(",
"obj",
")",
":",
"if",
"not",
"isiterable",
"(",
"obj",
")",
":",
"return",
"obj",
"if",
"config",
".",
"get_option",
"(",
"'use_generators'",
")",
":",
"return",
"obj",
"if",
"isgenerator",
"(",
"obj",
")",
"else",
"(",
"i",
"for",
"i",
"in",
"obj",
")",
"else",
":",
"return",
"[",
"set_iterable_type",
"(",
"i",
")",
"for",
"i",
"in",
"obj",
"]"
] | Returns either a generator or a list depending on config-level
settings. Should be used to wrap almost every internal iterable return.
Also inspects elements recursively in the case of list returns, to
ensure that there are no nested generators. | [
"Returns",
"either",
"a",
"generator",
"or",
"a",
"list",
"depending",
"on",
"config",
"-",
"level",
"settings",
".",
"Should",
"be",
"used",
"to",
"wrap",
"almost",
"every",
"internal",
"iterable",
"return",
".",
"Also",
"inspects",
"elements",
"recursively",
"in",
"the",
"case",
"of",
"list",
"returns",
"to",
"ensure",
"that",
"there",
"are",
"no",
"nested",
"generators",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L55-L66 | train | 238,670 |
tyarkoni/pliers | pliers/utils/base.py | isgenerator | def isgenerator(obj):
''' Returns True if object is a generator, or a generator wrapped by a
tqdm object. '''
return isinstance(obj, GeneratorType) or (hasattr(obj, 'iterable') and
isinstance(getattr(obj, 'iterable'), GeneratorType)) | python | def isgenerator(obj):
''' Returns True if object is a generator, or a generator wrapped by a
tqdm object. '''
return isinstance(obj, GeneratorType) or (hasattr(obj, 'iterable') and
isinstance(getattr(obj, 'iterable'), GeneratorType)) | [
"def",
"isgenerator",
"(",
"obj",
")",
":",
"return",
"isinstance",
"(",
"obj",
",",
"GeneratorType",
")",
"or",
"(",
"hasattr",
"(",
"obj",
",",
"'iterable'",
")",
"and",
"isinstance",
"(",
"getattr",
"(",
"obj",
",",
"'iterable'",
")",
",",
"GeneratorType",
")",
")"
] | Returns True if object is a generator, or a generator wrapped by a
tqdm object. | [
"Returns",
"True",
"if",
"object",
"is",
"a",
"generator",
"or",
"a",
"generator",
"wrapped",
"by",
"a",
"tqdm",
"object",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L85-L89 | train | 238,671 |
tyarkoni/pliers | pliers/utils/base.py | progress_bar_wrapper | def progress_bar_wrapper(iterable, **kwargs):
''' Wrapper that applies tqdm progress bar conditional on config settings.
'''
return tqdm(iterable, **kwargs) if (config.get_option('progress_bar')
and not isinstance(iterable, tqdm)) else iterable | python | def progress_bar_wrapper(iterable, **kwargs):
''' Wrapper that applies tqdm progress bar conditional on config settings.
'''
return tqdm(iterable, **kwargs) if (config.get_option('progress_bar')
and not isinstance(iterable, tqdm)) else iterable | [
"def",
"progress_bar_wrapper",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
":",
"return",
"tqdm",
"(",
"iterable",
",",
"*",
"*",
"kwargs",
")",
"if",
"(",
"config",
".",
"get_option",
"(",
"'progress_bar'",
")",
"and",
"not",
"isinstance",
"(",
"iterable",
",",
"tqdm",
")",
")",
"else",
"iterable"
] | Wrapper that applies tqdm progress bar conditional on config settings. | [
"Wrapper",
"that",
"applies",
"tqdm",
"progress",
"bar",
"conditional",
"on",
"config",
"settings",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/base.py#L92-L96 | train | 238,672 |
tyarkoni/pliers | pliers/stimuli/video.py | VideoFrameCollectionStim.get_frame | def get_frame(self, index):
''' Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame.
'''
frame_num = self.frame_index[index]
onset = float(frame_num) / self.fps
if index < self.n_frames - 1:
next_frame_num = self.frame_index[index + 1]
end = float(next_frame_num) / self.fps
else:
end = float(self.duration)
duration = end - onset if end > onset else 0.0
return VideoFrameStim(self, frame_num,
data=self.clip.get_frame(onset),
duration=duration) | python | def get_frame(self, index):
''' Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame.
'''
frame_num = self.frame_index[index]
onset = float(frame_num) / self.fps
if index < self.n_frames - 1:
next_frame_num = self.frame_index[index + 1]
end = float(next_frame_num) / self.fps
else:
end = float(self.duration)
duration = end - onset if end > onset else 0.0
return VideoFrameStim(self, frame_num,
data=self.clip.get_frame(onset),
duration=duration) | [
"def",
"get_frame",
"(",
"self",
",",
"index",
")",
":",
"frame_num",
"=",
"self",
".",
"frame_index",
"[",
"index",
"]",
"onset",
"=",
"float",
"(",
"frame_num",
")",
"/",
"self",
".",
"fps",
"if",
"index",
"<",
"self",
".",
"n_frames",
"-",
"1",
":",
"next_frame_num",
"=",
"self",
".",
"frame_index",
"[",
"index",
"+",
"1",
"]",
"end",
"=",
"float",
"(",
"next_frame_num",
")",
"/",
"self",
".",
"fps",
"else",
":",
"end",
"=",
"float",
"(",
"self",
".",
"duration",
")",
"duration",
"=",
"end",
"-",
"onset",
"if",
"end",
">",
"onset",
"else",
"0.0",
"return",
"VideoFrameStim",
"(",
"self",
",",
"frame_num",
",",
"data",
"=",
"self",
".",
"clip",
".",
"get_frame",
"(",
"onset",
")",
",",
"duration",
"=",
"duration",
")"
] | Get video frame at the specified index.
Args:
index (int): Positional index of the desired frame. | [
"Get",
"video",
"frame",
"at",
"the",
"specified",
"index",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L94-L114 | train | 238,673 |
tyarkoni/pliers | pliers/stimuli/video.py | VideoFrameCollectionStim.save | def save(self, path):
''' Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
'''
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile(path, audio_fps=self.clip.audio.fps) | python | def save(self, path):
''' Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames.
'''
# IMPORTANT WARNING: saves entire source video
self.clip.write_videofile(path, audio_fps=self.clip.audio.fps) | [
"def",
"save",
"(",
"self",
",",
"path",
")",
":",
"# IMPORTANT WARNING: saves entire source video",
"self",
".",
"clip",
".",
"write_videofile",
"(",
"path",
",",
"audio_fps",
"=",
"self",
".",
"clip",
".",
"audio",
".",
"fps",
")"
] | Save source video to file.
Args:
path (str): Filename to save to.
Notes: Saves entire source video to file, not just currently selected
frames. | [
"Save",
"source",
"video",
"to",
"file",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L125-L135 | train | 238,674 |
tyarkoni/pliers | pliers/stimuli/video.py | VideoStim.get_frame | def get_frame(self, index=None, onset=None):
''' Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame.
'''
if onset:
index = int(onset * self.fps)
return super(VideoStim, self).get_frame(index) | python | def get_frame(self, index=None, onset=None):
''' Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame.
'''
if onset:
index = int(onset * self.fps)
return super(VideoStim, self).get_frame(index) | [
"def",
"get_frame",
"(",
"self",
",",
"index",
"=",
"None",
",",
"onset",
"=",
"None",
")",
":",
"if",
"onset",
":",
"index",
"=",
"int",
"(",
"onset",
"*",
"self",
".",
"fps",
")",
"return",
"super",
"(",
"VideoStim",
",",
"self",
")",
".",
"get_frame",
"(",
"index",
")"
] | Overrides the default behavior by giving access to the onset
argument.
Args:
index (int): Positional index of the desired frame.
onset (float): Onset (in seconds) of the desired frame. | [
"Overrides",
"the",
"default",
"behavior",
"by",
"giving",
"access",
"to",
"the",
"onset",
"argument",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/stimuli/video.py#L159-L170 | train | 238,675 |
tyarkoni/pliers | pliers/utils/updater.py | hash_data | def hash_data(data, blocksize=65536):
"""" Hashes list of data, strings or data """
data = pickle.dumps(data)
hasher = hashlib.sha1()
hasher.update(data)
return hasher.hexdigest() | python | def hash_data(data, blocksize=65536):
"""" Hashes list of data, strings or data """
data = pickle.dumps(data)
hasher = hashlib.sha1()
hasher.update(data)
return hasher.hexdigest() | [
"def",
"hash_data",
"(",
"data",
",",
"blocksize",
"=",
"65536",
")",
":",
"data",
"=",
"pickle",
".",
"dumps",
"(",
"data",
")",
"hasher",
"=",
"hashlib",
".",
"sha1",
"(",
")",
"hasher",
".",
"update",
"(",
"data",
")",
"return",
"hasher",
".",
"hexdigest",
"(",
")"
] | Hashes list of data, strings or data | [
"Hashes",
"list",
"of",
"data",
"strings",
"or",
"data"
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/updater.py#L13-L20 | train | 238,676 |
tyarkoni/pliers | pliers/utils/updater.py | check_updates | def check_updates(transformers, datastore=None, stimuli=None):
""" Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data.
"""
# Find datastore file
datastore = datastore or expanduser('~/.pliers_updates')
prior_data = pd.read_csv(datastore) if exists(datastore) else None
# Load stimuli
stimuli = stimuli or glob.glob(
join(dirname(realpath(__file__)), '../tests/data/image/CC0/*'))
stimuli = load_stims(stimuli)
# Get transformers
loaded_transformers = {get_transformer(name, **params): (name, params)
for name, params in transformers}
# Transform stimuli
results = pd.DataFrame({'time_extracted': [datetime.datetime.now()]})
for trans in loaded_transformers.keys():
for stim in stimuli:
if trans._stim_matches_input_types(stim):
res = trans.transform(stim)
try: # Add iterable
res = [getattr(res, '_data', res.data) for r in res]
except TypeError:
res = getattr(res, '_data', res.data)
res = hash_data(res)
results["{}.{}".format(trans.__hash__(), stim.name)] = [res]
# Check for mismatches
mismatches = []
if prior_data is not None:
last = prior_data[
prior_data.time_extracted == prior_data.time_extracted.max()]. \
iloc[0].drop('time_extracted')
for label, value in results.iteritems():
old = last.get(label)
new = value.values[0]
if old is not None:
if isinstance(new, str):
if new != old:
mismatches.append(label)
elif not np.isclose(old, new):
mismatches.append(label)
results = prior_data.append(results)
results.to_csv(datastore, index=False)
# Get corresponding transformer name and parameters
def get_trans(hash_tr):
for obj, attr in loaded_transformers.items():
if str(obj.__hash__()) == hash_tr:
return attr
delta_t = set([m.split('.')[0] for m in mismatches])
delta_t = [get_trans(dt) for dt in delta_t]
return {'transformers': delta_t, 'mismatches': mismatches} | python | def check_updates(transformers, datastore=None, stimuli=None):
""" Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data.
"""
# Find datastore file
datastore = datastore or expanduser('~/.pliers_updates')
prior_data = pd.read_csv(datastore) if exists(datastore) else None
# Load stimuli
stimuli = stimuli or glob.glob(
join(dirname(realpath(__file__)), '../tests/data/image/CC0/*'))
stimuli = load_stims(stimuli)
# Get transformers
loaded_transformers = {get_transformer(name, **params): (name, params)
for name, params in transformers}
# Transform stimuli
results = pd.DataFrame({'time_extracted': [datetime.datetime.now()]})
for trans in loaded_transformers.keys():
for stim in stimuli:
if trans._stim_matches_input_types(stim):
res = trans.transform(stim)
try: # Add iterable
res = [getattr(res, '_data', res.data) for r in res]
except TypeError:
res = getattr(res, '_data', res.data)
res = hash_data(res)
results["{}.{}".format(trans.__hash__(), stim.name)] = [res]
# Check for mismatches
mismatches = []
if prior_data is not None:
last = prior_data[
prior_data.time_extracted == prior_data.time_extracted.max()]. \
iloc[0].drop('time_extracted')
for label, value in results.iteritems():
old = last.get(label)
new = value.values[0]
if old is not None:
if isinstance(new, str):
if new != old:
mismatches.append(label)
elif not np.isclose(old, new):
mismatches.append(label)
results = prior_data.append(results)
results.to_csv(datastore, index=False)
# Get corresponding transformer name and parameters
def get_trans(hash_tr):
for obj, attr in loaded_transformers.items():
if str(obj.__hash__()) == hash_tr:
return attr
delta_t = set([m.split('.')[0] for m in mismatches])
delta_t = [get_trans(dt) for dt in delta_t]
return {'transformers': delta_t, 'mismatches': mismatches} | [
"def",
"check_updates",
"(",
"transformers",
",",
"datastore",
"=",
"None",
",",
"stimuli",
"=",
"None",
")",
":",
"# Find datastore file",
"datastore",
"=",
"datastore",
"or",
"expanduser",
"(",
"'~/.pliers_updates'",
")",
"prior_data",
"=",
"pd",
".",
"read_csv",
"(",
"datastore",
")",
"if",
"exists",
"(",
"datastore",
")",
"else",
"None",
"# Load stimuli",
"stimuli",
"=",
"stimuli",
"or",
"glob",
".",
"glob",
"(",
"join",
"(",
"dirname",
"(",
"realpath",
"(",
"__file__",
")",
")",
",",
"'../tests/data/image/CC0/*'",
")",
")",
"stimuli",
"=",
"load_stims",
"(",
"stimuli",
")",
"# Get transformers",
"loaded_transformers",
"=",
"{",
"get_transformer",
"(",
"name",
",",
"*",
"*",
"params",
")",
":",
"(",
"name",
",",
"params",
")",
"for",
"name",
",",
"params",
"in",
"transformers",
"}",
"# Transform stimuli",
"results",
"=",
"pd",
".",
"DataFrame",
"(",
"{",
"'time_extracted'",
":",
"[",
"datetime",
".",
"datetime",
".",
"now",
"(",
")",
"]",
"}",
")",
"for",
"trans",
"in",
"loaded_transformers",
".",
"keys",
"(",
")",
":",
"for",
"stim",
"in",
"stimuli",
":",
"if",
"trans",
".",
"_stim_matches_input_types",
"(",
"stim",
")",
":",
"res",
"=",
"trans",
".",
"transform",
"(",
"stim",
")",
"try",
":",
"# Add iterable",
"res",
"=",
"[",
"getattr",
"(",
"res",
",",
"'_data'",
",",
"res",
".",
"data",
")",
"for",
"r",
"in",
"res",
"]",
"except",
"TypeError",
":",
"res",
"=",
"getattr",
"(",
"res",
",",
"'_data'",
",",
"res",
".",
"data",
")",
"res",
"=",
"hash_data",
"(",
"res",
")",
"results",
"[",
"\"{}.{}\"",
".",
"format",
"(",
"trans",
".",
"__hash__",
"(",
")",
",",
"stim",
".",
"name",
")",
"]",
"=",
"[",
"res",
"]",
"# Check for mismatches",
"mismatches",
"=",
"[",
"]",
"if",
"prior_data",
"is",
"not",
"None",
":",
"last",
"=",
"prior_data",
"[",
"prior_data",
".",
"time_extracted",
"==",
"prior_data",
".",
"time_extracted",
".",
"max",
"(",
")",
"]",
".",
"iloc",
"[",
"0",
"]",
".",
"drop",
"(",
"'time_extracted'",
")",
"for",
"label",
",",
"value",
"in",
"results",
".",
"iteritems",
"(",
")",
":",
"old",
"=",
"last",
".",
"get",
"(",
"label",
")",
"new",
"=",
"value",
".",
"values",
"[",
"0",
"]",
"if",
"old",
"is",
"not",
"None",
":",
"if",
"isinstance",
"(",
"new",
",",
"str",
")",
":",
"if",
"new",
"!=",
"old",
":",
"mismatches",
".",
"append",
"(",
"label",
")",
"elif",
"not",
"np",
".",
"isclose",
"(",
"old",
",",
"new",
")",
":",
"mismatches",
".",
"append",
"(",
"label",
")",
"results",
"=",
"prior_data",
".",
"append",
"(",
"results",
")",
"results",
".",
"to_csv",
"(",
"datastore",
",",
"index",
"=",
"False",
")",
"# Get corresponding transformer name and parameters",
"def",
"get_trans",
"(",
"hash_tr",
")",
":",
"for",
"obj",
",",
"attr",
"in",
"loaded_transformers",
".",
"items",
"(",
")",
":",
"if",
"str",
"(",
"obj",
".",
"__hash__",
"(",
")",
")",
"==",
"hash_tr",
":",
"return",
"attr",
"delta_t",
"=",
"set",
"(",
"[",
"m",
".",
"split",
"(",
"'.'",
")",
"[",
"0",
"]",
"for",
"m",
"in",
"mismatches",
"]",
")",
"delta_t",
"=",
"[",
"get_trans",
"(",
"dt",
")",
"for",
"dt",
"in",
"delta_t",
"]",
"return",
"{",
"'transformers'",
":",
"delta_t",
",",
"'mismatches'",
":",
"mismatches",
"}"
] | Run transformers through a battery of stimuli, and check if output has
changed. Store results in csv file for comparison.
Args:
transformers (list): A list of tuples of transformer names and
dictionary of parameters to instantiate with (or empty dict).
datastore (str): Filepath of CSV file with results. Stored in home dir
by default.
stimuli (list): List of stimuli file paths to extract from. If None,
use test data. | [
"Run",
"transformers",
"through",
"a",
"battery",
"of",
"stimuli",
"and",
"check",
"if",
"output",
"has",
"changed",
".",
"Store",
"results",
"in",
"csv",
"file",
"for",
"comparison",
"."
] | 5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b | https://github.com/tyarkoni/pliers/blob/5b3385960ebd8c6ef1e86dd5e1be0080b2cb7f2b/pliers/utils/updater.py#L23-L95 | train | 238,677 |
open-homeautomation/miflora | demo.py | scan | def scan(args):
"""Scan for sensors."""
backend = _get_backend(args)
print('Scanning for 10 seconds...')
devices = miflora_scanner.scan(backend, 10)
print('Found {} devices:'.format(len(devices)))
for device in devices:
print(' {}'.format(device)) | python | def scan(args):
"""Scan for sensors."""
backend = _get_backend(args)
print('Scanning for 10 seconds...')
devices = miflora_scanner.scan(backend, 10)
print('Found {} devices:'.format(len(devices)))
for device in devices:
print(' {}'.format(device)) | [
"def",
"scan",
"(",
"args",
")",
":",
"backend",
"=",
"_get_backend",
"(",
"args",
")",
"print",
"(",
"'Scanning for 10 seconds...'",
")",
"devices",
"=",
"miflora_scanner",
".",
"scan",
"(",
"backend",
",",
"10",
")",
"print",
"(",
"'Found {} devices:'",
".",
"format",
"(",
"len",
"(",
"devices",
")",
")",
")",
"for",
"device",
"in",
"devices",
":",
"print",
"(",
"' {}'",
".",
"format",
"(",
"device",
")",
")"
] | Scan for sensors. | [
"Scan",
"for",
"sensors",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L37-L44 | train | 238,678 |
open-homeautomation/miflora | demo.py | _get_backend | def _get_backend(args):
"""Extract the backend class from the command line arguments."""
if args.backend == 'gatttool':
backend = GatttoolBackend
elif args.backend == 'bluepy':
backend = BluepyBackend
elif args.backend == 'pygatt':
backend = PygattBackend
else:
raise Exception('unknown backend: {}'.format(args.backend))
return backend | python | def _get_backend(args):
"""Extract the backend class from the command line arguments."""
if args.backend == 'gatttool':
backend = GatttoolBackend
elif args.backend == 'bluepy':
backend = BluepyBackend
elif args.backend == 'pygatt':
backend = PygattBackend
else:
raise Exception('unknown backend: {}'.format(args.backend))
return backend | [
"def",
"_get_backend",
"(",
"args",
")",
":",
"if",
"args",
".",
"backend",
"==",
"'gatttool'",
":",
"backend",
"=",
"GatttoolBackend",
"elif",
"args",
".",
"backend",
"==",
"'bluepy'",
":",
"backend",
"=",
"BluepyBackend",
"elif",
"args",
".",
"backend",
"==",
"'pygatt'",
":",
"backend",
"=",
"PygattBackend",
"else",
":",
"raise",
"Exception",
"(",
"'unknown backend: {}'",
".",
"format",
"(",
"args",
".",
"backend",
")",
")",
"return",
"backend"
] | Extract the backend class from the command line arguments. | [
"Extract",
"the",
"backend",
"class",
"from",
"the",
"command",
"line",
"arguments",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L47-L57 | train | 238,679 |
open-homeautomation/miflora | demo.py | list_backends | def list_backends(_):
"""List all available backends."""
backends = [b.__name__ for b in available_backends()]
print('\n'.join(backends)) | python | def list_backends(_):
"""List all available backends."""
backends = [b.__name__ for b in available_backends()]
print('\n'.join(backends)) | [
"def",
"list_backends",
"(",
"_",
")",
":",
"backends",
"=",
"[",
"b",
".",
"__name__",
"for",
"b",
"in",
"available_backends",
"(",
")",
"]",
"print",
"(",
"'\\n'",
".",
"join",
"(",
"backends",
")",
")"
] | List all available backends. | [
"List",
"all",
"available",
"backends",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/demo.py#L60-L63 | train | 238,680 |
open-homeautomation/miflora | miflora/miflora_scanner.py | scan | def scan(backend, timeout=10):
"""Scan for miflora devices.
Note: this must be run as root!
"""
result = []
for (mac, name) in backend.scan_for_devices(timeout):
if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \
mac is not None and mac.upper().startswith(DEVICE_PREFIX):
result.append(mac.upper())
return result | python | def scan(backend, timeout=10):
"""Scan for miflora devices.
Note: this must be run as root!
"""
result = []
for (mac, name) in backend.scan_for_devices(timeout):
if (name is not None and name.lower() in VALID_DEVICE_NAMES) or \
mac is not None and mac.upper().startswith(DEVICE_PREFIX):
result.append(mac.upper())
return result | [
"def",
"scan",
"(",
"backend",
",",
"timeout",
"=",
"10",
")",
":",
"result",
"=",
"[",
"]",
"for",
"(",
"mac",
",",
"name",
")",
"in",
"backend",
".",
"scan_for_devices",
"(",
"timeout",
")",
":",
"if",
"(",
"name",
"is",
"not",
"None",
"and",
"name",
".",
"lower",
"(",
")",
"in",
"VALID_DEVICE_NAMES",
")",
"or",
"mac",
"is",
"not",
"None",
"and",
"mac",
".",
"upper",
"(",
")",
".",
"startswith",
"(",
"DEVICE_PREFIX",
")",
":",
"result",
".",
"append",
"(",
"mac",
".",
"upper",
"(",
")",
")",
"return",
"result"
] | Scan for miflora devices.
Note: this must be run as root! | [
"Scan",
"for",
"miflora",
"devices",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_scanner.py#L10-L20 | train | 238,681 |
open-homeautomation/miflora | miflora/miflora_poller.py | MiFloraPoller.parameter_value | def parameter_value(self, parameter, read_cached=True):
"""Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter.
"""
# Special handling for battery attribute
if parameter == MI_BATTERY:
return self.battery_level()
# Use the lock to make sure the cache isn't updated multiple times
with self.lock:
if (read_cached is False) or \
(self._last_read is None) or \
(datetime.now() - self._cache_timeout > self._last_read):
self.fill_cache()
else:
_LOGGER.debug("Using cache (%s < %s)",
datetime.now() - self._last_read,
self._cache_timeout)
if self.cache_available() and (len(self._cache) == 16):
return self._parse_data()[parameter]
else:
raise BluetoothBackendException("Could not read data from Mi Flora sensor %s" % self._mac) | python | def parameter_value(self, parameter, read_cached=True):
"""Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter.
"""
# Special handling for battery attribute
if parameter == MI_BATTERY:
return self.battery_level()
# Use the lock to make sure the cache isn't updated multiple times
with self.lock:
if (read_cached is False) or \
(self._last_read is None) or \
(datetime.now() - self._cache_timeout > self._last_read):
self.fill_cache()
else:
_LOGGER.debug("Using cache (%s < %s)",
datetime.now() - self._last_read,
self._cache_timeout)
if self.cache_available() and (len(self._cache) == 16):
return self._parse_data()[parameter]
else:
raise BluetoothBackendException("Could not read data from Mi Flora sensor %s" % self._mac) | [
"def",
"parameter_value",
"(",
"self",
",",
"parameter",
",",
"read_cached",
"=",
"True",
")",
":",
"# Special handling for battery attribute",
"if",
"parameter",
"==",
"MI_BATTERY",
":",
"return",
"self",
".",
"battery_level",
"(",
")",
"# Use the lock to make sure the cache isn't updated multiple times",
"with",
"self",
".",
"lock",
":",
"if",
"(",
"read_cached",
"is",
"False",
")",
"or",
"(",
"self",
".",
"_last_read",
"is",
"None",
")",
"or",
"(",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_cache_timeout",
">",
"self",
".",
"_last_read",
")",
":",
"self",
".",
"fill_cache",
"(",
")",
"else",
":",
"_LOGGER",
".",
"debug",
"(",
"\"Using cache (%s < %s)\"",
",",
"datetime",
".",
"now",
"(",
")",
"-",
"self",
".",
"_last_read",
",",
"self",
".",
"_cache_timeout",
")",
"if",
"self",
".",
"cache_available",
"(",
")",
"and",
"(",
"len",
"(",
"self",
".",
"_cache",
")",
"==",
"16",
")",
":",
"return",
"self",
".",
"_parse_data",
"(",
")",
"[",
"parameter",
"]",
"else",
":",
"raise",
"BluetoothBackendException",
"(",
"\"Could not read data from Mi Flora sensor %s\"",
"%",
"self",
".",
"_mac",
")"
] | Return a value of one of the monitored paramaters.
This method will try to retrieve the data from cache and only
request it by bluetooth if no cached value is stored or the cache is
expired.
This behaviour can be overwritten by the "read_cached" parameter. | [
"Return",
"a",
"value",
"of",
"one",
"of",
"the",
"monitored",
"paramaters",
"."
] | 916606e7edc70bdc017dfbe681bc81771e0df7f3 | https://github.com/open-homeautomation/miflora/blob/916606e7edc70bdc017dfbe681bc81771e0df7f3/miflora/miflora_poller.py#L115-L141 | train | 238,682 |
halcy/Mastodon.py | mastodon/Mastodon.py | parse_version_string | def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
version_parts = [
int(re.match("([0-9]*)", string_parts[0]).group(0)),
int(re.match("([0-9]*)", string_parts[1]).group(0)),
int(re.match("([0-9]*)", string_parts[2]).group(0))
]
return version_parts | python | def parse_version_string(version_string):
"""Parses a semver version string, stripping off "rc" stuff if present."""
string_parts = version_string.split(".")
version_parts = [
int(re.match("([0-9]*)", string_parts[0]).group(0)),
int(re.match("([0-9]*)", string_parts[1]).group(0)),
int(re.match("([0-9]*)", string_parts[2]).group(0))
]
return version_parts | [
"def",
"parse_version_string",
"(",
"version_string",
")",
":",
"string_parts",
"=",
"version_string",
".",
"split",
"(",
"\".\"",
")",
"version_parts",
"=",
"[",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"0",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
",",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"1",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
",",
"int",
"(",
"re",
".",
"match",
"(",
"\"([0-9]*)\"",
",",
"string_parts",
"[",
"2",
"]",
")",
".",
"group",
"(",
"0",
")",
")",
"]",
"return",
"version_parts"
] | Parses a semver version string, stripping off "rc" stuff if present. | [
"Parses",
"a",
"semver",
"version",
"string",
"stripping",
"off",
"rc",
"stuff",
"if",
"present",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L42-L50 | train | 238,683 |
halcy/Mastodon.py | mastodon/Mastodon.py | bigger_version | def bigger_version(version_string_a, version_string_b):
"""Returns the bigger version of two version strings."""
major_a, minor_a, patch_a = parse_version_string(version_string_a)
major_b, minor_b, patch_b = parse_version_string(version_string_b)
if major_a > major_b:
return version_string_a
elif major_a == major_b and minor_a > minor_b:
return version_string_a
elif major_a == major_b and minor_a == minor_b and patch_a > patch_b:
return version_string_a
return version_string_b | python | def bigger_version(version_string_a, version_string_b):
"""Returns the bigger version of two version strings."""
major_a, minor_a, patch_a = parse_version_string(version_string_a)
major_b, minor_b, patch_b = parse_version_string(version_string_b)
if major_a > major_b:
return version_string_a
elif major_a == major_b and minor_a > minor_b:
return version_string_a
elif major_a == major_b and minor_a == minor_b and patch_a > patch_b:
return version_string_a
return version_string_b | [
"def",
"bigger_version",
"(",
"version_string_a",
",",
"version_string_b",
")",
":",
"major_a",
",",
"minor_a",
",",
"patch_a",
"=",
"parse_version_string",
"(",
"version_string_a",
")",
"major_b",
",",
"minor_b",
",",
"patch_b",
"=",
"parse_version_string",
"(",
"version_string_b",
")",
"if",
"major_a",
">",
"major_b",
":",
"return",
"version_string_a",
"elif",
"major_a",
"==",
"major_b",
"and",
"minor_a",
">",
"minor_b",
":",
"return",
"version_string_a",
"elif",
"major_a",
"==",
"major_b",
"and",
"minor_a",
"==",
"minor_b",
"and",
"patch_a",
">",
"patch_b",
":",
"return",
"version_string_a",
"return",
"version_string_b"
] | Returns the bigger version of two version strings. | [
"Returns",
"the",
"bigger",
"version",
"of",
"two",
"version",
"strings",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L52-L63 | train | 238,684 |
halcy/Mastodon.py | mastodon/Mastodon.py | api_version | def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.version_check_mode == "created":
version = created_ver
else:
version = bigger_version(last_changed_ver, return_value_ver)
major, minor, patch = parse_version_string(version)
if major > self.mastodon_major:
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor > self.mastodon_minor:
print(self.mastodon_minor)
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")")
return function(self, *args, **kwargs)
function.__doc__ = function.__doc__ + "\n\n *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*"
return decorate(function, wrapper)
return api_min_version_decorator | python | def api_version(created_ver, last_changed_ver, return_value_ver):
"""Version check decorator. Currently only checks Bigger Than."""
def api_min_version_decorator(function):
def wrapper(function, self, *args, **kwargs):
if not self.version_check_mode == "none":
if self.version_check_mode == "created":
version = created_ver
else:
version = bigger_version(last_changed_ver, return_value_ver)
major, minor, patch = parse_version_string(version)
if major > self.mastodon_major:
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor > self.mastodon_minor:
print(self.mastodon_minor)
raise MastodonVersionError("Version check failed (Need version " + version + ")")
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
raise MastodonVersionError("Version check failed (Need version " + version + ", patch is " + str(self.mastodon_patch) + ")")
return function(self, *args, **kwargs)
function.__doc__ = function.__doc__ + "\n\n *Added: Mastodon v" + created_ver + ", last changed: Mastodon v" + last_changed_ver + "*"
return decorate(function, wrapper)
return api_min_version_decorator | [
"def",
"api_version",
"(",
"created_ver",
",",
"last_changed_ver",
",",
"return_value_ver",
")",
":",
"def",
"api_min_version_decorator",
"(",
"function",
")",
":",
"def",
"wrapper",
"(",
"function",
",",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"not",
"self",
".",
"version_check_mode",
"==",
"\"none\"",
":",
"if",
"self",
".",
"version_check_mode",
"==",
"\"created\"",
":",
"version",
"=",
"created_ver",
"else",
":",
"version",
"=",
"bigger_version",
"(",
"last_changed_ver",
",",
"return_value_ver",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"parse_version_string",
"(",
"version",
")",
"if",
"major",
">",
"self",
".",
"mastodon_major",
":",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\")\"",
")",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
">",
"self",
".",
"mastodon_minor",
":",
"print",
"(",
"self",
".",
"mastodon_minor",
")",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\")\"",
")",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
"==",
"self",
".",
"mastodon_minor",
"and",
"patch",
">",
"self",
".",
"mastodon_patch",
":",
"raise",
"MastodonVersionError",
"(",
"\"Version check failed (Need version \"",
"+",
"version",
"+",
"\", patch is \"",
"+",
"str",
"(",
"self",
".",
"mastodon_patch",
")",
"+",
"\")\"",
")",
"return",
"function",
"(",
"self",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"function",
".",
"__doc__",
"=",
"function",
".",
"__doc__",
"+",
"\"\\n\\n *Added: Mastodon v\"",
"+",
"created_ver",
"+",
"\", last changed: Mastodon v\"",
"+",
"last_changed_ver",
"+",
"\"*\"",
"return",
"decorate",
"(",
"function",
",",
"wrapper",
")",
"return",
"api_min_version_decorator"
] | Version check decorator. Currently only checks Bigger Than. | [
"Version",
"check",
"decorator",
".",
"Currently",
"only",
"checks",
"Bigger",
"Than",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L65-L85 | train | 238,685 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.verify_minimum_version | def verify_minimum_version(self, version_str):
"""
Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not.
"""
self.retrieve_mastodon_version()
major, minor, patch = parse_version_string(version_str)
if major > self.mastodon_major:
return False
elif major == self.mastodon_major and minor > self.mastodon_minor:
return False
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
return False
return True | python | def verify_minimum_version(self, version_str):
"""
Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not.
"""
self.retrieve_mastodon_version()
major, minor, patch = parse_version_string(version_str)
if major > self.mastodon_major:
return False
elif major == self.mastodon_major and minor > self.mastodon_minor:
return False
elif major == self.mastodon_major and minor == self.mastodon_minor and patch > self.mastodon_patch:
return False
return True | [
"def",
"verify_minimum_version",
"(",
"self",
",",
"version_str",
")",
":",
"self",
".",
"retrieve_mastodon_version",
"(",
")",
"major",
",",
"minor",
",",
"patch",
"=",
"parse_version_string",
"(",
"version_str",
")",
"if",
"major",
">",
"self",
".",
"mastodon_major",
":",
"return",
"False",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
">",
"self",
".",
"mastodon_minor",
":",
"return",
"False",
"elif",
"major",
"==",
"self",
".",
"mastodon_major",
"and",
"minor",
"==",
"self",
".",
"mastodon_minor",
"and",
"patch",
">",
"self",
".",
"mastodon_patch",
":",
"return",
"False",
"return",
"True"
] | Update version info from server and verify that at least the specified version is present.
Returns True if version requirement is satisfied, False if not. | [
"Update",
"version",
"info",
"from",
"server",
"and",
"verify",
"that",
"at",
"least",
"the",
"specified",
"version",
"is",
"present",
".",
"Returns",
"True",
"if",
"version",
"requirement",
"is",
"satisfied",
"False",
"if",
"not",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L359-L373 | train | 238,686 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.log_in | def log_in(self, username=None, password=None,
code=None, redirect_uri="urn:ietf:wg:oauth:2.0:oob", refresh_token=None,
scopes=__DEFAULT_SCOPES, to_file=None):
"""
Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string.
"""
if username is not None and password is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'code', 'refresh_token'])
params['grant_type'] = 'password'
elif code is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'refresh_token'])
params['grant_type'] = 'authorization_code'
elif refresh_token is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'code'])
params['grant_type'] = 'refresh_token'
else:
raise MastodonIllegalArgumentError('Invalid arguments given. username and password or code are required.')
params['client_id'] = self.client_id
params['client_secret'] = self.client_secret
params['scope'] = " ".join(scopes)
try:
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
self.__set_token_expired(int(response.get('expires_in', 0)))
except Exception as e:
if username is not None or password is not None:
raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e)
elif code is not None:
raise MastodonIllegalArgumentError('Invalid access token or redirect_uris: %s' % e)
else:
raise MastodonIllegalArgumentError('Invalid request: %s' % e)
received_scopes = response["scope"].split(" ")
for scope_set in self.__SCOPE_SETS.keys():
if scope_set in received_scopes:
received_scopes += self.__SCOPE_SETS[scope_set]
if not set(scopes) <= set(received_scopes):
raise MastodonAPIError(
'Granted scopes "' + " ".join(received_scopes) + '" do not contain all of the requested scopes "' + " ".join(scopes) + '".')
if to_file is not None:
with open(to_file, 'w') as token_file:
token_file.write(response['access_token'] + '\n')
self.__logged_in_id = None
return response['access_token'] | python | def log_in(self, username=None, password=None,
code=None, redirect_uri="urn:ietf:wg:oauth:2.0:oob", refresh_token=None,
scopes=__DEFAULT_SCOPES, to_file=None):
"""
Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string.
"""
if username is not None and password is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'code', 'refresh_token'])
params['grant_type'] = 'password'
elif code is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'refresh_token'])
params['grant_type'] = 'authorization_code'
elif refresh_token is not None:
params = self.__generate_params(locals(), ['scopes', 'to_file', 'username', 'password', 'code'])
params['grant_type'] = 'refresh_token'
else:
raise MastodonIllegalArgumentError('Invalid arguments given. username and password or code are required.')
params['client_id'] = self.client_id
params['client_secret'] = self.client_secret
params['scope'] = " ".join(scopes)
try:
response = self.__api_request('POST', '/oauth/token', params, do_ratelimiting=False)
self.access_token = response['access_token']
self.__set_refresh_token(response.get('refresh_token'))
self.__set_token_expired(int(response.get('expires_in', 0)))
except Exception as e:
if username is not None or password is not None:
raise MastodonIllegalArgumentError('Invalid user name, password, or redirect_uris: %s' % e)
elif code is not None:
raise MastodonIllegalArgumentError('Invalid access token or redirect_uris: %s' % e)
else:
raise MastodonIllegalArgumentError('Invalid request: %s' % e)
received_scopes = response["scope"].split(" ")
for scope_set in self.__SCOPE_SETS.keys():
if scope_set in received_scopes:
received_scopes += self.__SCOPE_SETS[scope_set]
if not set(scopes) <= set(received_scopes):
raise MastodonAPIError(
'Granted scopes "' + " ".join(received_scopes) + '" do not contain all of the requested scopes "' + " ".join(scopes) + '".')
if to_file is not None:
with open(to_file, 'w') as token_file:
token_file.write(response['access_token'] + '\n')
self.__logged_in_id = None
return response['access_token'] | [
"def",
"log_in",
"(",
"self",
",",
"username",
"=",
"None",
",",
"password",
"=",
"None",
",",
"code",
"=",
"None",
",",
"redirect_uri",
"=",
"\"urn:ietf:wg:oauth:2.0:oob\"",
",",
"refresh_token",
"=",
"None",
",",
"scopes",
"=",
"__DEFAULT_SCOPES",
",",
"to_file",
"=",
"None",
")",
":",
"if",
"username",
"is",
"not",
"None",
"and",
"password",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'code'",
",",
"'refresh_token'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'password'",
"elif",
"code",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'username'",
",",
"'password'",
",",
"'refresh_token'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'authorization_code'",
"elif",
"refresh_token",
"is",
"not",
"None",
":",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'scopes'",
",",
"'to_file'",
",",
"'username'",
",",
"'password'",
",",
"'code'",
"]",
")",
"params",
"[",
"'grant_type'",
"]",
"=",
"'refresh_token'",
"else",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid arguments given. username and password or code are required.'",
")",
"params",
"[",
"'client_id'",
"]",
"=",
"self",
".",
"client_id",
"params",
"[",
"'client_secret'",
"]",
"=",
"self",
".",
"client_secret",
"params",
"[",
"'scope'",
"]",
"=",
"\" \"",
".",
"join",
"(",
"scopes",
")",
"try",
":",
"response",
"=",
"self",
".",
"__api_request",
"(",
"'POST'",
",",
"'/oauth/token'",
",",
"params",
",",
"do_ratelimiting",
"=",
"False",
")",
"self",
".",
"access_token",
"=",
"response",
"[",
"'access_token'",
"]",
"self",
".",
"__set_refresh_token",
"(",
"response",
".",
"get",
"(",
"'refresh_token'",
")",
")",
"self",
".",
"__set_token_expired",
"(",
"int",
"(",
"response",
".",
"get",
"(",
"'expires_in'",
",",
"0",
")",
")",
")",
"except",
"Exception",
"as",
"e",
":",
"if",
"username",
"is",
"not",
"None",
"or",
"password",
"is",
"not",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid user name, password, or redirect_uris: %s'",
"%",
"e",
")",
"elif",
"code",
"is",
"not",
"None",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid access token or redirect_uris: %s'",
"%",
"e",
")",
"else",
":",
"raise",
"MastodonIllegalArgumentError",
"(",
"'Invalid request: %s'",
"%",
"e",
")",
"received_scopes",
"=",
"response",
"[",
"\"scope\"",
"]",
".",
"split",
"(",
"\" \"",
")",
"for",
"scope_set",
"in",
"self",
".",
"__SCOPE_SETS",
".",
"keys",
"(",
")",
":",
"if",
"scope_set",
"in",
"received_scopes",
":",
"received_scopes",
"+=",
"self",
".",
"__SCOPE_SETS",
"[",
"scope_set",
"]",
"if",
"not",
"set",
"(",
"scopes",
")",
"<=",
"set",
"(",
"received_scopes",
")",
":",
"raise",
"MastodonAPIError",
"(",
"'Granted scopes \"'",
"+",
"\" \"",
".",
"join",
"(",
"received_scopes",
")",
"+",
"'\" do not contain all of the requested scopes \"'",
"+",
"\" \"",
".",
"join",
"(",
"scopes",
")",
"+",
"'\".'",
")",
"if",
"to_file",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"to_file",
",",
"'w'",
")",
"as",
"token_file",
":",
"token_file",
".",
"write",
"(",
"response",
"[",
"'access_token'",
"]",
"+",
"'\\n'",
")",
"self",
".",
"__logged_in_id",
"=",
"None",
"return",
"response",
"[",
"'access_token'",
"]"
] | Get the access token for a user.
The username is the e-mail used to log in into mastodon.
Can persist access token to file `to_file`, to be used in the constructor.
Handles password and OAuth-based authorization.
Will throw a `MastodonIllegalArgumentError` if the OAuth or the
username / password credentials given are incorrect, and
`MastodonAPIError` if all of the requested scopes were not granted.
For OAuth2, obtain a code via having your user go to the url returned by
`auth_request_url()`_ and pass it as the code parameter. In this case,
make sure to also pass the same redirect_uri parameter as you used when
generating the auth request URL.
Returns the access token as a string. | [
"Get",
"the",
"access",
"token",
"for",
"a",
"user",
".",
"The",
"username",
"is",
"the",
"e",
"-",
"mail",
"used",
"to",
"log",
"in",
"into",
"mastodon",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L414-L481 | train | 238,687 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.timeline_list | def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_.
"""
id = self.__unpack_id(id)
return self.timeline('list/{0}'.format(id), max_id=max_id,
min_id=min_id, since_id=since_id, limit=limit) | python | def timeline_list(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_.
"""
id = self.__unpack_id(id)
return self.timeline('list/{0}'.format(id), max_id=max_id,
min_id=min_id, since_id=since_id, limit=limit) | [
"def",
"timeline_list",
"(",
"self",
",",
"id",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"return",
"self",
".",
"timeline",
"(",
"'list/{0}'",
".",
"format",
"(",
"id",
")",
",",
"max_id",
"=",
"max_id",
",",
"min_id",
"=",
"min_id",
",",
"since_id",
"=",
"since_id",
",",
"limit",
"=",
"limit",
")"
] | Fetches a timeline containing all the toots by users in a given list.
Returns a list of `toot dicts`_. | [
"Fetches",
"a",
"timeline",
"containing",
"all",
"the",
"toots",
"by",
"users",
"in",
"a",
"given",
"list",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L709-L717 | train | 238,688 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.conversations | def conversations(self, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a users conversations.
Returns a list of `conversation dicts`_.
"""
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals())
return self.__api_request('GET', "/api/v1/conversations/", params) | python | def conversations(self, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetches a users conversations.
Returns a list of `conversation dicts`_.
"""
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals())
return self.__api_request('GET', "/api/v1/conversations/", params) | [
"def",
"conversations",
"(",
"self",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"if",
"max_id",
"!=",
"None",
":",
"max_id",
"=",
"self",
".",
"__unpack_id",
"(",
"max_id",
")",
"if",
"min_id",
"!=",
"None",
":",
"min_id",
"=",
"self",
".",
"__unpack_id",
"(",
"min_id",
")",
"if",
"since_id",
"!=",
"None",
":",
"since_id",
"=",
"self",
".",
"__unpack_id",
"(",
"since_id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"\"/api/v1/conversations/\"",
",",
"params",
")"
] | Fetches a users conversations.
Returns a list of `conversation dicts`_. | [
"Fetches",
"a",
"users",
"conversations",
".",
"Returns",
"a",
"list",
"of",
"conversation",
"dicts",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L720-L736 | train | 238,689 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status | def status(self, id):
"""
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def status(self, id):
"""
Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about a single toot.
Does not require authentication for publicly visible statuses.
Returns a `toot dict`_. | [
"Fetch",
"information",
"about",
"a",
"single",
"toot",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L742-L752 | train | 238,690 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_context | def status_context(self, id):
"""
Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/context'.format(str(id))
return self.__api_request('GET', url) | python | def status_context(self, id):
"""
Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/context'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_context",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/context'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about ancestors and descendants of a toot.
Does not require authentication for publicly visible statuses.
Returns a `context dict`_. | [
"Fetch",
"information",
"about",
"ancestors",
"and",
"descendants",
"of",
"a",
"toot",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L769-L779 | train | 238,691 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_reblogged_by | def status_reblogged_by(self, id):
"""
Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/reblogged_by'.format(str(id))
return self.__api_request('GET', url) | python | def status_reblogged_by(self, id):
"""
Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/reblogged_by'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_reblogged_by",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/reblogged_by'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch a list of users that have reblogged a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_. | [
"Fetch",
"a",
"list",
"of",
"users",
"that",
"have",
"reblogged",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L782-L792 | train | 238,692 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.status_favourited_by | def status_favourited_by(self, id):
"""
Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourited_by'.format(str(id))
return self.__api_request('GET', url) | python | def status_favourited_by(self, id):
"""
Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/statuses/{0}/favourited_by'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"status_favourited_by",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/statuses/{0}/favourited_by'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch a list of users that have favourited a status.
Does not require authentication for publicly visible statuses.
Returns a list of `user dicts`_. | [
"Fetch",
"a",
"list",
"of",
"users",
"that",
"have",
"favourited",
"a",
"status",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L795-L805 | train | 238,693 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.scheduled_status | def scheduled_status(self, id):
"""
Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def scheduled_status(self, id):
"""
Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/scheduled_statuses/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"scheduled_status",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/scheduled_statuses/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about the scheduled status with the given id.
Returns a `scheduled toot dict`_. | [
"Fetch",
"information",
"about",
"the",
"scheduled",
"status",
"with",
"the",
"given",
"id",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L820-L828 | train | 238,694 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.poll | def poll(self, id):
"""
Fetch information about the poll with the given id
Returns a `poll dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/polls/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def poll(self, id):
"""
Fetch information about the poll with the given id
Returns a `poll dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/polls/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"poll",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/polls/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch information about the poll with the given id
Returns a `poll dict`_. | [
"Fetch",
"information",
"about",
"the",
"poll",
"with",
"the",
"given",
"id"
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L834-L842 | train | 238,695 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account | def account(self, id):
"""
Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def account(self, id):
"""
Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/accounts/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"account",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/accounts/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetch account information by user `id`.
Does not require authentication.
Returns a `user dict`_. | [
"Fetch",
"account",
"information",
"by",
"user",
"id",
".",
"Does",
"not",
"require",
"authentication",
".",
"Returns",
"a",
"user",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L878-L888 | train | 238,696 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_following | def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetch users the given user is following.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/following'.format(str(id))
return self.__api_request('GET', url, params) | python | def account_following(self, id, max_id=None, min_id=None, since_id=None, limit=None):
"""
Fetch users the given user is following.
Returns a list of `user dicts`_.
"""
id = self.__unpack_id(id)
if max_id != None:
max_id = self.__unpack_id(max_id)
if min_id != None:
min_id = self.__unpack_id(min_id)
if since_id != None:
since_id = self.__unpack_id(since_id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/following'.format(str(id))
return self.__api_request('GET', url, params) | [
"def",
"account_following",
"(",
"self",
",",
"id",
",",
"max_id",
"=",
"None",
",",
"min_id",
"=",
"None",
",",
"since_id",
"=",
"None",
",",
"limit",
"=",
"None",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"if",
"max_id",
"!=",
"None",
":",
"max_id",
"=",
"self",
".",
"__unpack_id",
"(",
"max_id",
")",
"if",
"min_id",
"!=",
"None",
":",
"min_id",
"=",
"self",
".",
"__unpack_id",
"(",
"min_id",
")",
"if",
"since_id",
"!=",
"None",
":",
"since_id",
"=",
"self",
".",
"__unpack_id",
"(",
"since_id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/following'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
",",
"params",
")"
] | Fetch users the given user is following.
Returns a list of `user dicts`_. | [
"Fetch",
"users",
"the",
"given",
"user",
"is",
"following",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L938-L956 | train | 238,697 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.account_lists | def account_lists(self, id):
"""
Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/lists'.format(str(id))
return self.__api_request('GET', url, params) | python | def account_lists(self, id):
"""
Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_.
"""
id = self.__unpack_id(id)
params = self.__generate_params(locals(), ['id'])
url = '/api/v1/accounts/{0}/lists'.format(str(id))
return self.__api_request('GET', url, params) | [
"def",
"account_lists",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"params",
"=",
"self",
".",
"__generate_params",
"(",
"locals",
"(",
")",
",",
"[",
"'id'",
"]",
")",
"url",
"=",
"'/api/v1/accounts/{0}/lists'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
",",
"params",
")"
] | Get all of the logged-in users lists which the specified user is
a member of.
Returns a list of `list dicts`_. | [
"Get",
"all",
"of",
"the",
"logged",
"-",
"in",
"users",
"lists",
"which",
"the",
"specified",
"user",
"is",
"a",
"member",
"of",
".",
"Returns",
"a",
"list",
"of",
"list",
"dicts",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1009-L1019 | train | 238,698 |
halcy/Mastodon.py | mastodon/Mastodon.py | Mastodon.filter | def filter(self, id):
"""
Fetches information about the filter with the specified `id`.
Returns a `filter dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
return self.__api_request('GET', url) | python | def filter(self, id):
"""
Fetches information about the filter with the specified `id`.
Returns a `filter dict`_.
"""
id = self.__unpack_id(id)
url = '/api/v1/filters/{0}'.format(str(id))
return self.__api_request('GET', url) | [
"def",
"filter",
"(",
"self",
",",
"id",
")",
":",
"id",
"=",
"self",
".",
"__unpack_id",
"(",
"id",
")",
"url",
"=",
"'/api/v1/filters/{0}'",
".",
"format",
"(",
"str",
"(",
"id",
")",
")",
"return",
"self",
".",
"__api_request",
"(",
"'GET'",
",",
"url",
")"
] | Fetches information about the filter with the specified `id`.
Returns a `filter dict`_. | [
"Fetches",
"information",
"about",
"the",
"filter",
"with",
"the",
"specified",
"id",
".",
"Returns",
"a",
"filter",
"dict",
"_",
"."
] | 35c43562dd3d34d6ebf7a0f757c09e8fcccc957c | https://github.com/halcy/Mastodon.py/blob/35c43562dd3d34d6ebf7a0f757c09e8fcccc957c/mastodon/Mastodon.py#L1034-L1042 | train | 238,699 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.