repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
| partition
stringclasses 1
value |
---|---|---|---|---|---|---|---|---|---|---|---|
Azure/azure-python-devtools | src/azure_devtools/ci_tools/bot_framework.py | BotHandler.orders | def orders(self):
"""Return method tagged "order" in the handler.
"""
return [order_cmd for order_cmd in dir(self.handler)
if getattr(getattr(self.handler, order_cmd), "bot_order", False)] | python | def orders(self):
"""Return method tagged "order" in the handler.
"""
return [order_cmd for order_cmd in dir(self.handler)
if getattr(getattr(self.handler, order_cmd), "bot_order", False)] | [
"def",
"orders",
"(",
"self",
")",
":",
"return",
"[",
"order_cmd",
"for",
"order_cmd",
"in",
"dir",
"(",
"self",
".",
"handler",
")",
"if",
"getattr",
"(",
"getattr",
"(",
"self",
".",
"handler",
",",
"order_cmd",
")",
",",
"\"bot_order\"",
",",
"False",
")",
"]"
] | Return method tagged "order" in the handler. | [
"Return",
"method",
"tagged",
"order",
"in",
"the",
"handler",
"."
] | 2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936 | https://github.com/Azure/azure-python-devtools/blob/2bf87b1f3cedd2b26fb2e4fd47a9baf435dcf936/src/azure_devtools/ci_tools/bot_framework.py#L80-L84 | train |
TkTech/Jawa | jawa/util/flags.py | Flags.set | def set(self, name, value):
"""
Sets the value of the field `name` to `value`, which is `True` or
`False`.
"""
flag = self.flags[name]
self._value = (self.value | flag) if value else (self.value & ~flag) | python | def set(self, name, value):
"""
Sets the value of the field `name` to `value`, which is `True` or
`False`.
"""
flag = self.flags[name]
self._value = (self.value | flag) if value else (self.value & ~flag) | [
"def",
"set",
"(",
"self",
",",
"name",
",",
"value",
")",
":",
"flag",
"=",
"self",
".",
"flags",
"[",
"name",
"]",
"self",
".",
"_value",
"=",
"(",
"self",
".",
"value",
"|",
"flag",
")",
"if",
"value",
"else",
"(",
"self",
".",
"value",
"&",
"~",
"flag",
")"
] | Sets the value of the field `name` to `value`, which is `True` or
`False`. | [
"Sets",
"the",
"value",
"of",
"the",
"field",
"name",
"to",
"value",
"which",
"is",
"True",
"or",
"False",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/flags.py#L40-L46 | train |
TkTech/Jawa | jawa/util/flags.py | Flags.to_dict | def to_dict(self):
"""
Returns this `Flags` object's fields as a dictionary.
"""
return dict((k, self.get(k)) for k in self.flags.keys()) | python | def to_dict(self):
"""
Returns this `Flags` object's fields as a dictionary.
"""
return dict((k, self.get(k)) for k in self.flags.keys()) | [
"def",
"to_dict",
"(",
"self",
")",
":",
"return",
"dict",
"(",
"(",
"k",
",",
"self",
".",
"get",
"(",
"k",
")",
")",
"for",
"k",
"in",
"self",
".",
"flags",
".",
"keys",
"(",
")",
")"
] | Returns this `Flags` object's fields as a dictionary. | [
"Returns",
"this",
"Flags",
"object",
"s",
"fields",
"as",
"a",
"dictionary",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/flags.py#L58-L62 | train |
piotr-rusin/spam-lists | spam_lists/host_collections.py | BaseHostCollection.add | def add(self, host_value):
"""Add the given value to the collection.
:param host: an ip address or a hostname
:raises InvalidHostError: raised when the given value
is not a valid ip address nor a hostname
"""
host_obj = self._host_factory(host_value)
if self._get_match(host_obj) is not None:
return
self._add_new(host_obj) | python | def add(self, host_value):
"""Add the given value to the collection.
:param host: an ip address or a hostname
:raises InvalidHostError: raised when the given value
is not a valid ip address nor a hostname
"""
host_obj = self._host_factory(host_value)
if self._get_match(host_obj) is not None:
return
self._add_new(host_obj) | [
"def",
"add",
"(",
"self",
",",
"host_value",
")",
":",
"host_obj",
"=",
"self",
".",
"_host_factory",
"(",
"host_value",
")",
"if",
"self",
".",
"_get_match",
"(",
"host_obj",
")",
"is",
"not",
"None",
":",
"return",
"self",
".",
"_add_new",
"(",
"host_obj",
")"
] | Add the given value to the collection.
:param host: an ip address or a hostname
:raises InvalidHostError: raised when the given value
is not a valid ip address nor a hostname | [
"Add",
"the",
"given",
"value",
"to",
"the",
"collection",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L64-L74 | train |
piotr-rusin/spam-lists | spam_lists/host_collections.py | SortedHostCollection._get_match | def _get_match(self, host_object):
"""Get an item matching the given host object.
The item may be either a parent domain or identical value.
Parent domains and existing identical values always precede
insertion point for given value - therefore, we treat
an item just before insertion point as potential match.
:param host_object: an object representing ip address
or hostname whose match we are trying to find
"""
i = self._get_insertion_point(host_object)
potential_match = None
try:
potential_match = self[i-1]
except IndexError:
pass
if host_object.is_match(potential_match):
return potential_match
return None | python | def _get_match(self, host_object):
"""Get an item matching the given host object.
The item may be either a parent domain or identical value.
Parent domains and existing identical values always precede
insertion point for given value - therefore, we treat
an item just before insertion point as potential match.
:param host_object: an object representing ip address
or hostname whose match we are trying to find
"""
i = self._get_insertion_point(host_object)
potential_match = None
try:
potential_match = self[i-1]
except IndexError:
pass
if host_object.is_match(potential_match):
return potential_match
return None | [
"def",
"_get_match",
"(",
"self",
",",
"host_object",
")",
":",
"i",
"=",
"self",
".",
"_get_insertion_point",
"(",
"host_object",
")",
"potential_match",
"=",
"None",
"try",
":",
"potential_match",
"=",
"self",
"[",
"i",
"-",
"1",
"]",
"except",
"IndexError",
":",
"pass",
"if",
"host_object",
".",
"is_match",
"(",
"potential_match",
")",
":",
"return",
"potential_match",
"return",
"None"
] | Get an item matching the given host object.
The item may be either a parent domain or identical value.
Parent domains and existing identical values always precede
insertion point for given value - therefore, we treat
an item just before insertion point as potential match.
:param host_object: an object representing ip address
or hostname whose match we are trying to find | [
"Get",
"an",
"item",
"matching",
"the",
"given",
"host",
"object",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L118-L138 | train |
piotr-rusin/spam-lists | spam_lists/host_collections.py | SortedHostCollection._add_new | def _add_new(self, host_object):
"""Add a new host to the collection.
Before a new hostname can be added, all its subdomains already
present in the collection must be removed. Since the collection
is sorted, we can limit our search for them to a slice of
the collection starting from insertion point and ending with
the last detected subdomain.
:param host_obj: an object representing value to be added.
It is assumed that, during execution of this method,
the value to be added is not currently listed.
"""
i = self._get_insertion_point(host_object)
for listed in self[i:]:
if not listed.is_subdomain(host_object):
break
self.hosts.pop(i)
self.hosts.insert(i, host_object.to_unicode()) | python | def _add_new(self, host_object):
"""Add a new host to the collection.
Before a new hostname can be added, all its subdomains already
present in the collection must be removed. Since the collection
is sorted, we can limit our search for them to a slice of
the collection starting from insertion point and ending with
the last detected subdomain.
:param host_obj: an object representing value to be added.
It is assumed that, during execution of this method,
the value to be added is not currently listed.
"""
i = self._get_insertion_point(host_object)
for listed in self[i:]:
if not listed.is_subdomain(host_object):
break
self.hosts.pop(i)
self.hosts.insert(i, host_object.to_unicode()) | [
"def",
"_add_new",
"(",
"self",
",",
"host_object",
")",
":",
"i",
"=",
"self",
".",
"_get_insertion_point",
"(",
"host_object",
")",
"for",
"listed",
"in",
"self",
"[",
"i",
":",
"]",
":",
"if",
"not",
"listed",
".",
"is_subdomain",
"(",
"host_object",
")",
":",
"break",
"self",
".",
"hosts",
".",
"pop",
"(",
"i",
")",
"self",
".",
"hosts",
".",
"insert",
"(",
"i",
",",
"host_object",
".",
"to_unicode",
"(",
")",
")"
] | Add a new host to the collection.
Before a new hostname can be added, all its subdomains already
present in the collection must be removed. Since the collection
is sorted, we can limit our search for them to a slice of
the collection starting from insertion point and ending with
the last detected subdomain.
:param host_obj: an object representing value to be added.
It is assumed that, during execution of this method,
the value to be added is not currently listed. | [
"Add",
"a",
"new",
"host",
"to",
"the",
"collection",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_collections.py#L140-L160 | train |
TkTech/Jawa | jawa/util/descriptor.py | method_descriptor | def method_descriptor(descriptor: str) -> MethodDescriptor:
"""
Parses a Method descriptor as described in section 4.3.3 of the JVM
specification.
"""
end_para = descriptor.find(')')
returns = descriptor[end_para + 1:]
args = descriptor[1:end_para]
return MethodDescriptor(
parse_descriptor(returns)[0],
parse_descriptor(args),
returns,
args,
descriptor
) | python | def method_descriptor(descriptor: str) -> MethodDescriptor:
"""
Parses a Method descriptor as described in section 4.3.3 of the JVM
specification.
"""
end_para = descriptor.find(')')
returns = descriptor[end_para + 1:]
args = descriptor[1:end_para]
return MethodDescriptor(
parse_descriptor(returns)[0],
parse_descriptor(args),
returns,
args,
descriptor
) | [
"def",
"method_descriptor",
"(",
"descriptor",
":",
"str",
")",
"->",
"MethodDescriptor",
":",
"end_para",
"=",
"descriptor",
".",
"find",
"(",
"')'",
")",
"returns",
"=",
"descriptor",
"[",
"end_para",
"+",
"1",
":",
"]",
"args",
"=",
"descriptor",
"[",
"1",
":",
"end_para",
"]",
"return",
"MethodDescriptor",
"(",
"parse_descriptor",
"(",
"returns",
")",
"[",
"0",
"]",
",",
"parse_descriptor",
"(",
"args",
")",
",",
"returns",
",",
"args",
",",
"descriptor",
")"
] | Parses a Method descriptor as described in section 4.3.3 of the JVM
specification. | [
"Parses",
"a",
"Method",
"descriptor",
"as",
"described",
"in",
"section",
"4",
".",
"3",
".",
"3",
"of",
"the",
"JVM",
"specification",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/descriptor.py#L22-L37 | train |
qwiglydee/drf-mongo-filters | drf_mongo_filters/filters.py | Filter.make_field | def make_field(self, **kwargs):
""" create serializer field """
kwargs['required'] = False
kwargs['allow_null'] = True
return self.field_class(**kwargs) | python | def make_field(self, **kwargs):
""" create serializer field """
kwargs['required'] = False
kwargs['allow_null'] = True
return self.field_class(**kwargs) | [
"def",
"make_field",
"(",
"self",
",",
"*",
"*",
"kwargs",
")",
":",
"kwargs",
"[",
"'required'",
"]",
"=",
"False",
"kwargs",
"[",
"'allow_null'",
"]",
"=",
"True",
"return",
"self",
".",
"field_class",
"(",
"*",
"*",
"kwargs",
")"
] | create serializer field | [
"create",
"serializer",
"field"
] | f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec | https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filters.py#L48-L52 | train |
qwiglydee/drf-mongo-filters | drf_mongo_filters/filters.py | Filter.bind | def bind(self, name, filterset):
""" attach filter to filterset
gives a name to use to extract arguments from querydict
"""
if self.name is not None:
name = self.name
self.field.bind(name, self) | python | def bind(self, name, filterset):
""" attach filter to filterset
gives a name to use to extract arguments from querydict
"""
if self.name is not None:
name = self.name
self.field.bind(name, self) | [
"def",
"bind",
"(",
"self",
",",
"name",
",",
"filterset",
")",
":",
"if",
"self",
".",
"name",
"is",
"not",
"None",
":",
"name",
"=",
"self",
".",
"name",
"self",
".",
"field",
".",
"bind",
"(",
"name",
",",
"self",
")"
] | attach filter to filterset
gives a name to use to extract arguments from querydict | [
"attach",
"filter",
"to",
"filterset"
] | f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec | https://github.com/qwiglydee/drf-mongo-filters/blob/f7e397c329bac6d7b8cbb1df70d96eccdcfbc1ec/drf_mongo_filters/filters.py#L54-L61 | train |
mardix/pylot | pylot/utils.py | get_base_dir | def get_base_dir():
"""
Return the base directory
"""
return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] | python | def get_base_dir():
"""
Return the base directory
"""
return os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] | [
"def",
"get_base_dir",
"(",
")",
":",
"return",
"os",
".",
"path",
".",
"split",
"(",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"[",
"0",
"]"
] | Return the base directory | [
"Return",
"the",
"base",
"directory"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L20-L24 | train |
mardix/pylot | pylot/utils.py | is_valid_url | def is_valid_url(url):
"""
Check if url is valid
"""
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
#r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return bool(regex.match(url)) | python | def is_valid_url(url):
"""
Check if url is valid
"""
regex = re.compile(
r'^(?:http|ftp)s?://' # http:// or https://
r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\.)+(?:[A-Z]{2,6}\.?|[A-Z0-9-]{2,}\.?)|' #domain...
#r'localhost|' #localhost...
r'\d{1,3}\.\d{1,3}\.\d{1,3}\.\d{1,3})' # ...or ip
r'(?::\d+)?' # optional port
r'(?:/?|[/?]\S+)$', re.IGNORECASE)
return bool(regex.match(url)) | [
"def",
"is_valid_url",
"(",
"url",
")",
":",
"regex",
"=",
"re",
".",
"compile",
"(",
"r'^(?:http|ftp)s?://'",
"# http:// or https://",
"r'(?:(?:[A-Z0-9](?:[A-Z0-9-]{0,61}[A-Z0-9])?\\.)+(?:[A-Z]{2,6}\\.?|[A-Z0-9-]{2,}\\.?)|'",
"#domain...",
"#r'localhost|' #localhost...",
"r'\\d{1,3}\\.\\d{1,3}\\.\\d{1,3}\\.\\d{1,3})'",
"# ...or ip",
"r'(?::\\d+)?'",
"# optional port",
"r'(?:/?|[/?]\\S+)$'",
",",
"re",
".",
"IGNORECASE",
")",
"return",
"bool",
"(",
"regex",
".",
"match",
"(",
"url",
")",
")"
] | Check if url is valid | [
"Check",
"if",
"url",
"is",
"valid"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L43-L54 | train |
mardix/pylot | pylot/utils.py | generate_random_string | def generate_random_string(length=8):
"""
Generate a random string
"""
char_set = string.ascii_uppercase + string.digits
return ''.join(random.sample(char_set * (length - 1), length)) | python | def generate_random_string(length=8):
"""
Generate a random string
"""
char_set = string.ascii_uppercase + string.digits
return ''.join(random.sample(char_set * (length - 1), length)) | [
"def",
"generate_random_string",
"(",
"length",
"=",
"8",
")",
":",
"char_set",
"=",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
"return",
"''",
".",
"join",
"(",
"random",
".",
"sample",
"(",
"char_set",
"*",
"(",
"length",
"-",
"1",
")",
",",
"length",
")",
")"
] | Generate a random string | [
"Generate",
"a",
"random",
"string"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L117-L122 | train |
mardix/pylot | pylot/utils.py | filter_stopwords | def filter_stopwords(str):
"""
Stop word filter
returns list
"""
STOPWORDS = ['a', 'able', 'about', 'across', 'after', 'all', 'almost',
'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at',
'be', 'because', 'been', 'but', 'by', 'can', 'cannot',
'could', 'dear', 'did', 'do', 'does', 'either', 'else',
'ever', 'every', 'for', 'from', 'get', 'got', 'had', 'has',
'have', 'he', 'her', 'hers', 'him', 'his', 'how', 'however',
'i', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'least',
'let', 'like', 'likely', 'may', 'me', 'might', 'most', 'must',
'my', 'neither', 'no', 'nor', 'not', 'of', 'off', 'often',
'on', 'only', 'or', 'other', 'our', 'own', 'rather', 'said',
'say', 'says', 'she', 'should', 'since', 'so', 'some', 'than',
'that', 'the', 'their', 'them', 'then', 'there', 'these',
'they', 'this', 'tis', 'to', 'too', 'twas', 'us',
'wants', 'was', 'we', 'were', 'what', 'when', 'where',
'which', 'while', 'who', 'whom', 'why', 'will', 'with',
'would', 'yet', 'you', 'your']
return [t for t in str.split() if t.lower() not in STOPWORDS] | python | def filter_stopwords(str):
"""
Stop word filter
returns list
"""
STOPWORDS = ['a', 'able', 'about', 'across', 'after', 'all', 'almost',
'also', 'am', 'among', 'an', 'and', 'any', 'are', 'as', 'at',
'be', 'because', 'been', 'but', 'by', 'can', 'cannot',
'could', 'dear', 'did', 'do', 'does', 'either', 'else',
'ever', 'every', 'for', 'from', 'get', 'got', 'had', 'has',
'have', 'he', 'her', 'hers', 'him', 'his', 'how', 'however',
'i', 'if', 'in', 'into', 'is', 'it', 'its', 'just', 'least',
'let', 'like', 'likely', 'may', 'me', 'might', 'most', 'must',
'my', 'neither', 'no', 'nor', 'not', 'of', 'off', 'often',
'on', 'only', 'or', 'other', 'our', 'own', 'rather', 'said',
'say', 'says', 'she', 'should', 'since', 'so', 'some', 'than',
'that', 'the', 'their', 'them', 'then', 'there', 'these',
'they', 'this', 'tis', 'to', 'too', 'twas', 'us',
'wants', 'was', 'we', 'were', 'what', 'when', 'where',
'which', 'while', 'who', 'whom', 'why', 'will', 'with',
'would', 'yet', 'you', 'your']
return [t for t in str.split() if t.lower() not in STOPWORDS] | [
"def",
"filter_stopwords",
"(",
"str",
")",
":",
"STOPWORDS",
"=",
"[",
"'a'",
",",
"'able'",
",",
"'about'",
",",
"'across'",
",",
"'after'",
",",
"'all'",
",",
"'almost'",
",",
"'also'",
",",
"'am'",
",",
"'among'",
",",
"'an'",
",",
"'and'",
",",
"'any'",
",",
"'are'",
",",
"'as'",
",",
"'at'",
",",
"'be'",
",",
"'because'",
",",
"'been'",
",",
"'but'",
",",
"'by'",
",",
"'can'",
",",
"'cannot'",
",",
"'could'",
",",
"'dear'",
",",
"'did'",
",",
"'do'",
",",
"'does'",
",",
"'either'",
",",
"'else'",
",",
"'ever'",
",",
"'every'",
",",
"'for'",
",",
"'from'",
",",
"'get'",
",",
"'got'",
",",
"'had'",
",",
"'has'",
",",
"'have'",
",",
"'he'",
",",
"'her'",
",",
"'hers'",
",",
"'him'",
",",
"'his'",
",",
"'how'",
",",
"'however'",
",",
"'i'",
",",
"'if'",
",",
"'in'",
",",
"'into'",
",",
"'is'",
",",
"'it'",
",",
"'its'",
",",
"'just'",
",",
"'least'",
",",
"'let'",
",",
"'like'",
",",
"'likely'",
",",
"'may'",
",",
"'me'",
",",
"'might'",
",",
"'most'",
",",
"'must'",
",",
"'my'",
",",
"'neither'",
",",
"'no'",
",",
"'nor'",
",",
"'not'",
",",
"'of'",
",",
"'off'",
",",
"'often'",
",",
"'on'",
",",
"'only'",
",",
"'or'",
",",
"'other'",
",",
"'our'",
",",
"'own'",
",",
"'rather'",
",",
"'said'",
",",
"'say'",
",",
"'says'",
",",
"'she'",
",",
"'should'",
",",
"'since'",
",",
"'so'",
",",
"'some'",
",",
"'than'",
",",
"'that'",
",",
"'the'",
",",
"'their'",
",",
"'them'",
",",
"'then'",
",",
"'there'",
",",
"'these'",
",",
"'they'",
",",
"'this'",
",",
"'tis'",
",",
"'to'",
",",
"'too'",
",",
"'twas'",
",",
"'us'",
",",
"'wants'",
",",
"'was'",
",",
"'we'",
",",
"'were'",
",",
"'what'",
",",
"'when'",
",",
"'where'",
",",
"'which'",
",",
"'while'",
",",
"'who'",
",",
"'whom'",
",",
"'why'",
",",
"'will'",
",",
"'with'",
",",
"'would'",
",",
"'yet'",
",",
"'you'",
",",
"'your'",
"]",
"return",
"[",
"t",
"for",
"t",
"in",
"str",
".",
"split",
"(",
")",
"if",
"t",
".",
"lower",
"(",
")",
"not",
"in",
"STOPWORDS",
"]"
] | Stop word filter
returns list | [
"Stop",
"word",
"filter",
"returns",
"list"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L139-L161 | train |
mardix/pylot | pylot/utils.py | convert_bytes | def convert_bytes(bytes):
"""
Convert bytes into human readable
"""
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fM' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % bytes
return size | python | def convert_bytes(bytes):
"""
Convert bytes into human readable
"""
bytes = float(bytes)
if bytes >= 1099511627776:
terabytes = bytes / 1099511627776
size = '%.2fT' % terabytes
elif bytes >= 1073741824:
gigabytes = bytes / 1073741824
size = '%.2fG' % gigabytes
elif bytes >= 1048576:
megabytes = bytes / 1048576
size = '%.2fM' % megabytes
elif bytes >= 1024:
kilobytes = bytes / 1024
size = '%.2fK' % kilobytes
else:
size = '%.2fb' % bytes
return size | [
"def",
"convert_bytes",
"(",
"bytes",
")",
":",
"bytes",
"=",
"float",
"(",
"bytes",
")",
"if",
"bytes",
">=",
"1099511627776",
":",
"terabytes",
"=",
"bytes",
"/",
"1099511627776",
"size",
"=",
"'%.2fT'",
"%",
"terabytes",
"elif",
"bytes",
">=",
"1073741824",
":",
"gigabytes",
"=",
"bytes",
"/",
"1073741824",
"size",
"=",
"'%.2fG'",
"%",
"gigabytes",
"elif",
"bytes",
">=",
"1048576",
":",
"megabytes",
"=",
"bytes",
"/",
"1048576",
"size",
"=",
"'%.2fM'",
"%",
"megabytes",
"elif",
"bytes",
">=",
"1024",
":",
"kilobytes",
"=",
"bytes",
"/",
"1024",
"size",
"=",
"'%.2fK'",
"%",
"kilobytes",
"else",
":",
"size",
"=",
"'%.2fb'",
"%",
"bytes",
"return",
"size"
] | Convert bytes into human readable | [
"Convert",
"bytes",
"into",
"human",
"readable"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/utils.py#L192-L211 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDiskXML.find | def find(self, node, path):
"""Wrapper for lxml`s find."""
return node.find(path, namespaces=self.namespaces) | python | def find(self, node, path):
"""Wrapper for lxml`s find."""
return node.find(path, namespaces=self.namespaces) | [
"def",
"find",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"return",
"node",
".",
"find",
"(",
"path",
",",
"namespaces",
"=",
"self",
".",
"namespaces",
")"
] | Wrapper for lxml`s find. | [
"Wrapper",
"for",
"lxml",
"s",
"find",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L24-L27 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDiskXML.xpath | def xpath(self, node, path):
"""Wrapper for lxml`s xpath."""
return node.xpath(path, namespaces=self.namespaces) | python | def xpath(self, node, path):
"""Wrapper for lxml`s xpath."""
return node.xpath(path, namespaces=self.namespaces) | [
"def",
"xpath",
"(",
"self",
",",
"node",
",",
"path",
")",
":",
"return",
"node",
".",
"xpath",
"(",
"path",
",",
"namespaces",
"=",
"self",
".",
"namespaces",
")"
] | Wrapper for lxml`s xpath. | [
"Wrapper",
"for",
"lxml",
"s",
"xpath",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L29-L32 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDisk.mkdir | def mkdir(self, path):
"""Create directory. All part of path must be exists. Raise exception when path already exists."""
resp = self._sendRequest("MKCOL", path)
if resp.status_code != 201:
if resp.status_code == 409:
raise YaDiskException(409, "Part of path {} does not exists".format(path))
elif resp.status_code == 405:
raise YaDiskException(405, "Path {} already exists".format(path))
else:
raise YaDiskException(resp.status_code, resp.content) | python | def mkdir(self, path):
"""Create directory. All part of path must be exists. Raise exception when path already exists."""
resp = self._sendRequest("MKCOL", path)
if resp.status_code != 201:
if resp.status_code == 409:
raise YaDiskException(409, "Part of path {} does not exists".format(path))
elif resp.status_code == 405:
raise YaDiskException(405, "Path {} already exists".format(path))
else:
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"mkdir",
"(",
"self",
",",
"path",
")",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"MKCOL\"",
",",
"path",
")",
"if",
"resp",
".",
"status_code",
"!=",
"201",
":",
"if",
"resp",
".",
"status_code",
"==",
"409",
":",
"raise",
"YaDiskException",
"(",
"409",
",",
"\"Part of path {} does not exists\"",
".",
"format",
"(",
"path",
")",
")",
"elif",
"resp",
".",
"status_code",
"==",
"405",
":",
"raise",
"YaDiskException",
"(",
"405",
",",
"\"Path {} already exists\"",
".",
"format",
"(",
"path",
")",
")",
"else",
":",
"raise",
"YaDiskException",
"(",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")"
] | Create directory. All part of path must be exists. Raise exception when path already exists. | [
"Create",
"directory",
".",
"All",
"part",
"of",
"path",
"must",
"be",
"exists",
".",
"Raise",
"exception",
"when",
"path",
"already",
"exists",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L118-L128 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDisk.rm | def rm(self, path):
"""Delete file or directory."""
resp = self._sendRequest("DELETE", path)
# By documentation server must return 200 "OK", but I get 204 "No Content".
# Anyway file or directory have been removed.
if not (resp.status_code in (200, 204)):
raise YaDiskException(resp.status_code, resp.content) | python | def rm(self, path):
"""Delete file or directory."""
resp = self._sendRequest("DELETE", path)
# By documentation server must return 200 "OK", but I get 204 "No Content".
# Anyway file or directory have been removed.
if not (resp.status_code in (200, 204)):
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"rm",
"(",
"self",
",",
"path",
")",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"DELETE\"",
",",
"path",
")",
"# By documentation server must return 200 \"OK\", but I get 204 \"No Content\".",
"# Anyway file or directory have been removed.",
"if",
"not",
"(",
"resp",
".",
"status_code",
"in",
"(",
"200",
",",
"204",
")",
")",
":",
"raise",
"YaDiskException",
"(",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")"
] | Delete file or directory. | [
"Delete",
"file",
"or",
"directory",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L130-L137 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDisk.upload | def upload(self, file, path):
"""Upload file."""
with open(file, "rb") as f:
resp = self._sendRequest("PUT", path, data=f)
if resp.status_code != 201:
raise YaDiskException(resp.status_code, resp.content) | python | def upload(self, file, path):
"""Upload file."""
with open(file, "rb") as f:
resp = self._sendRequest("PUT", path, data=f)
if resp.status_code != 201:
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"upload",
"(",
"self",
",",
"file",
",",
"path",
")",
":",
"with",
"open",
"(",
"file",
",",
"\"rb\"",
")",
"as",
"f",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"PUT\"",
",",
"path",
",",
"data",
"=",
"f",
")",
"if",
"resp",
".",
"status_code",
"!=",
"201",
":",
"raise",
"YaDiskException",
"(",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")"
] | Upload file. | [
"Upload",
"file",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L155-L161 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDisk.download | def download(self, path, file):
"""Download remote file to disk."""
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | python | def download(self, path, file):
"""Download remote file to disk."""
resp = self._sendRequest("GET", path)
if resp.status_code == 200:
with open(file, "wb") as f:
f.write(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"download",
"(",
"self",
",",
"path",
",",
"file",
")",
":",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"GET\"",
",",
"path",
")",
"if",
"resp",
".",
"status_code",
"==",
"200",
":",
"with",
"open",
"(",
"file",
",",
"\"wb\"",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"resp",
".",
"content",
")",
"else",
":",
"raise",
"YaDiskException",
"(",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")"
] | Download remote file to disk. | [
"Download",
"remote",
"file",
"to",
"disk",
"."
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L163-L171 | train |
TyVik/YaDiskClient | YaDiskClient/YaDiskClient.py | YaDisk.publish | def publish(self, path):
"""Publish file or folder and return public url"""
def parseContent(content):
root = ET.fromstring(content)
prop = root.find(".//d:prop", namespaces=self.namespaces)
return prop.find("{urn:yandex:disk:meta}public_url").text.strip()
data = """
<propertyupdate xmlns="DAV:">
<set>
<prop>
<public_url xmlns="urn:yandex:disk:meta">true</public_url>
</prop>
</set>
</propertyupdate>
"""
_check_dst_absolute(path)
resp = self._sendRequest("PROPPATCH", addUrl=path, data=data)
if resp.status_code == 207:
return parseContent(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | python | def publish(self, path):
"""Publish file or folder and return public url"""
def parseContent(content):
root = ET.fromstring(content)
prop = root.find(".//d:prop", namespaces=self.namespaces)
return prop.find("{urn:yandex:disk:meta}public_url").text.strip()
data = """
<propertyupdate xmlns="DAV:">
<set>
<prop>
<public_url xmlns="urn:yandex:disk:meta">true</public_url>
</prop>
</set>
</propertyupdate>
"""
_check_dst_absolute(path)
resp = self._sendRequest("PROPPATCH", addUrl=path, data=data)
if resp.status_code == 207:
return parseContent(resp.content)
else:
raise YaDiskException(resp.status_code, resp.content) | [
"def",
"publish",
"(",
"self",
",",
"path",
")",
":",
"def",
"parseContent",
"(",
"content",
")",
":",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"content",
")",
"prop",
"=",
"root",
".",
"find",
"(",
"\".//d:prop\"",
",",
"namespaces",
"=",
"self",
".",
"namespaces",
")",
"return",
"prop",
".",
"find",
"(",
"\"{urn:yandex:disk:meta}public_url\"",
")",
".",
"text",
".",
"strip",
"(",
")",
"data",
"=",
"\"\"\"\n<propertyupdate xmlns=\"DAV:\">\n <set>\n <prop>\n <public_url xmlns=\"urn:yandex:disk:meta\">true</public_url>\n </prop>\n </set>\n</propertyupdate>\n \"\"\"",
"_check_dst_absolute",
"(",
"path",
")",
"resp",
"=",
"self",
".",
"_sendRequest",
"(",
"\"PROPPATCH\"",
",",
"addUrl",
"=",
"path",
",",
"data",
"=",
"data",
")",
"if",
"resp",
".",
"status_code",
"==",
"207",
":",
"return",
"parseContent",
"(",
"resp",
".",
"content",
")",
"else",
":",
"raise",
"YaDiskException",
"(",
"resp",
".",
"status_code",
",",
"resp",
".",
"content",
")"
] | Publish file or folder and return public url | [
"Publish",
"file",
"or",
"folder",
"and",
"return",
"public",
"url"
] | ee60163bac8c5696d81e98c8ee1d8b321e46fae4 | https://github.com/TyVik/YaDiskClient/blob/ee60163bac8c5696d81e98c8ee1d8b321e46fae4/YaDiskClient/YaDiskClient.py#L173-L196 | train |
TkTech/Jawa | jawa/util/bytecode.py | write_instruction | def write_instruction(fout, start_pos, ins):
"""
Writes a single instruction of `opcode` with `operands` to `fout`.
:param fout: Any file-like object providing ``write()``.
:param start_pos: The current position in the stream.
:param ins: The `Instruction` to write.
"""
opcode, operands = ins.opcode, ins.operands
fmt_operands = opcode_table[opcode]['operands']
if ins.wide:
# The "WIDE" prefix
fout.write(pack('>B', 0xC4))
# The real opcode.
fout.write(pack('>B', opcode))
fout.write(pack('>H', operands[0].value))
if opcode == 0x84:
fout.write(pack('>h', operands[1].value))
elif fmt_operands:
# A normal simple opcode with simple operands.
fout.write(pack('>B', opcode))
for i, (fmt, _) in enumerate(fmt_operands):
fout.write(fmt.value.pack(operands[i].value))
elif opcode == 0xAB:
# Special case for lookupswitch.
fout.write(pack('>B', opcode))
# assemble([
# ('lookupswitch', {
# 2: -3,
# 4: 5
# }, <default>)
# ])
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fout.write(pack(f'{padding}x'))
fout.write(pack('>ii', operands[1].value, len(operands[0])))
for key in sorted(operands[0].keys()):
fout.write(pack('>ii', key, operands[0][key]))
elif opcode == 0xAA:
# Special case for table switch.
fout.write(pack('>B', opcode))
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fout.write(pack(f'{padding}x'))
fout.write(pack(
f'>iii{len(operands) - 3}i',
# Default branch offset
operands[0].value,
operands[1].value,
operands[2].value,
*(o.value for o in operands[3:])
))
else:
# opcode with no operands.
fout.write(pack('>B', opcode)) | python | def write_instruction(fout, start_pos, ins):
"""
Writes a single instruction of `opcode` with `operands` to `fout`.
:param fout: Any file-like object providing ``write()``.
:param start_pos: The current position in the stream.
:param ins: The `Instruction` to write.
"""
opcode, operands = ins.opcode, ins.operands
fmt_operands = opcode_table[opcode]['operands']
if ins.wide:
# The "WIDE" prefix
fout.write(pack('>B', 0xC4))
# The real opcode.
fout.write(pack('>B', opcode))
fout.write(pack('>H', operands[0].value))
if opcode == 0x84:
fout.write(pack('>h', operands[1].value))
elif fmt_operands:
# A normal simple opcode with simple operands.
fout.write(pack('>B', opcode))
for i, (fmt, _) in enumerate(fmt_operands):
fout.write(fmt.value.pack(operands[i].value))
elif opcode == 0xAB:
# Special case for lookupswitch.
fout.write(pack('>B', opcode))
# assemble([
# ('lookupswitch', {
# 2: -3,
# 4: 5
# }, <default>)
# ])
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fout.write(pack(f'{padding}x'))
fout.write(pack('>ii', operands[1].value, len(operands[0])))
for key in sorted(operands[0].keys()):
fout.write(pack('>ii', key, operands[0][key]))
elif opcode == 0xAA:
# Special case for table switch.
fout.write(pack('>B', opcode))
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fout.write(pack(f'{padding}x'))
fout.write(pack(
f'>iii{len(operands) - 3}i',
# Default branch offset
operands[0].value,
operands[1].value,
operands[2].value,
*(o.value for o in operands[3:])
))
else:
# opcode with no operands.
fout.write(pack('>B', opcode)) | [
"def",
"write_instruction",
"(",
"fout",
",",
"start_pos",
",",
"ins",
")",
":",
"opcode",
",",
"operands",
"=",
"ins",
".",
"opcode",
",",
"ins",
".",
"operands",
"fmt_operands",
"=",
"opcode_table",
"[",
"opcode",
"]",
"[",
"'operands'",
"]",
"if",
"ins",
".",
"wide",
":",
"# The \"WIDE\" prefix",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"0xC4",
")",
")",
"# The real opcode.",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"opcode",
")",
")",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"operands",
"[",
"0",
"]",
".",
"value",
")",
")",
"if",
"opcode",
"==",
"0x84",
":",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>h'",
",",
"operands",
"[",
"1",
"]",
".",
"value",
")",
")",
"elif",
"fmt_operands",
":",
"# A normal simple opcode with simple operands.",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"opcode",
")",
")",
"for",
"i",
",",
"(",
"fmt",
",",
"_",
")",
"in",
"enumerate",
"(",
"fmt_operands",
")",
":",
"fout",
".",
"write",
"(",
"fmt",
".",
"value",
".",
"pack",
"(",
"operands",
"[",
"i",
"]",
".",
"value",
")",
")",
"elif",
"opcode",
"==",
"0xAB",
":",
"# Special case for lookupswitch.",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"opcode",
")",
")",
"# assemble([",
"# ('lookupswitch', {",
"# 2: -3,",
"# 4: 5",
"# }, <default>)",
"# ])",
"padding",
"=",
"4",
"-",
"(",
"start_pos",
"+",
"1",
")",
"%",
"4",
"padding",
"=",
"padding",
"if",
"padding",
"!=",
"4",
"else",
"0",
"fout",
".",
"write",
"(",
"pack",
"(",
"f'{padding}x'",
")",
")",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>ii'",
",",
"operands",
"[",
"1",
"]",
".",
"value",
",",
"len",
"(",
"operands",
"[",
"0",
"]",
")",
")",
")",
"for",
"key",
"in",
"sorted",
"(",
"operands",
"[",
"0",
"]",
".",
"keys",
"(",
")",
")",
":",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>ii'",
",",
"key",
",",
"operands",
"[",
"0",
"]",
"[",
"key",
"]",
")",
")",
"elif",
"opcode",
"==",
"0xAA",
":",
"# Special case for table switch.",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"opcode",
")",
")",
"padding",
"=",
"4",
"-",
"(",
"start_pos",
"+",
"1",
")",
"%",
"4",
"padding",
"=",
"padding",
"if",
"padding",
"!=",
"4",
"else",
"0",
"fout",
".",
"write",
"(",
"pack",
"(",
"f'{padding}x'",
")",
")",
"fout",
".",
"write",
"(",
"pack",
"(",
"f'>iii{len(operands) - 3}i'",
",",
"# Default branch offset",
"operands",
"[",
"0",
"]",
".",
"value",
",",
"operands",
"[",
"1",
"]",
".",
"value",
",",
"operands",
"[",
"2",
"]",
".",
"value",
",",
"*",
"(",
"o",
".",
"value",
"for",
"o",
"in",
"operands",
"[",
"3",
":",
"]",
")",
")",
")",
"else",
":",
"# opcode with no operands.",
"fout",
".",
"write",
"(",
"pack",
"(",
"'>B'",
",",
"opcode",
")",
")"
] | Writes a single instruction of `opcode` with `operands` to `fout`.
:param fout: Any file-like object providing ``write()``.
:param start_pos: The current position in the stream.
:param ins: The `Instruction` to write. | [
"Writes",
"a",
"single",
"instruction",
"of",
"opcode",
"with",
"operands",
"to",
"fout",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L123-L178 | train |
TkTech/Jawa | jawa/util/bytecode.py | read_instruction | def read_instruction(fio, start_pos):
"""
Reads a single instruction from `fio` and returns it, or ``None`` if
the stream is empty.
:param fio: Any file-like object providing ``read()``.
:param start_pos: The current position in the stream.
"""
op = fio.read(1)
if not op:
return None
op = ord(op)
ins = opcode_table[op]
operands = ins['operands']
name = ins['mnemonic']
final_operands = []
# Most opcodes have simple operands.
if operands:
for fmt, type_ in operands:
final_operands.append(
Operand(
type_,
fmt.value.unpack(fio.read(fmt.value.size))[0]
)
)
# Special case for lookupswitch.
elif op == 0xAB:
# Get rid of the alignment padding.
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fio.read(padding)
# Default branch address and branch count.
default, npairs = unpack('>ii', fio.read(8))
pairs = {}
for _ in repeat(None, npairs):
match, offset = unpack('>ii', fio.read(8))
pairs[match] = offset
final_operands.append(pairs)
final_operands.append(Operand(OperandTypes.BRANCH, default))
# Special case for tableswitch
elif op == 0xAA:
# Get rid of the alignment padding.
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fio.read(padding)
default, low, high = unpack('>iii', fio.read(12))
final_operands.append(Operand(OperandTypes.BRANCH, default))
final_operands.append(Operand(OperandTypes.LITERAL, low))
final_operands.append(Operand(OperandTypes.LITERAL, high))
for _ in repeat(None, high - low + 1):
offset = unpack('>i', fio.read(4))[0]
final_operands.append(Operand(OperandTypes.BRANCH, offset))
# Special case for the wide prefix
elif op == 0xC4:
real_op = unpack('>B', fio.read(1))[0]
ins = opcode_table[real_op]
name = ins['mnemonic']
final_operands.append(Operand(
OperandTypes.LOCAL_INDEX,
unpack('>H', fio.read(2))[0]
))
# Further special case for iinc.
if real_op == 0x84:
final_operands.append(Operand(
OperandTypes.LITERAL,
unpack('>H', fio.read(2))[0]
))
return Instruction(name, op, final_operands, start_pos) | python | def read_instruction(fio, start_pos):
"""
Reads a single instruction from `fio` and returns it, or ``None`` if
the stream is empty.
:param fio: Any file-like object providing ``read()``.
:param start_pos: The current position in the stream.
"""
op = fio.read(1)
if not op:
return None
op = ord(op)
ins = opcode_table[op]
operands = ins['operands']
name = ins['mnemonic']
final_operands = []
# Most opcodes have simple operands.
if operands:
for fmt, type_ in operands:
final_operands.append(
Operand(
type_,
fmt.value.unpack(fio.read(fmt.value.size))[0]
)
)
# Special case for lookupswitch.
elif op == 0xAB:
# Get rid of the alignment padding.
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fio.read(padding)
# Default branch address and branch count.
default, npairs = unpack('>ii', fio.read(8))
pairs = {}
for _ in repeat(None, npairs):
match, offset = unpack('>ii', fio.read(8))
pairs[match] = offset
final_operands.append(pairs)
final_operands.append(Operand(OperandTypes.BRANCH, default))
# Special case for tableswitch
elif op == 0xAA:
# Get rid of the alignment padding.
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
fio.read(padding)
default, low, high = unpack('>iii', fio.read(12))
final_operands.append(Operand(OperandTypes.BRANCH, default))
final_operands.append(Operand(OperandTypes.LITERAL, low))
final_operands.append(Operand(OperandTypes.LITERAL, high))
for _ in repeat(None, high - low + 1):
offset = unpack('>i', fio.read(4))[0]
final_operands.append(Operand(OperandTypes.BRANCH, offset))
# Special case for the wide prefix
elif op == 0xC4:
real_op = unpack('>B', fio.read(1))[0]
ins = opcode_table[real_op]
name = ins['mnemonic']
final_operands.append(Operand(
OperandTypes.LOCAL_INDEX,
unpack('>H', fio.read(2))[0]
))
# Further special case for iinc.
if real_op == 0x84:
final_operands.append(Operand(
OperandTypes.LITERAL,
unpack('>H', fio.read(2))[0]
))
return Instruction(name, op, final_operands, start_pos) | [
"def",
"read_instruction",
"(",
"fio",
",",
"start_pos",
")",
":",
"op",
"=",
"fio",
".",
"read",
"(",
"1",
")",
"if",
"not",
"op",
":",
"return",
"None",
"op",
"=",
"ord",
"(",
"op",
")",
"ins",
"=",
"opcode_table",
"[",
"op",
"]",
"operands",
"=",
"ins",
"[",
"'operands'",
"]",
"name",
"=",
"ins",
"[",
"'mnemonic'",
"]",
"final_operands",
"=",
"[",
"]",
"# Most opcodes have simple operands.",
"if",
"operands",
":",
"for",
"fmt",
",",
"type_",
"in",
"operands",
":",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"type_",
",",
"fmt",
".",
"value",
".",
"unpack",
"(",
"fio",
".",
"read",
"(",
"fmt",
".",
"value",
".",
"size",
")",
")",
"[",
"0",
"]",
")",
")",
"# Special case for lookupswitch.",
"elif",
"op",
"==",
"0xAB",
":",
"# Get rid of the alignment padding.",
"padding",
"=",
"4",
"-",
"(",
"start_pos",
"+",
"1",
")",
"%",
"4",
"padding",
"=",
"padding",
"if",
"padding",
"!=",
"4",
"else",
"0",
"fio",
".",
"read",
"(",
"padding",
")",
"# Default branch address and branch count.",
"default",
",",
"npairs",
"=",
"unpack",
"(",
"'>ii'",
",",
"fio",
".",
"read",
"(",
"8",
")",
")",
"pairs",
"=",
"{",
"}",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"npairs",
")",
":",
"match",
",",
"offset",
"=",
"unpack",
"(",
"'>ii'",
",",
"fio",
".",
"read",
"(",
"8",
")",
")",
"pairs",
"[",
"match",
"]",
"=",
"offset",
"final_operands",
".",
"append",
"(",
"pairs",
")",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"BRANCH",
",",
"default",
")",
")",
"# Special case for tableswitch",
"elif",
"op",
"==",
"0xAA",
":",
"# Get rid of the alignment padding.",
"padding",
"=",
"4",
"-",
"(",
"start_pos",
"+",
"1",
")",
"%",
"4",
"padding",
"=",
"padding",
"if",
"padding",
"!=",
"4",
"else",
"0",
"fio",
".",
"read",
"(",
"padding",
")",
"default",
",",
"low",
",",
"high",
"=",
"unpack",
"(",
"'>iii'",
",",
"fio",
".",
"read",
"(",
"12",
")",
")",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"BRANCH",
",",
"default",
")",
")",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"LITERAL",
",",
"low",
")",
")",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"LITERAL",
",",
"high",
")",
")",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"high",
"-",
"low",
"+",
"1",
")",
":",
"offset",
"=",
"unpack",
"(",
"'>i'",
",",
"fio",
".",
"read",
"(",
"4",
")",
")",
"[",
"0",
"]",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"BRANCH",
",",
"offset",
")",
")",
"# Special case for the wide prefix",
"elif",
"op",
"==",
"0xC4",
":",
"real_op",
"=",
"unpack",
"(",
"'>B'",
",",
"fio",
".",
"read",
"(",
"1",
")",
")",
"[",
"0",
"]",
"ins",
"=",
"opcode_table",
"[",
"real_op",
"]",
"name",
"=",
"ins",
"[",
"'mnemonic'",
"]",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"LOCAL_INDEX",
",",
"unpack",
"(",
"'>H'",
",",
"fio",
".",
"read",
"(",
"2",
")",
")",
"[",
"0",
"]",
")",
")",
"# Further special case for iinc.",
"if",
"real_op",
"==",
"0x84",
":",
"final_operands",
".",
"append",
"(",
"Operand",
"(",
"OperandTypes",
".",
"LITERAL",
",",
"unpack",
"(",
"'>H'",
",",
"fio",
".",
"read",
"(",
"2",
")",
")",
"[",
"0",
"]",
")",
")",
"return",
"Instruction",
"(",
"name",
",",
"op",
",",
"final_operands",
",",
"start_pos",
")"
] | Reads a single instruction from `fio` and returns it, or ``None`` if
the stream is empty.
:param fio: Any file-like object providing ``read()``.
:param start_pos: The current position in the stream. | [
"Reads",
"a",
"single",
"instruction",
"from",
"fio",
"and",
"returns",
"it",
"or",
"None",
"if",
"the",
"stream",
"is",
"empty",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L181-L259 | train |
TkTech/Jawa | jawa/util/bytecode.py | load_bytecode_definitions | def load_bytecode_definitions(*, path=None) -> dict:
"""Load bytecode definitions from JSON file.
If no path is provided the default bytecode.json will be loaded.
:param path: Either None or a path to a JSON file to load containing
bytecode definitions.
"""
if path is not None:
with open(path, 'rb') as file_in:
j = json.load(file_in)
else:
try:
j = json.loads(pkgutil.get_data('jawa.util', 'bytecode.json'))
except json.JSONDecodeError:
# Unfortunately our best way to handle missing/malformed/empty
# bytecode.json files since it may not actually be backed by a
# "real" file.
return {}
for definition in j.values():
# If the entry has any operands take the text labels and convert
# them into pre-cached struct objects and operand types.
operands = definition['operands']
if operands:
definition['operands'] = [
[getattr(OperandFmts, oo[0]), OperandTypes[oo[1]]]
for oo in operands
]
# Return one dict that contains both mnemonic keys and opcode keys.
return {**j, **{v['op']: v for v in j.values()}} | python | def load_bytecode_definitions(*, path=None) -> dict:
"""Load bytecode definitions from JSON file.
If no path is provided the default bytecode.json will be loaded.
:param path: Either None or a path to a JSON file to load containing
bytecode definitions.
"""
if path is not None:
with open(path, 'rb') as file_in:
j = json.load(file_in)
else:
try:
j = json.loads(pkgutil.get_data('jawa.util', 'bytecode.json'))
except json.JSONDecodeError:
# Unfortunately our best way to handle missing/malformed/empty
# bytecode.json files since it may not actually be backed by a
# "real" file.
return {}
for definition in j.values():
# If the entry has any operands take the text labels and convert
# them into pre-cached struct objects and operand types.
operands = definition['operands']
if operands:
definition['operands'] = [
[getattr(OperandFmts, oo[0]), OperandTypes[oo[1]]]
for oo in operands
]
# Return one dict that contains both mnemonic keys and opcode keys.
return {**j, **{v['op']: v for v in j.values()}} | [
"def",
"load_bytecode_definitions",
"(",
"*",
",",
"path",
"=",
"None",
")",
"->",
"dict",
":",
"if",
"path",
"is",
"not",
"None",
":",
"with",
"open",
"(",
"path",
",",
"'rb'",
")",
"as",
"file_in",
":",
"j",
"=",
"json",
".",
"load",
"(",
"file_in",
")",
"else",
":",
"try",
":",
"j",
"=",
"json",
".",
"loads",
"(",
"pkgutil",
".",
"get_data",
"(",
"'jawa.util'",
",",
"'bytecode.json'",
")",
")",
"except",
"json",
".",
"JSONDecodeError",
":",
"# Unfortunately our best way to handle missing/malformed/empty",
"# bytecode.json files since it may not actually be backed by a",
"# \"real\" file.",
"return",
"{",
"}",
"for",
"definition",
"in",
"j",
".",
"values",
"(",
")",
":",
"# If the entry has any operands take the text labels and convert",
"# them into pre-cached struct objects and operand types.",
"operands",
"=",
"definition",
"[",
"'operands'",
"]",
"if",
"operands",
":",
"definition",
"[",
"'operands'",
"]",
"=",
"[",
"[",
"getattr",
"(",
"OperandFmts",
",",
"oo",
"[",
"0",
"]",
")",
",",
"OperandTypes",
"[",
"oo",
"[",
"1",
"]",
"]",
"]",
"for",
"oo",
"in",
"operands",
"]",
"# Return one dict that contains both mnemonic keys and opcode keys.",
"return",
"{",
"*",
"*",
"j",
",",
"*",
"*",
"{",
"v",
"[",
"'op'",
"]",
":",
"v",
"for",
"v",
"in",
"j",
".",
"values",
"(",
")",
"}",
"}"
] | Load bytecode definitions from JSON file.
If no path is provided the default bytecode.json will be loaded.
:param path: Either None or a path to a JSON file to load containing
bytecode definitions. | [
"Load",
"bytecode",
"definitions",
"from",
"JSON",
"file",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L262-L293 | train |
TkTech/Jawa | jawa/util/bytecode.py | Instruction.size_on_disk | def size_on_disk(self, start_pos=0):
"""
Returns the size of this instruction and its operands when
packed. `start_pos` is required for the `tableswitch` and
`lookupswitch` instruction as the padding depends on alignment.
"""
# All instructions are at least 1 byte (the opcode itself)
size = 1
fmts = opcode_table[self.opcode]['operands']
if self.wide:
size += 2
# Special case for iinc which has a 2nd extended operand.
if self.opcode == 0x84:
size += 2
elif fmts:
# A simple opcode with simple operands.
for fmt, _ in fmts:
size += fmt.value.size
elif self.opcode == 0xAB:
# lookupswitch
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
size += padding
# default & npairs
size += 8
size += len(self.operands[0]) * 8
elif self.opcode == 0xAA:
# tableswitch
raise NotImplementedError()
return size | python | def size_on_disk(self, start_pos=0):
"""
Returns the size of this instruction and its operands when
packed. `start_pos` is required for the `tableswitch` and
`lookupswitch` instruction as the padding depends on alignment.
"""
# All instructions are at least 1 byte (the opcode itself)
size = 1
fmts = opcode_table[self.opcode]['operands']
if self.wide:
size += 2
# Special case for iinc which has a 2nd extended operand.
if self.opcode == 0x84:
size += 2
elif fmts:
# A simple opcode with simple operands.
for fmt, _ in fmts:
size += fmt.value.size
elif self.opcode == 0xAB:
# lookupswitch
padding = 4 - (start_pos + 1) % 4
padding = padding if padding != 4 else 0
size += padding
# default & npairs
size += 8
size += len(self.operands[0]) * 8
elif self.opcode == 0xAA:
# tableswitch
raise NotImplementedError()
return size | [
"def",
"size_on_disk",
"(",
"self",
",",
"start_pos",
"=",
"0",
")",
":",
"# All instructions are at least 1 byte (the opcode itself)",
"size",
"=",
"1",
"fmts",
"=",
"opcode_table",
"[",
"self",
".",
"opcode",
"]",
"[",
"'operands'",
"]",
"if",
"self",
".",
"wide",
":",
"size",
"+=",
"2",
"# Special case for iinc which has a 2nd extended operand.",
"if",
"self",
".",
"opcode",
"==",
"0x84",
":",
"size",
"+=",
"2",
"elif",
"fmts",
":",
"# A simple opcode with simple operands.",
"for",
"fmt",
",",
"_",
"in",
"fmts",
":",
"size",
"+=",
"fmt",
".",
"value",
".",
"size",
"elif",
"self",
".",
"opcode",
"==",
"0xAB",
":",
"# lookupswitch",
"padding",
"=",
"4",
"-",
"(",
"start_pos",
"+",
"1",
")",
"%",
"4",
"padding",
"=",
"padding",
"if",
"padding",
"!=",
"4",
"else",
"0",
"size",
"+=",
"padding",
"# default & npairs",
"size",
"+=",
"8",
"size",
"+=",
"len",
"(",
"self",
".",
"operands",
"[",
"0",
"]",
")",
"*",
"8",
"elif",
"self",
".",
"opcode",
"==",
"0xAA",
":",
"# tableswitch",
"raise",
"NotImplementedError",
"(",
")",
"return",
"size"
] | Returns the size of this instruction and its operands when
packed. `start_pos` is required for the `tableswitch` and
`lookupswitch` instruction as the padding depends on alignment. | [
"Returns",
"the",
"size",
"of",
"this",
"instruction",
"and",
"its",
"operands",
"when",
"packed",
".",
"start_pos",
"is",
"required",
"for",
"the",
"tableswitch",
"and",
"lookupswitch",
"instruction",
"as",
"the",
"padding",
"depends",
"on",
"alignment",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L27-L58 | train |
TkTech/Jawa | jawa/util/bytecode.py | Instruction.wide | def wide(self):
"""
``True`` if this instruction needs to be prefixed by the WIDE
opcode.
"""
if not opcode_table[self.opcode].get('can_be_wide'):
return False
if self.operands[0].value >= 255:
return True
if self.opcode == 0x84:
if self.operands[1].value >= 255:
return True
return False | python | def wide(self):
"""
``True`` if this instruction needs to be prefixed by the WIDE
opcode.
"""
if not opcode_table[self.opcode].get('can_be_wide'):
return False
if self.operands[0].value >= 255:
return True
if self.opcode == 0x84:
if self.operands[1].value >= 255:
return True
return False | [
"def",
"wide",
"(",
"self",
")",
":",
"if",
"not",
"opcode_table",
"[",
"self",
".",
"opcode",
"]",
".",
"get",
"(",
"'can_be_wide'",
")",
":",
"return",
"False",
"if",
"self",
".",
"operands",
"[",
"0",
"]",
".",
"value",
">=",
"255",
":",
"return",
"True",
"if",
"self",
".",
"opcode",
"==",
"0x84",
":",
"if",
"self",
".",
"operands",
"[",
"1",
"]",
".",
"value",
">=",
"255",
":",
"return",
"True",
"return",
"False"
] | ``True`` if this instruction needs to be prefixed by the WIDE
opcode. | [
"True",
"if",
"this",
"instruction",
"needs",
"to",
"be",
"prefixed",
"by",
"the",
"WIDE",
"opcode",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/bytecode.py#L61-L76 | train |
thespacedoctor/polyglot | polyglot/kindle.py | kindle.get_attachment | def get_attachment(self, file_path):
'''Get file as MIMEBase message'''
try:
file_ = open(file_path, 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(file_.read())
file_.close()
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(file_path))
return attachment
except IOError:
traceback.print_exc()
message = ('The requested file could not be read. Maybe wrong '
'permissions?')
print >> sys.stderr, message
sys.exit(6) | python | def get_attachment(self, file_path):
'''Get file as MIMEBase message'''
try:
file_ = open(file_path, 'rb')
attachment = MIMEBase('application', 'octet-stream')
attachment.set_payload(file_.read())
file_.close()
encoders.encode_base64(attachment)
attachment.add_header('Content-Disposition', 'attachment',
filename=os.path.basename(file_path))
return attachment
except IOError:
traceback.print_exc()
message = ('The requested file could not be read. Maybe wrong '
'permissions?')
print >> sys.stderr, message
sys.exit(6) | [
"def",
"get_attachment",
"(",
"self",
",",
"file_path",
")",
":",
"try",
":",
"file_",
"=",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"attachment",
"=",
"MIMEBase",
"(",
"'application'",
",",
"'octet-stream'",
")",
"attachment",
".",
"set_payload",
"(",
"file_",
".",
"read",
"(",
")",
")",
"file_",
".",
"close",
"(",
")",
"encoders",
".",
"encode_base64",
"(",
"attachment",
")",
"attachment",
".",
"add_header",
"(",
"'Content-Disposition'",
",",
"'attachment'",
",",
"filename",
"=",
"os",
".",
"path",
".",
"basename",
"(",
"file_path",
")",
")",
"return",
"attachment",
"except",
"IOError",
":",
"traceback",
".",
"print_exc",
"(",
")",
"message",
"=",
"(",
"'The requested file could not be read. Maybe wrong '",
"'permissions?'",
")",
"print",
">>",
"sys",
".",
"stderr",
",",
"message",
"sys",
".",
"exit",
"(",
"6",
")"
] | Get file as MIMEBase message | [
"Get",
"file",
"as",
"MIMEBase",
"message"
] | 98038d746aa67e343b73b3ccee1e02d31dab81ec | https://github.com/thespacedoctor/polyglot/blob/98038d746aa67e343b73b3ccee1e02d31dab81ec/polyglot/kindle.py#L148-L166 | train |
piotr-rusin/spam-lists | spam_lists/host_list.py | HostList.lookup | def lookup(self, host_value):
"""Get a host value matching the given value.
:param host_value: a value of the host of a type that can be
listed by the service
:returns: an instance of AddressListItem representing
a matched value
:raises InvalidHostError: if the argument is not a valid
host string
"""
try:
host_object = self._host_factory(host_value)
except InvalidHostError:
return None
result = self._get_match_and_classification(
host_object
)
host_item, classification = result
if host_item is not None:
return AddressListItem(
host_item.to_unicode(),
self,
classification
)
return None | python | def lookup(self, host_value):
"""Get a host value matching the given value.
:param host_value: a value of the host of a type that can be
listed by the service
:returns: an instance of AddressListItem representing
a matched value
:raises InvalidHostError: if the argument is not a valid
host string
"""
try:
host_object = self._host_factory(host_value)
except InvalidHostError:
return None
result = self._get_match_and_classification(
host_object
)
host_item, classification = result
if host_item is not None:
return AddressListItem(
host_item.to_unicode(),
self,
classification
)
return None | [
"def",
"lookup",
"(",
"self",
",",
"host_value",
")",
":",
"try",
":",
"host_object",
"=",
"self",
".",
"_host_factory",
"(",
"host_value",
")",
"except",
"InvalidHostError",
":",
"return",
"None",
"result",
"=",
"self",
".",
"_get_match_and_classification",
"(",
"host_object",
")",
"host_item",
",",
"classification",
"=",
"result",
"if",
"host_item",
"is",
"not",
"None",
":",
"return",
"AddressListItem",
"(",
"host_item",
".",
"to_unicode",
"(",
")",
",",
"self",
",",
"classification",
")",
"return",
"None"
] | Get a host value matching the given value.
:param host_value: a value of the host of a type that can be
listed by the service
:returns: an instance of AddressListItem representing
a matched value
:raises InvalidHostError: if the argument is not a valid
host string | [
"Get",
"a",
"host",
"value",
"matching",
"the",
"given",
"value",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L66-L90 | train |
piotr-rusin/spam-lists | spam_lists/host_list.py | HostList.any_match | def any_match(self, urls):
"""Check if any of the given URLs has a matching host.
:param urls: an iterable containing URLs
:returns: True if any host has a listed match
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
return any(urlparse(u).hostname in self for u in urls) | python | def any_match(self, urls):
"""Check if any of the given URLs has a matching host.
:param urls: an iterable containing URLs
:returns: True if any host has a listed match
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
return any(urlparse(u).hostname in self for u in urls) | [
"def",
"any_match",
"(",
"self",
",",
"urls",
")",
":",
"return",
"any",
"(",
"urlparse",
"(",
"u",
")",
".",
"hostname",
"in",
"self",
"for",
"u",
"in",
"urls",
")"
] | Check if any of the given URLs has a matching host.
:param urls: an iterable containing URLs
:returns: True if any host has a listed match
:raises InvalidURLError: if there are any invalid URLs in
the sequence | [
"Check",
"if",
"any",
"of",
"the",
"given",
"URLs",
"has",
"a",
"matching",
"host",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L93-L101 | train |
piotr-rusin/spam-lists | spam_lists/host_list.py | HostList.lookup_matching | def lookup_matching(self, urls):
"""Get matching hosts for the given URLs.
:param urls: an iterable containing URLs
:returns: instances of AddressListItem representing listed
hosts matching the ones used by the given URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
hosts = (urlparse(u).hostname for u in urls)
for val in hosts:
item = self.lookup(val)
if item is not None:
yield item | python | def lookup_matching(self, urls):
"""Get matching hosts for the given URLs.
:param urls: an iterable containing URLs
:returns: instances of AddressListItem representing listed
hosts matching the ones used by the given URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
hosts = (urlparse(u).hostname for u in urls)
for val in hosts:
item = self.lookup(val)
if item is not None:
yield item | [
"def",
"lookup_matching",
"(",
"self",
",",
"urls",
")",
":",
"hosts",
"=",
"(",
"urlparse",
"(",
"u",
")",
".",
"hostname",
"for",
"u",
"in",
"urls",
")",
"for",
"val",
"in",
"hosts",
":",
"item",
"=",
"self",
".",
"lookup",
"(",
"val",
")",
"if",
"item",
"is",
"not",
"None",
":",
"yield",
"item"
] | Get matching hosts for the given URLs.
:param urls: an iterable containing URLs
:returns: instances of AddressListItem representing listed
hosts matching the ones used by the given URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence | [
"Get",
"matching",
"hosts",
"for",
"the",
"given",
"URLs",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L104-L117 | train |
piotr-rusin/spam-lists | spam_lists/host_list.py | HostList.filter_matching | def filter_matching(self, urls):
"""Get URLs with hosts matching any listed ones.
:param urls: an iterable containing URLs to filter
:returns: a generator yielding matching URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
for url in urls:
if urlparse(url).hostname in self:
yield url | python | def filter_matching(self, urls):
"""Get URLs with hosts matching any listed ones.
:param urls: an iterable containing URLs to filter
:returns: a generator yielding matching URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
for url in urls:
if urlparse(url).hostname in self:
yield url | [
"def",
"filter_matching",
"(",
"self",
",",
"urls",
")",
":",
"for",
"url",
"in",
"urls",
":",
"if",
"urlparse",
"(",
"url",
")",
".",
"hostname",
"in",
"self",
":",
"yield",
"url"
] | Get URLs with hosts matching any listed ones.
:param urls: an iterable containing URLs to filter
:returns: a generator yielding matching URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence | [
"Get",
"URLs",
"with",
"hosts",
"matching",
"any",
"listed",
"ones",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/host_list.py#L120-L130 | train |
TkTech/Jawa | jawa/util/utf.py | decode_modified_utf8 | def decode_modified_utf8(s: bytes) -> str:
"""
Decodes a bytestring containing modified UTF-8 as defined in section
4.4.7 of the JVM specification.
:param s: bytestring to be converted.
:returns: A unicode representation of the original string.
"""
s = bytearray(s)
buff = []
buffer_append = buff.append
ix = 0
while ix < len(s):
x = s[ix]
ix += 1
if x >> 7 == 0:
# Just an ASCII character, nothing else to do.
pass
elif x >> 6 == 6:
y = s[ix]
ix += 1
x = ((x & 0x1F) << 6) + (y & 0x3F)
elif x >> 4 == 14:
y, z = s[ix:ix+2]
ix += 2
x = ((x & 0xF) << 12) + ((y & 0x3F) << 6) + (z & 0x3F)
elif x == 0xED:
v, w, x, y, z = s[ix:ix+6]
ix += 5
x = 0x10000 + (
((v & 0x0F) << 16) +
((w & 0x3F) << 10) +
((y & 0x0F) << 6) +
(z & 0x3F)
)
elif x == 0xC0 and s[ix] == 0x80:
ix += 1
x = 0
buffer_append(x)
return u''.join(chr(b) for b in buff) | python | def decode_modified_utf8(s: bytes) -> str:
"""
Decodes a bytestring containing modified UTF-8 as defined in section
4.4.7 of the JVM specification.
:param s: bytestring to be converted.
:returns: A unicode representation of the original string.
"""
s = bytearray(s)
buff = []
buffer_append = buff.append
ix = 0
while ix < len(s):
x = s[ix]
ix += 1
if x >> 7 == 0:
# Just an ASCII character, nothing else to do.
pass
elif x >> 6 == 6:
y = s[ix]
ix += 1
x = ((x & 0x1F) << 6) + (y & 0x3F)
elif x >> 4 == 14:
y, z = s[ix:ix+2]
ix += 2
x = ((x & 0xF) << 12) + ((y & 0x3F) << 6) + (z & 0x3F)
elif x == 0xED:
v, w, x, y, z = s[ix:ix+6]
ix += 5
x = 0x10000 + (
((v & 0x0F) << 16) +
((w & 0x3F) << 10) +
((y & 0x0F) << 6) +
(z & 0x3F)
)
elif x == 0xC0 and s[ix] == 0x80:
ix += 1
x = 0
buffer_append(x)
return u''.join(chr(b) for b in buff) | [
"def",
"decode_modified_utf8",
"(",
"s",
":",
"bytes",
")",
"->",
"str",
":",
"s",
"=",
"bytearray",
"(",
"s",
")",
"buff",
"=",
"[",
"]",
"buffer_append",
"=",
"buff",
".",
"append",
"ix",
"=",
"0",
"while",
"ix",
"<",
"len",
"(",
"s",
")",
":",
"x",
"=",
"s",
"[",
"ix",
"]",
"ix",
"+=",
"1",
"if",
"x",
">>",
"7",
"==",
"0",
":",
"# Just an ASCII character, nothing else to do.",
"pass",
"elif",
"x",
">>",
"6",
"==",
"6",
":",
"y",
"=",
"s",
"[",
"ix",
"]",
"ix",
"+=",
"1",
"x",
"=",
"(",
"(",
"x",
"&",
"0x1F",
")",
"<<",
"6",
")",
"+",
"(",
"y",
"&",
"0x3F",
")",
"elif",
"x",
">>",
"4",
"==",
"14",
":",
"y",
",",
"z",
"=",
"s",
"[",
"ix",
":",
"ix",
"+",
"2",
"]",
"ix",
"+=",
"2",
"x",
"=",
"(",
"(",
"x",
"&",
"0xF",
")",
"<<",
"12",
")",
"+",
"(",
"(",
"y",
"&",
"0x3F",
")",
"<<",
"6",
")",
"+",
"(",
"z",
"&",
"0x3F",
")",
"elif",
"x",
"==",
"0xED",
":",
"v",
",",
"w",
",",
"x",
",",
"y",
",",
"z",
"=",
"s",
"[",
"ix",
":",
"ix",
"+",
"6",
"]",
"ix",
"+=",
"5",
"x",
"=",
"0x10000",
"+",
"(",
"(",
"(",
"v",
"&",
"0x0F",
")",
"<<",
"16",
")",
"+",
"(",
"(",
"w",
"&",
"0x3F",
")",
"<<",
"10",
")",
"+",
"(",
"(",
"y",
"&",
"0x0F",
")",
"<<",
"6",
")",
"+",
"(",
"z",
"&",
"0x3F",
")",
")",
"elif",
"x",
"==",
"0xC0",
"and",
"s",
"[",
"ix",
"]",
"==",
"0x80",
":",
"ix",
"+=",
"1",
"x",
"=",
"0",
"buffer_append",
"(",
"x",
")",
"return",
"u''",
".",
"join",
"(",
"chr",
"(",
"b",
")",
"for",
"b",
"in",
"buff",
")"
] | Decodes a bytestring containing modified UTF-8 as defined in section
4.4.7 of the JVM specification.
:param s: bytestring to be converted.
:returns: A unicode representation of the original string. | [
"Decodes",
"a",
"bytestring",
"containing",
"modified",
"UTF",
"-",
"8",
"as",
"defined",
"in",
"section",
"4",
".",
"4",
".",
"7",
"of",
"the",
"JVM",
"specification",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/utf.py#L12-L52 | train |
TkTech/Jawa | jawa/util/utf.py | encode_modified_utf8 | def encode_modified_utf8(u: str) -> bytearray:
"""
Encodes a unicode string as modified UTF-8 as defined in section 4.4.7
of the JVM specification.
:param u: unicode string to be converted.
:returns: A decoded bytearray.
"""
final_string = bytearray()
for c in [ord(char) for char in u]:
if c == 0x00 or (0x80 < c < 0x7FF):
final_string.extend([
(0xC0 | (0x1F & (c >> 6))),
(0x80 | (0x3F & c))]
)
elif c < 0x7F:
final_string.append(c)
elif 0x800 < c < 0xFFFF:
final_string.extend([
(0xE0 | (0x0F & (c >> 12))),
(0x80 | (0x3F & (c >> 6))),
(0x80 | (0x3F & c))]
)
return final_string | python | def encode_modified_utf8(u: str) -> bytearray:
"""
Encodes a unicode string as modified UTF-8 as defined in section 4.4.7
of the JVM specification.
:param u: unicode string to be converted.
:returns: A decoded bytearray.
"""
final_string = bytearray()
for c in [ord(char) for char in u]:
if c == 0x00 or (0x80 < c < 0x7FF):
final_string.extend([
(0xC0 | (0x1F & (c >> 6))),
(0x80 | (0x3F & c))]
)
elif c < 0x7F:
final_string.append(c)
elif 0x800 < c < 0xFFFF:
final_string.extend([
(0xE0 | (0x0F & (c >> 12))),
(0x80 | (0x3F & (c >> 6))),
(0x80 | (0x3F & c))]
)
return final_string | [
"def",
"encode_modified_utf8",
"(",
"u",
":",
"str",
")",
"->",
"bytearray",
":",
"final_string",
"=",
"bytearray",
"(",
")",
"for",
"c",
"in",
"[",
"ord",
"(",
"char",
")",
"for",
"char",
"in",
"u",
"]",
":",
"if",
"c",
"==",
"0x00",
"or",
"(",
"0x80",
"<",
"c",
"<",
"0x7FF",
")",
":",
"final_string",
".",
"extend",
"(",
"[",
"(",
"0xC0",
"|",
"(",
"0x1F",
"&",
"(",
"c",
">>",
"6",
")",
")",
")",
",",
"(",
"0x80",
"|",
"(",
"0x3F",
"&",
"c",
")",
")",
"]",
")",
"elif",
"c",
"<",
"0x7F",
":",
"final_string",
".",
"append",
"(",
"c",
")",
"elif",
"0x800",
"<",
"c",
"<",
"0xFFFF",
":",
"final_string",
".",
"extend",
"(",
"[",
"(",
"0xE0",
"|",
"(",
"0x0F",
"&",
"(",
"c",
">>",
"12",
")",
")",
")",
",",
"(",
"0x80",
"|",
"(",
"0x3F",
"&",
"(",
"c",
">>",
"6",
")",
")",
")",
",",
"(",
"0x80",
"|",
"(",
"0x3F",
"&",
"c",
")",
")",
"]",
")",
"return",
"final_string"
] | Encodes a unicode string as modified UTF-8 as defined in section 4.4.7
of the JVM specification.
:param u: unicode string to be converted.
:returns: A decoded bytearray. | [
"Encodes",
"a",
"unicode",
"string",
"as",
"modified",
"UTF",
"-",
"8",
"as",
"defined",
"in",
"section",
"4",
".",
"4",
".",
"7",
"of",
"the",
"JVM",
"specification",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/util/utf.py#L55-L80 | train |
nitely/django-hooks | hooks/templatehook.py | Hook.unregister | def unregister(self, name, func):
"""
Remove a previously registered callback
:param str name: Hook name
:param callable func: A function reference\
that was registered previously
"""
try:
templatehook = self._registry[name]
except KeyError:
return
templatehook.unregister(func) | python | def unregister(self, name, func):
"""
Remove a previously registered callback
:param str name: Hook name
:param callable func: A function reference\
that was registered previously
"""
try:
templatehook = self._registry[name]
except KeyError:
return
templatehook.unregister(func) | [
"def",
"unregister",
"(",
"self",
",",
"name",
",",
"func",
")",
":",
"try",
":",
"templatehook",
"=",
"self",
".",
"_registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"templatehook",
".",
"unregister",
"(",
"func",
")"
] | Remove a previously registered callback
:param str name: Hook name
:param callable func: A function reference\
that was registered previously | [
"Remove",
"a",
"previously",
"registered",
"callback"
] | 26ea2150c9be110e90b9ee60fbfd1065ac30ab1d | https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatehook.py#L117-L130 | train |
nitely/django-hooks | hooks/templatehook.py | Hook.unregister_all | def unregister_all(self, name):
"""
Remove all callbacks
:param str name: Hook name
"""
try:
templatehook = self._registry[name]
except KeyError:
return
templatehook.unregister_all() | python | def unregister_all(self, name):
"""
Remove all callbacks
:param str name: Hook name
"""
try:
templatehook = self._registry[name]
except KeyError:
return
templatehook.unregister_all() | [
"def",
"unregister_all",
"(",
"self",
",",
"name",
")",
":",
"try",
":",
"templatehook",
"=",
"self",
".",
"_registry",
"[",
"name",
"]",
"except",
"KeyError",
":",
"return",
"templatehook",
".",
"unregister_all",
"(",
")"
] | Remove all callbacks
:param str name: Hook name | [
"Remove",
"all",
"callbacks"
] | 26ea2150c9be110e90b9ee60fbfd1065ac30ab1d | https://github.com/nitely/django-hooks/blob/26ea2150c9be110e90b9ee60fbfd1065ac30ab1d/hooks/templatehook.py#L132-L143 | train |
mezz64/pyEmby | pyemby/helpers.py | deprecated_name | def deprecated_name(name):
"""Allow old method names for backwards compatability. """
def decorator(func):
"""Decorator function."""
def func_wrapper(self):
"""Wrapper for original function."""
if hasattr(self, name):
# Return the old property
return getattr(self, name)
else:
return func(self)
return func_wrapper
return decorator | python | def deprecated_name(name):
"""Allow old method names for backwards compatability. """
def decorator(func):
"""Decorator function."""
def func_wrapper(self):
"""Wrapper for original function."""
if hasattr(self, name):
# Return the old property
return getattr(self, name)
else:
return func(self)
return func_wrapper
return decorator | [
"def",
"deprecated_name",
"(",
"name",
")",
":",
"def",
"decorator",
"(",
"func",
")",
":",
"\"\"\"Decorator function.\"\"\"",
"def",
"func_wrapper",
"(",
"self",
")",
":",
"\"\"\"Wrapper for original function.\"\"\"",
"if",
"hasattr",
"(",
"self",
",",
"name",
")",
":",
"# Return the old property",
"return",
"getattr",
"(",
"self",
",",
"name",
")",
"else",
":",
"return",
"func",
"(",
"self",
")",
"return",
"func_wrapper",
"return",
"decorator"
] | Allow old method names for backwards compatability. | [
"Allow",
"old",
"method",
"names",
"for",
"backwards",
"compatability",
"."
] | 6bb621e4e25bf1b9b0aba2c38b588e68f8816226 | https://github.com/mezz64/pyEmby/blob/6bb621e4e25bf1b9b0aba2c38b588e68f8816226/pyemby/helpers.py#L10-L22 | train |
rhattersley/pyepsg | pyepsg.py | get | def get(code):
"""
Return an object that corresponds to the given EPSG code.
Currently supported object types are:
- :class:`GeodeticCRS`
- :class:`ProjectedCRS`
- :class:`CartesianCS`
- :class:`UOM`
For example::
>>> print(get(27700))
<ProjectedCRS: 27700, OSGB 1936 / British National Grid>
>>> print(get('4400-cs'))
<CartesianCS: Cartesian 2D CS. Axes: easting, northi..>
>>> print(get(5973))
<CompoundCRS: 5973, ETRS89 / UTM zone 33 + NN2000 height>
"""
instance = _cache.get(code)
if instance is None:
url = '{prefix}{code}.gml?download'.format(prefix=EPSG_IO_URL,
code=code)
xml = requests.get(url).content
root = ET.fromstring(xml)
class_for_tag = {
GML_NS + 'CartesianCS': CartesianCS,
GML_NS + 'GeodeticCRS': GeodeticCRS,
GML_NS + 'ProjectedCRS': ProjectedCRS,
GML_NS + 'CompoundCRS': CompoundCRS,
GML_NS + 'BaseUnit': UOM,
}
if root.tag in class_for_tag:
instance = class_for_tag[root.tag](root)
else:
raise ValueError('Unsupported code type: {}'.format(root.tag))
_cache[code] = instance
return instance | python | def get(code):
"""
Return an object that corresponds to the given EPSG code.
Currently supported object types are:
- :class:`GeodeticCRS`
- :class:`ProjectedCRS`
- :class:`CartesianCS`
- :class:`UOM`
For example::
>>> print(get(27700))
<ProjectedCRS: 27700, OSGB 1936 / British National Grid>
>>> print(get('4400-cs'))
<CartesianCS: Cartesian 2D CS. Axes: easting, northi..>
>>> print(get(5973))
<CompoundCRS: 5973, ETRS89 / UTM zone 33 + NN2000 height>
"""
instance = _cache.get(code)
if instance is None:
url = '{prefix}{code}.gml?download'.format(prefix=EPSG_IO_URL,
code=code)
xml = requests.get(url).content
root = ET.fromstring(xml)
class_for_tag = {
GML_NS + 'CartesianCS': CartesianCS,
GML_NS + 'GeodeticCRS': GeodeticCRS,
GML_NS + 'ProjectedCRS': ProjectedCRS,
GML_NS + 'CompoundCRS': CompoundCRS,
GML_NS + 'BaseUnit': UOM,
}
if root.tag in class_for_tag:
instance = class_for_tag[root.tag](root)
else:
raise ValueError('Unsupported code type: {}'.format(root.tag))
_cache[code] = instance
return instance | [
"def",
"get",
"(",
"code",
")",
":",
"instance",
"=",
"_cache",
".",
"get",
"(",
"code",
")",
"if",
"instance",
"is",
"None",
":",
"url",
"=",
"'{prefix}{code}.gml?download'",
".",
"format",
"(",
"prefix",
"=",
"EPSG_IO_URL",
",",
"code",
"=",
"code",
")",
"xml",
"=",
"requests",
".",
"get",
"(",
"url",
")",
".",
"content",
"root",
"=",
"ET",
".",
"fromstring",
"(",
"xml",
")",
"class_for_tag",
"=",
"{",
"GML_NS",
"+",
"'CartesianCS'",
":",
"CartesianCS",
",",
"GML_NS",
"+",
"'GeodeticCRS'",
":",
"GeodeticCRS",
",",
"GML_NS",
"+",
"'ProjectedCRS'",
":",
"ProjectedCRS",
",",
"GML_NS",
"+",
"'CompoundCRS'",
":",
"CompoundCRS",
",",
"GML_NS",
"+",
"'BaseUnit'",
":",
"UOM",
",",
"}",
"if",
"root",
".",
"tag",
"in",
"class_for_tag",
":",
"instance",
"=",
"class_for_tag",
"[",
"root",
".",
"tag",
"]",
"(",
"root",
")",
"else",
":",
"raise",
"ValueError",
"(",
"'Unsupported code type: {}'",
".",
"format",
"(",
"root",
".",
"tag",
")",
")",
"_cache",
"[",
"code",
"]",
"=",
"instance",
"return",
"instance"
] | Return an object that corresponds to the given EPSG code.
Currently supported object types are:
- :class:`GeodeticCRS`
- :class:`ProjectedCRS`
- :class:`CartesianCS`
- :class:`UOM`
For example::
>>> print(get(27700))
<ProjectedCRS: 27700, OSGB 1936 / British National Grid>
>>> print(get('4400-cs'))
<CartesianCS: Cartesian 2D CS. Axes: easting, northi..>
>>> print(get(5973))
<CompoundCRS: 5973, ETRS89 / UTM zone 33 + NN2000 height> | [
"Return",
"an",
"object",
"that",
"corresponds",
"to",
"the",
"given",
"EPSG",
"code",
"."
] | 0ddd79287f8d42483c8f70ce50aba1cc6b5d780a | https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L263-L301 | train |
rhattersley/pyepsg | pyepsg.py | CRS.id | def id(self):
"""The EPSG code for this CRS."""
id = self.element.attrib[GML_NS + 'id']
code = id.split('-')[-1]
return code | python | def id(self):
"""The EPSG code for this CRS."""
id = self.element.attrib[GML_NS + 'id']
code = id.split('-')[-1]
return code | [
"def",
"id",
"(",
"self",
")",
":",
"id",
"=",
"self",
".",
"element",
".",
"attrib",
"[",
"GML_NS",
"+",
"'id'",
"]",
"code",
"=",
"id",
".",
"split",
"(",
"'-'",
")",
"[",
"-",
"1",
"]",
"return",
"code"
] | The EPSG code for this CRS. | [
"The",
"EPSG",
"code",
"for",
"this",
"CRS",
"."
] | 0ddd79287f8d42483c8f70ce50aba1cc6b5d780a | https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L112-L116 | train |
rhattersley/pyepsg | pyepsg.py | CRS.as_html | def as_html(self):
"""
Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span...
"""
url = '{prefix}{code}.html?download'.format(prefix=EPSG_IO_URL,
code=self.id)
return requests.get(url).text | python | def as_html(self):
"""
Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span...
"""
url = '{prefix}{code}.html?download'.format(prefix=EPSG_IO_URL,
code=self.id)
return requests.get(url).text | [
"def",
"as_html",
"(",
"self",
")",
":",
"url",
"=",
"'{prefix}{code}.html?download'",
".",
"format",
"(",
"prefix",
"=",
"EPSG_IO_URL",
",",
"code",
"=",
"self",
".",
"id",
")",
"return",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text"
] | Return the OGC WKT which corresponds to the CRS as HTML.
For example::
>>> print(get(27700).as_html()) # doctest: +ELLIPSIS
<div class="syntax"><pre><span class="gh">PROJCS</span><span... | [
"Return",
"the",
"OGC",
"WKT",
"which",
"corresponds",
"to",
"the",
"CRS",
"as",
"HTML",
"."
] | 0ddd79287f8d42483c8f70ce50aba1cc6b5d780a | https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L142-L154 | train |
rhattersley/pyepsg | pyepsg.py | CRS.as_proj4 | def as_proj4(self):
"""
Return the PROJ.4 string which corresponds to the CRS.
For example::
>>> print(get(21781).as_proj4())
+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \
+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \
+towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs
"""
url = '{prefix}{code}.proj4?download'.format(prefix=EPSG_IO_URL,
code=self.id)
return requests.get(url).text.strip() | python | def as_proj4(self):
"""
Return the PROJ.4 string which corresponds to the CRS.
For example::
>>> print(get(21781).as_proj4())
+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \
+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \
+towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs
"""
url = '{prefix}{code}.proj4?download'.format(prefix=EPSG_IO_URL,
code=self.id)
return requests.get(url).text.strip() | [
"def",
"as_proj4",
"(",
"self",
")",
":",
"url",
"=",
"'{prefix}{code}.proj4?download'",
".",
"format",
"(",
"prefix",
"=",
"EPSG_IO_URL",
",",
"code",
"=",
"self",
".",
"id",
")",
"return",
"requests",
".",
"get",
"(",
"url",
")",
".",
"text",
".",
"strip",
"(",
")"
] | Return the PROJ.4 string which corresponds to the CRS.
For example::
>>> print(get(21781).as_proj4())
+proj=somerc +lat_0=46.95240555555556 +lon_0=7.439583333333333 \
+k_0=1 +x_0=600000 +y_0=200000 +ellps=bessel \
+towgs84=674.4,15.1,405.3,0,0,0,0 +units=m +no_defs | [
"Return",
"the",
"PROJ",
".",
"4",
"string",
"which",
"corresponds",
"to",
"the",
"CRS",
"."
] | 0ddd79287f8d42483c8f70ce50aba1cc6b5d780a | https://github.com/rhattersley/pyepsg/blob/0ddd79287f8d42483c8f70ce50aba1cc6b5d780a/pyepsg.py#L156-L170 | train |
TkTech/Jawa | jawa/methods.py | MethodTable.remove | def remove(self, method: Method):
"""
Removes a `method` from the table by identity.
"""
self._table = [fld for fld in self._table if fld is not method] | python | def remove(self, method: Method):
"""
Removes a `method` from the table by identity.
"""
self._table = [fld for fld in self._table if fld is not method] | [
"def",
"remove",
"(",
"self",
",",
"method",
":",
"Method",
")",
":",
"self",
".",
"_table",
"=",
"[",
"fld",
"for",
"fld",
"in",
"self",
".",
"_table",
"if",
"fld",
"is",
"not",
"method",
"]"
] | Removes a `method` from the table by identity. | [
"Removes",
"a",
"method",
"from",
"the",
"table",
"by",
"identity",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L122-L126 | train |
TkTech/Jawa | jawa/methods.py | MethodTable.create | def create(self, name: str, descriptor: str,
code: CodeAttribute=None) -> Method:
"""
Creates a new method from `name` and `descriptor`. If `code` is not
``None``, add a `Code` attribute to this method.
"""
method = Method(self._cf)
name = self._cf.constants.create_utf8(name)
descriptor = self._cf.constants.create_utf8(descriptor)
method._name_index = name.index
method._descriptor_index = descriptor.index
method.access_flags.acc_public = True
if code is not None:
method.attributes.create(CodeAttribute)
self.append(method)
return method | python | def create(self, name: str, descriptor: str,
code: CodeAttribute=None) -> Method:
"""
Creates a new method from `name` and `descriptor`. If `code` is not
``None``, add a `Code` attribute to this method.
"""
method = Method(self._cf)
name = self._cf.constants.create_utf8(name)
descriptor = self._cf.constants.create_utf8(descriptor)
method._name_index = name.index
method._descriptor_index = descriptor.index
method.access_flags.acc_public = True
if code is not None:
method.attributes.create(CodeAttribute)
self.append(method)
return method | [
"def",
"create",
"(",
"self",
",",
"name",
":",
"str",
",",
"descriptor",
":",
"str",
",",
"code",
":",
"CodeAttribute",
"=",
"None",
")",
"->",
"Method",
":",
"method",
"=",
"Method",
"(",
"self",
".",
"_cf",
")",
"name",
"=",
"self",
".",
"_cf",
".",
"constants",
".",
"create_utf8",
"(",
"name",
")",
"descriptor",
"=",
"self",
".",
"_cf",
".",
"constants",
".",
"create_utf8",
"(",
"descriptor",
")",
"method",
".",
"_name_index",
"=",
"name",
".",
"index",
"method",
".",
"_descriptor_index",
"=",
"descriptor",
".",
"index",
"method",
".",
"access_flags",
".",
"acc_public",
"=",
"True",
"if",
"code",
"is",
"not",
"None",
":",
"method",
".",
"attributes",
".",
"create",
"(",
"CodeAttribute",
")",
"self",
".",
"append",
"(",
"method",
")",
"return",
"method"
] | Creates a new method from `name` and `descriptor`. If `code` is not
``None``, add a `Code` attribute to this method. | [
"Creates",
"a",
"new",
"method",
"from",
"name",
"and",
"descriptor",
".",
"If",
"code",
"is",
"not",
"None",
"add",
"a",
"Code",
"attribute",
"to",
"this",
"method",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L128-L145 | train |
TkTech/Jawa | jawa/methods.py | MethodTable.unpack | def unpack(self, source: IO):
"""
Read the MethodTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
method_count = unpack('>H', source.read(2))[0]
for _ in repeat(None, method_count):
method = Method(self._cf)
method.unpack(source)
self.append(method) | python | def unpack(self, source: IO):
"""
Read the MethodTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()`
"""
method_count = unpack('>H', source.read(2))[0]
for _ in repeat(None, method_count):
method = Method(self._cf)
method.unpack(source)
self.append(method) | [
"def",
"unpack",
"(",
"self",
",",
"source",
":",
"IO",
")",
":",
"method_count",
"=",
"unpack",
"(",
"'>H'",
",",
"source",
".",
"read",
"(",
"2",
")",
")",
"[",
"0",
"]",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"method_count",
")",
":",
"method",
"=",
"Method",
"(",
"self",
".",
"_cf",
")",
"method",
".",
"unpack",
"(",
"source",
")",
"self",
".",
"append",
"(",
"method",
")"
] | Read the MethodTable from the file-like object `source`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param source: Any file-like object providing `read()` | [
"Read",
"the",
"MethodTable",
"from",
"the",
"file",
"-",
"like",
"object",
"source",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L151-L166 | train |
TkTech/Jawa | jawa/methods.py | MethodTable.pack | def pack(self, out: IO):
"""
Write the MethodTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self)))
for method in self._table:
method.pack(out) | python | def pack(self, out: IO):
"""
Write the MethodTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()`
"""
out.write(pack('>H', len(self)))
for method in self._table:
method.pack(out) | [
"def",
"pack",
"(",
"self",
",",
"out",
":",
"IO",
")",
":",
"out",
".",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"len",
"(",
"self",
")",
")",
")",
"for",
"method",
"in",
"self",
".",
"_table",
":",
"method",
".",
"pack",
"(",
"out",
")"
] | Write the MethodTable to the file-like object `out`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when saving a ClassFile.
:param out: Any file-like object providing `write()` | [
"Write",
"the",
"MethodTable",
"to",
"the",
"file",
"-",
"like",
"object",
"out",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/methods.py#L168-L181 | train |
TkTech/Jawa | jawa/attributes/code.py | CodeAttribute.unpack | def unpack(self, info):
"""
Read the CodeAttribute from the byte string `info`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param info: A byte string containing an unparsed CodeAttribute.
"""
self.max_stack, self.max_locals, c_len = info.unpack('>HHI')
self._code = info.read(c_len)
# The exception table
ex_table_len = info.u2()
for _ in repeat(None, ex_table_len):
self.exception_table.append(CodeException(
*info.unpack('>HHHH')
))
self.attributes = AttributeTable(self.cf, parent=self)
self.attributes.unpack(info) | python | def unpack(self, info):
"""
Read the CodeAttribute from the byte string `info`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param info: A byte string containing an unparsed CodeAttribute.
"""
self.max_stack, self.max_locals, c_len = info.unpack('>HHI')
self._code = info.read(c_len)
# The exception table
ex_table_len = info.u2()
for _ in repeat(None, ex_table_len):
self.exception_table.append(CodeException(
*info.unpack('>HHHH')
))
self.attributes = AttributeTable(self.cf, parent=self)
self.attributes.unpack(info) | [
"def",
"unpack",
"(",
"self",
",",
"info",
")",
":",
"self",
".",
"max_stack",
",",
"self",
".",
"max_locals",
",",
"c_len",
"=",
"info",
".",
"unpack",
"(",
"'>HHI'",
")",
"self",
".",
"_code",
"=",
"info",
".",
"read",
"(",
"c_len",
")",
"# The exception table",
"ex_table_len",
"=",
"info",
".",
"u2",
"(",
")",
"for",
"_",
"in",
"repeat",
"(",
"None",
",",
"ex_table_len",
")",
":",
"self",
".",
"exception_table",
".",
"append",
"(",
"CodeException",
"(",
"*",
"info",
".",
"unpack",
"(",
"'>HHHH'",
")",
")",
")",
"self",
".",
"attributes",
"=",
"AttributeTable",
"(",
"self",
".",
"cf",
",",
"parent",
"=",
"self",
")",
"self",
".",
"attributes",
".",
"unpack",
"(",
"info",
")"
] | Read the CodeAttribute from the byte string `info`.
.. note::
Advanced usage only. You will typically never need to call this
method as it will be called for you when loading a ClassFile.
:param info: A byte string containing an unparsed CodeAttribute. | [
"Read",
"the",
"CodeAttribute",
"from",
"the",
"byte",
"string",
"info",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attributes/code.py#L70-L91 | train |
TkTech/Jawa | jawa/attributes/code.py | CodeAttribute.pack | def pack(self):
"""
The `CodeAttribute` in packed byte string form.
"""
with io.BytesIO() as file_out:
file_out.write(pack(
'>HHI',
self.max_stack,
self.max_locals,
len(self._code)
))
file_out.write(self._code)
file_out.write(pack('>H', len(self.exception_table)))
for exception in self.exception_table:
file_out.write(pack('>HHHH', *exception))
self.attributes.pack(file_out)
return file_out.getvalue() | python | def pack(self):
"""
The `CodeAttribute` in packed byte string form.
"""
with io.BytesIO() as file_out:
file_out.write(pack(
'>HHI',
self.max_stack,
self.max_locals,
len(self._code)
))
file_out.write(self._code)
file_out.write(pack('>H', len(self.exception_table)))
for exception in self.exception_table:
file_out.write(pack('>HHHH', *exception))
self.attributes.pack(file_out)
return file_out.getvalue() | [
"def",
"pack",
"(",
"self",
")",
":",
"with",
"io",
".",
"BytesIO",
"(",
")",
"as",
"file_out",
":",
"file_out",
".",
"write",
"(",
"pack",
"(",
"'>HHI'",
",",
"self",
".",
"max_stack",
",",
"self",
".",
"max_locals",
",",
"len",
"(",
"self",
".",
"_code",
")",
")",
")",
"file_out",
".",
"write",
"(",
"self",
".",
"_code",
")",
"file_out",
".",
"write",
"(",
"pack",
"(",
"'>H'",
",",
"len",
"(",
"self",
".",
"exception_table",
")",
")",
")",
"for",
"exception",
"in",
"self",
".",
"exception_table",
":",
"file_out",
".",
"write",
"(",
"pack",
"(",
"'>HHHH'",
",",
"*",
"exception",
")",
")",
"self",
".",
"attributes",
".",
"pack",
"(",
"file_out",
")",
"return",
"file_out",
".",
"getvalue",
"(",
")"
] | The `CodeAttribute` in packed byte string form. | [
"The",
"CodeAttribute",
"in",
"packed",
"byte",
"string",
"form",
"."
] | 94c8424e699029ac33fbc0e866fff0ecb2742289 | https://github.com/TkTech/Jawa/blob/94c8424e699029ac33fbc0e866fff0ecb2742289/jawa/attributes/code.py#L93-L111 | train |
jaapz/cast | cast.py | _volume_command | def _volume_command(ramp, volume):
""" Set the value if a volume level is provided, else print the current
volume level. """
if volume is not None:
ramp.set_volume(float(volume))
else:
print ramp.volume | python | def _volume_command(ramp, volume):
""" Set the value if a volume level is provided, else print the current
volume level. """
if volume is not None:
ramp.set_volume(float(volume))
else:
print ramp.volume | [
"def",
"_volume_command",
"(",
"ramp",
",",
"volume",
")",
":",
"if",
"volume",
"is",
"not",
"None",
":",
"ramp",
".",
"set_volume",
"(",
"float",
"(",
"volume",
")",
")",
"else",
":",
"print",
"ramp",
".",
"volume"
] | Set the value if a volume level is provided, else print the current
volume level. | [
"Set",
"the",
"value",
"if",
"a",
"volume",
"level",
"is",
"provided",
"else",
"print",
"the",
"current",
"volume",
"level",
"."
] | 1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b | https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L39-L45 | train |
jaapz/cast | cast.py | _status_command | def _status_command(cast, ramp):
""" Build a nice status message and print it to stdout. """
if ramp.is_playing:
play_symbol = u'\u25B6'
else:
play_symbol = u'\u2759\u2759'
print u' %s %s by %s from %s via %s, %s of %s' % (
play_symbol,
ramp.title,
ramp.artist,
ramp.album,
cast.app.app_id,
_to_minutes(ramp.current_time),
_to_minutes(ramp.duration)
) | python | def _status_command(cast, ramp):
""" Build a nice status message and print it to stdout. """
if ramp.is_playing:
play_symbol = u'\u25B6'
else:
play_symbol = u'\u2759\u2759'
print u' %s %s by %s from %s via %s, %s of %s' % (
play_symbol,
ramp.title,
ramp.artist,
ramp.album,
cast.app.app_id,
_to_minutes(ramp.current_time),
_to_minutes(ramp.duration)
) | [
"def",
"_status_command",
"(",
"cast",
",",
"ramp",
")",
":",
"if",
"ramp",
".",
"is_playing",
":",
"play_symbol",
"=",
"u'\\u25B6'",
"else",
":",
"play_symbol",
"=",
"u'\\u2759\\u2759'",
"print",
"u' %s %s by %s from %s via %s, %s of %s'",
"%",
"(",
"play_symbol",
",",
"ramp",
".",
"title",
",",
"ramp",
".",
"artist",
",",
"ramp",
".",
"album",
",",
"cast",
".",
"app",
".",
"app_id",
",",
"_to_minutes",
"(",
"ramp",
".",
"current_time",
")",
",",
"_to_minutes",
"(",
"ramp",
".",
"duration",
")",
")"
] | Build a nice status message and print it to stdout. | [
"Build",
"a",
"nice",
"status",
"message",
"and",
"print",
"it",
"to",
"stdout",
"."
] | 1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b | https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L48-L63 | train |
jaapz/cast | cast.py | main | def main():
""" Read the options given on the command line and do the required actions.
This method is used in the entry_point `cast`.
"""
opts = docopt(__doc__, version="cast 0.1")
cast = pychromecast.PyChromecast(CHROMECAST_HOST)
ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)
# Wait for ramp connection to be initted.
time.sleep(SLEEP_TIME)
if ramp is None:
print 'Chromecast is not up or current app does not handle RAMP.'
return 1
if opts['next']:
ramp.next()
elif opts['pause']:
ramp.pause()
elif opts['play']:
ramp.play()
elif opts['toggle']:
ramp.playpause()
elif opts['seek']:
ramp.seek(opts['<second>'])
elif opts['rewind']:
ramp.rewind()
elif opts['status']:
_status_command(cast, ramp)
elif opts['volume']:
_volume_command(ramp, opts['<value>'])
# Wait for command to be sent.
time.sleep(SLEEP_TIME) | python | def main():
""" Read the options given on the command line and do the required actions.
This method is used in the entry_point `cast`.
"""
opts = docopt(__doc__, version="cast 0.1")
cast = pychromecast.PyChromecast(CHROMECAST_HOST)
ramp = cast.get_protocol(pychromecast.PROTOCOL_RAMP)
# Wait for ramp connection to be initted.
time.sleep(SLEEP_TIME)
if ramp is None:
print 'Chromecast is not up or current app does not handle RAMP.'
return 1
if opts['next']:
ramp.next()
elif opts['pause']:
ramp.pause()
elif opts['play']:
ramp.play()
elif opts['toggle']:
ramp.playpause()
elif opts['seek']:
ramp.seek(opts['<second>'])
elif opts['rewind']:
ramp.rewind()
elif opts['status']:
_status_command(cast, ramp)
elif opts['volume']:
_volume_command(ramp, opts['<value>'])
# Wait for command to be sent.
time.sleep(SLEEP_TIME) | [
"def",
"main",
"(",
")",
":",
"opts",
"=",
"docopt",
"(",
"__doc__",
",",
"version",
"=",
"\"cast 0.1\"",
")",
"cast",
"=",
"pychromecast",
".",
"PyChromecast",
"(",
"CHROMECAST_HOST",
")",
"ramp",
"=",
"cast",
".",
"get_protocol",
"(",
"pychromecast",
".",
"PROTOCOL_RAMP",
")",
"# Wait for ramp connection to be initted.",
"time",
".",
"sleep",
"(",
"SLEEP_TIME",
")",
"if",
"ramp",
"is",
"None",
":",
"print",
"'Chromecast is not up or current app does not handle RAMP.'",
"return",
"1",
"if",
"opts",
"[",
"'next'",
"]",
":",
"ramp",
".",
"next",
"(",
")",
"elif",
"opts",
"[",
"'pause'",
"]",
":",
"ramp",
".",
"pause",
"(",
")",
"elif",
"opts",
"[",
"'play'",
"]",
":",
"ramp",
".",
"play",
"(",
")",
"elif",
"opts",
"[",
"'toggle'",
"]",
":",
"ramp",
".",
"playpause",
"(",
")",
"elif",
"opts",
"[",
"'seek'",
"]",
":",
"ramp",
".",
"seek",
"(",
"opts",
"[",
"'<second>'",
"]",
")",
"elif",
"opts",
"[",
"'rewind'",
"]",
":",
"ramp",
".",
"rewind",
"(",
")",
"elif",
"opts",
"[",
"'status'",
"]",
":",
"_status_command",
"(",
"cast",
",",
"ramp",
")",
"elif",
"opts",
"[",
"'volume'",
"]",
":",
"_volume_command",
"(",
"ramp",
",",
"opts",
"[",
"'<value>'",
"]",
")",
"# Wait for command to be sent.",
"time",
".",
"sleep",
"(",
"SLEEP_TIME",
")"
] | Read the options given on the command line and do the required actions.
This method is used in the entry_point `cast`. | [
"Read",
"the",
"options",
"given",
"on",
"the",
"command",
"line",
"and",
"do",
"the",
"required",
"actions",
"."
] | 1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b | https://github.com/jaapz/cast/blob/1c451b11b7c9ce1c65d53ae1f4d2e44969676a1b/cast.py#L66-L101 | train |
JarryShaw/f2format | src/lib/tokenize.py | untokenize | def untokenize(iterable):
"""Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited input:
# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2
"""
ut = Untokenizer()
out = ut.untokenize(iterable)
if ut.encoding is not None:
out = out.encode(ut.encoding)
return out | python | def untokenize(iterable):
"""Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited input:
# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2
"""
ut = Untokenizer()
out = ut.untokenize(iterable)
if ut.encoding is not None:
out = out.encode(ut.encoding)
return out | [
"def",
"untokenize",
"(",
"iterable",
")",
":",
"ut",
"=",
"Untokenizer",
"(",
")",
"out",
"=",
"ut",
".",
"untokenize",
"(",
"iterable",
")",
"if",
"ut",
".",
"encoding",
"is",
"not",
"None",
":",
"out",
"=",
"out",
".",
"encode",
"(",
"ut",
".",
"encoding",
")",
"return",
"out"
] | Transform tokens back into Python source code.
It returns a bytes object, encoded using the ENCODING
token, which is the first token sequence output by tokenize.
Each element returned by the iterable must be a token sequence
with at least two elements, a token number and token value. If
only two tokens are passed, the resulting output is poor.
Round-trip invariant for full input:
Untokenized source will match input source exactly
Round-trip invariant for limited input:
# Output bytes will tokenize back to the input
t1 = [tok[:2] for tok in tokenize(f.readline)]
newcode = untokenize(t1)
readline = BytesIO(newcode).readline
t2 = [tok[:2] for tok in tokenize(readline)]
assert t1 == t2 | [
"Transform",
"tokens",
"back",
"into",
"Python",
"source",
"code",
".",
"It",
"returns",
"a",
"bytes",
"object",
"encoded",
"using",
"the",
"ENCODING",
"token",
"which",
"is",
"the",
"first",
"token",
"sequence",
"output",
"by",
"tokenize",
"."
] | a144250268247ce0a98d734a26d53faadff7a6f8 | https://github.com/JarryShaw/f2format/blob/a144250268247ce0a98d734a26d53faadff7a6f8/src/lib/tokenize.py#L312-L336 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | get_powers_of_2 | def get_powers_of_2(_sum):
"""Get powers of 2 that sum up to the given number.
This function transforms given integer to a binary string.
A reversed value limited to digits of binary number is extracted
from it, and each of its characters is enumerated.
Each digit is tested for not being 0. If the test passes, the index
associated with the digit is used as an exponent to get the next
value in the sequence to be returned.
:param _sum: a sum of all elements of the sequence to be returned
:returns: a list of powers of two whose sum is given
"""
return [2**y for y, x in enumerate(bin(_sum)[:1:-1]) if int(x)] | python | def get_powers_of_2(_sum):
"""Get powers of 2 that sum up to the given number.
This function transforms given integer to a binary string.
A reversed value limited to digits of binary number is extracted
from it, and each of its characters is enumerated.
Each digit is tested for not being 0. If the test passes, the index
associated with the digit is used as an exponent to get the next
value in the sequence to be returned.
:param _sum: a sum of all elements of the sequence to be returned
:returns: a list of powers of two whose sum is given
"""
return [2**y for y, x in enumerate(bin(_sum)[:1:-1]) if int(x)] | [
"def",
"get_powers_of_2",
"(",
"_sum",
")",
":",
"return",
"[",
"2",
"**",
"y",
"for",
"y",
",",
"x",
"in",
"enumerate",
"(",
"bin",
"(",
"_sum",
")",
"[",
":",
"1",
":",
"-",
"1",
"]",
")",
"if",
"int",
"(",
"x",
")",
"]"
] | Get powers of 2 that sum up to the given number.
This function transforms given integer to a binary string.
A reversed value limited to digits of binary number is extracted
from it, and each of its characters is enumerated.
Each digit is tested for not being 0. If the test passes, the index
associated with the digit is used as an exponent to get the next
value in the sequence to be returned.
:param _sum: a sum of all elements of the sequence to be returned
:returns: a list of powers of two whose sum is given | [
"Get",
"powers",
"of",
"2",
"that",
"sum",
"up",
"to",
"the",
"given",
"number",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L101-L115 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | DNSBL._query | def _query(self, host_object):
"""Query the DNSBL service for given value.
:param host_object: an object representing host, created by
self._host_factory
:returns: an instance of dns.resolver.Answer for given value if
it is listed. Otherwise, it returns None.
"""
host_to_query = host_object.relative_domain
query_name = host_to_query.derelativize(self._query_suffix)
try:
return query(query_name)
except NXDOMAIN:
return None | python | def _query(self, host_object):
"""Query the DNSBL service for given value.
:param host_object: an object representing host, created by
self._host_factory
:returns: an instance of dns.resolver.Answer for given value if
it is listed. Otherwise, it returns None.
"""
host_to_query = host_object.relative_domain
query_name = host_to_query.derelativize(self._query_suffix)
try:
return query(query_name)
except NXDOMAIN:
return None | [
"def",
"_query",
"(",
"self",
",",
"host_object",
")",
":",
"host_to_query",
"=",
"host_object",
".",
"relative_domain",
"query_name",
"=",
"host_to_query",
".",
"derelativize",
"(",
"self",
".",
"_query_suffix",
")",
"try",
":",
"return",
"query",
"(",
"query_name",
")",
"except",
"NXDOMAIN",
":",
"return",
"None"
] | Query the DNSBL service for given value.
:param host_object: an object representing host, created by
self._host_factory
:returns: an instance of dns.resolver.Answer for given value if
it is listed. Otherwise, it returns None. | [
"Query",
"the",
"DNSBL",
"service",
"for",
"given",
"value",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L59-L72 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | HpHosts._query | def _query(self, host_object, classification=False):
"""Query the client for data of given host.
:param host_object: an object representing a host value
:param classification: if True: hpHosts is queried also
for classification for given host, if listed
:returns: content of response to GET request to hpHosts
for data on the given host
"""
template = 'http://verify.hosts-file.net/?v={}&s={}'
url = template.format(self.app_id, host_object.to_unicode())
url = url + '&class=true' if classification else url
return get(url).text | python | def _query(self, host_object, classification=False):
"""Query the client for data of given host.
:param host_object: an object representing a host value
:param classification: if True: hpHosts is queried also
for classification for given host, if listed
:returns: content of response to GET request to hpHosts
for data on the given host
"""
template = 'http://verify.hosts-file.net/?v={}&s={}'
url = template.format(self.app_id, host_object.to_unicode())
url = url + '&class=true' if classification else url
return get(url).text | [
"def",
"_query",
"(",
"self",
",",
"host_object",
",",
"classification",
"=",
"False",
")",
":",
"template",
"=",
"'http://verify.hosts-file.net/?v={}&s={}'",
"url",
"=",
"template",
".",
"format",
"(",
"self",
".",
"app_id",
",",
"host_object",
".",
"to_unicode",
"(",
")",
")",
"url",
"=",
"url",
"+",
"'&class=true'",
"if",
"classification",
"else",
"url",
"return",
"get",
"(",
"url",
")",
".",
"text"
] | Query the client for data of given host.
:param host_object: an object representing a host value
:param classification: if True: hpHosts is queried also
for classification for given host, if listed
:returns: content of response to GET request to hpHosts
for data on the given host | [
"Query",
"the",
"client",
"for",
"data",
"of",
"given",
"host",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L146-L158 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | GoogleSafeBrowsing._request_address | def _request_address(self):
"""Get address of a POST request to the service."""
if not self._request_address_val:
template = (
'https://sb-ssl.google.com/safebrowsing/api/lookup'
'?client={0}&key={1}&appver={2}&pver={3}'
)
self._request_address_val = template.format(
self.client_name,
self.api_key,
self.app_version,
self.protocol_version
)
return self._request_address_val | python | def _request_address(self):
"""Get address of a POST request to the service."""
if not self._request_address_val:
template = (
'https://sb-ssl.google.com/safebrowsing/api/lookup'
'?client={0}&key={1}&appver={2}&pver={3}'
)
self._request_address_val = template.format(
self.client_name,
self.api_key,
self.app_version,
self.protocol_version
)
return self._request_address_val | [
"def",
"_request_address",
"(",
"self",
")",
":",
"if",
"not",
"self",
".",
"_request_address_val",
":",
"template",
"=",
"(",
"'https://sb-ssl.google.com/safebrowsing/api/lookup'",
"'?client={0}&key={1}&appver={2}&pver={3}'",
")",
"self",
".",
"_request_address_val",
"=",
"template",
".",
"format",
"(",
"self",
".",
"client_name",
",",
"self",
".",
"api_key",
",",
"self",
".",
"app_version",
",",
"self",
".",
"protocol_version",
")",
"return",
"self",
".",
"_request_address_val"
] | Get address of a POST request to the service. | [
"Get",
"address",
"of",
"a",
"POST",
"request",
"to",
"the",
"service",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L192-L205 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | GoogleSafeBrowsing._query_once | def _query_once(self, urls):
"""Perform a single POST request using lookup API.
:param urls: a sequence of URLs to put in request body
:returns: a response object
:raises UnathorizedAPIKeyError: when the API key for this
instance is not valid
:raises HTTPError: if the HTTPError was raised for a HTTP code
other than 401, the exception is reraised
"""
request_body = '{}\n{}'.format(len(urls), '\n'.join(urls))
response = post(self._request_address, request_body)
try:
response.raise_for_status()
except HTTPError as error:
if response.status_code == 401:
msg = 'The API key is not authorized'
raise_from(UnathorizedAPIKeyError(msg), error)
else:
raise
return response | python | def _query_once(self, urls):
"""Perform a single POST request using lookup API.
:param urls: a sequence of URLs to put in request body
:returns: a response object
:raises UnathorizedAPIKeyError: when the API key for this
instance is not valid
:raises HTTPError: if the HTTPError was raised for a HTTP code
other than 401, the exception is reraised
"""
request_body = '{}\n{}'.format(len(urls), '\n'.join(urls))
response = post(self._request_address, request_body)
try:
response.raise_for_status()
except HTTPError as error:
if response.status_code == 401:
msg = 'The API key is not authorized'
raise_from(UnathorizedAPIKeyError(msg), error)
else:
raise
return response | [
"def",
"_query_once",
"(",
"self",
",",
"urls",
")",
":",
"request_body",
"=",
"'{}\\n{}'",
".",
"format",
"(",
"len",
"(",
"urls",
")",
",",
"'\\n'",
".",
"join",
"(",
"urls",
")",
")",
"response",
"=",
"post",
"(",
"self",
".",
"_request_address",
",",
"request_body",
")",
"try",
":",
"response",
".",
"raise_for_status",
"(",
")",
"except",
"HTTPError",
"as",
"error",
":",
"if",
"response",
".",
"status_code",
"==",
"401",
":",
"msg",
"=",
"'The API key is not authorized'",
"raise_from",
"(",
"UnathorizedAPIKeyError",
"(",
"msg",
")",
",",
"error",
")",
"else",
":",
"raise",
"return",
"response"
] | Perform a single POST request using lookup API.
:param urls: a sequence of URLs to put in request body
:returns: a response object
:raises UnathorizedAPIKeyError: when the API key for this
instance is not valid
:raises HTTPError: if the HTTPError was raised for a HTTP code
other than 401, the exception is reraised | [
"Perform",
"a",
"single",
"POST",
"request",
"using",
"lookup",
"API",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L207-L227 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | GoogleSafeBrowsing._query | def _query(self, urls):
"""Test URLs for being listed by the service.
:param urls: a sequence of URLs to be tested
:returns: a tuple containing chunk of URLs and a response
pertaining to them if the code of response was 200, which
means at least one of the queried URLs is matched in either
the phishing, malware, or unwanted software lists.
"""
urls = list(set(urls))
for i in range(0, len(urls), self.max_urls_per_request):
chunk = urls[i:i+self.max_urls_per_request]
response = self._query_once(chunk)
if response.status_code == 200:
yield chunk, response | python | def _query(self, urls):
"""Test URLs for being listed by the service.
:param urls: a sequence of URLs to be tested
:returns: a tuple containing chunk of URLs and a response
pertaining to them if the code of response was 200, which
means at least one of the queried URLs is matched in either
the phishing, malware, or unwanted software lists.
"""
urls = list(set(urls))
for i in range(0, len(urls), self.max_urls_per_request):
chunk = urls[i:i+self.max_urls_per_request]
response = self._query_once(chunk)
if response.status_code == 200:
yield chunk, response | [
"def",
"_query",
"(",
"self",
",",
"urls",
")",
":",
"urls",
"=",
"list",
"(",
"set",
"(",
"urls",
")",
")",
"for",
"i",
"in",
"range",
"(",
"0",
",",
"len",
"(",
"urls",
")",
",",
"self",
".",
"max_urls_per_request",
")",
":",
"chunk",
"=",
"urls",
"[",
"i",
":",
"i",
"+",
"self",
".",
"max_urls_per_request",
"]",
"response",
"=",
"self",
".",
"_query_once",
"(",
"chunk",
")",
"if",
"response",
".",
"status_code",
"==",
"200",
":",
"yield",
"chunk",
",",
"response"
] | Test URLs for being listed by the service.
:param urls: a sequence of URLs to be tested
:returns: a tuple containing chunk of URLs and a response
pertaining to them if the code of response was 200, which
means at least one of the queried URLs is matched in either
the phishing, malware, or unwanted software lists. | [
"Test",
"URLs",
"for",
"being",
"listed",
"by",
"the",
"service",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L229-L243 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | GoogleSafeBrowsing._get_match_and_classification | def _get_match_and_classification(self, urls):
"""Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it
"""
for url_list, response in self._query(urls):
classification_set = response.text.splitlines()
for url, _class in zip(url_list, classification_set):
if _class != 'ok':
yield url, _class | python | def _get_match_and_classification(self, urls):
"""Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it
"""
for url_list, response in self._query(urls):
classification_set = response.text.splitlines()
for url, _class in zip(url_list, classification_set):
if _class != 'ok':
yield url, _class | [
"def",
"_get_match_and_classification",
"(",
"self",
",",
"urls",
")",
":",
"for",
"url_list",
",",
"response",
"in",
"self",
".",
"_query",
"(",
"urls",
")",
":",
"classification_set",
"=",
"response",
".",
"text",
".",
"splitlines",
"(",
")",
"for",
"url",
",",
"_class",
"in",
"zip",
"(",
"url_list",
",",
"classification_set",
")",
":",
"if",
"_class",
"!=",
"'ok'",
":",
"yield",
"url",
",",
"_class"
] | Get classification for all matching URLs.
:param urls: a sequence of URLs to test
:return: a tuple containing matching URL and classification
string pertaining to it | [
"Get",
"classification",
"for",
"all",
"matching",
"URLs",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L256-L267 | train |
piotr-rusin/spam-lists | spam_lists/clients.py | GoogleSafeBrowsing.lookup_matching | def lookup_matching(self, urls):
"""Get items for all listed URLs.
:param urls: a sequence of URLs to be tested
:returns: objects representing listed URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
for url, _class in self._get_match_and_classification(urls):
classification = set(_class.split(','))
yield AddressListItem(url, self, classification) | python | def lookup_matching(self, urls):
"""Get items for all listed URLs.
:param urls: a sequence of URLs to be tested
:returns: objects representing listed URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence
"""
for url, _class in self._get_match_and_classification(urls):
classification = set(_class.split(','))
yield AddressListItem(url, self, classification) | [
"def",
"lookup_matching",
"(",
"self",
",",
"urls",
")",
":",
"for",
"url",
",",
"_class",
"in",
"self",
".",
"_get_match_and_classification",
"(",
"urls",
")",
":",
"classification",
"=",
"set",
"(",
"_class",
".",
"split",
"(",
"','",
")",
")",
"yield",
"AddressListItem",
"(",
"url",
",",
"self",
",",
"classification",
")"
] | Get items for all listed URLs.
:param urls: a sequence of URLs to be tested
:returns: objects representing listed URLs
:raises InvalidURLError: if there are any invalid URLs in
the sequence | [
"Get",
"items",
"for",
"all",
"listed",
"URLs",
"."
] | fd616e8761b28f3eaa503fee5e45f7748e8f88f2 | https://github.com/piotr-rusin/spam-lists/blob/fd616e8761b28f3eaa503fee5e45f7748e8f88f2/spam_lists/clients.py#L270-L280 | train |
mardix/pylot | pylot/__init__.py | Pylot.extends_ | def extends_(cls, kls):
"""
A view decorator to extend another view class or function to itself
It will inherit all its methods and propeties and use them on itself
-- EXAMPLES --
class Index(Pylot):
pass
index = Index()
::-> As decorator on classes ::
@index.extends_
class A(object):
def hello(self):
pass
@index.extends_
class C()
def world(self):
pass
::-> Decorator With function call ::
@index.extends_
def hello(self):
pass
"""
if inspect.isclass(kls):
for _name, _val in kls.__dict__.items():
if not _name.startswith("__"):
setattr(cls, _name, _val)
elif inspect.isfunction(kls):
setattr(cls, kls.__name__, kls)
return cls | python | def extends_(cls, kls):
"""
A view decorator to extend another view class or function to itself
It will inherit all its methods and propeties and use them on itself
-- EXAMPLES --
class Index(Pylot):
pass
index = Index()
::-> As decorator on classes ::
@index.extends_
class A(object):
def hello(self):
pass
@index.extends_
class C()
def world(self):
pass
::-> Decorator With function call ::
@index.extends_
def hello(self):
pass
"""
if inspect.isclass(kls):
for _name, _val in kls.__dict__.items():
if not _name.startswith("__"):
setattr(cls, _name, _val)
elif inspect.isfunction(kls):
setattr(cls, kls.__name__, kls)
return cls | [
"def",
"extends_",
"(",
"cls",
",",
"kls",
")",
":",
"if",
"inspect",
".",
"isclass",
"(",
"kls",
")",
":",
"for",
"_name",
",",
"_val",
"in",
"kls",
".",
"__dict__",
".",
"items",
"(",
")",
":",
"if",
"not",
"_name",
".",
"startswith",
"(",
"\"__\"",
")",
":",
"setattr",
"(",
"cls",
",",
"_name",
",",
"_val",
")",
"elif",
"inspect",
".",
"isfunction",
"(",
"kls",
")",
":",
"setattr",
"(",
"cls",
",",
"kls",
".",
"__name__",
",",
"kls",
")",
"return",
"cls"
] | A view decorator to extend another view class or function to itself
It will inherit all its methods and propeties and use them on itself
-- EXAMPLES --
class Index(Pylot):
pass
index = Index()
::-> As decorator on classes ::
@index.extends_
class A(object):
def hello(self):
pass
@index.extends_
class C()
def world(self):
pass
::-> Decorator With function call ::
@index.extends_
def hello(self):
pass | [
"A",
"view",
"decorator",
"to",
"extend",
"another",
"view",
"class",
"or",
"function",
"to",
"itself",
"It",
"will",
"inherit",
"all",
"its",
"methods",
"and",
"propeties",
"and",
"use",
"them",
"on",
"itself"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L115-L150 | train |
mardix/pylot | pylot/__init__.py | Mailer.send | def send(self, to, subject, body, reply_to=None, **kwargs):
"""
Send simple message
"""
if self.provider == "SES":
self.mail.send(to=to,
subject=subject,
body=body,
reply_to=reply_to,
**kwargs)
elif self.provider == "FLASK-MAIL":
msg = flask_mail.Message(recipients=to, subject=subject, body=body, reply_to=reply_to,
sender=self.app.config.get("MAIL_DEFAULT_SENDER"))
self.mail.send(msg) | python | def send(self, to, subject, body, reply_to=None, **kwargs):
"""
Send simple message
"""
if self.provider == "SES":
self.mail.send(to=to,
subject=subject,
body=body,
reply_to=reply_to,
**kwargs)
elif self.provider == "FLASK-MAIL":
msg = flask_mail.Message(recipients=to, subject=subject, body=body, reply_to=reply_to,
sender=self.app.config.get("MAIL_DEFAULT_SENDER"))
self.mail.send(msg) | [
"def",
"send",
"(",
"self",
",",
"to",
",",
"subject",
",",
"body",
",",
"reply_to",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"if",
"self",
".",
"provider",
"==",
"\"SES\"",
":",
"self",
".",
"mail",
".",
"send",
"(",
"to",
"=",
"to",
",",
"subject",
"=",
"subject",
",",
"body",
"=",
"body",
",",
"reply_to",
"=",
"reply_to",
",",
"*",
"*",
"kwargs",
")",
"elif",
"self",
".",
"provider",
"==",
"\"FLASK-MAIL\"",
":",
"msg",
"=",
"flask_mail",
".",
"Message",
"(",
"recipients",
"=",
"to",
",",
"subject",
"=",
"subject",
",",
"body",
"=",
"body",
",",
"reply_to",
"=",
"reply_to",
",",
"sender",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"\"MAIL_DEFAULT_SENDER\"",
")",
")",
"self",
".",
"mail",
".",
"send",
"(",
"msg",
")"
] | Send simple message | [
"Send",
"simple",
"message"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L275-L288 | train |
mardix/pylot | pylot/__init__.py | Mailer.send_template | def send_template(self, template, to, reply_to=None, **context):
"""
Send Template message
"""
if self.provider == "SES":
self.mail.send_template(template=template, to=to, reply_to=reply_to, **context)
elif self.provider == "FLASK-MAIL":
ses_mail = ses_mailer.Mail(app=self.app)
data = ses_mail.parse_template(template=template, **context)
msg = flask_mail.Message(recipients=to,
subject=data["subject"],
body=data["body"],
reply_to=reply_to,
sender=self.app.config.get("MAIL_DEFAULT_SENDER")
)
self.mail.send(msg) | python | def send_template(self, template, to, reply_to=None, **context):
"""
Send Template message
"""
if self.provider == "SES":
self.mail.send_template(template=template, to=to, reply_to=reply_to, **context)
elif self.provider == "FLASK-MAIL":
ses_mail = ses_mailer.Mail(app=self.app)
data = ses_mail.parse_template(template=template, **context)
msg = flask_mail.Message(recipients=to,
subject=data["subject"],
body=data["body"],
reply_to=reply_to,
sender=self.app.config.get("MAIL_DEFAULT_SENDER")
)
self.mail.send(msg) | [
"def",
"send_template",
"(",
"self",
",",
"template",
",",
"to",
",",
"reply_to",
"=",
"None",
",",
"*",
"*",
"context",
")",
":",
"if",
"self",
".",
"provider",
"==",
"\"SES\"",
":",
"self",
".",
"mail",
".",
"send_template",
"(",
"template",
"=",
"template",
",",
"to",
"=",
"to",
",",
"reply_to",
"=",
"reply_to",
",",
"*",
"*",
"context",
")",
"elif",
"self",
".",
"provider",
"==",
"\"FLASK-MAIL\"",
":",
"ses_mail",
"=",
"ses_mailer",
".",
"Mail",
"(",
"app",
"=",
"self",
".",
"app",
")",
"data",
"=",
"ses_mail",
".",
"parse_template",
"(",
"template",
"=",
"template",
",",
"*",
"*",
"context",
")",
"msg",
"=",
"flask_mail",
".",
"Message",
"(",
"recipients",
"=",
"to",
",",
"subject",
"=",
"data",
"[",
"\"subject\"",
"]",
",",
"body",
"=",
"data",
"[",
"\"body\"",
"]",
",",
"reply_to",
"=",
"reply_to",
",",
"sender",
"=",
"self",
".",
"app",
".",
"config",
".",
"get",
"(",
"\"MAIL_DEFAULT_SENDER\"",
")",
")",
"self",
".",
"mail",
".",
"send",
"(",
"msg",
")"
] | Send Template message | [
"Send",
"Template",
"message"
] | 506a33a56ebdfc0925b94015e8cf98ccb16a143c | https://github.com/mardix/pylot/blob/506a33a56ebdfc0925b94015e8cf98ccb16a143c/pylot/__init__.py#L290-L306 | train |
astraw38/lint | lint/utils/general.py | dump_to_console | def dump_to_console(pylint_data):
"""
Displays pylint data to the console.
:param pylint_data:
:return:
"""
for key, value in list(pylint_data.items()):
if key not in ('errors', 'total', 'scores', 'average') and len(value) > 0:
print("\n*********** {}".format(key))
for line in value:
print(line.strip('\n'))
f_score = [score[1] for score in pylint_data['scores'] if score[0] == key][0]
print("Score: {}".format(f_score)) | python | def dump_to_console(pylint_data):
"""
Displays pylint data to the console.
:param pylint_data:
:return:
"""
for key, value in list(pylint_data.items()):
if key not in ('errors', 'total', 'scores', 'average') and len(value) > 0:
print("\n*********** {}".format(key))
for line in value:
print(line.strip('\n'))
f_score = [score[1] for score in pylint_data['scores'] if score[0] == key][0]
print("Score: {}".format(f_score)) | [
"def",
"dump_to_console",
"(",
"pylint_data",
")",
":",
"for",
"key",
",",
"value",
"in",
"list",
"(",
"pylint_data",
".",
"items",
"(",
")",
")",
":",
"if",
"key",
"not",
"in",
"(",
"'errors'",
",",
"'total'",
",",
"'scores'",
",",
"'average'",
")",
"and",
"len",
"(",
"value",
")",
">",
"0",
":",
"print",
"(",
"\"\\n*********** {}\"",
".",
"format",
"(",
"key",
")",
")",
"for",
"line",
"in",
"value",
":",
"print",
"(",
"line",
".",
"strip",
"(",
"'\\n'",
")",
")",
"f_score",
"=",
"[",
"score",
"[",
"1",
"]",
"for",
"score",
"in",
"pylint_data",
"[",
"'scores'",
"]",
"if",
"score",
"[",
"0",
"]",
"==",
"key",
"]",
"[",
"0",
"]",
"print",
"(",
"\"Score: {}\"",
".",
"format",
"(",
"f_score",
")",
")"
] | Displays pylint data to the console.
:param pylint_data:
:return: | [
"Displays",
"pylint",
"data",
"to",
"the",
"console",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L26-L39 | train |
astraw38/lint | lint/utils/general.py | post_to_gerrit | def post_to_gerrit(commit, score=0, message='', user='lunatest', gerrit=None):
"""
Post the data to gerrit. This right now is a stub, as
I'll need to write the code to post up to gerrit.
:param commit: Commit ID of the review.
:param message: Message to accompany the review score.
:param user: SSH User for posting to gerrit.
:param gerrit: Hostname of the gerrit server.
:param score: Score to post to gerrit (+1/-1, etc)
:return:
"""
# ssh -p 29418 review.example.com gerrit review --code-review +1 <commit_id>
if score > 0:
score = "+{}".format(score)
else:
url = "{}job/{}/{}/consoleText".format(os.environ.get('JENKINS_URL'),
os.environ.get('JOB_NAME'),
os.environ.get('BUILD_NUMBER'))
message = ("{}\r\n\r\n"
"Check output here: {}").format(message, url)
score = str(score)
# Format the message in a way that is readable both by shell command
#as well as Gerrit (need to double quote, once for shell, once for gerrit).
message = "'\"{}\"'".format(message)
subprocess.check_output(["ssh",
"-p", str(os.environ.get("GERRIT_PORT", "29418")),
"{}@{}".format(user, gerrit),
"gerrit", "review", "--code-review " + score,
"-m", message, commit]) | python | def post_to_gerrit(commit, score=0, message='', user='lunatest', gerrit=None):
"""
Post the data to gerrit. This right now is a stub, as
I'll need to write the code to post up to gerrit.
:param commit: Commit ID of the review.
:param message: Message to accompany the review score.
:param user: SSH User for posting to gerrit.
:param gerrit: Hostname of the gerrit server.
:param score: Score to post to gerrit (+1/-1, etc)
:return:
"""
# ssh -p 29418 review.example.com gerrit review --code-review +1 <commit_id>
if score > 0:
score = "+{}".format(score)
else:
url = "{}job/{}/{}/consoleText".format(os.environ.get('JENKINS_URL'),
os.environ.get('JOB_NAME'),
os.environ.get('BUILD_NUMBER'))
message = ("{}\r\n\r\n"
"Check output here: {}").format(message, url)
score = str(score)
# Format the message in a way that is readable both by shell command
#as well as Gerrit (need to double quote, once for shell, once for gerrit).
message = "'\"{}\"'".format(message)
subprocess.check_output(["ssh",
"-p", str(os.environ.get("GERRIT_PORT", "29418")),
"{}@{}".format(user, gerrit),
"gerrit", "review", "--code-review " + score,
"-m", message, commit]) | [
"def",
"post_to_gerrit",
"(",
"commit",
",",
"score",
"=",
"0",
",",
"message",
"=",
"''",
",",
"user",
"=",
"'lunatest'",
",",
"gerrit",
"=",
"None",
")",
":",
"# ssh -p 29418 review.example.com gerrit review --code-review +1 <commit_id>",
"if",
"score",
">",
"0",
":",
"score",
"=",
"\"+{}\"",
".",
"format",
"(",
"score",
")",
"else",
":",
"url",
"=",
"\"{}job/{}/{}/consoleText\"",
".",
"format",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'JENKINS_URL'",
")",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'JOB_NAME'",
")",
",",
"os",
".",
"environ",
".",
"get",
"(",
"'BUILD_NUMBER'",
")",
")",
"message",
"=",
"(",
"\"{}\\r\\n\\r\\n\"",
"\"Check output here: {}\"",
")",
".",
"format",
"(",
"message",
",",
"url",
")",
"score",
"=",
"str",
"(",
"score",
")",
"# Format the message in a way that is readable both by shell command",
"#as well as Gerrit (need to double quote, once for shell, once for gerrit).",
"message",
"=",
"\"'\\\"{}\\\"'\"",
".",
"format",
"(",
"message",
")",
"subprocess",
".",
"check_output",
"(",
"[",
"\"ssh\"",
",",
"\"-p\"",
",",
"str",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"\"GERRIT_PORT\"",
",",
"\"29418\"",
")",
")",
",",
"\"{}@{}\"",
".",
"format",
"(",
"user",
",",
"gerrit",
")",
",",
"\"gerrit\"",
",",
"\"review\"",
",",
"\"--code-review \"",
"+",
"score",
",",
"\"-m\"",
",",
"message",
",",
"commit",
"]",
")"
] | Post the data to gerrit. This right now is a stub, as
I'll need to write the code to post up to gerrit.
:param commit: Commit ID of the review.
:param message: Message to accompany the review score.
:param user: SSH User for posting to gerrit.
:param gerrit: Hostname of the gerrit server.
:param score: Score to post to gerrit (+1/-1, etc)
:return: | [
"Post",
"the",
"data",
"to",
"gerrit",
".",
"This",
"right",
"now",
"is",
"a",
"stub",
"as",
"I",
"ll",
"need",
"to",
"write",
"the",
"code",
"to",
"post",
"up",
"to",
"gerrit",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L42-L72 | train |
astraw38/lint | lint/utils/general.py | sort_by_type | def sort_by_type(file_list):
"""
Sorts a list of files into types.
:param file_list: List of file paths.
:return: {extension: [<list of file paths with that extension>]}
"""
ret_dict = defaultdict(list)
for filepath in file_list:
_, ext = os.path.splitext(filepath)
ret_dict[ext.replace('.', '')].append(filepath)
return ret_dict | python | def sort_by_type(file_list):
"""
Sorts a list of files into types.
:param file_list: List of file paths.
:return: {extension: [<list of file paths with that extension>]}
"""
ret_dict = defaultdict(list)
for filepath in file_list:
_, ext = os.path.splitext(filepath)
ret_dict[ext.replace('.', '')].append(filepath)
return ret_dict | [
"def",
"sort_by_type",
"(",
"file_list",
")",
":",
"ret_dict",
"=",
"defaultdict",
"(",
"list",
")",
"for",
"filepath",
"in",
"file_list",
":",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"filepath",
")",
"ret_dict",
"[",
"ext",
".",
"replace",
"(",
"'.'",
",",
"''",
")",
"]",
".",
"append",
"(",
"filepath",
")",
"return",
"ret_dict"
] | Sorts a list of files into types.
:param file_list: List of file paths.
:return: {extension: [<list of file paths with that extension>]} | [
"Sorts",
"a",
"list",
"of",
"files",
"into",
"types",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/general.py#L75-L87 | train |
astraw38/lint | lint/utils/git_utils.py | checkout | def checkout(repository, target):
"""
Check out target into the current directory.
Target can be a branch, review Id, or commit.
:param repository: Current git repository.
:param target: Review ID, commit, branch.
:return: Return the most recent commit ID (top of the git log).
"""
# git fetch <remote> refs/changes/<review_id>
#git checkout FETCH_HEAD
repository.git.fetch([next(iter(repository.remotes)), target])
repository.git.checkout("FETCH_HEAD")
return repository.git.rev_parse(["--short", "HEAD"]).encode('ascii', 'ignore') | python | def checkout(repository, target):
"""
Check out target into the current directory.
Target can be a branch, review Id, or commit.
:param repository: Current git repository.
:param target: Review ID, commit, branch.
:return: Return the most recent commit ID (top of the git log).
"""
# git fetch <remote> refs/changes/<review_id>
#git checkout FETCH_HEAD
repository.git.fetch([next(iter(repository.remotes)), target])
repository.git.checkout("FETCH_HEAD")
return repository.git.rev_parse(["--short", "HEAD"]).encode('ascii', 'ignore') | [
"def",
"checkout",
"(",
"repository",
",",
"target",
")",
":",
"# git fetch <remote> refs/changes/<review_id>",
"#git checkout FETCH_HEAD",
"repository",
".",
"git",
".",
"fetch",
"(",
"[",
"next",
"(",
"iter",
"(",
"repository",
".",
"remotes",
")",
")",
",",
"target",
"]",
")",
"repository",
".",
"git",
".",
"checkout",
"(",
"\"FETCH_HEAD\"",
")",
"return",
"repository",
".",
"git",
".",
"rev_parse",
"(",
"[",
"\"--short\"",
",",
"\"HEAD\"",
"]",
")",
".",
"encode",
"(",
"'ascii'",
",",
"'ignore'",
")"
] | Check out target into the current directory.
Target can be a branch, review Id, or commit.
:param repository: Current git repository.
:param target: Review ID, commit, branch.
:return: Return the most recent commit ID (top of the git log). | [
"Check",
"out",
"target",
"into",
"the",
"current",
"directory",
".",
"Target",
"can",
"be",
"a",
"branch",
"review",
"Id",
"or",
"commit",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/git_utils.py#L6-L19 | train |
astraw38/lint | lint/utils/git_utils.py | get_files_changed | def get_files_changed(repository, review_id):
"""
Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List of file paths relative to current directory.
"""
repository.git.fetch([next(iter(repository.remotes)), review_id])
files_changed = repository.git.diff_tree(["--no-commit-id",
"--name-only",
"-r",
"FETCH_HEAD"]).splitlines()
print("Found {} files changed".format(len(files_changed)))
return files_changed | python | def get_files_changed(repository, review_id):
"""
Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List of file paths relative to current directory.
"""
repository.git.fetch([next(iter(repository.remotes)), review_id])
files_changed = repository.git.diff_tree(["--no-commit-id",
"--name-only",
"-r",
"FETCH_HEAD"]).splitlines()
print("Found {} files changed".format(len(files_changed)))
return files_changed | [
"def",
"get_files_changed",
"(",
"repository",
",",
"review_id",
")",
":",
"repository",
".",
"git",
".",
"fetch",
"(",
"[",
"next",
"(",
"iter",
"(",
"repository",
".",
"remotes",
")",
")",
",",
"review_id",
"]",
")",
"files_changed",
"=",
"repository",
".",
"git",
".",
"diff_tree",
"(",
"[",
"\"--no-commit-id\"",
",",
"\"--name-only\"",
",",
"\"-r\"",
",",
"\"FETCH_HEAD\"",
"]",
")",
".",
"splitlines",
"(",
")",
"print",
"(",
"\"Found {} files changed\"",
".",
"format",
"(",
"len",
"(",
"files_changed",
")",
")",
")",
"return",
"files_changed"
] | Get a list of files changed compared to the given review.
Compares against current directory.
:param repository: Git repository. Used to get remote.
- By default uses first remote in list.
:param review_id: Gerrit review ID.
:return: List of file paths relative to current directory. | [
"Get",
"a",
"list",
"of",
"files",
"changed",
"compared",
"to",
"the",
"given",
"review",
".",
"Compares",
"against",
"current",
"directory",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/utils/git_utils.py#L22-L38 | train |
jim-easterbrook/pyctools | src/pyctools/core/compound.py | Compound.start | def start(self):
"""Start the component running."""
for name, child in self._compound_children.items():
self.logger.debug('start %s (%s)', name, child.__class__.__name__)
child.start() | python | def start(self):
"""Start the component running."""
for name, child in self._compound_children.items():
self.logger.debug('start %s (%s)', name, child.__class__.__name__)
child.start() | [
"def",
"start",
"(",
"self",
")",
":",
"for",
"name",
",",
"child",
"in",
"self",
".",
"_compound_children",
".",
"items",
"(",
")",
":",
"self",
".",
"logger",
".",
"debug",
"(",
"'start %s (%s)'",
",",
"name",
",",
"child",
".",
"__class__",
".",
"__name__",
")",
"child",
".",
"start",
"(",
")"
] | Start the component running. | [
"Start",
"the",
"component",
"running",
"."
] | 2a958665326892f45f249bebe62c2c23f306732b | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/compound.py#L209-L213 | train |
jim-easterbrook/pyctools | src/pyctools/core/compound.py | Compound.join | def join(self, end_comps=False):
"""Wait for the compound component's children to stop running.
:param bool end_comps: only wait for the components that end a
pipeline. This is useful for complex graphs where it is
normal for some components not to terminate.
"""
for name, child in self._compound_children.items():
if end_comps and not child.is_pipe_end():
continue
self.logger.debug('join %s (%s)', name, child.__class__.__name__)
child.join() | python | def join(self, end_comps=False):
"""Wait for the compound component's children to stop running.
:param bool end_comps: only wait for the components that end a
pipeline. This is useful for complex graphs where it is
normal for some components not to terminate.
"""
for name, child in self._compound_children.items():
if end_comps and not child.is_pipe_end():
continue
self.logger.debug('join %s (%s)', name, child.__class__.__name__)
child.join() | [
"def",
"join",
"(",
"self",
",",
"end_comps",
"=",
"False",
")",
":",
"for",
"name",
",",
"child",
"in",
"self",
".",
"_compound_children",
".",
"items",
"(",
")",
":",
"if",
"end_comps",
"and",
"not",
"child",
".",
"is_pipe_end",
"(",
")",
":",
"continue",
"self",
".",
"logger",
".",
"debug",
"(",
"'join %s (%s)'",
",",
"name",
",",
"child",
".",
"__class__",
".",
"__name__",
")",
"child",
".",
"join",
"(",
")"
] | Wait for the compound component's children to stop running.
:param bool end_comps: only wait for the components that end a
pipeline. This is useful for complex graphs where it is
normal for some components not to terminate. | [
"Wait",
"for",
"the",
"compound",
"component",
"s",
"children",
"to",
"stop",
"running",
"."
] | 2a958665326892f45f249bebe62c2c23f306732b | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/compound.py#L221-L233 | train |
astraw38/lint | bin/gpylinter.py | main | def main(review_id, repository, branch="development", user='admin', gerrit=None):
"""
Do the bulk of the work
Exit status will be 1 if pylint fails.
Exit status will be 0 if pylint passes.
:param review_id: Target gerrit review ID. ex: refs/changes/99/299/3
:param repository: Git repository.
:param branch: Git branch to compare to.
:param user: SSH User that can connect to gerrit and post scores.
:param gerrit: Gerrit hostname.
"""
checkout(repository, branch)
raw_file_list = get_files_changed(repository=repository, review_id=review_id)
checkout(repository=repository, target=branch)
files = sort_by_type(raw_file_list)
old_data = run_linters(files)
commit_id = checkout(repository=repository, target=review_id)
new_data = run_linters(files)
dump_to_console(new_data['py'])
validations = run_validators(new_data, old_data)
# Get the lowest score from all validators.
final_score = min(list(validations.values()), key=lambda x: x[0])[0]
comment = ""
for name, validation in list(validations.items()):
score, message = validation
# Each validator should return it's own specialized comment
# Ex: 'Passed <name> Validation!\n', or 'Failed <name> Validation!\n<reasons/data>\n'
if message[-1:] != "\n":
message += "\n"
comment += message
exit_code = 1 if final_score < 0 else 0
post_to_gerrit(commit_id, score=final_score, message=comment, user=user, gerrit=gerrit)
exit(exit_code) | python | def main(review_id, repository, branch="development", user='admin', gerrit=None):
"""
Do the bulk of the work
Exit status will be 1 if pylint fails.
Exit status will be 0 if pylint passes.
:param review_id: Target gerrit review ID. ex: refs/changes/99/299/3
:param repository: Git repository.
:param branch: Git branch to compare to.
:param user: SSH User that can connect to gerrit and post scores.
:param gerrit: Gerrit hostname.
"""
checkout(repository, branch)
raw_file_list = get_files_changed(repository=repository, review_id=review_id)
checkout(repository=repository, target=branch)
files = sort_by_type(raw_file_list)
old_data = run_linters(files)
commit_id = checkout(repository=repository, target=review_id)
new_data = run_linters(files)
dump_to_console(new_data['py'])
validations = run_validators(new_data, old_data)
# Get the lowest score from all validators.
final_score = min(list(validations.values()), key=lambda x: x[0])[0]
comment = ""
for name, validation in list(validations.items()):
score, message = validation
# Each validator should return it's own specialized comment
# Ex: 'Passed <name> Validation!\n', or 'Failed <name> Validation!\n<reasons/data>\n'
if message[-1:] != "\n":
message += "\n"
comment += message
exit_code = 1 if final_score < 0 else 0
post_to_gerrit(commit_id, score=final_score, message=comment, user=user, gerrit=gerrit)
exit(exit_code) | [
"def",
"main",
"(",
"review_id",
",",
"repository",
",",
"branch",
"=",
"\"development\"",
",",
"user",
"=",
"'admin'",
",",
"gerrit",
"=",
"None",
")",
":",
"checkout",
"(",
"repository",
",",
"branch",
")",
"raw_file_list",
"=",
"get_files_changed",
"(",
"repository",
"=",
"repository",
",",
"review_id",
"=",
"review_id",
")",
"checkout",
"(",
"repository",
"=",
"repository",
",",
"target",
"=",
"branch",
")",
"files",
"=",
"sort_by_type",
"(",
"raw_file_list",
")",
"old_data",
"=",
"run_linters",
"(",
"files",
")",
"commit_id",
"=",
"checkout",
"(",
"repository",
"=",
"repository",
",",
"target",
"=",
"review_id",
")",
"new_data",
"=",
"run_linters",
"(",
"files",
")",
"dump_to_console",
"(",
"new_data",
"[",
"'py'",
"]",
")",
"validations",
"=",
"run_validators",
"(",
"new_data",
",",
"old_data",
")",
"# Get the lowest score from all validators.",
"final_score",
"=",
"min",
"(",
"list",
"(",
"validations",
".",
"values",
"(",
")",
")",
",",
"key",
"=",
"lambda",
"x",
":",
"x",
"[",
"0",
"]",
")",
"[",
"0",
"]",
"comment",
"=",
"\"\"",
"for",
"name",
",",
"validation",
"in",
"list",
"(",
"validations",
".",
"items",
"(",
")",
")",
":",
"score",
",",
"message",
"=",
"validation",
"# Each validator should return it's own specialized comment",
"# Ex: 'Passed <name> Validation!\\n', or 'Failed <name> Validation!\\n<reasons/data>\\n'",
"if",
"message",
"[",
"-",
"1",
":",
"]",
"!=",
"\"\\n\"",
":",
"message",
"+=",
"\"\\n\"",
"comment",
"+=",
"message",
"exit_code",
"=",
"1",
"if",
"final_score",
"<",
"0",
"else",
"0",
"post_to_gerrit",
"(",
"commit_id",
",",
"score",
"=",
"final_score",
",",
"message",
"=",
"comment",
",",
"user",
"=",
"user",
",",
"gerrit",
"=",
"gerrit",
")",
"exit",
"(",
"exit_code",
")"
] | Do the bulk of the work
Exit status will be 1 if pylint fails.
Exit status will be 0 if pylint passes.
:param review_id: Target gerrit review ID. ex: refs/changes/99/299/3
:param repository: Git repository.
:param branch: Git branch to compare to.
:param user: SSH User that can connect to gerrit and post scores.
:param gerrit: Gerrit hostname. | [
"Do",
"the",
"bulk",
"of",
"the",
"work"
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/bin/gpylinter.py#L14-L55 | train |
nicfit/MishMash | mishmash/orm.py | set_sqlite_pragma | def set_sqlite_pragma(dbapi_connection, connection_record):
"""Allows foreign keys to work in sqlite."""
import sqlite3
if dbapi_connection.__class__ is sqlite3.Connection:
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close() | python | def set_sqlite_pragma(dbapi_connection, connection_record):
"""Allows foreign keys to work in sqlite."""
import sqlite3
if dbapi_connection.__class__ is sqlite3.Connection:
cursor = dbapi_connection.cursor()
cursor.execute("PRAGMA foreign_keys=ON")
cursor.close() | [
"def",
"set_sqlite_pragma",
"(",
"dbapi_connection",
",",
"connection_record",
")",
":",
"import",
"sqlite3",
"if",
"dbapi_connection",
".",
"__class__",
"is",
"sqlite3",
".",
"Connection",
":",
"cursor",
"=",
"dbapi_connection",
".",
"cursor",
"(",
")",
"cursor",
".",
"execute",
"(",
"\"PRAGMA foreign_keys=ON\"",
")",
"cursor",
".",
"close",
"(",
")"
] | Allows foreign keys to work in sqlite. | [
"Allows",
"foreign",
"keys",
"to",
"work",
"in",
"sqlite",
"."
] | 8f988936340bf0ffb83ea90ea124efb3c36a1174 | https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/orm.py#L539-L545 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator.validate | def validate(self):
"""Iterate over all triples in the graph and validate each one
appropriately
"""
log.info("{}\nValidating against {}"
.format("-" * 100, self.schema_def.__class__.__name__))
if not self.schema_def:
raise ValueError("No schema definition supplied.")
self.checked_attributes = []
# TODO - this should maybe choose the actually used namespace, not just
# the first one in the list
result = ValidationResult(self.allowed_namespaces[0],
self.schema_def.__class__.__name__)
for subject, predicate, object_ in self.graph:
log.info("\nsubj: {subj}\npred: {pred}\n obj: {obj}"
.format(subj=subject, pred=predicate,
obj=object_.encode('utf-8')))
result.add_error(self._check_triple((subject, predicate, object_)))
return result | python | def validate(self):
"""Iterate over all triples in the graph and validate each one
appropriately
"""
log.info("{}\nValidating against {}"
.format("-" * 100, self.schema_def.__class__.__name__))
if not self.schema_def:
raise ValueError("No schema definition supplied.")
self.checked_attributes = []
# TODO - this should maybe choose the actually used namespace, not just
# the first one in the list
result = ValidationResult(self.allowed_namespaces[0],
self.schema_def.__class__.__name__)
for subject, predicate, object_ in self.graph:
log.info("\nsubj: {subj}\npred: {pred}\n obj: {obj}"
.format(subj=subject, pred=predicate,
obj=object_.encode('utf-8')))
result.add_error(self._check_triple((subject, predicate, object_)))
return result | [
"def",
"validate",
"(",
"self",
")",
":",
"log",
".",
"info",
"(",
"\"{}\\nValidating against {}\"",
".",
"format",
"(",
"\"-\"",
"*",
"100",
",",
"self",
".",
"schema_def",
".",
"__class__",
".",
"__name__",
")",
")",
"if",
"not",
"self",
".",
"schema_def",
":",
"raise",
"ValueError",
"(",
"\"No schema definition supplied.\"",
")",
"self",
".",
"checked_attributes",
"=",
"[",
"]",
"# TODO - this should maybe choose the actually used namespace, not just",
"# the first one in the list",
"result",
"=",
"ValidationResult",
"(",
"self",
".",
"allowed_namespaces",
"[",
"0",
"]",
",",
"self",
".",
"schema_def",
".",
"__class__",
".",
"__name__",
")",
"for",
"subject",
",",
"predicate",
",",
"object_",
"in",
"self",
".",
"graph",
":",
"log",
".",
"info",
"(",
"\"\\nsubj: {subj}\\npred: {pred}\\n obj: {obj}\"",
".",
"format",
"(",
"subj",
"=",
"subject",
",",
"pred",
"=",
"predicate",
",",
"obj",
"=",
"object_",
".",
"encode",
"(",
"'utf-8'",
")",
")",
")",
"result",
".",
"add_error",
"(",
"self",
".",
"_check_triple",
"(",
"(",
"subject",
",",
"predicate",
",",
"object_",
")",
")",
")",
"return",
"result"
] | Iterate over all triples in the graph and validate each one
appropriately | [
"Iterate",
"over",
"all",
"triples",
"in",
"the",
"graph",
"and",
"validate",
"each",
"one",
"appropriately"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L34-L55 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._check_triple | def _check_triple(self, triple):
"""compare triple to ontology, return error or None"""
subj, pred, obj = triple
if self._should_ignore_predicate(pred):
log.info("Ignoring triple with predicate '{}'"
.format(self._field_name_from_uri(pred)))
return
classes = []
log.warning("Possible member %s found" % pred)
pred = self._expand_qname(pred)
if self._namespace_from_uri(pred) not in self.allowed_namespaces:
log.info("Member %s does not use an allowed namespace", pred)
return
instanceof = self._is_instance((subj, pred, obj))
if type(instanceof) == rt.URIRef:
instanceof = self._expand_qname(instanceof)
if hasattr(self.schema_def, "attributes_by_class") and \
not self.schema_def.attributes_by_class:
log.info("Parsed ontology not found. Parsing...")
self.schema_def.parse_ontology()
class_invalid = self._validate_class(instanceof)
if class_invalid:
log.warning("Invalid class %s" % instanceof)
return class_invalid
# TODO - the above sometimes fails when a single object has more than
# one rdfa type (eg <span property="schema:creator rnews:creator"
# typeof="schema:Person rnews:Person">
# Graph chooses the type in an arbitrary order, so it's unreliable
# eg: http://semanticweb.com/the-impact-of-rdfa_b35003
classes = self._superclasses_for_subject(self.graph, instanceof)
classes.append(instanceof)
member_invalid = self._validate_member(pred, classes, instanceof)
if member_invalid:
log.warning("Invalid member of class")
return member_invalid
dupe_invalid = self._validate_duplication((subj, pred), instanceof)
if dupe_invalid:
log.warning("Duplication found")
return dupe_invalid
# collect a list of checked attributes
self.checked_attributes.append((subj, pred))
log.warning("successfully validated triple, no errors")
return | python | def _check_triple(self, triple):
"""compare triple to ontology, return error or None"""
subj, pred, obj = triple
if self._should_ignore_predicate(pred):
log.info("Ignoring triple with predicate '{}'"
.format(self._field_name_from_uri(pred)))
return
classes = []
log.warning("Possible member %s found" % pred)
pred = self._expand_qname(pred)
if self._namespace_from_uri(pred) not in self.allowed_namespaces:
log.info("Member %s does not use an allowed namespace", pred)
return
instanceof = self._is_instance((subj, pred, obj))
if type(instanceof) == rt.URIRef:
instanceof = self._expand_qname(instanceof)
if hasattr(self.schema_def, "attributes_by_class") and \
not self.schema_def.attributes_by_class:
log.info("Parsed ontology not found. Parsing...")
self.schema_def.parse_ontology()
class_invalid = self._validate_class(instanceof)
if class_invalid:
log.warning("Invalid class %s" % instanceof)
return class_invalid
# TODO - the above sometimes fails when a single object has more than
# one rdfa type (eg <span property="schema:creator rnews:creator"
# typeof="schema:Person rnews:Person">
# Graph chooses the type in an arbitrary order, so it's unreliable
# eg: http://semanticweb.com/the-impact-of-rdfa_b35003
classes = self._superclasses_for_subject(self.graph, instanceof)
classes.append(instanceof)
member_invalid = self._validate_member(pred, classes, instanceof)
if member_invalid:
log.warning("Invalid member of class")
return member_invalid
dupe_invalid = self._validate_duplication((subj, pred), instanceof)
if dupe_invalid:
log.warning("Duplication found")
return dupe_invalid
# collect a list of checked attributes
self.checked_attributes.append((subj, pred))
log.warning("successfully validated triple, no errors")
return | [
"def",
"_check_triple",
"(",
"self",
",",
"triple",
")",
":",
"subj",
",",
"pred",
",",
"obj",
"=",
"triple",
"if",
"self",
".",
"_should_ignore_predicate",
"(",
"pred",
")",
":",
"log",
".",
"info",
"(",
"\"Ignoring triple with predicate '{}'\"",
".",
"format",
"(",
"self",
".",
"_field_name_from_uri",
"(",
"pred",
")",
")",
")",
"return",
"classes",
"=",
"[",
"]",
"log",
".",
"warning",
"(",
"\"Possible member %s found\"",
"%",
"pred",
")",
"pred",
"=",
"self",
".",
"_expand_qname",
"(",
"pred",
")",
"if",
"self",
".",
"_namespace_from_uri",
"(",
"pred",
")",
"not",
"in",
"self",
".",
"allowed_namespaces",
":",
"log",
".",
"info",
"(",
"\"Member %s does not use an allowed namespace\"",
",",
"pred",
")",
"return",
"instanceof",
"=",
"self",
".",
"_is_instance",
"(",
"(",
"subj",
",",
"pred",
",",
"obj",
")",
")",
"if",
"type",
"(",
"instanceof",
")",
"==",
"rt",
".",
"URIRef",
":",
"instanceof",
"=",
"self",
".",
"_expand_qname",
"(",
"instanceof",
")",
"if",
"hasattr",
"(",
"self",
".",
"schema_def",
",",
"\"attributes_by_class\"",
")",
"and",
"not",
"self",
".",
"schema_def",
".",
"attributes_by_class",
":",
"log",
".",
"info",
"(",
"\"Parsed ontology not found. Parsing...\"",
")",
"self",
".",
"schema_def",
".",
"parse_ontology",
"(",
")",
"class_invalid",
"=",
"self",
".",
"_validate_class",
"(",
"instanceof",
")",
"if",
"class_invalid",
":",
"log",
".",
"warning",
"(",
"\"Invalid class %s\"",
"%",
"instanceof",
")",
"return",
"class_invalid",
"# TODO - the above sometimes fails when a single object has more than",
"# one rdfa type (eg <span property=\"schema:creator rnews:creator\"",
"# typeof=\"schema:Person rnews:Person\">",
"# Graph chooses the type in an arbitrary order, so it's unreliable",
"# eg: http://semanticweb.com/the-impact-of-rdfa_b35003",
"classes",
"=",
"self",
".",
"_superclasses_for_subject",
"(",
"self",
".",
"graph",
",",
"instanceof",
")",
"classes",
".",
"append",
"(",
"instanceof",
")",
"member_invalid",
"=",
"self",
".",
"_validate_member",
"(",
"pred",
",",
"classes",
",",
"instanceof",
")",
"if",
"member_invalid",
":",
"log",
".",
"warning",
"(",
"\"Invalid member of class\"",
")",
"return",
"member_invalid",
"dupe_invalid",
"=",
"self",
".",
"_validate_duplication",
"(",
"(",
"subj",
",",
"pred",
")",
",",
"instanceof",
")",
"if",
"dupe_invalid",
":",
"log",
".",
"warning",
"(",
"\"Duplication found\"",
")",
"return",
"dupe_invalid",
"# collect a list of checked attributes",
"self",
".",
"checked_attributes",
".",
"append",
"(",
"(",
"subj",
",",
"pred",
")",
")",
"log",
".",
"warning",
"(",
"\"successfully validated triple, no errors\"",
")",
"return"
] | compare triple to ontology, return error or None | [
"compare",
"triple",
"to",
"ontology",
"return",
"error",
"or",
"None"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L61-L114 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._validate_class | def _validate_class(self, cl):
"""return error if class `cl` is not found in the ontology"""
if cl not in self.schema_def.attributes_by_class:
search_string = self._build_search_string(cl)
err = self.err(
"{0} - invalid class", self._field_name_from_uri(cl),
search_string=search_string)
return ValidationWarning(ValidationResult.ERROR, err['err'],
err['line'], err['num']) | python | def _validate_class(self, cl):
"""return error if class `cl` is not found in the ontology"""
if cl not in self.schema_def.attributes_by_class:
search_string = self._build_search_string(cl)
err = self.err(
"{0} - invalid class", self._field_name_from_uri(cl),
search_string=search_string)
return ValidationWarning(ValidationResult.ERROR, err['err'],
err['line'], err['num']) | [
"def",
"_validate_class",
"(",
"self",
",",
"cl",
")",
":",
"if",
"cl",
"not",
"in",
"self",
".",
"schema_def",
".",
"attributes_by_class",
":",
"search_string",
"=",
"self",
".",
"_build_search_string",
"(",
"cl",
")",
"err",
"=",
"self",
".",
"err",
"(",
"\"{0} - invalid class\"",
",",
"self",
".",
"_field_name_from_uri",
"(",
"cl",
")",
",",
"search_string",
"=",
"search_string",
")",
"return",
"ValidationWarning",
"(",
"ValidationResult",
".",
"ERROR",
",",
"err",
"[",
"'err'",
"]",
",",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'num'",
"]",
")"
] | return error if class `cl` is not found in the ontology | [
"return",
"error",
"if",
"class",
"cl",
"is",
"not",
"found",
"in",
"the",
"ontology"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L116-L124 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._validate_member | def _validate_member(self, member, classes, instanceof):
"""return error if `member` is not a member of any class in
`classes`
"""
log.info("Validating member %s" % member)
stripped = self._get_stripped_attributes(member, classes)
if self._field_name_from_uri(member) in stripped:
all_class_members = sum([self.schema_def.attributes_by_class[cl]
for cl in classes], [])
if member in all_class_members:
return
if self._namespace_from_uri(member) in self.allowed_namespaces:
err = self.err("Unoficially allowed namespace {0}",
self._namespace_from_uri(member))
return ValidationWarning(ValidationResult.WARNING, err['err'],
err['line'], err['num'])
else:
err = self.err("{0} - invalid member of {1}",
self._field_name_from_uri(member),
self._field_name_from_uri(instanceof))
return ValidationWarning(ValidationResult.ERROR, err['err'],
err['line'], err['num']) | python | def _validate_member(self, member, classes, instanceof):
"""return error if `member` is not a member of any class in
`classes`
"""
log.info("Validating member %s" % member)
stripped = self._get_stripped_attributes(member, classes)
if self._field_name_from_uri(member) in stripped:
all_class_members = sum([self.schema_def.attributes_by_class[cl]
for cl in classes], [])
if member in all_class_members:
return
if self._namespace_from_uri(member) in self.allowed_namespaces:
err = self.err("Unoficially allowed namespace {0}",
self._namespace_from_uri(member))
return ValidationWarning(ValidationResult.WARNING, err['err'],
err['line'], err['num'])
else:
err = self.err("{0} - invalid member of {1}",
self._field_name_from_uri(member),
self._field_name_from_uri(instanceof))
return ValidationWarning(ValidationResult.ERROR, err['err'],
err['line'], err['num']) | [
"def",
"_validate_member",
"(",
"self",
",",
"member",
",",
"classes",
",",
"instanceof",
")",
":",
"log",
".",
"info",
"(",
"\"Validating member %s\"",
"%",
"member",
")",
"stripped",
"=",
"self",
".",
"_get_stripped_attributes",
"(",
"member",
",",
"classes",
")",
"if",
"self",
".",
"_field_name_from_uri",
"(",
"member",
")",
"in",
"stripped",
":",
"all_class_members",
"=",
"sum",
"(",
"[",
"self",
".",
"schema_def",
".",
"attributes_by_class",
"[",
"cl",
"]",
"for",
"cl",
"in",
"classes",
"]",
",",
"[",
"]",
")",
"if",
"member",
"in",
"all_class_members",
":",
"return",
"if",
"self",
".",
"_namespace_from_uri",
"(",
"member",
")",
"in",
"self",
".",
"allowed_namespaces",
":",
"err",
"=",
"self",
".",
"err",
"(",
"\"Unoficially allowed namespace {0}\"",
",",
"self",
".",
"_namespace_from_uri",
"(",
"member",
")",
")",
"return",
"ValidationWarning",
"(",
"ValidationResult",
".",
"WARNING",
",",
"err",
"[",
"'err'",
"]",
",",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'num'",
"]",
")",
"else",
":",
"err",
"=",
"self",
".",
"err",
"(",
"\"{0} - invalid member of {1}\"",
",",
"self",
".",
"_field_name_from_uri",
"(",
"member",
")",
",",
"self",
".",
"_field_name_from_uri",
"(",
"instanceof",
")",
")",
"return",
"ValidationWarning",
"(",
"ValidationResult",
".",
"ERROR",
",",
"err",
"[",
"'err'",
"]",
",",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'num'",
"]",
")"
] | return error if `member` is not a member of any class in
`classes` | [
"return",
"error",
"if",
"member",
"is",
"not",
"a",
"member",
"of",
"any",
"class",
"in",
"classes"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L138-L160 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._validate_duplication | def _validate_duplication(self, subj_and_pred, cl):
"""returns error if we've already seen the member `pred` on `subj`"""
subj, pred = subj_and_pred
log.info("Validating duplication of member %s" % pred)
if (subj, pred) in self.checked_attributes:
err = self.err("{0} - duplicated member of {1}",
self._field_name_from_uri(pred),
self._field_name_from_uri(cl))
return ValidationWarning(ValidationResult.WARNING, err['err'],
err['line'], err['num']) | python | def _validate_duplication(self, subj_and_pred, cl):
"""returns error if we've already seen the member `pred` on `subj`"""
subj, pred = subj_and_pred
log.info("Validating duplication of member %s" % pred)
if (subj, pred) in self.checked_attributes:
err = self.err("{0} - duplicated member of {1}",
self._field_name_from_uri(pred),
self._field_name_from_uri(cl))
return ValidationWarning(ValidationResult.WARNING, err['err'],
err['line'], err['num']) | [
"def",
"_validate_duplication",
"(",
"self",
",",
"subj_and_pred",
",",
"cl",
")",
":",
"subj",
",",
"pred",
"=",
"subj_and_pred",
"log",
".",
"info",
"(",
"\"Validating duplication of member %s\"",
"%",
"pred",
")",
"if",
"(",
"subj",
",",
"pred",
")",
"in",
"self",
".",
"checked_attributes",
":",
"err",
"=",
"self",
".",
"err",
"(",
"\"{0} - duplicated member of {1}\"",
",",
"self",
".",
"_field_name_from_uri",
"(",
"pred",
")",
",",
"self",
".",
"_field_name_from_uri",
"(",
"cl",
")",
")",
"return",
"ValidationWarning",
"(",
"ValidationResult",
".",
"WARNING",
",",
"err",
"[",
"'err'",
"]",
",",
"err",
"[",
"'line'",
"]",
",",
"err",
"[",
"'num'",
"]",
")"
] | returns error if we've already seen the member `pred` on `subj` | [
"returns",
"error",
"if",
"we",
"ve",
"already",
"seen",
"the",
"member",
"pred",
"on",
"subj"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L162-L172 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._superclasses_for_subject | def _superclasses_for_subject(self, graph, typeof):
"""helper, returns a list of all superclasses of a given class"""
# TODO - this might be replacing a fairly simple graph API query where
# it doesn't need to
classes = []
superclass = typeof
while True:
found = False
for p, o in self.schema_def.ontology[superclass]:
if self.schema_def.lexicon['subclass'] == str(p):
found = True
classes.append(o)
superclass = o
if not found:
break
return classes | python | def _superclasses_for_subject(self, graph, typeof):
"""helper, returns a list of all superclasses of a given class"""
# TODO - this might be replacing a fairly simple graph API query where
# it doesn't need to
classes = []
superclass = typeof
while True:
found = False
for p, o in self.schema_def.ontology[superclass]:
if self.schema_def.lexicon['subclass'] == str(p):
found = True
classes.append(o)
superclass = o
if not found:
break
return classes | [
"def",
"_superclasses_for_subject",
"(",
"self",
",",
"graph",
",",
"typeof",
")",
":",
"# TODO - this might be replacing a fairly simple graph API query where",
"# it doesn't need to",
"classes",
"=",
"[",
"]",
"superclass",
"=",
"typeof",
"while",
"True",
":",
"found",
"=",
"False",
"for",
"p",
",",
"o",
"in",
"self",
".",
"schema_def",
".",
"ontology",
"[",
"superclass",
"]",
":",
"if",
"self",
".",
"schema_def",
".",
"lexicon",
"[",
"'subclass'",
"]",
"==",
"str",
"(",
"p",
")",
":",
"found",
"=",
"True",
"classes",
".",
"append",
"(",
"o",
")",
"superclass",
"=",
"o",
"if",
"not",
"found",
":",
"break",
"return",
"classes"
] | helper, returns a list of all superclasses of a given class | [
"helper",
"returns",
"a",
"list",
"of",
"all",
"superclasses",
"of",
"a",
"given",
"class"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L174-L189 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._is_instance | def _is_instance(self, triple):
"""helper, returns the class type of subj"""
subj, pred, obj = triple
input_pred_ns = self._namespace_from_uri(self._expand_qname(pred))
triples = self.graph.triples(
(subj, rt.URIRef(self.schema_def.lexicon['type']), None)
)
if triples:
for tr in triples:
triple_obj_ns = self._namespace_from_uri(
self._expand_qname(tr[2]))
if input_pred_ns == triple_obj_ns: # match namespaces
return tr[2] | python | def _is_instance(self, triple):
"""helper, returns the class type of subj"""
subj, pred, obj = triple
input_pred_ns = self._namespace_from_uri(self._expand_qname(pred))
triples = self.graph.triples(
(subj, rt.URIRef(self.schema_def.lexicon['type']), None)
)
if triples:
for tr in triples:
triple_obj_ns = self._namespace_from_uri(
self._expand_qname(tr[2]))
if input_pred_ns == triple_obj_ns: # match namespaces
return tr[2] | [
"def",
"_is_instance",
"(",
"self",
",",
"triple",
")",
":",
"subj",
",",
"pred",
",",
"obj",
"=",
"triple",
"input_pred_ns",
"=",
"self",
".",
"_namespace_from_uri",
"(",
"self",
".",
"_expand_qname",
"(",
"pred",
")",
")",
"triples",
"=",
"self",
".",
"graph",
".",
"triples",
"(",
"(",
"subj",
",",
"rt",
".",
"URIRef",
"(",
"self",
".",
"schema_def",
".",
"lexicon",
"[",
"'type'",
"]",
")",
",",
"None",
")",
")",
"if",
"triples",
":",
"for",
"tr",
"in",
"triples",
":",
"triple_obj_ns",
"=",
"self",
".",
"_namespace_from_uri",
"(",
"self",
".",
"_expand_qname",
"(",
"tr",
"[",
"2",
"]",
")",
")",
"if",
"input_pred_ns",
"==",
"triple_obj_ns",
":",
"# match namespaces",
"return",
"tr",
"[",
"2",
"]"
] | helper, returns the class type of subj | [
"helper",
"returns",
"the",
"class",
"type",
"of",
"subj"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L191-L203 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._namespace_from_uri | def _namespace_from_uri(self, uri):
"""returns the expanded namespace prefix of a uri"""
# TODO - this could be helped a bunch with proper use of the graph API
# it seems a bit fragile to treat these as simple string-splits
uri = str(uri)
parts = uri.split('#')
if len(parts) == 1:
return "%s/" % '/'.join(uri.split('/')[:-1])
return "%s#" % '#'.join(parts[:-1]) | python | def _namespace_from_uri(self, uri):
"""returns the expanded namespace prefix of a uri"""
# TODO - this could be helped a bunch with proper use of the graph API
# it seems a bit fragile to treat these as simple string-splits
uri = str(uri)
parts = uri.split('#')
if len(parts) == 1:
return "%s/" % '/'.join(uri.split('/')[:-1])
return "%s#" % '#'.join(parts[:-1]) | [
"def",
"_namespace_from_uri",
"(",
"self",
",",
"uri",
")",
":",
"# TODO - this could be helped a bunch with proper use of the graph API",
"# it seems a bit fragile to treat these as simple string-splits",
"uri",
"=",
"str",
"(",
"uri",
")",
"parts",
"=",
"uri",
".",
"split",
"(",
"'#'",
")",
"if",
"len",
"(",
"parts",
")",
"==",
"1",
":",
"return",
"\"%s/\"",
"%",
"'/'",
".",
"join",
"(",
"uri",
".",
"split",
"(",
"'/'",
")",
"[",
":",
"-",
"1",
"]",
")",
"return",
"\"%s#\"",
"%",
"'#'",
".",
"join",
"(",
"parts",
"[",
":",
"-",
"1",
"]",
")"
] | returns the expanded namespace prefix of a uri | [
"returns",
"the",
"expanded",
"namespace",
"prefix",
"of",
"a",
"uri"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L215-L223 | train |
Parsely/schemato | schemato/validator.py | SchemaValidator._expand_qname | def _expand_qname(self, qname):
"""expand a qualified name's namespace prefix to include the resolved
namespace root url"""
if type(qname) is not rt.URIRef:
raise TypeError("Cannot expand qname of type {}, must be URIRef"
.format(type(qname)))
for ns in self.graph.namespaces():
if ns[0] == qname.split(':')[0]:
return rt.URIRef("%s%s" % (ns[1], qname.split(':')[-1]))
return qname | python | def _expand_qname(self, qname):
"""expand a qualified name's namespace prefix to include the resolved
namespace root url"""
if type(qname) is not rt.URIRef:
raise TypeError("Cannot expand qname of type {}, must be URIRef"
.format(type(qname)))
for ns in self.graph.namespaces():
if ns[0] == qname.split(':')[0]:
return rt.URIRef("%s%s" % (ns[1], qname.split(':')[-1]))
return qname | [
"def",
"_expand_qname",
"(",
"self",
",",
"qname",
")",
":",
"if",
"type",
"(",
"qname",
")",
"is",
"not",
"rt",
".",
"URIRef",
":",
"raise",
"TypeError",
"(",
"\"Cannot expand qname of type {}, must be URIRef\"",
".",
"format",
"(",
"type",
"(",
"qname",
")",
")",
")",
"for",
"ns",
"in",
"self",
".",
"graph",
".",
"namespaces",
"(",
")",
":",
"if",
"ns",
"[",
"0",
"]",
"==",
"qname",
".",
"split",
"(",
"':'",
")",
"[",
"0",
"]",
":",
"return",
"rt",
".",
"URIRef",
"(",
"\"%s%s\"",
"%",
"(",
"ns",
"[",
"1",
"]",
",",
"qname",
".",
"split",
"(",
"':'",
")",
"[",
"-",
"1",
"]",
")",
")",
"return",
"qname"
] | expand a qualified name's namespace prefix to include the resolved
namespace root url | [
"expand",
"a",
"qualified",
"name",
"s",
"namespace",
"prefix",
"to",
"include",
"the",
"resolved",
"namespace",
"root",
"url"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/validator.py#L225-L234 | train |
kmike/port-for | port_for/_download_ranges.py | _write_unassigned_ranges | def _write_unassigned_ranges(out_filename):
"""
Downloads ports data from IANA & Wikipedia and converts
it to a python module. This function is used to generate _ranges.py.
"""
with open(out_filename, 'wt') as f:
f.write('# auto-generated by port_for._download_ranges (%s)\n' % datetime.date.today())
f.write('UNASSIGNED_RANGES = [\n')
for range in to_ranges(sorted(list(_unassigned_ports()))):
f.write(" (%d, %d),\n" % range)
f.write(']\n') | python | def _write_unassigned_ranges(out_filename):
"""
Downloads ports data from IANA & Wikipedia and converts
it to a python module. This function is used to generate _ranges.py.
"""
with open(out_filename, 'wt') as f:
f.write('# auto-generated by port_for._download_ranges (%s)\n' % datetime.date.today())
f.write('UNASSIGNED_RANGES = [\n')
for range in to_ranges(sorted(list(_unassigned_ports()))):
f.write(" (%d, %d),\n" % range)
f.write(']\n') | [
"def",
"_write_unassigned_ranges",
"(",
"out_filename",
")",
":",
"with",
"open",
"(",
"out_filename",
",",
"'wt'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"'# auto-generated by port_for._download_ranges (%s)\\n'",
"%",
"datetime",
".",
"date",
".",
"today",
"(",
")",
")",
"f",
".",
"write",
"(",
"'UNASSIGNED_RANGES = [\\n'",
")",
"for",
"range",
"in",
"to_ranges",
"(",
"sorted",
"(",
"list",
"(",
"_unassigned_ports",
"(",
")",
")",
")",
")",
":",
"f",
".",
"write",
"(",
"\" (%d, %d),\\n\"",
"%",
"range",
")",
"f",
".",
"write",
"(",
"']\\n'",
")"
] | Downloads ports data from IANA & Wikipedia and converts
it to a python module. This function is used to generate _ranges.py. | [
"Downloads",
"ports",
"data",
"from",
"IANA",
"&",
"Wikipedia",
"and",
"converts",
"it",
"to",
"a",
"python",
"module",
".",
"This",
"function",
"is",
"used",
"to",
"generate",
"_ranges",
".",
"py",
"."
] | f61ebf3c2caf54eabe8233b40ef67b973176a6f5 | https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L24-L34 | train |
kmike/port-for | port_for/_download_ranges.py | _wikipedia_known_port_ranges | def _wikipedia_known_port_ranges():
"""
Returns used port ranges according to Wikipedia page.
This page contains unofficial well-known ports.
"""
req = urllib2.Request(WIKIPEDIA_PAGE, headers={'User-Agent' : "Magic Browser"})
page = urllib2.urlopen(req).read().decode('utf8')
# just find all numbers in table cells
ports = re.findall('<td>((\d+)(\W(\d+))?)</td>', page, re.U)
return ((int(p[1]), int(p[3] if p[3] else p[1])) for p in ports) | python | def _wikipedia_known_port_ranges():
"""
Returns used port ranges according to Wikipedia page.
This page contains unofficial well-known ports.
"""
req = urllib2.Request(WIKIPEDIA_PAGE, headers={'User-Agent' : "Magic Browser"})
page = urllib2.urlopen(req).read().decode('utf8')
# just find all numbers in table cells
ports = re.findall('<td>((\d+)(\W(\d+))?)</td>', page, re.U)
return ((int(p[1]), int(p[3] if p[3] else p[1])) for p in ports) | [
"def",
"_wikipedia_known_port_ranges",
"(",
")",
":",
"req",
"=",
"urllib2",
".",
"Request",
"(",
"WIKIPEDIA_PAGE",
",",
"headers",
"=",
"{",
"'User-Agent'",
":",
"\"Magic Browser\"",
"}",
")",
"page",
"=",
"urllib2",
".",
"urlopen",
"(",
"req",
")",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf8'",
")",
"# just find all numbers in table cells",
"ports",
"=",
"re",
".",
"findall",
"(",
"'<td>((\\d+)(\\W(\\d+))?)</td>'",
",",
"page",
",",
"re",
".",
"U",
")",
"return",
"(",
"(",
"int",
"(",
"p",
"[",
"1",
"]",
")",
",",
"int",
"(",
"p",
"[",
"3",
"]",
"if",
"p",
"[",
"3",
"]",
"else",
"p",
"[",
"1",
"]",
")",
")",
"for",
"p",
"in",
"ports",
")"
] | Returns used port ranges according to Wikipedia page.
This page contains unofficial well-known ports. | [
"Returns",
"used",
"port",
"ranges",
"according",
"to",
"Wikipedia",
"page",
".",
"This",
"page",
"contains",
"unofficial",
"well",
"-",
"known",
"ports",
"."
] | f61ebf3c2caf54eabe8233b40ef67b973176a6f5 | https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L44-L54 | train |
kmike/port-for | port_for/_download_ranges.py | _iana_unassigned_port_ranges | def _iana_unassigned_port_ranges():
"""
Returns unassigned port ranges according to IANA.
"""
page = urllib2.urlopen(IANA_DOWNLOAD_URL).read()
xml = ElementTree.fromstring(page)
records = xml.findall('{%s}record' % IANA_NS)
for record in records:
description = record.find('{%s}description' % IANA_NS).text
if description == 'Unassigned':
numbers = record.find('{%s}number' % IANA_NS).text
yield numbers | python | def _iana_unassigned_port_ranges():
"""
Returns unassigned port ranges according to IANA.
"""
page = urllib2.urlopen(IANA_DOWNLOAD_URL).read()
xml = ElementTree.fromstring(page)
records = xml.findall('{%s}record' % IANA_NS)
for record in records:
description = record.find('{%s}description' % IANA_NS).text
if description == 'Unassigned':
numbers = record.find('{%s}number' % IANA_NS).text
yield numbers | [
"def",
"_iana_unassigned_port_ranges",
"(",
")",
":",
"page",
"=",
"urllib2",
".",
"urlopen",
"(",
"IANA_DOWNLOAD_URL",
")",
".",
"read",
"(",
")",
"xml",
"=",
"ElementTree",
".",
"fromstring",
"(",
"page",
")",
"records",
"=",
"xml",
".",
"findall",
"(",
"'{%s}record'",
"%",
"IANA_NS",
")",
"for",
"record",
"in",
"records",
":",
"description",
"=",
"record",
".",
"find",
"(",
"'{%s}description'",
"%",
"IANA_NS",
")",
".",
"text",
"if",
"description",
"==",
"'Unassigned'",
":",
"numbers",
"=",
"record",
".",
"find",
"(",
"'{%s}number'",
"%",
"IANA_NS",
")",
".",
"text",
"yield",
"numbers"
] | Returns unassigned port ranges according to IANA. | [
"Returns",
"unassigned",
"port",
"ranges",
"according",
"to",
"IANA",
"."
] | f61ebf3c2caf54eabe8233b40ef67b973176a6f5 | https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/_download_ranges.py#L57-L68 | train |
astraw38/lint | lint/main.py | run_linters | def run_linters(files):
"""
Run through file list, and try to find a linter
that matches the given file type.
If it finds a linter, it will run it, and store the
resulting data in a dictionary (keyed to file_type).
:param files:
:return: {file_extension: lint_data}
"""
data = {}
for file_type, file_list in list(files.items()):
linter = LintFactory.get_linter(file_type)
if linter is not None:
data[file_type] = linter.run(file_list)
return data | python | def run_linters(files):
"""
Run through file list, and try to find a linter
that matches the given file type.
If it finds a linter, it will run it, and store the
resulting data in a dictionary (keyed to file_type).
:param files:
:return: {file_extension: lint_data}
"""
data = {}
for file_type, file_list in list(files.items()):
linter = LintFactory.get_linter(file_type)
if linter is not None:
data[file_type] = linter.run(file_list)
return data | [
"def",
"run_linters",
"(",
"files",
")",
":",
"data",
"=",
"{",
"}",
"for",
"file_type",
",",
"file_list",
"in",
"list",
"(",
"files",
".",
"items",
"(",
")",
")",
":",
"linter",
"=",
"LintFactory",
".",
"get_linter",
"(",
"file_type",
")",
"if",
"linter",
"is",
"not",
"None",
":",
"data",
"[",
"file_type",
"]",
"=",
"linter",
".",
"run",
"(",
"file_list",
")",
"return",
"data"
] | Run through file list, and try to find a linter
that matches the given file type.
If it finds a linter, it will run it, and store the
resulting data in a dictionary (keyed to file_type).
:param files:
:return: {file_extension: lint_data} | [
"Run",
"through",
"file",
"list",
"and",
"try",
"to",
"find",
"a",
"linter",
"that",
"matches",
"the",
"given",
"file",
"type",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/main.py#L12-L28 | train |
astraw38/lint | lint/main.py | run_validators | def run_validators(new_data, old_data):
"""
Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return:
"""
#{'validator_name': (success, score, message)}
validation_data = {}
for file_type, lint_data in list(new_data.items()):
#TODO: What to do if old data doesn't have this filetype?
old_lint_data = old_data.get(file_type, {})
validator = ValidatorFactory.get_validator(file_type)
if validator is not None:
validation_data[validator.name] = validator.run(lint_data, old_lint_data)
return validation_data | python | def run_validators(new_data, old_data):
"""
Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return:
"""
#{'validator_name': (success, score, message)}
validation_data = {}
for file_type, lint_data in list(new_data.items()):
#TODO: What to do if old data doesn't have this filetype?
old_lint_data = old_data.get(file_type, {})
validator = ValidatorFactory.get_validator(file_type)
if validator is not None:
validation_data[validator.name] = validator.run(lint_data, old_lint_data)
return validation_data | [
"def",
"run_validators",
"(",
"new_data",
",",
"old_data",
")",
":",
"#{'validator_name': (success, score, message)}",
"validation_data",
"=",
"{",
"}",
"for",
"file_type",
",",
"lint_data",
"in",
"list",
"(",
"new_data",
".",
"items",
"(",
")",
")",
":",
"#TODO: What to do if old data doesn't have this filetype?",
"old_lint_data",
"=",
"old_data",
".",
"get",
"(",
"file_type",
",",
"{",
"}",
")",
"validator",
"=",
"ValidatorFactory",
".",
"get_validator",
"(",
"file_type",
")",
"if",
"validator",
"is",
"not",
"None",
":",
"validation_data",
"[",
"validator",
".",
"name",
"]",
"=",
"validator",
".",
"run",
"(",
"lint_data",
",",
"old_lint_data",
")",
"return",
"validation_data"
] | Run through all matching validators.
:param new_data: New lint data.
:param old_data: Old lint data (before review)
:return: | [
"Run",
"through",
"all",
"matching",
"validators",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/main.py#L31-L47 | train |
Parsely/schemato | schemato/schemas/parselypage.py | ParselyPageParser.original_unescape | def original_unescape(self, s):
"""Since we need to use this sometimes"""
if isinstance(s, basestring):
return unicode(HTMLParser.unescape(self, s))
elif isinstance(s, list):
return [unicode(HTMLParser.unescape(self, item)) for item in s]
else:
return s | python | def original_unescape(self, s):
"""Since we need to use this sometimes"""
if isinstance(s, basestring):
return unicode(HTMLParser.unescape(self, s))
elif isinstance(s, list):
return [unicode(HTMLParser.unescape(self, item)) for item in s]
else:
return s | [
"def",
"original_unescape",
"(",
"self",
",",
"s",
")",
":",
"if",
"isinstance",
"(",
"s",
",",
"basestring",
")",
":",
"return",
"unicode",
"(",
"HTMLParser",
".",
"unescape",
"(",
"self",
",",
"s",
")",
")",
"elif",
"isinstance",
"(",
"s",
",",
"list",
")",
":",
"return",
"[",
"unicode",
"(",
"HTMLParser",
".",
"unescape",
"(",
"self",
",",
"item",
")",
")",
"for",
"item",
"in",
"s",
"]",
"else",
":",
"return",
"s"
] | Since we need to use this sometimes | [
"Since",
"we",
"need",
"to",
"use",
"this",
"sometimes"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L35-L42 | train |
Parsely/schemato | schemato/schemas/parselypage.py | ParselyPageValidator.get_standard | def get_standard(self):
"""get list of allowed parameters"""
try:
res = urlopen(PARSELY_PAGE_SCHEMA)
except:
return []
text = res.read()
if isinstance(text, bytes):
text = text.decode('utf-8')
tree = etree.parse(StringIO(text))
stdref = tree.xpath("//div/@about")
return [a.split(':')[1] for a in stdref] | python | def get_standard(self):
"""get list of allowed parameters"""
try:
res = urlopen(PARSELY_PAGE_SCHEMA)
except:
return []
text = res.read()
if isinstance(text, bytes):
text = text.decode('utf-8')
tree = etree.parse(StringIO(text))
stdref = tree.xpath("//div/@about")
return [a.split(':')[1] for a in stdref] | [
"def",
"get_standard",
"(",
"self",
")",
":",
"try",
":",
"res",
"=",
"urlopen",
"(",
"PARSELY_PAGE_SCHEMA",
")",
"except",
":",
"return",
"[",
"]",
"text",
"=",
"res",
".",
"read",
"(",
")",
"if",
"isinstance",
"(",
"text",
",",
"bytes",
")",
":",
"text",
"=",
"text",
".",
"decode",
"(",
"'utf-8'",
")",
"tree",
"=",
"etree",
".",
"parse",
"(",
"StringIO",
"(",
"text",
")",
")",
"stdref",
"=",
"tree",
".",
"xpath",
"(",
"\"//div/@about\"",
")",
"return",
"[",
"a",
".",
"split",
"(",
"':'",
")",
"[",
"1",
"]",
"for",
"a",
"in",
"stdref",
"]"
] | get list of allowed parameters | [
"get",
"list",
"of",
"allowed",
"parameters"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L56-L67 | train |
Parsely/schemato | schemato/schemas/parselypage.py | ParselyPageValidator._get_parselypage | def _get_parselypage(self, body):
"""extract the parsely-page meta content from a page"""
parser = ParselyPageParser()
ret = None
try:
parser.feed(body)
except HTMLParseError:
pass # ignore and hope we got ppage
if parser.ppage is None:
return
ret = parser.ppage
if ret:
ret = {parser.original_unescape(k): parser.original_unescape(v)
for k, v in iteritems(ret)}
return ret | python | def _get_parselypage(self, body):
"""extract the parsely-page meta content from a page"""
parser = ParselyPageParser()
ret = None
try:
parser.feed(body)
except HTMLParseError:
pass # ignore and hope we got ppage
if parser.ppage is None:
return
ret = parser.ppage
if ret:
ret = {parser.original_unescape(k): parser.original_unescape(v)
for k, v in iteritems(ret)}
return ret | [
"def",
"_get_parselypage",
"(",
"self",
",",
"body",
")",
":",
"parser",
"=",
"ParselyPageParser",
"(",
")",
"ret",
"=",
"None",
"try",
":",
"parser",
".",
"feed",
"(",
"body",
")",
"except",
"HTMLParseError",
":",
"pass",
"# ignore and hope we got ppage",
"if",
"parser",
".",
"ppage",
"is",
"None",
":",
"return",
"ret",
"=",
"parser",
".",
"ppage",
"if",
"ret",
":",
"ret",
"=",
"{",
"parser",
".",
"original_unescape",
"(",
"k",
")",
":",
"parser",
".",
"original_unescape",
"(",
"v",
")",
"for",
"k",
",",
"v",
"in",
"iteritems",
"(",
"ret",
")",
"}",
"return",
"ret"
] | extract the parsely-page meta content from a page | [
"extract",
"the",
"parsely",
"-",
"page",
"meta",
"content",
"from",
"a",
"page"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemas/parselypage.py#L69-L84 | train |
Parsely/schemato | schemato/schemadef.py | SchemaDef._read_schema | def _read_schema(self):
"""return the local filename of the definition file for this schema
if not present or older than expiry, pull the latest version from
the web at self._ontology_file"""
cache_filename = os.path.join(
CACHE_ROOT, "%s.smt" % self._representation)
log.info("Attempting to read local schema at %s" % cache_filename)
try:
if time.time() - os.stat(cache_filename).st_mtime > CACHE_EXPIRY:
log.warning("Cache expired, re-pulling")
self._pull_schema_definition(cache_filename)
except OSError:
log.warning("Local schema not found. Pulling from web.")
self._pull_schema_definition(cache_filename)
else:
log.info("Success")
return cache_filename | python | def _read_schema(self):
"""return the local filename of the definition file for this schema
if not present or older than expiry, pull the latest version from
the web at self._ontology_file"""
cache_filename = os.path.join(
CACHE_ROOT, "%s.smt" % self._representation)
log.info("Attempting to read local schema at %s" % cache_filename)
try:
if time.time() - os.stat(cache_filename).st_mtime > CACHE_EXPIRY:
log.warning("Cache expired, re-pulling")
self._pull_schema_definition(cache_filename)
except OSError:
log.warning("Local schema not found. Pulling from web.")
self._pull_schema_definition(cache_filename)
else:
log.info("Success")
return cache_filename | [
"def",
"_read_schema",
"(",
"self",
")",
":",
"cache_filename",
"=",
"os",
".",
"path",
".",
"join",
"(",
"CACHE_ROOT",
",",
"\"%s.smt\"",
"%",
"self",
".",
"_representation",
")",
"log",
".",
"info",
"(",
"\"Attempting to read local schema at %s\"",
"%",
"cache_filename",
")",
"try",
":",
"if",
"time",
".",
"time",
"(",
")",
"-",
"os",
".",
"stat",
"(",
"cache_filename",
")",
".",
"st_mtime",
">",
"CACHE_EXPIRY",
":",
"log",
".",
"warning",
"(",
"\"Cache expired, re-pulling\"",
")",
"self",
".",
"_pull_schema_definition",
"(",
"cache_filename",
")",
"except",
"OSError",
":",
"log",
".",
"warning",
"(",
"\"Local schema not found. Pulling from web.\"",
")",
"self",
".",
"_pull_schema_definition",
"(",
"cache_filename",
")",
"else",
":",
"log",
".",
"info",
"(",
"\"Success\"",
")",
"return",
"cache_filename"
] | return the local filename of the definition file for this schema
if not present or older than expiry, pull the latest version from
the web at self._ontology_file | [
"return",
"the",
"local",
"filename",
"of",
"the",
"definition",
"file",
"for",
"this",
"schema",
"if",
"not",
"present",
"or",
"older",
"than",
"expiry",
"pull",
"the",
"latest",
"version",
"from",
"the",
"web",
"at",
"self",
".",
"_ontology_file"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L38-L55 | train |
Parsely/schemato | schemato/schemadef.py | SchemaDef._pull_schema_definition | def _pull_schema_definition(self, fname):
"""download an ontology definition from the web"""
std_url = urlopen(self._ontology_file)
cached_std = open(fname, "w+")
cached_std.write(std_url.read())
cached_std.close() | python | def _pull_schema_definition(self, fname):
"""download an ontology definition from the web"""
std_url = urlopen(self._ontology_file)
cached_std = open(fname, "w+")
cached_std.write(std_url.read())
cached_std.close() | [
"def",
"_pull_schema_definition",
"(",
"self",
",",
"fname",
")",
":",
"std_url",
"=",
"urlopen",
"(",
"self",
".",
"_ontology_file",
")",
"cached_std",
"=",
"open",
"(",
"fname",
",",
"\"w+\"",
")",
"cached_std",
".",
"write",
"(",
"std_url",
".",
"read",
"(",
")",
")",
"cached_std",
".",
"close",
"(",
")"
] | download an ontology definition from the web | [
"download",
"an",
"ontology",
"definition",
"from",
"the",
"web"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L57-L62 | train |
Parsely/schemato | schemato/schemadef.py | SchemaDef.parse_ontology | def parse_ontology(self):
"""place the ontology graph into a set of custom data structures
for use by the validator"""
start = time.clock()
log.info("Parsing ontology file for %s" % self.__class__.__name__)
for subj, pred, obj in self._schema_nodes():
if subj not in self.attributes_by_class:
if obj == rt.URIRef(self.lexicon['class']) and \
pred == rt.URIRef(self.lexicon['type']):
self.attributes_by_class[subj] = []
leaves = [(subj, pred, obj)]
if type(obj) == rt.BNode:
leaves = deepest_node((subj, pred, obj), self.graph)
for s, p, o in leaves:
if o not in self.attributes_by_class:
self.attributes_by_class[o] = []
if pred == rt.URIRef(self.lexicon['domain']):
self.attributes_by_class[o].append(subj)
if not self.attributes_by_class:
log.info("No nodes found in ontology")
log.info("Ontology parsing complete in {}".format(
(time.clock() - start) * 1000)) | python | def parse_ontology(self):
"""place the ontology graph into a set of custom data structures
for use by the validator"""
start = time.clock()
log.info("Parsing ontology file for %s" % self.__class__.__name__)
for subj, pred, obj in self._schema_nodes():
if subj not in self.attributes_by_class:
if obj == rt.URIRef(self.lexicon['class']) and \
pred == rt.URIRef(self.lexicon['type']):
self.attributes_by_class[subj] = []
leaves = [(subj, pred, obj)]
if type(obj) == rt.BNode:
leaves = deepest_node((subj, pred, obj), self.graph)
for s, p, o in leaves:
if o not in self.attributes_by_class:
self.attributes_by_class[o] = []
if pred == rt.URIRef(self.lexicon['domain']):
self.attributes_by_class[o].append(subj)
if not self.attributes_by_class:
log.info("No nodes found in ontology")
log.info("Ontology parsing complete in {}".format(
(time.clock() - start) * 1000)) | [
"def",
"parse_ontology",
"(",
"self",
")",
":",
"start",
"=",
"time",
".",
"clock",
"(",
")",
"log",
".",
"info",
"(",
"\"Parsing ontology file for %s\"",
"%",
"self",
".",
"__class__",
".",
"__name__",
")",
"for",
"subj",
",",
"pred",
",",
"obj",
"in",
"self",
".",
"_schema_nodes",
"(",
")",
":",
"if",
"subj",
"not",
"in",
"self",
".",
"attributes_by_class",
":",
"if",
"obj",
"==",
"rt",
".",
"URIRef",
"(",
"self",
".",
"lexicon",
"[",
"'class'",
"]",
")",
"and",
"pred",
"==",
"rt",
".",
"URIRef",
"(",
"self",
".",
"lexicon",
"[",
"'type'",
"]",
")",
":",
"self",
".",
"attributes_by_class",
"[",
"subj",
"]",
"=",
"[",
"]",
"leaves",
"=",
"[",
"(",
"subj",
",",
"pred",
",",
"obj",
")",
"]",
"if",
"type",
"(",
"obj",
")",
"==",
"rt",
".",
"BNode",
":",
"leaves",
"=",
"deepest_node",
"(",
"(",
"subj",
",",
"pred",
",",
"obj",
")",
",",
"self",
".",
"graph",
")",
"for",
"s",
",",
"p",
",",
"o",
"in",
"leaves",
":",
"if",
"o",
"not",
"in",
"self",
".",
"attributes_by_class",
":",
"self",
".",
"attributes_by_class",
"[",
"o",
"]",
"=",
"[",
"]",
"if",
"pred",
"==",
"rt",
".",
"URIRef",
"(",
"self",
".",
"lexicon",
"[",
"'domain'",
"]",
")",
":",
"self",
".",
"attributes_by_class",
"[",
"o",
"]",
".",
"append",
"(",
"subj",
")",
"if",
"not",
"self",
".",
"attributes_by_class",
":",
"log",
".",
"info",
"(",
"\"No nodes found in ontology\"",
")",
"log",
".",
"info",
"(",
"\"Ontology parsing complete in {}\"",
".",
"format",
"(",
"(",
"time",
".",
"clock",
"(",
")",
"-",
"start",
")",
"*",
"1000",
")",
")"
] | place the ontology graph into a set of custom data structures
for use by the validator | [
"place",
"the",
"ontology",
"graph",
"into",
"a",
"set",
"of",
"custom",
"data",
"structures",
"for",
"use",
"by",
"the",
"validator"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L64-L87 | train |
Parsely/schemato | schemato/schemadef.py | SchemaDef._schema_nodes | def _schema_nodes(self):
"""parse self._ontology_file into a graph"""
name, ext = os.path.splitext(self._ontology_file)
if ext in ['.ttl']:
self._ontology_parser_function = \
lambda s: rdflib.Graph().parse(s, format='n3')
else:
self._ontology_parser_function = \
lambda s: pyRdfa().graph_from_source(s)
if not self._ontology_parser_function:
raise ValueError(
"No function found to parse ontology. %s" %
self.errorstring_base)
if not self._ontology_file:
raise ValueError(
"No ontology file specified. %s" % self.errorstring_base)
if not self.lexicon:
raise ValueError(
"No lexicon object assigned. %s" % self.errorstring_base)
latest_file = self._read_schema()
try:
self.graph = self._ontology_parser_function(latest_file)
except:
raise IOError("Error parsing ontology at %s" % latest_file)
for subj, pred, obj in self.graph:
self.ontology[subj].append((pred, obj))
yield (subj, pred, obj) | python | def _schema_nodes(self):
"""parse self._ontology_file into a graph"""
name, ext = os.path.splitext(self._ontology_file)
if ext in ['.ttl']:
self._ontology_parser_function = \
lambda s: rdflib.Graph().parse(s, format='n3')
else:
self._ontology_parser_function = \
lambda s: pyRdfa().graph_from_source(s)
if not self._ontology_parser_function:
raise ValueError(
"No function found to parse ontology. %s" %
self.errorstring_base)
if not self._ontology_file:
raise ValueError(
"No ontology file specified. %s" % self.errorstring_base)
if not self.lexicon:
raise ValueError(
"No lexicon object assigned. %s" % self.errorstring_base)
latest_file = self._read_schema()
try:
self.graph = self._ontology_parser_function(latest_file)
except:
raise IOError("Error parsing ontology at %s" % latest_file)
for subj, pred, obj in self.graph:
self.ontology[subj].append((pred, obj))
yield (subj, pred, obj) | [
"def",
"_schema_nodes",
"(",
"self",
")",
":",
"name",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"self",
".",
"_ontology_file",
")",
"if",
"ext",
"in",
"[",
"'.ttl'",
"]",
":",
"self",
".",
"_ontology_parser_function",
"=",
"lambda",
"s",
":",
"rdflib",
".",
"Graph",
"(",
")",
".",
"parse",
"(",
"s",
",",
"format",
"=",
"'n3'",
")",
"else",
":",
"self",
".",
"_ontology_parser_function",
"=",
"lambda",
"s",
":",
"pyRdfa",
"(",
")",
".",
"graph_from_source",
"(",
"s",
")",
"if",
"not",
"self",
".",
"_ontology_parser_function",
":",
"raise",
"ValueError",
"(",
"\"No function found to parse ontology. %s\"",
"%",
"self",
".",
"errorstring_base",
")",
"if",
"not",
"self",
".",
"_ontology_file",
":",
"raise",
"ValueError",
"(",
"\"No ontology file specified. %s\"",
"%",
"self",
".",
"errorstring_base",
")",
"if",
"not",
"self",
".",
"lexicon",
":",
"raise",
"ValueError",
"(",
"\"No lexicon object assigned. %s\"",
"%",
"self",
".",
"errorstring_base",
")",
"latest_file",
"=",
"self",
".",
"_read_schema",
"(",
")",
"try",
":",
"self",
".",
"graph",
"=",
"self",
".",
"_ontology_parser_function",
"(",
"latest_file",
")",
"except",
":",
"raise",
"IOError",
"(",
"\"Error parsing ontology at %s\"",
"%",
"latest_file",
")",
"for",
"subj",
",",
"pred",
",",
"obj",
"in",
"self",
".",
"graph",
":",
"self",
".",
"ontology",
"[",
"subj",
"]",
".",
"append",
"(",
"(",
"pred",
",",
"obj",
")",
")",
"yield",
"(",
"subj",
",",
"pred",
",",
"obj",
")"
] | parse self._ontology_file into a graph | [
"parse",
"self",
".",
"_ontology_file",
"into",
"a",
"graph"
] | 7002316fbcd52f2e669f8372bf1338c572e3df4b | https://github.com/Parsely/schemato/blob/7002316fbcd52f2e669f8372bf1338c572e3df4b/schemato/schemadef.py#L89-L118 | train |
bear/bearlib | bearlib/tools.py | baseDomain | def baseDomain(domain, includeScheme=True):
"""Return only the network location portion of the given domain
unless includeScheme is True
"""
result = ''
url = urlparse(domain)
if includeScheme:
result = '%s://' % url.scheme
if len(url.netloc) == 0:
result += url.path
else:
result += url.netloc
return result | python | def baseDomain(domain, includeScheme=True):
"""Return only the network location portion of the given domain
unless includeScheme is True
"""
result = ''
url = urlparse(domain)
if includeScheme:
result = '%s://' % url.scheme
if len(url.netloc) == 0:
result += url.path
else:
result += url.netloc
return result | [
"def",
"baseDomain",
"(",
"domain",
",",
"includeScheme",
"=",
"True",
")",
":",
"result",
"=",
"''",
"url",
"=",
"urlparse",
"(",
"domain",
")",
"if",
"includeScheme",
":",
"result",
"=",
"'%s://'",
"%",
"url",
".",
"scheme",
"if",
"len",
"(",
"url",
".",
"netloc",
")",
"==",
"0",
":",
"result",
"+=",
"url",
".",
"path",
"else",
":",
"result",
"+=",
"url",
".",
"netloc",
"return",
"result"
] | Return only the network location portion of the given domain
unless includeScheme is True | [
"Return",
"only",
"the",
"network",
"location",
"portion",
"of",
"the",
"given",
"domain",
"unless",
"includeScheme",
"is",
"True"
] | 30f9b8ba4b7a8db4cd2f4c6e07966ae51d0a00dd | https://github.com/bear/bearlib/blob/30f9b8ba4b7a8db4cd2f4c6e07966ae51d0a00dd/bearlib/tools.py#L22-L34 | train |
nicfit/MishMash | mishmash/database.py | search | def search(session, query):
"""Naive search of the database for `query`.
:return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list
of the respective ORM type.
"""
flat_query = "".join(query.split())
artists = session.query(Artist).filter(
or_(Artist.name.ilike(f"%%{query}%%"),
Artist.name.ilike(f"%%{flat_query}%%"))
).all()
albums = session.query(Album).filter(
Album.title.ilike(f"%%{query}%%")).all()
tracks = session.query(Track).filter(
Track.title.ilike(f"%%{query}%%")).all()
return dict(artists=artists,
albums=albums,
tracks=tracks) | python | def search(session, query):
"""Naive search of the database for `query`.
:return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list
of the respective ORM type.
"""
flat_query = "".join(query.split())
artists = session.query(Artist).filter(
or_(Artist.name.ilike(f"%%{query}%%"),
Artist.name.ilike(f"%%{flat_query}%%"))
).all()
albums = session.query(Album).filter(
Album.title.ilike(f"%%{query}%%")).all()
tracks = session.query(Track).filter(
Track.title.ilike(f"%%{query}%%")).all()
return dict(artists=artists,
albums=albums,
tracks=tracks) | [
"def",
"search",
"(",
"session",
",",
"query",
")",
":",
"flat_query",
"=",
"\"\"",
".",
"join",
"(",
"query",
".",
"split",
"(",
")",
")",
"artists",
"=",
"session",
".",
"query",
"(",
"Artist",
")",
".",
"filter",
"(",
"or_",
"(",
"Artist",
".",
"name",
".",
"ilike",
"(",
"f\"%%{query}%%\"",
")",
",",
"Artist",
".",
"name",
".",
"ilike",
"(",
"f\"%%{flat_query}%%\"",
")",
")",
")",
".",
"all",
"(",
")",
"albums",
"=",
"session",
".",
"query",
"(",
"Album",
")",
".",
"filter",
"(",
"Album",
".",
"title",
".",
"ilike",
"(",
"f\"%%{query}%%\"",
")",
")",
".",
"all",
"(",
")",
"tracks",
"=",
"session",
".",
"query",
"(",
"Track",
")",
".",
"filter",
"(",
"Track",
".",
"title",
".",
"ilike",
"(",
"f\"%%{query}%%\"",
")",
")",
".",
"all",
"(",
")",
"return",
"dict",
"(",
"artists",
"=",
"artists",
",",
"albums",
"=",
"albums",
",",
"tracks",
"=",
"tracks",
")"
] | Naive search of the database for `query`.
:return: A dict with keys 'artists', 'albums', and 'tracks'. Each containing a list
of the respective ORM type. | [
"Naive",
"search",
"of",
"the",
"database",
"for",
"query",
"."
] | 8f988936340bf0ffb83ea90ea124efb3c36a1174 | https://github.com/nicfit/MishMash/blob/8f988936340bf0ffb83ea90ea124efb3c36a1174/mishmash/database.py#L86-L105 | train |
tylerdave/prompter | prompter/__init__.py | prompt | def prompt(message, default=None, strip=True, suffix=' '):
""" Print a message and prompt user for input. Return user input. """
if default is not None:
prompt_text = "{0} [{1}]{2}".format(message, default, suffix)
else:
prompt_text = "{0}{1}".format(message, suffix)
input_value = get_input(prompt_text)
if input_value and strip:
input_value = input_value.strip()
if not input_value:
input_value = default
return input_value | python | def prompt(message, default=None, strip=True, suffix=' '):
""" Print a message and prompt user for input. Return user input. """
if default is not None:
prompt_text = "{0} [{1}]{2}".format(message, default, suffix)
else:
prompt_text = "{0}{1}".format(message, suffix)
input_value = get_input(prompt_text)
if input_value and strip:
input_value = input_value.strip()
if not input_value:
input_value = default
return input_value | [
"def",
"prompt",
"(",
"message",
",",
"default",
"=",
"None",
",",
"strip",
"=",
"True",
",",
"suffix",
"=",
"' '",
")",
":",
"if",
"default",
"is",
"not",
"None",
":",
"prompt_text",
"=",
"\"{0} [{1}]{2}\"",
".",
"format",
"(",
"message",
",",
"default",
",",
"suffix",
")",
"else",
":",
"prompt_text",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"message",
",",
"suffix",
")",
"input_value",
"=",
"get_input",
"(",
"prompt_text",
")",
"if",
"input_value",
"and",
"strip",
":",
"input_value",
"=",
"input_value",
".",
"strip",
"(",
")",
"if",
"not",
"input_value",
":",
"input_value",
"=",
"default",
"return",
"input_value"
] | Print a message and prompt user for input. Return user input. | [
"Print",
"a",
"message",
"and",
"prompt",
"user",
"for",
"input",
".",
"Return",
"user",
"input",
"."
] | b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda | https://github.com/tylerdave/prompter/blob/b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda/prompter/__init__.py#L66-L81 | train |
tylerdave/prompter | prompter/__init__.py | yesno | def yesno(message, default='yes', suffix=' '):
""" Prompt user to answer yes or no. Return True if the default is chosen,
otherwise False. """
if default == 'yes':
yesno_prompt = '[Y/n]'
elif default == 'no':
yesno_prompt = '[y/N]'
else:
raise ValueError("default must be 'yes' or 'no'.")
if message != '':
prompt_text = "{0} {1}{2}".format(message, yesno_prompt, suffix)
else:
prompt_text = "{0}{1}".format(yesno_prompt, suffix)
while True:
response = get_input(prompt_text).strip()
if response == '':
return True
else:
if re.match('^(y)(es)?$', response, re.IGNORECASE):
if default == 'yes':
return True
else:
return False
elif re.match('^(n)(o)?$', response, re.IGNORECASE):
if default == 'no':
return True
else:
return False | python | def yesno(message, default='yes', suffix=' '):
""" Prompt user to answer yes or no. Return True if the default is chosen,
otherwise False. """
if default == 'yes':
yesno_prompt = '[Y/n]'
elif default == 'no':
yesno_prompt = '[y/N]'
else:
raise ValueError("default must be 'yes' or 'no'.")
if message != '':
prompt_text = "{0} {1}{2}".format(message, yesno_prompt, suffix)
else:
prompt_text = "{0}{1}".format(yesno_prompt, suffix)
while True:
response = get_input(prompt_text).strip()
if response == '':
return True
else:
if re.match('^(y)(es)?$', response, re.IGNORECASE):
if default == 'yes':
return True
else:
return False
elif re.match('^(n)(o)?$', response, re.IGNORECASE):
if default == 'no':
return True
else:
return False | [
"def",
"yesno",
"(",
"message",
",",
"default",
"=",
"'yes'",
",",
"suffix",
"=",
"' '",
")",
":",
"if",
"default",
"==",
"'yes'",
":",
"yesno_prompt",
"=",
"'[Y/n]'",
"elif",
"default",
"==",
"'no'",
":",
"yesno_prompt",
"=",
"'[y/N]'",
"else",
":",
"raise",
"ValueError",
"(",
"\"default must be 'yes' or 'no'.\"",
")",
"if",
"message",
"!=",
"''",
":",
"prompt_text",
"=",
"\"{0} {1}{2}\"",
".",
"format",
"(",
"message",
",",
"yesno_prompt",
",",
"suffix",
")",
"else",
":",
"prompt_text",
"=",
"\"{0}{1}\"",
".",
"format",
"(",
"yesno_prompt",
",",
"suffix",
")",
"while",
"True",
":",
"response",
"=",
"get_input",
"(",
"prompt_text",
")",
".",
"strip",
"(",
")",
"if",
"response",
"==",
"''",
":",
"return",
"True",
"else",
":",
"if",
"re",
".",
"match",
"(",
"'^(y)(es)?$'",
",",
"response",
",",
"re",
".",
"IGNORECASE",
")",
":",
"if",
"default",
"==",
"'yes'",
":",
"return",
"True",
"else",
":",
"return",
"False",
"elif",
"re",
".",
"match",
"(",
"'^(n)(o)?$'",
",",
"response",
",",
"re",
".",
"IGNORECASE",
")",
":",
"if",
"default",
"==",
"'no'",
":",
"return",
"True",
"else",
":",
"return",
"False"
] | Prompt user to answer yes or no. Return True if the default is chosen,
otherwise False. | [
"Prompt",
"user",
"to",
"answer",
"yes",
"or",
"no",
".",
"Return",
"True",
"if",
"the",
"default",
"is",
"chosen",
"otherwise",
"False",
"."
] | b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda | https://github.com/tylerdave/prompter/blob/b6a72f4d02cd68c6d9a2bbe00bfc5bf62b25feda/prompter/__init__.py#L83-L112 | train |
astraw38/lint | lint/validators/validation_factory.py | ValidatorFactory.register_validator | def register_validator(validator):
"""
Register a Validator class for file verification.
:param validator:
:return:
"""
if hasattr(validator, "EXTS") and hasattr(validator, "run"):
ValidatorFactory.PLUGINS.append(validator)
else:
raise ValidatorException("Validator does not have 'run' method or EXTS variable!") | python | def register_validator(validator):
"""
Register a Validator class for file verification.
:param validator:
:return:
"""
if hasattr(validator, "EXTS") and hasattr(validator, "run"):
ValidatorFactory.PLUGINS.append(validator)
else:
raise ValidatorException("Validator does not have 'run' method or EXTS variable!") | [
"def",
"register_validator",
"(",
"validator",
")",
":",
"if",
"hasattr",
"(",
"validator",
",",
"\"EXTS\"",
")",
"and",
"hasattr",
"(",
"validator",
",",
"\"run\"",
")",
":",
"ValidatorFactory",
".",
"PLUGINS",
".",
"append",
"(",
"validator",
")",
"else",
":",
"raise",
"ValidatorException",
"(",
"\"Validator does not have 'run' method or EXTS variable!\"",
")"
] | Register a Validator class for file verification.
:param validator:
:return: | [
"Register",
"a",
"Validator",
"class",
"for",
"file",
"verification",
"."
] | 162ceefcb812f07d18544aaa887b9ec4f102cfb1 | https://github.com/astraw38/lint/blob/162ceefcb812f07d18544aaa887b9ec4f102cfb1/lint/validators/validation_factory.py#L32-L42 | train |
jim-easterbrook/pyctools | src/pyctools/components/io/videofilewriter.py | VideoFileWriter.file_writer | def file_writer(self, in_frame):
"""Generator process to write file"""
self.update_config()
path = self.config['path']
encoder = self.config['encoder']
fps = self.config['fps']
bit16 = self.config['16bit']
numpy_image = in_frame.as_numpy()
ylen, xlen, bpc = numpy_image.shape
if bpc == 3:
if in_frame.type != 'RGB':
self.logger.warning('Expected RGB input, got %s', in_frame.type)
pix_fmt = ('rgb24', 'rgb48le')[bit16]
elif bpc == 1:
if in_frame.type != 'Y':
self.logger.warning('Expected Y input, got %s', in_frame.type)
pix_fmt = ('gray', 'gray16le')[bit16]
else:
self.logger.critical(
'Cannot write %s frame with %d components', in_frame.type, bpc)
return
md = Metadata().copy(in_frame.metadata)
audit = md.get('audit')
audit += '%s = data\n' % path
audit += ' encoder: "%s"\n' % (encoder)
audit += ' 16bit: %s\n' % (self.config['16bit'])
md.set('audit', audit)
md.to_file(path)
with self.subprocess(
['ffmpeg', '-v', 'warning', '-y', '-an',
'-s', '%dx%d' % (xlen, ylen),
'-f', 'rawvideo', '-c:v', 'rawvideo',
'-r', '%d' % fps, '-pix_fmt', pix_fmt, '-i', '-',
'-r', '%d' % fps] + encoder.split() + [path],
stdin=subprocess.PIPE) as sp:
while True:
in_frame = yield True
if not in_frame:
break
if bit16:
numpy_image = in_frame.as_numpy(dtype=pt_float)
numpy_image = numpy_image * pt_float(256.0)
numpy_image = numpy_image.clip(
pt_float(0), pt_float(2**16 - 1)).astype(numpy.uint16)
else:
numpy_image = in_frame.as_numpy(dtype=numpy.uint8)
sp.stdin.write(numpy_image.tostring())
del in_frame | python | def file_writer(self, in_frame):
"""Generator process to write file"""
self.update_config()
path = self.config['path']
encoder = self.config['encoder']
fps = self.config['fps']
bit16 = self.config['16bit']
numpy_image = in_frame.as_numpy()
ylen, xlen, bpc = numpy_image.shape
if bpc == 3:
if in_frame.type != 'RGB':
self.logger.warning('Expected RGB input, got %s', in_frame.type)
pix_fmt = ('rgb24', 'rgb48le')[bit16]
elif bpc == 1:
if in_frame.type != 'Y':
self.logger.warning('Expected Y input, got %s', in_frame.type)
pix_fmt = ('gray', 'gray16le')[bit16]
else:
self.logger.critical(
'Cannot write %s frame with %d components', in_frame.type, bpc)
return
md = Metadata().copy(in_frame.metadata)
audit = md.get('audit')
audit += '%s = data\n' % path
audit += ' encoder: "%s"\n' % (encoder)
audit += ' 16bit: %s\n' % (self.config['16bit'])
md.set('audit', audit)
md.to_file(path)
with self.subprocess(
['ffmpeg', '-v', 'warning', '-y', '-an',
'-s', '%dx%d' % (xlen, ylen),
'-f', 'rawvideo', '-c:v', 'rawvideo',
'-r', '%d' % fps, '-pix_fmt', pix_fmt, '-i', '-',
'-r', '%d' % fps] + encoder.split() + [path],
stdin=subprocess.PIPE) as sp:
while True:
in_frame = yield True
if not in_frame:
break
if bit16:
numpy_image = in_frame.as_numpy(dtype=pt_float)
numpy_image = numpy_image * pt_float(256.0)
numpy_image = numpy_image.clip(
pt_float(0), pt_float(2**16 - 1)).astype(numpy.uint16)
else:
numpy_image = in_frame.as_numpy(dtype=numpy.uint8)
sp.stdin.write(numpy_image.tostring())
del in_frame | [
"def",
"file_writer",
"(",
"self",
",",
"in_frame",
")",
":",
"self",
".",
"update_config",
"(",
")",
"path",
"=",
"self",
".",
"config",
"[",
"'path'",
"]",
"encoder",
"=",
"self",
".",
"config",
"[",
"'encoder'",
"]",
"fps",
"=",
"self",
".",
"config",
"[",
"'fps'",
"]",
"bit16",
"=",
"self",
".",
"config",
"[",
"'16bit'",
"]",
"numpy_image",
"=",
"in_frame",
".",
"as_numpy",
"(",
")",
"ylen",
",",
"xlen",
",",
"bpc",
"=",
"numpy_image",
".",
"shape",
"if",
"bpc",
"==",
"3",
":",
"if",
"in_frame",
".",
"type",
"!=",
"'RGB'",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Expected RGB input, got %s'",
",",
"in_frame",
".",
"type",
")",
"pix_fmt",
"=",
"(",
"'rgb24'",
",",
"'rgb48le'",
")",
"[",
"bit16",
"]",
"elif",
"bpc",
"==",
"1",
":",
"if",
"in_frame",
".",
"type",
"!=",
"'Y'",
":",
"self",
".",
"logger",
".",
"warning",
"(",
"'Expected Y input, got %s'",
",",
"in_frame",
".",
"type",
")",
"pix_fmt",
"=",
"(",
"'gray'",
",",
"'gray16le'",
")",
"[",
"bit16",
"]",
"else",
":",
"self",
".",
"logger",
".",
"critical",
"(",
"'Cannot write %s frame with %d components'",
",",
"in_frame",
".",
"type",
",",
"bpc",
")",
"return",
"md",
"=",
"Metadata",
"(",
")",
".",
"copy",
"(",
"in_frame",
".",
"metadata",
")",
"audit",
"=",
"md",
".",
"get",
"(",
"'audit'",
")",
"audit",
"+=",
"'%s = data\\n'",
"%",
"path",
"audit",
"+=",
"' encoder: \"%s\"\\n'",
"%",
"(",
"encoder",
")",
"audit",
"+=",
"' 16bit: %s\\n'",
"%",
"(",
"self",
".",
"config",
"[",
"'16bit'",
"]",
")",
"md",
".",
"set",
"(",
"'audit'",
",",
"audit",
")",
"md",
".",
"to_file",
"(",
"path",
")",
"with",
"self",
".",
"subprocess",
"(",
"[",
"'ffmpeg'",
",",
"'-v'",
",",
"'warning'",
",",
"'-y'",
",",
"'-an'",
",",
"'-s'",
",",
"'%dx%d'",
"%",
"(",
"xlen",
",",
"ylen",
")",
",",
"'-f'",
",",
"'rawvideo'",
",",
"'-c:v'",
",",
"'rawvideo'",
",",
"'-r'",
",",
"'%d'",
"%",
"fps",
",",
"'-pix_fmt'",
",",
"pix_fmt",
",",
"'-i'",
",",
"'-'",
",",
"'-r'",
",",
"'%d'",
"%",
"fps",
"]",
"+",
"encoder",
".",
"split",
"(",
")",
"+",
"[",
"path",
"]",
",",
"stdin",
"=",
"subprocess",
".",
"PIPE",
")",
"as",
"sp",
":",
"while",
"True",
":",
"in_frame",
"=",
"yield",
"True",
"if",
"not",
"in_frame",
":",
"break",
"if",
"bit16",
":",
"numpy_image",
"=",
"in_frame",
".",
"as_numpy",
"(",
"dtype",
"=",
"pt_float",
")",
"numpy_image",
"=",
"numpy_image",
"*",
"pt_float",
"(",
"256.0",
")",
"numpy_image",
"=",
"numpy_image",
".",
"clip",
"(",
"pt_float",
"(",
"0",
")",
",",
"pt_float",
"(",
"2",
"**",
"16",
"-",
"1",
")",
")",
".",
"astype",
"(",
"numpy",
".",
"uint16",
")",
"else",
":",
"numpy_image",
"=",
"in_frame",
".",
"as_numpy",
"(",
"dtype",
"=",
"numpy",
".",
"uint8",
")",
"sp",
".",
"stdin",
".",
"write",
"(",
"numpy_image",
".",
"tostring",
"(",
")",
")",
"del",
"in_frame"
] | Generator process to write file | [
"Generator",
"process",
"to",
"write",
"file"
] | 2a958665326892f45f249bebe62c2c23f306732b | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/io/videofilewriter.py#L85-L132 | train |
jim-easterbrook/pyctools | src/pyctools/components/deinterlace/hhiprefilter.py | HHIPreFilter | def HHIPreFilter(config={}):
"""HHI pre-interlace filter.
A widely used prefilter to prevent line twitter when converting
sequential images to interlace.
Coefficients taken from: 'Specification of a Generic Format
Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison,
CEC RACE/HAMLET Deliverable no R2110/WP2/DS/S/006/b1, September
1995. http://www.stephanepigeon.com/Docs/deliv2.pdf
"""
fil = numpy.array(
[-4, 8, 25, -123, 230, 728, 230, -123, 25, 8, -4],
dtype=numpy.float32).reshape((-1, 1, 1)) / numpy.float32(1000)
resize = Resize(config=config)
out_frame = Frame()
out_frame.data = fil
out_frame.type = 'fil'
audit = out_frame.metadata.get('audit')
audit += 'data = HHI pre-interlace filter\n'
out_frame.metadata.set('audit', audit)
resize.filter(out_frame)
return resize | python | def HHIPreFilter(config={}):
"""HHI pre-interlace filter.
A widely used prefilter to prevent line twitter when converting
sequential images to interlace.
Coefficients taken from: 'Specification of a Generic Format
Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison,
CEC RACE/HAMLET Deliverable no R2110/WP2/DS/S/006/b1, September
1995. http://www.stephanepigeon.com/Docs/deliv2.pdf
"""
fil = numpy.array(
[-4, 8, 25, -123, 230, 728, 230, -123, 25, 8, -4],
dtype=numpy.float32).reshape((-1, 1, 1)) / numpy.float32(1000)
resize = Resize(config=config)
out_frame = Frame()
out_frame.data = fil
out_frame.type = 'fil'
audit = out_frame.metadata.get('audit')
audit += 'data = HHI pre-interlace filter\n'
out_frame.metadata.set('audit', audit)
resize.filter(out_frame)
return resize | [
"def",
"HHIPreFilter",
"(",
"config",
"=",
"{",
"}",
")",
":",
"fil",
"=",
"numpy",
".",
"array",
"(",
"[",
"-",
"4",
",",
"8",
",",
"25",
",",
"-",
"123",
",",
"230",
",",
"728",
",",
"230",
",",
"-",
"123",
",",
"25",
",",
"8",
",",
"-",
"4",
"]",
",",
"dtype",
"=",
"numpy",
".",
"float32",
")",
".",
"reshape",
"(",
"(",
"-",
"1",
",",
"1",
",",
"1",
")",
")",
"/",
"numpy",
".",
"float32",
"(",
"1000",
")",
"resize",
"=",
"Resize",
"(",
"config",
"=",
"config",
")",
"out_frame",
"=",
"Frame",
"(",
")",
"out_frame",
".",
"data",
"=",
"fil",
"out_frame",
".",
"type",
"=",
"'fil'",
"audit",
"=",
"out_frame",
".",
"metadata",
".",
"get",
"(",
"'audit'",
")",
"audit",
"+=",
"'data = HHI pre-interlace filter\\n'",
"out_frame",
".",
"metadata",
".",
"set",
"(",
"'audit'",
",",
"audit",
")",
"resize",
".",
"filter",
"(",
"out_frame",
")",
"return",
"resize"
] | HHI pre-interlace filter.
A widely used prefilter to prevent line twitter when converting
sequential images to interlace.
Coefficients taken from: 'Specification of a Generic Format
Converter', S. Pigeon, L. Vandendorpe, L. Cuvelier and B. Maison,
CEC RACE/HAMLET Deliverable no R2110/WP2/DS/S/006/b1, September
1995. http://www.stephanepigeon.com/Docs/deliv2.pdf | [
"HHI",
"pre",
"-",
"interlace",
"filter",
"."
] | 2a958665326892f45f249bebe62c2c23f306732b | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/components/deinterlace/hhiprefilter.py#L27-L51 | train |
kmike/port-for | port_for/ephemeral.py | port_ranges | def port_ranges():
"""
Returns a list of ephemeral port ranges for current machine.
"""
try:
return _linux_ranges()
except (OSError, IOError): # not linux, try BSD
try:
ranges = _bsd_ranges()
if ranges:
return ranges
except (OSError, IOError):
pass
# fallback
return [DEFAULT_EPHEMERAL_PORT_RANGE] | python | def port_ranges():
"""
Returns a list of ephemeral port ranges for current machine.
"""
try:
return _linux_ranges()
except (OSError, IOError): # not linux, try BSD
try:
ranges = _bsd_ranges()
if ranges:
return ranges
except (OSError, IOError):
pass
# fallback
return [DEFAULT_EPHEMERAL_PORT_RANGE] | [
"def",
"port_ranges",
"(",
")",
":",
"try",
":",
"return",
"_linux_ranges",
"(",
")",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"# not linux, try BSD",
"try",
":",
"ranges",
"=",
"_bsd_ranges",
"(",
")",
"if",
"ranges",
":",
"return",
"ranges",
"except",
"(",
"OSError",
",",
"IOError",
")",
":",
"pass",
"# fallback",
"return",
"[",
"DEFAULT_EPHEMERAL_PORT_RANGE",
"]"
] | Returns a list of ephemeral port ranges for current machine. | [
"Returns",
"a",
"list",
"of",
"ephemeral",
"port",
"ranges",
"for",
"current",
"machine",
"."
] | f61ebf3c2caf54eabe8233b40ef67b973176a6f5 | https://github.com/kmike/port-for/blob/f61ebf3c2caf54eabe8233b40ef67b973176a6f5/port_for/ephemeral.py#L15-L30 | train |
jim-easterbrook/pyctools | src/pyctools/core/base.py | ThreadEventLoop.run | def run(self):
"""The actual event loop.
Calls the ``owner``'s :py:meth:`~Component.start_event` method,
then calls its :py:meth:`~Component.new_frame_event` and
:py:meth:`~Component.new_config_event` methods as required until
:py:meth:`~Component.stop` is called. Finally the ``owner``'s
:py:meth:`~Component.stop_event` method is called before the
thread terminates.
"""
try:
self.owner.start_event()
while True:
while not self.incoming:
time.sleep(0.01)
while self.incoming:
command = self.incoming.popleft()
if command is None:
raise StopIteration()
command()
except StopIteration:
pass
self.owner.stop_event() | python | def run(self):
"""The actual event loop.
Calls the ``owner``'s :py:meth:`~Component.start_event` method,
then calls its :py:meth:`~Component.new_frame_event` and
:py:meth:`~Component.new_config_event` methods as required until
:py:meth:`~Component.stop` is called. Finally the ``owner``'s
:py:meth:`~Component.stop_event` method is called before the
thread terminates.
"""
try:
self.owner.start_event()
while True:
while not self.incoming:
time.sleep(0.01)
while self.incoming:
command = self.incoming.popleft()
if command is None:
raise StopIteration()
command()
except StopIteration:
pass
self.owner.stop_event() | [
"def",
"run",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"owner",
".",
"start_event",
"(",
")",
"while",
"True",
":",
"while",
"not",
"self",
".",
"incoming",
":",
"time",
".",
"sleep",
"(",
"0.01",
")",
"while",
"self",
".",
"incoming",
":",
"command",
"=",
"self",
".",
"incoming",
".",
"popleft",
"(",
")",
"if",
"command",
"is",
"None",
":",
"raise",
"StopIteration",
"(",
")",
"command",
"(",
")",
"except",
"StopIteration",
":",
"pass",
"self",
".",
"owner",
".",
"stop_event",
"(",
")"
] | The actual event loop.
Calls the ``owner``'s :py:meth:`~Component.start_event` method,
then calls its :py:meth:`~Component.new_frame_event` and
:py:meth:`~Component.new_config_event` methods as required until
:py:meth:`~Component.stop` is called. Finally the ``owner``'s
:py:meth:`~Component.stop_event` method is called before the
thread terminates. | [
"The",
"actual",
"event",
"loop",
"."
] | 2a958665326892f45f249bebe62c2c23f306732b | https://github.com/jim-easterbrook/pyctools/blob/2a958665326892f45f249bebe62c2c23f306732b/src/pyctools/core/base.py#L131-L154 | train |
Subsets and Splits