partition stringclasses 3 values | func_name stringlengths 1 134 | docstring stringlengths 1 46.9k | path stringlengths 4 223 | original_string stringlengths 75 104k | code stringlengths 75 104k | docstring_tokens listlengths 1 1.97k | repo stringlengths 7 55 | language stringclasses 1 value | url stringlengths 87 315 | code_tokens listlengths 19 28.4k | sha stringlengths 40 40 |
|---|---|---|---|---|---|---|---|---|---|---|---|
test | Val.internal_name | Return the unique internal name | pyrser/type_system/val.py | def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq | def internal_name(self):
"""
Return the unique internal name
"""
unq = super().internal_name()
if self.tret is not None:
unq += "_" + self.tret
return unq | [
"Return",
"the",
"unique",
"internal",
"name"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/val.py#L30-L37 | [
"def",
"internal_name",
"(",
"self",
")",
":",
"unq",
"=",
"super",
"(",
")",
".",
"internal_name",
"(",
")",
"if",
"self",
".",
"tret",
"is",
"not",
"None",
":",
"unq",
"+=",
"\"_\"",
"+",
"self",
".",
"tret",
"return",
"unq"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | S3Saver._delete_local | Deletes the specified file from the local filesystem. | s3_saver.py | def _delete_local(self, filename):
"""Deletes the specified file from the local filesystem."""
if os.path.exists(filename):
os.remove(filename) | def _delete_local(self, filename):
"""Deletes the specified file from the local filesystem."""
if os.path.exists(filename):
os.remove(filename) | [
"Deletes",
"the",
"specified",
"file",
"from",
"the",
"local",
"filesystem",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L53-L57 | [
"def",
"_delete_local",
"(",
"self",
",",
"filename",
")",
":",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"filename",
")",
":",
"os",
".",
"remove",
"(",
"filename",
")"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver._delete_s3 | Deletes the specified file from the given S3 bucket. | s3_saver.py | def _delete_s3(self, filename, bucket_name):
"""Deletes the specified file from the given S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
if type(filename).__name__ == 'Key':
filename = '/' + filename.name
path = self._get_s3_path(filename)
k = Key(bucket)
k.key = path
try:
bucket.delete_key(k)
except S3ResponseError:
pass | def _delete_s3(self, filename, bucket_name):
"""Deletes the specified file from the given S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
if type(filename).__name__ == 'Key':
filename = '/' + filename.name
path = self._get_s3_path(filename)
k = Key(bucket)
k.key = path
try:
bucket.delete_key(k)
except S3ResponseError:
pass | [
"Deletes",
"the",
"specified",
"file",
"from",
"the",
"given",
"S3",
"bucket",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L59-L75 | [
"def",
"_delete_s3",
"(",
"self",
",",
"filename",
",",
"bucket_name",
")",
":",
"conn",
"=",
"S3Connection",
"(",
"self",
".",
"access_key_id",
",",
"self",
".",
"access_key_secret",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"bucket_name",
")",
"if",
"type",
"(",
"filename",
")",
".",
"__name__",
"==",
"'Key'",
":",
"filename",
"=",
"'/'",
"+",
"filename",
".",
"name",
"path",
"=",
"self",
".",
"_get_s3_path",
"(",
"filename",
")",
"k",
"=",
"Key",
"(",
"bucket",
")",
"k",
".",
"key",
"=",
"path",
"try",
":",
"bucket",
".",
"delete_key",
"(",
"k",
")",
"except",
"S3ResponseError",
":",
"pass"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver.delete | Deletes the specified file, either locally or from S3, depending on the file's storage type. | s3_saver.py | def delete(self, filename, storage_type=None, bucket_name=None):
"""Deletes the specified file, either locally or from S3, depending on the file's storage type."""
if not (storage_type and bucket_name):
self._delete_local(filename)
else:
if storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % storage_type)
self._delete_s3(filename, bucket_name) | def delete(self, filename, storage_type=None, bucket_name=None):
"""Deletes the specified file, either locally or from S3, depending on the file's storage type."""
if not (storage_type and bucket_name):
self._delete_local(filename)
else:
if storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % storage_type)
self._delete_s3(filename, bucket_name) | [
"Deletes",
"the",
"specified",
"file",
"either",
"locally",
"or",
"from",
"S3",
"depending",
"on",
"the",
"file",
"s",
"storage",
"type",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L77-L86 | [
"def",
"delete",
"(",
"self",
",",
"filename",
",",
"storage_type",
"=",
"None",
",",
"bucket_name",
"=",
"None",
")",
":",
"if",
"not",
"(",
"storage_type",
"and",
"bucket_name",
")",
":",
"self",
".",
"_delete_local",
"(",
"filename",
")",
"else",
":",
"if",
"storage_type",
"!=",
"'s3'",
":",
"raise",
"ValueError",
"(",
"'Storage type \"%s\" is invalid, the only supported storage type (apart from default local storage) is s3.'",
"%",
"storage_type",
")",
"self",
".",
"_delete_s3",
"(",
"filename",
",",
"bucket_name",
")"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver._save_local | Saves the specified file to the local file system. | s3_saver.py | def _save_local(self, temp_file, filename, obj):
"""Saves the specified file to the local file system."""
path = self._get_path(filename)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path), self.permission | 0o111)
fd = open(path, 'wb')
# Thanks to:
# http://stackoverflow.com/a/3253276/2066849
temp_file.seek(0)
t = temp_file.read(1048576)
while t:
fd.write(t)
t = temp_file.read(1048576)
fd.close()
if self.filesize_field:
setattr(obj, self.filesize_field, os.path.getsize(path))
return filename | def _save_local(self, temp_file, filename, obj):
"""Saves the specified file to the local file system."""
path = self._get_path(filename)
if not os.path.exists(os.path.dirname(path)):
os.makedirs(os.path.dirname(path), self.permission | 0o111)
fd = open(path, 'wb')
# Thanks to:
# http://stackoverflow.com/a/3253276/2066849
temp_file.seek(0)
t = temp_file.read(1048576)
while t:
fd.write(t)
t = temp_file.read(1048576)
fd.close()
if self.filesize_field:
setattr(obj, self.filesize_field, os.path.getsize(path))
return filename | [
"Saves",
"the",
"specified",
"file",
"to",
"the",
"local",
"file",
"system",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L88-L110 | [
"def",
"_save_local",
"(",
"self",
",",
"temp_file",
",",
"filename",
",",
"obj",
")",
":",
"path",
"=",
"self",
".",
"_get_path",
"(",
"filename",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
")",
":",
"os",
".",
"makedirs",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"path",
")",
",",
"self",
".",
"permission",
"|",
"0o111",
")",
"fd",
"=",
"open",
"(",
"path",
",",
"'wb'",
")",
"# Thanks to:",
"# http://stackoverflow.com/a/3253276/2066849",
"temp_file",
".",
"seek",
"(",
"0",
")",
"t",
"=",
"temp_file",
".",
"read",
"(",
"1048576",
")",
"while",
"t",
":",
"fd",
".",
"write",
"(",
"t",
")",
"t",
"=",
"temp_file",
".",
"read",
"(",
"1048576",
")",
"fd",
".",
"close",
"(",
")",
"if",
"self",
".",
"filesize_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"filesize_field",
",",
"os",
".",
"path",
".",
"getsize",
"(",
"path",
")",
")",
"return",
"filename"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver._save_s3 | Saves the specified file to the configured S3 bucket. | s3_saver.py | def _save_s3(self, temp_file, filename, obj):
"""Saves the specified file to the configured S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(self.bucket_name)
path = self._get_s3_path(filename)
k = bucket.new_key(path)
k.set_contents_from_string(temp_file.getvalue())
k.set_acl(self.acl)
if self.filesize_field:
setattr(obj, self.filesize_field, k.size)
return filename | def _save_s3(self, temp_file, filename, obj):
"""Saves the specified file to the configured S3 bucket."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(self.bucket_name)
path = self._get_s3_path(filename)
k = bucket.new_key(path)
k.set_contents_from_string(temp_file.getvalue())
k.set_acl(self.acl)
if self.filesize_field:
setattr(obj, self.filesize_field, k.size)
return filename | [
"Saves",
"the",
"specified",
"file",
"to",
"the",
"configured",
"S3",
"bucket",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L112-L126 | [
"def",
"_save_s3",
"(",
"self",
",",
"temp_file",
",",
"filename",
",",
"obj",
")",
":",
"conn",
"=",
"S3Connection",
"(",
"self",
".",
"access_key_id",
",",
"self",
".",
"access_key_secret",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"self",
".",
"bucket_name",
")",
"path",
"=",
"self",
".",
"_get_s3_path",
"(",
"filename",
")",
"k",
"=",
"bucket",
".",
"new_key",
"(",
"path",
")",
"k",
".",
"set_contents_from_string",
"(",
"temp_file",
".",
"getvalue",
"(",
")",
")",
"k",
".",
"set_acl",
"(",
"self",
".",
"acl",
")",
"if",
"self",
".",
"filesize_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"filesize_field",
",",
"k",
".",
"size",
")",
"return",
"filename"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver.save | Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type. | s3_saver.py | def save(self, temp_file, filename, obj):
"""Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type."""
if not (self.storage_type and self.bucket_name):
ret = self._save_local(temp_file, filename, obj)
else:
if self.storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % self.storage_type)
ret = self._save_s3(temp_file, filename, obj)
if self.field_name:
setattr(obj, self.field_name, ret)
if self.storage_type == 's3':
if self.storage_type_field:
setattr(obj, self.storage_type_field, self.storage_type)
if self.bucket_name_field:
setattr(obj, self.bucket_name_field, self.bucket_name)
else:
if self.storage_type_field:
setattr(obj, self.storage_type_field, '')
if self.bucket_name_field:
setattr(obj, self.bucket_name_field, '')
return ret | def save(self, temp_file, filename, obj):
"""Saves the specified file to either S3 or the local filesystem, depending on the currently enabled storage type."""
if not (self.storage_type and self.bucket_name):
ret = self._save_local(temp_file, filename, obj)
else:
if self.storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % self.storage_type)
ret = self._save_s3(temp_file, filename, obj)
if self.field_name:
setattr(obj, self.field_name, ret)
if self.storage_type == 's3':
if self.storage_type_field:
setattr(obj, self.storage_type_field, self.storage_type)
if self.bucket_name_field:
setattr(obj, self.bucket_name_field, self.bucket_name)
else:
if self.storage_type_field:
setattr(obj, self.storage_type_field, '')
if self.bucket_name_field:
setattr(obj, self.bucket_name_field, '')
return ret | [
"Saves",
"the",
"specified",
"file",
"to",
"either",
"S3",
"or",
"the",
"local",
"filesystem",
"depending",
"on",
"the",
"currently",
"enabled",
"storage",
"type",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L128-L153 | [
"def",
"save",
"(",
"self",
",",
"temp_file",
",",
"filename",
",",
"obj",
")",
":",
"if",
"not",
"(",
"self",
".",
"storage_type",
"and",
"self",
".",
"bucket_name",
")",
":",
"ret",
"=",
"self",
".",
"_save_local",
"(",
"temp_file",
",",
"filename",
",",
"obj",
")",
"else",
":",
"if",
"self",
".",
"storage_type",
"!=",
"'s3'",
":",
"raise",
"ValueError",
"(",
"'Storage type \"%s\" is invalid, the only supported storage type (apart from default local storage) is s3.'",
"%",
"self",
".",
"storage_type",
")",
"ret",
"=",
"self",
".",
"_save_s3",
"(",
"temp_file",
",",
"filename",
",",
"obj",
")",
"if",
"self",
".",
"field_name",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"field_name",
",",
"ret",
")",
"if",
"self",
".",
"storage_type",
"==",
"'s3'",
":",
"if",
"self",
".",
"storage_type_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"storage_type_field",
",",
"self",
".",
"storage_type",
")",
"if",
"self",
".",
"bucket_name_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"bucket_name_field",
",",
"self",
".",
"bucket_name",
")",
"else",
":",
"if",
"self",
".",
"storage_type_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"storage_type_field",
",",
"''",
")",
"if",
"self",
".",
"bucket_name_field",
":",
"setattr",
"(",
"obj",
",",
"self",
".",
"bucket_name_field",
",",
"''",
")",
"return",
"ret"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver._find_by_path_s3 | Finds files by licking an S3 bucket's contents by prefix. | s3_saver.py | def _find_by_path_s3(self, path, bucket_name):
"""Finds files by licking an S3 bucket's contents by prefix."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
s3_path = self._get_s3_path(path)
return bucket.list(prefix=s3_path) | def _find_by_path_s3(self, path, bucket_name):
"""Finds files by licking an S3 bucket's contents by prefix."""
conn = S3Connection(self.access_key_id, self.access_key_secret)
bucket = conn.get_bucket(bucket_name)
s3_path = self._get_s3_path(path)
return bucket.list(prefix=s3_path) | [
"Finds",
"files",
"by",
"licking",
"an",
"S3",
"bucket",
"s",
"contents",
"by",
"prefix",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L160-L168 | [
"def",
"_find_by_path_s3",
"(",
"self",
",",
"path",
",",
"bucket_name",
")",
":",
"conn",
"=",
"S3Connection",
"(",
"self",
".",
"access_key_id",
",",
"self",
".",
"access_key_secret",
")",
"bucket",
"=",
"conn",
".",
"get_bucket",
"(",
"bucket_name",
")",
"s3_path",
"=",
"self",
".",
"_get_s3_path",
"(",
"path",
")",
"return",
"bucket",
".",
"list",
"(",
"prefix",
"=",
"s3_path",
")"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | S3Saver.find_by_path | Finds files at the specified path / prefix, either on S3 or on the local filesystem. | s3_saver.py | def find_by_path(self, path, storage_type=None, bucket_name=None):
"""Finds files at the specified path / prefix, either on S3 or on the local filesystem."""
if not (storage_type and bucket_name):
return self._find_by_path_local(path)
else:
if storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % storage_type)
return self._find_by_path_s3(path, bucket_name) | def find_by_path(self, path, storage_type=None, bucket_name=None):
"""Finds files at the specified path / prefix, either on S3 or on the local filesystem."""
if not (storage_type and bucket_name):
return self._find_by_path_local(path)
else:
if storage_type != 's3':
raise ValueError('Storage type "%s" is invalid, the only supported storage type (apart from default local storage) is s3.' % storage_type)
return self._find_by_path_s3(path, bucket_name) | [
"Finds",
"files",
"at",
"the",
"specified",
"path",
"/",
"prefix",
"either",
"on",
"S3",
"or",
"on",
"the",
"local",
"filesystem",
"."
] | Jaza/s3-saver | python | https://github.com/Jaza/s3-saver/blob/81dc4447d76c2fc0b0238fb96fa70e879612e355/s3_saver.py#L170-L179 | [
"def",
"find_by_path",
"(",
"self",
",",
"path",
",",
"storage_type",
"=",
"None",
",",
"bucket_name",
"=",
"None",
")",
":",
"if",
"not",
"(",
"storage_type",
"and",
"bucket_name",
")",
":",
"return",
"self",
".",
"_find_by_path_local",
"(",
"path",
")",
"else",
":",
"if",
"storage_type",
"!=",
"'s3'",
":",
"raise",
"ValueError",
"(",
"'Storage type \"%s\" is invalid, the only supported storage type (apart from default local storage) is s3.'",
"%",
"storage_type",
")",
"return",
"self",
".",
"_find_by_path_s3",
"(",
"path",
",",
"bucket_name",
")"
] | 81dc4447d76c2fc0b0238fb96fa70e879612e355 |
test | enum | Build an enum statement | pyrser/meta.py | def enum(*sequential, **named):
"""
Build an enum statement
"""
#: build enums from parameter
enums = dict(zip(sequential, range(len(sequential))), **named)
enums['map'] = copy.copy(enums)
#: build reverse mapping
enums['rmap'] = {}
for key, value in enums.items():
if type(value) is int:
enums['rmap'][value] = key
return type('Enum', (), enums) | def enum(*sequential, **named):
"""
Build an enum statement
"""
#: build enums from parameter
enums = dict(zip(sequential, range(len(sequential))), **named)
enums['map'] = copy.copy(enums)
#: build reverse mapping
enums['rmap'] = {}
for key, value in enums.items():
if type(value) is int:
enums['rmap'][value] = key
return type('Enum', (), enums) | [
"Build",
"an",
"enum",
"statement"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L8-L20 | [
"def",
"enum",
"(",
"*",
"sequential",
",",
"*",
"*",
"named",
")",
":",
"#: build enums from parameter",
"enums",
"=",
"dict",
"(",
"zip",
"(",
"sequential",
",",
"range",
"(",
"len",
"(",
"sequential",
")",
")",
")",
",",
"*",
"*",
"named",
")",
"enums",
"[",
"'map'",
"]",
"=",
"copy",
".",
"copy",
"(",
"enums",
")",
"#: build reverse mapping",
"enums",
"[",
"'rmap'",
"]",
"=",
"{",
"}",
"for",
"key",
",",
"value",
"in",
"enums",
".",
"items",
"(",
")",
":",
"if",
"type",
"(",
"value",
")",
"is",
"int",
":",
"enums",
"[",
"'rmap'",
"]",
"[",
"value",
"]",
"=",
"key",
"return",
"type",
"(",
"'Enum'",
",",
"(",
")",
",",
"enums",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | checktypes | Decorator to verify arguments and return types. | pyrser/meta.py | def checktypes(func):
"""Decorator to verify arguments and return types."""
sig = inspect.signature(func)
types = {}
for param in sig.parameters.values():
# Iterate through function's parameters and build the list of
# arguments types
param_type = param.annotation
if param_type is param.empty or not inspect.isclass(param_type):
# Missing annotation or not a type, skip it
continue
types[param.name] = param_type
# If the argument has a type specified, let's check that its
# default value (if present) conforms with the type.
if (param.default is not param.empty and
not isinstance(param.default, param_type)):
raise ValueError(
"{func}: wrong type of a default value for {arg!r}".format(
func=func.__qualname__, arg=param.name)
)
def check_type(sig, arg_name, arg_type, arg_value):
# Internal function that encapsulates arguments type checking
if not isinstance(arg_value, arg_type):
raise ValueError("{func}: wrong type of {arg!r} argument, "
"{exp!r} expected, got {got!r}".
format(func=func.__qualname__, arg=arg_name,
exp=arg_type.__name__,
got=type(arg_value).__name__))
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Let's bind the arguments
ba = sig.bind(*args, **kwargs)
for arg_name, arg in ba.arguments.items():
# And iterate through the bound arguments
try:
type_ = types[arg_name]
except KeyError:
continue
else:
# OK, we have a type for the argument, lets get the
# corresponding parameter description from the signature object
param = sig.parameters[arg_name]
if param.kind == param.VAR_POSITIONAL:
# If this parameter is a variable-argument parameter,
# then we need to check each of its values
for value in arg:
check_type(sig, arg_name, type_, value)
elif param.kind == param.VAR_KEYWORD:
# If this parameter is a variable-keyword-argument
# parameter:
for subname, value in arg.items():
check_type(sig, arg_name + ':' + subname, type_, value)
else:
# And, finally, if this parameter a regular one:
check_type(sig, arg_name, type_, arg)
result = func(*ba.args, **ba.kwargs)
# The last bit - let's check that the result is correct
return_type = sig.return_annotation
if (return_type is not sig.empty and
isinstance(return_type, type) and
not isinstance(result, return_type)):
raise ValueError(
'{func}: wrong return type, {exp} expected, got {got}'.format(
func=func.__qualname__, exp=return_type.__name__,
got=type(result).__name__)
)
return result
return wrapper | def checktypes(func):
"""Decorator to verify arguments and return types."""
sig = inspect.signature(func)
types = {}
for param in sig.parameters.values():
# Iterate through function's parameters and build the list of
# arguments types
param_type = param.annotation
if param_type is param.empty or not inspect.isclass(param_type):
# Missing annotation or not a type, skip it
continue
types[param.name] = param_type
# If the argument has a type specified, let's check that its
# default value (if present) conforms with the type.
if (param.default is not param.empty and
not isinstance(param.default, param_type)):
raise ValueError(
"{func}: wrong type of a default value for {arg!r}".format(
func=func.__qualname__, arg=param.name)
)
def check_type(sig, arg_name, arg_type, arg_value):
# Internal function that encapsulates arguments type checking
if not isinstance(arg_value, arg_type):
raise ValueError("{func}: wrong type of {arg!r} argument, "
"{exp!r} expected, got {got!r}".
format(func=func.__qualname__, arg=arg_name,
exp=arg_type.__name__,
got=type(arg_value).__name__))
@functools.wraps(func)
def wrapper(*args, **kwargs):
# Let's bind the arguments
ba = sig.bind(*args, **kwargs)
for arg_name, arg in ba.arguments.items():
# And iterate through the bound arguments
try:
type_ = types[arg_name]
except KeyError:
continue
else:
# OK, we have a type for the argument, lets get the
# corresponding parameter description from the signature object
param = sig.parameters[arg_name]
if param.kind == param.VAR_POSITIONAL:
# If this parameter is a variable-argument parameter,
# then we need to check each of its values
for value in arg:
check_type(sig, arg_name, type_, value)
elif param.kind == param.VAR_KEYWORD:
# If this parameter is a variable-keyword-argument
# parameter:
for subname, value in arg.items():
check_type(sig, arg_name + ':' + subname, type_, value)
else:
# And, finally, if this parameter a regular one:
check_type(sig, arg_name, type_, arg)
result = func(*ba.args, **ba.kwargs)
# The last bit - let's check that the result is correct
return_type = sig.return_annotation
if (return_type is not sig.empty and
isinstance(return_type, type) and
not isinstance(result, return_type)):
raise ValueError(
'{func}: wrong return type, {exp} expected, got {got}'.format(
func=func.__qualname__, exp=return_type.__name__,
got=type(result).__name__)
)
return result
return wrapper | [
"Decorator",
"to",
"verify",
"arguments",
"and",
"return",
"types",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L24-L100 | [
"def",
"checktypes",
"(",
"func",
")",
":",
"sig",
"=",
"inspect",
".",
"signature",
"(",
"func",
")",
"types",
"=",
"{",
"}",
"for",
"param",
"in",
"sig",
".",
"parameters",
".",
"values",
"(",
")",
":",
"# Iterate through function's parameters and build the list of",
"# arguments types",
"param_type",
"=",
"param",
".",
"annotation",
"if",
"param_type",
"is",
"param",
".",
"empty",
"or",
"not",
"inspect",
".",
"isclass",
"(",
"param_type",
")",
":",
"# Missing annotation or not a type, skip it",
"continue",
"types",
"[",
"param",
".",
"name",
"]",
"=",
"param_type",
"# If the argument has a type specified, let's check that its",
"# default value (if present) conforms with the type.",
"if",
"(",
"param",
".",
"default",
"is",
"not",
"param",
".",
"empty",
"and",
"not",
"isinstance",
"(",
"param",
".",
"default",
",",
"param_type",
")",
")",
":",
"raise",
"ValueError",
"(",
"\"{func}: wrong type of a default value for {arg!r}\"",
".",
"format",
"(",
"func",
"=",
"func",
".",
"__qualname__",
",",
"arg",
"=",
"param",
".",
"name",
")",
")",
"def",
"check_type",
"(",
"sig",
",",
"arg_name",
",",
"arg_type",
",",
"arg_value",
")",
":",
"# Internal function that encapsulates arguments type checking",
"if",
"not",
"isinstance",
"(",
"arg_value",
",",
"arg_type",
")",
":",
"raise",
"ValueError",
"(",
"\"{func}: wrong type of {arg!r} argument, \"",
"\"{exp!r} expected, got {got!r}\"",
".",
"format",
"(",
"func",
"=",
"func",
".",
"__qualname__",
",",
"arg",
"=",
"arg_name",
",",
"exp",
"=",
"arg_type",
".",
"__name__",
",",
"got",
"=",
"type",
"(",
"arg_value",
")",
".",
"__name__",
")",
")",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapper",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"# Let's bind the arguments",
"ba",
"=",
"sig",
".",
"bind",
"(",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
"for",
"arg_name",
",",
"arg",
"in",
"ba",
".",
"arguments",
".",
"items",
"(",
")",
":",
"# And iterate through the bound arguments",
"try",
":",
"type_",
"=",
"types",
"[",
"arg_name",
"]",
"except",
"KeyError",
":",
"continue",
"else",
":",
"# OK, we have a type for the argument, lets get the",
"# corresponding parameter description from the signature object",
"param",
"=",
"sig",
".",
"parameters",
"[",
"arg_name",
"]",
"if",
"param",
".",
"kind",
"==",
"param",
".",
"VAR_POSITIONAL",
":",
"# If this parameter is a variable-argument parameter,",
"# then we need to check each of its values",
"for",
"value",
"in",
"arg",
":",
"check_type",
"(",
"sig",
",",
"arg_name",
",",
"type_",
",",
"value",
")",
"elif",
"param",
".",
"kind",
"==",
"param",
".",
"VAR_KEYWORD",
":",
"# If this parameter is a variable-keyword-argument",
"# parameter:",
"for",
"subname",
",",
"value",
"in",
"arg",
".",
"items",
"(",
")",
":",
"check_type",
"(",
"sig",
",",
"arg_name",
"+",
"':'",
"+",
"subname",
",",
"type_",
",",
"value",
")",
"else",
":",
"# And, finally, if this parameter a regular one:",
"check_type",
"(",
"sig",
",",
"arg_name",
",",
"type_",
",",
"arg",
")",
"result",
"=",
"func",
"(",
"*",
"ba",
".",
"args",
",",
"*",
"*",
"ba",
".",
"kwargs",
")",
"# The last bit - let's check that the result is correct",
"return_type",
"=",
"sig",
".",
"return_annotation",
"if",
"(",
"return_type",
"is",
"not",
"sig",
".",
"empty",
"and",
"isinstance",
"(",
"return_type",
",",
"type",
")",
"and",
"not",
"isinstance",
"(",
"result",
",",
"return_type",
")",
")",
":",
"raise",
"ValueError",
"(",
"'{func}: wrong return type, {exp} expected, got {got}'",
".",
"format",
"(",
"func",
"=",
"func",
".",
"__qualname__",
",",
"exp",
"=",
"return_type",
".",
"__name__",
",",
"got",
"=",
"type",
"(",
"result",
")",
".",
"__name__",
")",
")",
"return",
"result",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | set_one | Add a mapping with key thing_name for callobject in chainmap with
namespace handling. | pyrser/meta.py | def set_one(chainmap, thing_name, callobject):
""" Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
"""
namespaces = reversed(thing_name.split("."))
lstname = []
for name in namespaces:
lstname.insert(0, name)
strname = '.'.join(lstname)
chainmap[strname] = callobject | def set_one(chainmap, thing_name, callobject):
""" Add a mapping with key thing_name for callobject in chainmap with
namespace handling.
"""
namespaces = reversed(thing_name.split("."))
lstname = []
for name in namespaces:
lstname.insert(0, name)
strname = '.'.join(lstname)
chainmap[strname] = callobject | [
"Add",
"a",
"mapping",
"with",
"key",
"thing_name",
"for",
"callobject",
"in",
"chainmap",
"with",
"namespace",
"handling",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L105-L114 | [
"def",
"set_one",
"(",
"chainmap",
",",
"thing_name",
",",
"callobject",
")",
":",
"namespaces",
"=",
"reversed",
"(",
"thing_name",
".",
"split",
"(",
"\".\"",
")",
")",
"lstname",
"=",
"[",
"]",
"for",
"name",
"in",
"namespaces",
":",
"lstname",
".",
"insert",
"(",
"0",
",",
"name",
")",
"strname",
"=",
"'.'",
".",
"join",
"(",
"lstname",
")",
"chainmap",
"[",
"strname",
"]",
"=",
"callobject"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_method | Attach a method to a class. | pyrser/meta.py | def add_method(cls):
"""Attach a method to a class."""
def wrapper(f):
#if hasattr(cls, f.__name__):
# raise AttributeError("{} already has a '{}' attribute".format(
# cls.__name__, f.__name__))
setattr(cls, f.__name__, f)
return f
return wrapper | def add_method(cls):
"""Attach a method to a class."""
def wrapper(f):
#if hasattr(cls, f.__name__):
# raise AttributeError("{} already has a '{}' attribute".format(
# cls.__name__, f.__name__))
setattr(cls, f.__name__, f)
return f
return wrapper | [
"Attach",
"a",
"method",
"to",
"a",
"class",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L124-L132 | [
"def",
"add_method",
"(",
"cls",
")",
":",
"def",
"wrapper",
"(",
"f",
")",
":",
"#if hasattr(cls, f.__name__):",
"# raise AttributeError(\"{} already has a '{}' attribute\".format(",
"# cls.__name__, f.__name__))",
"setattr",
"(",
"cls",
",",
"f",
".",
"__name__",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | hook | Attach a method to a parsing class and register it as a parser hook.
The method is registered with its name unless hookname is provided. | pyrser/meta.py | def hook(cls, hookname=None, erase=False):
"""Attach a method to a parsing class and register it as a parser hook.
The method is registered with its name unless hookname is provided.
"""
if not hasattr(cls, '_hooks'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclasse" % cls.__name__)
class_hook_list = cls._hooks
class_rule_list = cls._rules
def wrapper(f):
nonlocal hookname
add_method(cls)(f)
if hookname is None:
hookname = f.__name__
if not erase and (hookname in class_hook_list or hookname in class_rule_list):
raise TypeError("%s is already define has rule or hook" % hookname)
if '.' not in hookname:
hookname = '.'.join([cls.__module__, cls.__name__, hookname])
set_one(class_hook_list, hookname, f)
return f
return wrapper | def hook(cls, hookname=None, erase=False):
"""Attach a method to a parsing class and register it as a parser hook.
The method is registered with its name unless hookname is provided.
"""
if not hasattr(cls, '_hooks'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclasse" % cls.__name__)
class_hook_list = cls._hooks
class_rule_list = cls._rules
def wrapper(f):
nonlocal hookname
add_method(cls)(f)
if hookname is None:
hookname = f.__name__
if not erase and (hookname in class_hook_list or hookname in class_rule_list):
raise TypeError("%s is already define has rule or hook" % hookname)
if '.' not in hookname:
hookname = '.'.join([cls.__module__, cls.__name__, hookname])
set_one(class_hook_list, hookname, f)
return f
return wrapper | [
"Attach",
"a",
"method",
"to",
"a",
"parsing",
"class",
"and",
"register",
"it",
"as",
"a",
"parser",
"hook",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L135-L157 | [
"def",
"hook",
"(",
"cls",
",",
"hookname",
"=",
"None",
",",
"erase",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'_hooks'",
")",
":",
"raise",
"TypeError",
"(",
"\"%s didn't seems to be a BasicParser subsclasse\"",
"%",
"cls",
".",
"__name__",
")",
"class_hook_list",
"=",
"cls",
".",
"_hooks",
"class_rule_list",
"=",
"cls",
".",
"_rules",
"def",
"wrapper",
"(",
"f",
")",
":",
"nonlocal",
"hookname",
"add_method",
"(",
"cls",
")",
"(",
"f",
")",
"if",
"hookname",
"is",
"None",
":",
"hookname",
"=",
"f",
".",
"__name__",
"if",
"not",
"erase",
"and",
"(",
"hookname",
"in",
"class_hook_list",
"or",
"hookname",
"in",
"class_rule_list",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is already define has rule or hook\"",
"%",
"hookname",
")",
"if",
"'.'",
"not",
"in",
"hookname",
":",
"hookname",
"=",
"'.'",
".",
"join",
"(",
"[",
"cls",
".",
"__module__",
",",
"cls",
".",
"__name__",
",",
"hookname",
"]",
")",
"set_one",
"(",
"class_hook_list",
",",
"hookname",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | rule | Attach a method to a parsing class and register it as a parser rule.
The method is registered with its name unless rulename is provided. | pyrser/meta.py | def rule(cls, rulename=None, erase=False):
"""Attach a method to a parsing class and register it as a parser rule.
The method is registered with its name unless rulename is provided.
"""
if not hasattr(cls, '_rules'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclasse" % cls.__name__)
class_hook_list = cls._hooks
class_rule_list = cls._rules
def wrapper(f):
nonlocal rulename
add_method(cls)(f)
if rulename is None:
rulename = f.__name__
if not erase and (rulename in class_hook_list or rulename in class_rule_list):
raise TypeError("%s is already define has rule or hook" % rulename)
if '.' not in rulename:
rulename = cls.__module__ + '.' + cls.__name__ + '.' + rulename
set_one(class_rule_list, rulename, f)
return f
return wrapper | def rule(cls, rulename=None, erase=False):
"""Attach a method to a parsing class and register it as a parser rule.
The method is registered with its name unless rulename is provided.
"""
if not hasattr(cls, '_rules'):
raise TypeError(
"%s didn't seems to be a BasicParser subsclasse" % cls.__name__)
class_hook_list = cls._hooks
class_rule_list = cls._rules
def wrapper(f):
nonlocal rulename
add_method(cls)(f)
if rulename is None:
rulename = f.__name__
if not erase and (rulename in class_hook_list or rulename in class_rule_list):
raise TypeError("%s is already define has rule or hook" % rulename)
if '.' not in rulename:
rulename = cls.__module__ + '.' + cls.__name__ + '.' + rulename
set_one(class_rule_list, rulename, f)
return f
return wrapper | [
"Attach",
"a",
"method",
"to",
"a",
"parsing",
"class",
"and",
"register",
"it",
"as",
"a",
"parser",
"rule",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L160-L182 | [
"def",
"rule",
"(",
"cls",
",",
"rulename",
"=",
"None",
",",
"erase",
"=",
"False",
")",
":",
"if",
"not",
"hasattr",
"(",
"cls",
",",
"'_rules'",
")",
":",
"raise",
"TypeError",
"(",
"\"%s didn't seems to be a BasicParser subsclasse\"",
"%",
"cls",
".",
"__name__",
")",
"class_hook_list",
"=",
"cls",
".",
"_hooks",
"class_rule_list",
"=",
"cls",
".",
"_rules",
"def",
"wrapper",
"(",
"f",
")",
":",
"nonlocal",
"rulename",
"add_method",
"(",
"cls",
")",
"(",
"f",
")",
"if",
"rulename",
"is",
"None",
":",
"rulename",
"=",
"f",
".",
"__name__",
"if",
"not",
"erase",
"and",
"(",
"rulename",
"in",
"class_hook_list",
"or",
"rulename",
"in",
"class_rule_list",
")",
":",
"raise",
"TypeError",
"(",
"\"%s is already define has rule or hook\"",
"%",
"rulename",
")",
"if",
"'.'",
"not",
"in",
"rulename",
":",
"rulename",
"=",
"cls",
".",
"__module__",
"+",
"'.'",
"+",
"cls",
".",
"__name__",
"+",
"'.'",
"+",
"rulename",
"set_one",
"(",
"class_rule_list",
",",
"rulename",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | directive | Attach a class to a parsing class and register it as a parser directive.
The class is registered with its name unless directname is provided. | pyrser/meta.py | def directive(directname=None):
"""Attach a class to a parsing class and register it as a parser directive.
The class is registered with its name unless directname is provided.
"""
global _directives
class_dir_list = _directives
def wrapper(f):
nonlocal directname
if directname is None:
directname = f.__name__
f.ns_name = directname
set_one(class_dir_list, directname, f)
return f
return wrapper | def directive(directname=None):
"""Attach a class to a parsing class and register it as a parser directive.
The class is registered with its name unless directname is provided.
"""
global _directives
class_dir_list = _directives
def wrapper(f):
nonlocal directname
if directname is None:
directname = f.__name__
f.ns_name = directname
set_one(class_dir_list, directname, f)
return f
return wrapper | [
"Attach",
"a",
"class",
"to",
"a",
"parsing",
"class",
"and",
"register",
"it",
"as",
"a",
"parser",
"directive",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L189-L204 | [
"def",
"directive",
"(",
"directname",
"=",
"None",
")",
":",
"global",
"_directives",
"class_dir_list",
"=",
"_directives",
"def",
"wrapper",
"(",
"f",
")",
":",
"nonlocal",
"directname",
"if",
"directname",
"is",
"None",
":",
"directname",
"=",
"f",
".",
"__name__",
"f",
".",
"ns_name",
"=",
"directname",
"set_one",
"(",
"class_dir_list",
",",
"directname",
",",
"f",
")",
"return",
"f",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | decorator | Attach a class to a parsing decorator and register it to the global
decorator list.
The class is registered with its name unless directname is provided | pyrser/meta.py | def decorator(directname=None):
"""
Attach a class to a parsing decorator and register it to the global
decorator list.
The class is registered with its name unless directname is provided
"""
global _decorators
class_deco_list = _decorators
def wrapper(f):
nonlocal directname
if directname is None:
directname = f.__name__
f.ns_name = directname
set_one(class_deco_list, directname, f)
return wrapper | def decorator(directname=None):
"""
Attach a class to a parsing decorator and register it to the global
decorator list.
The class is registered with its name unless directname is provided
"""
global _decorators
class_deco_list = _decorators
def wrapper(f):
nonlocal directname
if directname is None:
directname = f.__name__
f.ns_name = directname
set_one(class_deco_list, directname, f)
return wrapper | [
"Attach",
"a",
"class",
"to",
"a",
"parsing",
"decorator",
"and",
"register",
"it",
"to",
"the",
"global",
"decorator",
"list",
".",
"The",
"class",
"is",
"registered",
"with",
"its",
"name",
"unless",
"directname",
"is",
"provided"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/meta.py#L211-L227 | [
"def",
"decorator",
"(",
"directname",
"=",
"None",
")",
":",
"global",
"_decorators",
"class_deco_list",
"=",
"_decorators",
"def",
"wrapper",
"(",
"f",
")",
":",
"nonlocal",
"directname",
"if",
"directname",
"is",
"None",
":",
"directname",
"=",
"f",
".",
"__name__",
"f",
".",
"ns_name",
"=",
"directname",
"set_one",
"(",
"class_deco_list",
",",
"directname",
",",
"f",
")",
"return",
"wrapper"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | bind | Allow to alias a node to another name.
Useful to bind a node to _ as return of Rule::
R = [
__scope__:L [item:I #add_item(L, I]* #bind('_', L)
]
It's also the default behaviour of ':>' | pyrser/parsing/base.py | def bind(self, dst: str, src: Node) -> bool:
"""Allow to alias a node to another name.
Useful to bind a node to _ as return of Rule::
R = [
__scope__:L [item:I #add_item(L, I]* #bind('_', L)
]
It's also the default behaviour of ':>'
"""
for m in self.rule_nodes.maps:
for k, v in m.items():
if k == dst:
m[k] = src
return True
raise Exception('%s not found' % dst) | def bind(self, dst: str, src: Node) -> bool:
"""Allow to alias a node to another name.
Useful to bind a node to _ as return of Rule::
R = [
__scope__:L [item:I #add_item(L, I]* #bind('_', L)
]
It's also the default behaviour of ':>'
"""
for m in self.rule_nodes.maps:
for k, v in m.items():
if k == dst:
m[k] = src
return True
raise Exception('%s not found' % dst) | [
"Allow",
"to",
"alias",
"a",
"node",
"to",
"another",
"name",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L394-L412 | [
"def",
"bind",
"(",
"self",
",",
"dst",
":",
"str",
",",
"src",
":",
"Node",
")",
"->",
"bool",
":",
"for",
"m",
"in",
"self",
".",
"rule_nodes",
".",
"maps",
":",
"for",
"k",
",",
"v",
"in",
"m",
".",
"items",
"(",
")",
":",
"if",
"k",
"==",
"dst",
":",
"m",
"[",
"k",
"]",
"=",
"src",
"return",
"True",
"raise",
"Exception",
"(",
"'%s not found'",
"%",
"dst",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | read_eol | Return True if the parser can consume an EOL byte sequence. | pyrser/parsing/base.py | def read_eol(self) -> bool:
"""Return True if the parser can consume an EOL byte sequence."""
if self.read_eof():
return False
self._stream.save_context()
self.read_char('\r')
if self.read_char('\n'):
return self._stream.validate_context()
return self._stream.restore_context() | def read_eol(self) -> bool:
"""Return True if the parser can consume an EOL byte sequence."""
if self.read_eof():
return False
self._stream.save_context()
self.read_char('\r')
if self.read_char('\n'):
return self._stream.validate_context()
return self._stream.restore_context() | [
"Return",
"True",
"if",
"the",
"parser",
"can",
"consume",
"an",
"EOL",
"byte",
"sequence",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L428-L436 | [
"def",
"read_eol",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"self",
".",
"read_char",
"(",
"'\\r'",
")",
"if",
"self",
".",
"read_char",
"(",
"'\\n'",
")",
":",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | read_hex_integer | read a hexadecimal number
Read the following BNF rule else return False::
readHexInteger = [
[ '0'..'9' | 'a'..'f' | 'A'..'F' ]+
] | pyrser/parsing/base.py | def read_hex_integer(self) -> bool:
"""
read a hexadecimal number
Read the following BNF rule else return False::
readHexInteger = [
[ '0'..'9' | 'a'..'f' | 'A'..'F' ]+
]
"""
if self.read_eof():
return False
self._stream.save_context()
c = self._stream.peek_char
if c.isdigit() or ('a' <= c.lower() and c.lower() <= 'f'):
self._stream.incpos()
while not self.read_eof():
c = self._stream.peek_char
if not (c.isdigit() or ('a' <= c.lower() and c.lower() <= 'f')):
break
self._stream.incpos()
return self._stream.validate_context()
return self._stream.restore_context() | def read_hex_integer(self) -> bool:
"""
read a hexadecimal number
Read the following BNF rule else return False::
readHexInteger = [
[ '0'..'9' | 'a'..'f' | 'A'..'F' ]+
]
"""
if self.read_eof():
return False
self._stream.save_context()
c = self._stream.peek_char
if c.isdigit() or ('a' <= c.lower() and c.lower() <= 'f'):
self._stream.incpos()
while not self.read_eof():
c = self._stream.peek_char
if not (c.isdigit() or ('a' <= c.lower() and c.lower() <= 'f')):
break
self._stream.incpos()
return self._stream.validate_context()
return self._stream.restore_context() | [
"read",
"a",
"hexadecimal",
"number",
"Read",
"the",
"following",
"BNF",
"rule",
"else",
"return",
"False",
"::"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L440-L461 | [
"def",
"read_hex_integer",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"c",
"=",
"self",
".",
"_stream",
".",
"peek_char",
"if",
"c",
".",
"isdigit",
"(",
")",
"or",
"(",
"'a'",
"<=",
"c",
".",
"lower",
"(",
")",
"and",
"c",
".",
"lower",
"(",
")",
"<=",
"'f'",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
":",
"c",
"=",
"self",
".",
"_stream",
".",
"peek_char",
"if",
"not",
"(",
"c",
".",
"isdigit",
"(",
")",
"or",
"(",
"'a'",
"<=",
"c",
".",
"lower",
"(",
")",
"and",
"c",
".",
"lower",
"(",
")",
"<=",
"'f'",
")",
")",
":",
"break",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | read_cstring | read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"' | pyrser/parsing/base.py | def read_cstring(self) -> bool:
"""
read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"'
"""
self._stream.save_context()
idx = self._stream.index
if self.read_char("\"") and self.read_until("\"", "\\"):
txt = self._stream[idx:self._stream.index]
return self._stream.validate_context()
return self._stream.restore_context() | def read_cstring(self) -> bool:
"""
read a double quoted string
Read following BNF rule else return False::
'"' -> ['\\' #char | ~'\\'] '"'
"""
self._stream.save_context()
idx = self._stream.index
if self.read_char("\"") and self.read_until("\"", "\\"):
txt = self._stream[idx:self._stream.index]
return self._stream.validate_context()
return self._stream.restore_context() | [
"read",
"a",
"double",
"quoted",
"string",
"Read",
"following",
"BNF",
"rule",
"else",
"return",
"False",
"::"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L543-L556 | [
"def",
"read_cstring",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"idx",
"=",
"self",
".",
"_stream",
".",
"index",
"if",
"self",
".",
"read_char",
"(",
"\"\\\"\"",
")",
"and",
"self",
".",
"read_until",
"(",
"\"\\\"\"",
",",
"\"\\\\\"",
")",
":",
"txt",
"=",
"self",
".",
"_stream",
"[",
"idx",
":",
"self",
".",
"_stream",
".",
"index",
"]",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.push_rule_nodes | Push context variable to store rule nodes. | pyrser/parsing/base.py | def push_rule_nodes(self) -> bool:
"""Push context variable to store rule nodes."""
if self.rule_nodes is None:
self.rule_nodes = collections.ChainMap()
self.tag_cache = collections.ChainMap()
self.id_cache = collections.ChainMap()
else:
self.rule_nodes = self.rule_nodes.new_child()
self.tag_cache = self.tag_cache.new_child()
self.id_cache = self.id_cache.new_child()
return True | def push_rule_nodes(self) -> bool:
"""Push context variable to store rule nodes."""
if self.rule_nodes is None:
self.rule_nodes = collections.ChainMap()
self.tag_cache = collections.ChainMap()
self.id_cache = collections.ChainMap()
else:
self.rule_nodes = self.rule_nodes.new_child()
self.tag_cache = self.tag_cache.new_child()
self.id_cache = self.id_cache.new_child()
return True | [
"Push",
"context",
"variable",
"to",
"store",
"rule",
"nodes",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L99-L109 | [
"def",
"push_rule_nodes",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"rule_nodes",
"is",
"None",
":",
"self",
".",
"rule_nodes",
"=",
"collections",
".",
"ChainMap",
"(",
")",
"self",
".",
"tag_cache",
"=",
"collections",
".",
"ChainMap",
"(",
")",
"self",
".",
"id_cache",
"=",
"collections",
".",
"ChainMap",
"(",
")",
"else",
":",
"self",
".",
"rule_nodes",
"=",
"self",
".",
"rule_nodes",
".",
"new_child",
"(",
")",
"self",
".",
"tag_cache",
"=",
"self",
".",
"tag_cache",
".",
"new_child",
"(",
")",
"self",
".",
"id_cache",
"=",
"self",
".",
"id_cache",
".",
"new_child",
"(",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.pop_rule_nodes | Pop context variable that store rule nodes | pyrser/parsing/base.py | def pop_rule_nodes(self) -> bool:
"""Pop context variable that store rule nodes"""
self.rule_nodes = self.rule_nodes.parents
self.tag_cache = self.tag_cache.parents
self.id_cache = self.id_cache.parents
return True | def pop_rule_nodes(self) -> bool:
"""Pop context variable that store rule nodes"""
self.rule_nodes = self.rule_nodes.parents
self.tag_cache = self.tag_cache.parents
self.id_cache = self.id_cache.parents
return True | [
"Pop",
"context",
"variable",
"that",
"store",
"rule",
"nodes"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L111-L116 | [
"def",
"pop_rule_nodes",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"rule_nodes",
"=",
"self",
".",
"rule_nodes",
".",
"parents",
"self",
".",
"tag_cache",
"=",
"self",
".",
"tag_cache",
".",
"parents",
"self",
".",
"id_cache",
"=",
"self",
".",
"id_cache",
".",
"parents",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.value | Return the text value of the node | pyrser/parsing/base.py | def value(self, n: Node) -> str:
"""Return the text value of the node"""
id_n = id(n)
idcache = self.id_cache
if id_n not in idcache:
return ""
name = idcache[id_n]
tag_cache = self.tag_cache
if name not in tag_cache:
raise Exception("Incoherent tag cache")
tag = tag_cache[name]
k = "%d:%d" % (tag._begin, tag._end)
valcache = self._streams[-1].value_cache
if k not in valcache:
valcache[k] = str(tag)
return valcache[k] | def value(self, n: Node) -> str:
"""Return the text value of the node"""
id_n = id(n)
idcache = self.id_cache
if id_n not in idcache:
return ""
name = idcache[id_n]
tag_cache = self.tag_cache
if name not in tag_cache:
raise Exception("Incoherent tag cache")
tag = tag_cache[name]
k = "%d:%d" % (tag._begin, tag._end)
valcache = self._streams[-1].value_cache
if k not in valcache:
valcache[k] = str(tag)
return valcache[k] | [
"Return",
"the",
"text",
"value",
"of",
"the",
"node"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L118-L133 | [
"def",
"value",
"(",
"self",
",",
"n",
":",
"Node",
")",
"->",
"str",
":",
"id_n",
"=",
"id",
"(",
"n",
")",
"idcache",
"=",
"self",
".",
"id_cache",
"if",
"id_n",
"not",
"in",
"idcache",
":",
"return",
"\"\"",
"name",
"=",
"idcache",
"[",
"id_n",
"]",
"tag_cache",
"=",
"self",
".",
"tag_cache",
"if",
"name",
"not",
"in",
"tag_cache",
":",
"raise",
"Exception",
"(",
"\"Incoherent tag cache\"",
")",
"tag",
"=",
"tag_cache",
"[",
"name",
"]",
"k",
"=",
"\"%d:%d\"",
"%",
"(",
"tag",
".",
"_begin",
",",
"tag",
".",
"_end",
")",
"valcache",
"=",
"self",
".",
"_streams",
"[",
"-",
"1",
"]",
".",
"value_cache",
"if",
"k",
"not",
"in",
"valcache",
":",
"valcache",
"[",
"k",
"]",
"=",
"str",
"(",
"tag",
")",
"return",
"valcache",
"[",
"k",
"]"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.parsed_stream | Push a new Stream into the parser.
All subsequent called functions will parse this new stream,
until the 'popStream' function is called. | pyrser/parsing/base.py | def parsed_stream(self, content: str, name: str=None):
"""Push a new Stream into the parser.
All subsequent called functions will parse this new stream,
until the 'popStream' function is called.
"""
self._streams.append(Stream(content, name)) | def parsed_stream(self, content: str, name: str=None):
"""Push a new Stream into the parser.
All subsequent called functions will parse this new stream,
until the 'popStream' function is called.
"""
self._streams.append(Stream(content, name)) | [
"Push",
"a",
"new",
"Stream",
"into",
"the",
"parser",
".",
"All",
"subsequent",
"called",
"functions",
"will",
"parse",
"this",
"new",
"stream",
"until",
"the",
"popStream",
"function",
"is",
"called",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L137-L142 | [
"def",
"parsed_stream",
"(",
"self",
",",
"content",
":",
"str",
",",
"name",
":",
"str",
"=",
"None",
")",
":",
"self",
".",
"_streams",
".",
"append",
"(",
"Stream",
"(",
"content",
",",
"name",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.begin_tag | Save the current index under the given name. | pyrser/parsing/base.py | def begin_tag(self, name: str) -> Node:
"""Save the current index under the given name."""
# Check if we could attach tag cache to current rule_nodes scope
self.tag_cache[name] = Tag(self._stream, self._stream.index)
return True | def begin_tag(self, name: str) -> Node:
"""Save the current index under the given name."""
# Check if we could attach tag cache to current rule_nodes scope
self.tag_cache[name] = Tag(self._stream, self._stream.index)
return True | [
"Save",
"the",
"current",
"index",
"under",
"the",
"given",
"name",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L151-L155 | [
"def",
"begin_tag",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Node",
":",
"# Check if we could attach tag cache to current rule_nodes scope",
"self",
".",
"tag_cache",
"[",
"name",
"]",
"=",
"Tag",
"(",
"self",
".",
"_stream",
",",
"self",
".",
"_stream",
".",
"index",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.end_tag | Extract the string between saved and current index. | pyrser/parsing/base.py | def end_tag(self, name: str) -> Node:
"""Extract the string between saved and current index."""
self.tag_cache[name].set_end(self._stream.index)
return True | def end_tag(self, name: str) -> Node:
"""Extract the string between saved and current index."""
self.tag_cache[name].set_end(self._stream.index)
return True | [
"Extract",
"the",
"string",
"between",
"saved",
"and",
"current",
"index",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L157-L160 | [
"def",
"end_tag",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Node",
":",
"self",
".",
"tag_cache",
"[",
"name",
"]",
".",
"set_end",
"(",
"self",
".",
"_stream",
".",
"index",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.set_rules | Merge internal rules set with the given rules | pyrser/parsing/base.py | def set_rules(cls, rules: dict) -> bool:
"""
Merge internal rules set with the given rules
"""
cls._rules = cls._rules.new_child()
for rule_name, rule_pt in rules.items():
if '.' not in rule_name:
rule_name = cls.__module__ \
+ '.' + cls.__name__ \
+ '.' + rule_name
meta.set_one(cls._rules, rule_name, rule_pt)
return True | def set_rules(cls, rules: dict) -> bool:
"""
Merge internal rules set with the given rules
"""
cls._rules = cls._rules.new_child()
for rule_name, rule_pt in rules.items():
if '.' not in rule_name:
rule_name = cls.__module__ \
+ '.' + cls.__name__ \
+ '.' + rule_name
meta.set_one(cls._rules, rule_name, rule_pt)
return True | [
"Merge",
"internal",
"rules",
"set",
"with",
"the",
"given",
"rules"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L172-L183 | [
"def",
"set_rules",
"(",
"cls",
",",
"rules",
":",
"dict",
")",
"->",
"bool",
":",
"cls",
".",
"_rules",
"=",
"cls",
".",
"_rules",
".",
"new_child",
"(",
")",
"for",
"rule_name",
",",
"rule_pt",
"in",
"rules",
".",
"items",
"(",
")",
":",
"if",
"'.'",
"not",
"in",
"rule_name",
":",
"rule_name",
"=",
"cls",
".",
"__module__",
"+",
"'.'",
"+",
"cls",
".",
"__name__",
"+",
"'.'",
"+",
"rule_name",
"meta",
".",
"set_one",
"(",
"cls",
".",
"_rules",
",",
"rule_name",
",",
"rule_pt",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.set_hooks | Merge internal hooks set with the given hooks | pyrser/parsing/base.py | def set_hooks(cls, hooks: dict) -> bool:
"""
Merge internal hooks set with the given hooks
"""
cls._hooks = cls._hooks.new_child()
for hook_name, hook_pt in hooks.items():
if '.' not in hook_name:
hook_name = cls.__module__ \
+ '.' + cls.__name__ \
+ '.' + hook_name
meta.set_one(cls._hooks, hook_name, hook_pt)
return True | def set_hooks(cls, hooks: dict) -> bool:
"""
Merge internal hooks set with the given hooks
"""
cls._hooks = cls._hooks.new_child()
for hook_name, hook_pt in hooks.items():
if '.' not in hook_name:
hook_name = cls.__module__ \
+ '.' + cls.__name__ \
+ '.' + hook_name
meta.set_one(cls._hooks, hook_name, hook_pt)
return True | [
"Merge",
"internal",
"hooks",
"set",
"with",
"the",
"given",
"hooks"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L186-L197 | [
"def",
"set_hooks",
"(",
"cls",
",",
"hooks",
":",
"dict",
")",
"->",
"bool",
":",
"cls",
".",
"_hooks",
"=",
"cls",
".",
"_hooks",
".",
"new_child",
"(",
")",
"for",
"hook_name",
",",
"hook_pt",
"in",
"hooks",
".",
"items",
"(",
")",
":",
"if",
"'.'",
"not",
"in",
"hook_name",
":",
"hook_name",
"=",
"cls",
".",
"__module__",
"+",
"'.'",
"+",
"cls",
".",
"__name__",
"+",
"'.'",
"+",
"hook_name",
"meta",
".",
"set_one",
"(",
"cls",
".",
"_hooks",
",",
"hook_name",
",",
"hook_pt",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.set_directives | Merge internal directives set with the given directives.
For working directives, attach it only in the dsl.Parser class | pyrser/parsing/base.py | def set_directives(cls, directives: dict) -> bool:
"""
Merge internal directives set with the given directives.
For working directives, attach it only in the dsl.Parser class
"""
meta._directives = meta._directives.new_child()
for dir_name, dir_pt in directives.items():
meta.set_one(meta._directives, dir_name, dir_pt)
dir_pt.ns_name = dir_name
return True | def set_directives(cls, directives: dict) -> bool:
"""
Merge internal directives set with the given directives.
For working directives, attach it only in the dsl.Parser class
"""
meta._directives = meta._directives.new_child()
for dir_name, dir_pt in directives.items():
meta.set_one(meta._directives, dir_name, dir_pt)
dir_pt.ns_name = dir_name
return True | [
"Merge",
"internal",
"directives",
"set",
"with",
"the",
"given",
"directives",
".",
"For",
"working",
"directives",
"attach",
"it",
"only",
"in",
"the",
"dsl",
".",
"Parser",
"class"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L200-L209 | [
"def",
"set_directives",
"(",
"cls",
",",
"directives",
":",
"dict",
")",
"->",
"bool",
":",
"meta",
".",
"_directives",
"=",
"meta",
".",
"_directives",
".",
"new_child",
"(",
")",
"for",
"dir_name",
",",
"dir_pt",
"in",
"directives",
".",
"items",
"(",
")",
":",
"meta",
".",
"set_one",
"(",
"meta",
".",
"_directives",
",",
"dir_name",
",",
"dir_pt",
")",
"dir_pt",
".",
"ns_name",
"=",
"dir_name",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.eval_rule | Evaluate a rule by name. | pyrser/parsing/base.py | def eval_rule(self, name: str) -> Node:
"""Evaluate a rule by name."""
# context created by caller
n = Node()
id_n = id(n)
self.rule_nodes['_'] = n
self.id_cache[id_n] = '_'
# TODO: other behavior for empty rules?
if name not in self.__class__._rules:
self.diagnostic.notify(
error.Severity.ERROR,
"Unknown rule : %s" % name,
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
self._lastRule = name
rule_to_eval = self.__class__._rules[name]
# TODO: add packrat cache here, same rule - same pos == same res
res = rule_to_eval(self)
if res:
res = self.rule_nodes['_']
return res | def eval_rule(self, name: str) -> Node:
"""Evaluate a rule by name."""
# context created by caller
n = Node()
id_n = id(n)
self.rule_nodes['_'] = n
self.id_cache[id_n] = '_'
# TODO: other behavior for empty rules?
if name not in self.__class__._rules:
self.diagnostic.notify(
error.Severity.ERROR,
"Unknown rule : %s" % name,
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
self._lastRule = name
rule_to_eval = self.__class__._rules[name]
# TODO: add packrat cache here, same rule - same pos == same res
res = rule_to_eval(self)
if res:
res = self.rule_nodes['_']
return res | [
"Evaluate",
"a",
"rule",
"by",
"name",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L211-L232 | [
"def",
"eval_rule",
"(",
"self",
",",
"name",
":",
"str",
")",
"->",
"Node",
":",
"# context created by caller",
"n",
"=",
"Node",
"(",
")",
"id_n",
"=",
"id",
"(",
"n",
")",
"self",
".",
"rule_nodes",
"[",
"'_'",
"]",
"=",
"n",
"self",
".",
"id_cache",
"[",
"id_n",
"]",
"=",
"'_'",
"# TODO: other behavior for empty rules?",
"if",
"name",
"not",
"in",
"self",
".",
"__class__",
".",
"_rules",
":",
"self",
".",
"diagnostic",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Unknown rule : %s\"",
"%",
"name",
",",
"error",
".",
"LocationInfo",
".",
"from_stream",
"(",
"self",
".",
"_stream",
",",
"is_error",
"=",
"True",
")",
")",
"raise",
"self",
".",
"diagnostic",
"self",
".",
"_lastRule",
"=",
"name",
"rule_to_eval",
"=",
"self",
".",
"__class__",
".",
"_rules",
"[",
"name",
"]",
"# TODO: add packrat cache here, same rule - same pos == same res",
"res",
"=",
"rule_to_eval",
"(",
"self",
")",
"if",
"res",
":",
"res",
"=",
"self",
".",
"rule_nodes",
"[",
"'_'",
"]",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.eval_hook | Evaluate the hook by its name | pyrser/parsing/base.py | def eval_hook(self, name: str, ctx: list) -> Node:
"""Evaluate the hook by its name"""
if name not in self.__class__._hooks:
# TODO: don't always throw error, could have return True by default
self.diagnostic.notify(
error.Severity.ERROR,
"Unknown hook : %s" % name,
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
self._lastRule = '#' + name
res = self.__class__._hooks[name](self, *ctx)
if type(res) is not bool:
raise TypeError("Your hook %r didn't return a bool value" % name)
return res | def eval_hook(self, name: str, ctx: list) -> Node:
"""Evaluate the hook by its name"""
if name not in self.__class__._hooks:
# TODO: don't always throw error, could have return True by default
self.diagnostic.notify(
error.Severity.ERROR,
"Unknown hook : %s" % name,
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
self._lastRule = '#' + name
res = self.__class__._hooks[name](self, *ctx)
if type(res) is not bool:
raise TypeError("Your hook %r didn't return a bool value" % name)
return res | [
"Evaluate",
"the",
"hook",
"by",
"its",
"name"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L234-L248 | [
"def",
"eval_hook",
"(",
"self",
",",
"name",
":",
"str",
",",
"ctx",
":",
"list",
")",
"->",
"Node",
":",
"if",
"name",
"not",
"in",
"self",
".",
"__class__",
".",
"_hooks",
":",
"# TODO: don't always throw error, could have return True by default",
"self",
".",
"diagnostic",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Unknown hook : %s\"",
"%",
"name",
",",
"error",
".",
"LocationInfo",
".",
"from_stream",
"(",
"self",
".",
"_stream",
",",
"is_error",
"=",
"True",
")",
")",
"raise",
"self",
".",
"diagnostic",
"self",
".",
"_lastRule",
"=",
"'#'",
"+",
"name",
"res",
"=",
"self",
".",
"__class__",
".",
"_hooks",
"[",
"name",
"]",
"(",
"self",
",",
"*",
"ctx",
")",
"if",
"type",
"(",
"res",
")",
"is",
"not",
"bool",
":",
"raise",
"TypeError",
"(",
"\"Your hook %r didn't return a bool value\"",
"%",
"name",
")",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.peek_text | Same as readText but doesn't consume the stream. | pyrser/parsing/base.py | def peek_text(self, text: str) -> bool:
"""Same as readText but doesn't consume the stream."""
start = self._stream.index
stop = start + len(text)
if stop > self._stream.eos_index:
return False
return self._stream[self._stream.index:stop] == text | def peek_text(self, text: str) -> bool:
"""Same as readText but doesn't consume the stream."""
start = self._stream.index
stop = start + len(text)
if stop > self._stream.eos_index:
return False
return self._stream[self._stream.index:stop] == text | [
"Same",
"as",
"readText",
"but",
"doesn",
"t",
"consume",
"the",
"stream",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L257-L263 | [
"def",
"peek_text",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"bool",
":",
"start",
"=",
"self",
".",
"_stream",
".",
"index",
"stop",
"=",
"start",
"+",
"len",
"(",
"text",
")",
"if",
"stop",
">",
"self",
".",
"_stream",
".",
"eos_index",
":",
"return",
"False",
"return",
"self",
".",
"_stream",
"[",
"self",
".",
"_stream",
".",
"index",
":",
"stop",
"]",
"==",
"text"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.one_char | Read one byte in stream | pyrser/parsing/base.py | def one_char(self) -> bool:
"""Read one byte in stream"""
if self.read_eof():
return False
self._stream.incpos()
return True | def one_char(self) -> bool:
"""Read one byte in stream"""
if self.read_eof():
return False
self._stream.incpos()
return True | [
"Read",
"one",
"byte",
"in",
"stream"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L265-L270 | [
"def",
"one_char",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.read_char | Consume the c head byte, increment current index and return True
else return False. It use peekchar and it's the same as '' in BNF. | pyrser/parsing/base.py | def read_char(self, c: str) -> bool:
"""
Consume the c head byte, increment current index and return True
else return False. It use peekchar and it's the same as '' in BNF.
"""
if self.read_eof():
return False
self._stream.save_context()
if c == self._stream.peek_char:
self._stream.incpos()
return self._stream.validate_context()
return self._stream.restore_context() | def read_char(self, c: str) -> bool:
"""
Consume the c head byte, increment current index and return True
else return False. It use peekchar and it's the same as '' in BNF.
"""
if self.read_eof():
return False
self._stream.save_context()
if c == self._stream.peek_char:
self._stream.incpos()
return self._stream.validate_context()
return self._stream.restore_context() | [
"Consume",
"the",
"c",
"head",
"byte",
"increment",
"current",
"index",
"and",
"return",
"True",
"else",
"return",
"False",
".",
"It",
"use",
"peekchar",
"and",
"it",
"s",
"the",
"same",
"as",
"in",
"BNF",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L272-L283 | [
"def",
"read_char",
"(",
"self",
",",
"c",
":",
"str",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"if",
"c",
"==",
"self",
".",
"_stream",
".",
"peek_char",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.read_until | Consume the stream while the c byte is not read, else return false
ex : if stream is " abcdef ", read_until("d"); consume "abcd". | pyrser/parsing/base.py | def read_until(self, c: str, inhibitor='\\') -> bool:
"""
Consume the stream while the c byte is not read, else return false
ex : if stream is " abcdef ", read_until("d"); consume "abcd".
"""
if self.read_eof():
return False
self._stream.save_context()
while not self.read_eof():
if self.peek_char(inhibitor):
# Delete inhibitor and inhibited character
self.one_char()
self.one_char()
if self.peek_char(c):
self._stream.incpos()
return self._stream.validate_context()
self._stream.incpos()
return self._stream.restore_context() | def read_until(self, c: str, inhibitor='\\') -> bool:
"""
Consume the stream while the c byte is not read, else return false
ex : if stream is " abcdef ", read_until("d"); consume "abcd".
"""
if self.read_eof():
return False
self._stream.save_context()
while not self.read_eof():
if self.peek_char(inhibitor):
# Delete inhibitor and inhibited character
self.one_char()
self.one_char()
if self.peek_char(c):
self._stream.incpos()
return self._stream.validate_context()
self._stream.incpos()
return self._stream.restore_context() | [
"Consume",
"the",
"stream",
"while",
"the",
"c",
"byte",
"is",
"not",
"read",
"else",
"return",
"false",
"ex",
":",
"if",
"stream",
"is",
"abcdef",
"read_until",
"(",
"d",
")",
";",
"consume",
"abcd",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L285-L302 | [
"def",
"read_until",
"(",
"self",
",",
"c",
":",
"str",
",",
"inhibitor",
"=",
"'\\\\'",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
":",
"if",
"self",
".",
"peek_char",
"(",
"inhibitor",
")",
":",
"# Delete inhibitor and inhibited character",
"self",
".",
"one_char",
"(",
")",
"self",
".",
"one_char",
"(",
")",
"if",
"self",
".",
"peek_char",
"(",
"c",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.read_until_eof | Consume all the stream. Same as EOF in BNF. | pyrser/parsing/base.py | def read_until_eof(self) -> bool:
"""Consume all the stream. Same as EOF in BNF."""
if self.read_eof():
return True
# TODO: read ALL
self._stream.save_context()
while not self.read_eof():
self._stream.incpos()
return self._stream.validate_context() | def read_until_eof(self) -> bool:
"""Consume all the stream. Same as EOF in BNF."""
if self.read_eof():
return True
# TODO: read ALL
self._stream.save_context()
while not self.read_eof():
self._stream.incpos()
return self._stream.validate_context() | [
"Consume",
"all",
"the",
"stream",
".",
"Same",
"as",
"EOF",
"in",
"BNF",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L304-L312 | [
"def",
"read_until_eof",
"(",
"self",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"True",
"# TODO: read ALL",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.read_text | Consume a strlen(text) text at current position in the stream
else return False.
Same as "" in BNF
ex : read_text("ls");. | pyrser/parsing/base.py | def read_text(self, text: str) -> bool:
"""
Consume a strlen(text) text at current position in the stream
else return False.
Same as "" in BNF
ex : read_text("ls");.
"""
if self.read_eof():
return False
self._stream.save_context()
if self.peek_text(text):
self._stream.incpos(len(text))
return self._stream.validate_context()
return self._stream.restore_context() | def read_text(self, text: str) -> bool:
"""
Consume a strlen(text) text at current position in the stream
else return False.
Same as "" in BNF
ex : read_text("ls");.
"""
if self.read_eof():
return False
self._stream.save_context()
if self.peek_text(text):
self._stream.incpos(len(text))
return self._stream.validate_context()
return self._stream.restore_context() | [
"Consume",
"a",
"strlen",
"(",
"text",
")",
"text",
"at",
"current",
"position",
"in",
"the",
"stream",
"else",
"return",
"False",
".",
"Same",
"as",
"in",
"BNF",
"ex",
":",
"read_text",
"(",
"ls",
")",
";",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L314-L327 | [
"def",
"read_text",
"(",
"self",
",",
"text",
":",
"str",
")",
"->",
"bool",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"if",
"self",
".",
"peek_text",
"(",
"text",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
"len",
"(",
"text",
")",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.read_range | Consume head byte if it is >= begin and <= end else return false
Same as 'a'..'z' in BNF | pyrser/parsing/base.py | def read_range(self, begin: str, end: str) -> int:
"""
Consume head byte if it is >= begin and <= end else return false
Same as 'a'..'z' in BNF
"""
if self.read_eof():
return False
c = self._stream.peek_char
if begin <= c <= end:
self._stream.incpos()
return True
return False | def read_range(self, begin: str, end: str) -> int:
"""
Consume head byte if it is >= begin and <= end else return false
Same as 'a'..'z' in BNF
"""
if self.read_eof():
return False
c = self._stream.peek_char
if begin <= c <= end:
self._stream.incpos()
return True
return False | [
"Consume",
"head",
"byte",
"if",
"it",
"is",
">",
"=",
"begin",
"and",
"<",
"=",
"end",
"else",
"return",
"false",
"Same",
"as",
"a",
"..",
"z",
"in",
"BNF"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L329-L340 | [
"def",
"read_range",
"(",
"self",
",",
"begin",
":",
"str",
",",
"end",
":",
"str",
")",
"->",
"int",
":",
"if",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"False",
"c",
"=",
"self",
".",
"_stream",
".",
"peek_char",
"if",
"begin",
"<=",
"c",
"<=",
"end",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"True",
"return",
"False"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | BasicParser.ignore_blanks | Consume whitespace characters. | pyrser/parsing/base.py | def ignore_blanks(self) -> bool:
"""Consume whitespace characters."""
self._stream.save_context()
if not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n":
while (not self.read_eof()
and self._stream.peek_char in " \t\v\f\r\n"):
self._stream.incpos()
return self._stream.validate_context()
return self._stream.validate_context() | def ignore_blanks(self) -> bool:
"""Consume whitespace characters."""
self._stream.save_context()
if not self.read_eof() and self._stream.peek_char in " \t\v\f\r\n":
while (not self.read_eof()
and self._stream.peek_char in " \t\v\f\r\n"):
self._stream.incpos()
return self._stream.validate_context()
return self._stream.validate_context() | [
"Consume",
"whitespace",
"characters",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/base.py#L350-L358 | [
"def",
"ignore_blanks",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"if",
"not",
"self",
".",
"read_eof",
"(",
")",
"and",
"self",
".",
"_stream",
".",
"peek_char",
"in",
"\" \\t\\v\\f\\r\\n\"",
":",
"while",
"(",
"not",
"self",
".",
"read_eof",
"(",
")",
"and",
"self",
".",
"_stream",
".",
"peek_char",
"in",
"\" \\t\\v\\f\\r\\n\"",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Decorator.do_call | The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators) | pyrser/parsing/functors.py | def do_call(self, parser: BasicParser) -> Node:
"""
The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators)
"""
valueparam = []
for v, t in self.param:
if t is Node:
valueparam.append(parser.rule_nodes[v])
elif type(v) is t:
valueparam.append(v)
else:
raise TypeError(
"Type mismatch expected {} got {}".format(t, type(v)))
if not self.checkParam(self.decorator_class, valueparam):
return False
decorator = self.decorator_class(*valueparam)
global _decorators
_decorators.append(decorator)
res = self.pt(parser)
_decorators.pop()
return res | def do_call(self, parser: BasicParser) -> Node:
"""
The Decorator call is the one that actually pushes/pops
the decorator in the active decorators list (parsing._decorators)
"""
valueparam = []
for v, t in self.param:
if t is Node:
valueparam.append(parser.rule_nodes[v])
elif type(v) is t:
valueparam.append(v)
else:
raise TypeError(
"Type mismatch expected {} got {}".format(t, type(v)))
if not self.checkParam(self.decorator_class, valueparam):
return False
decorator = self.decorator_class(*valueparam)
global _decorators
_decorators.append(decorator)
res = self.pt(parser)
_decorators.pop()
return res | [
"The",
"Decorator",
"call",
"is",
"the",
"one",
"that",
"actually",
"pushes",
"/",
"pops",
"the",
"decorator",
"in",
"the",
"active",
"decorators",
"list",
"(",
"parsing",
".",
"_decorators",
")"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/parsing/functors.py#L695-L720 | [
"def",
"do_call",
"(",
"self",
",",
"parser",
":",
"BasicParser",
")",
"->",
"Node",
":",
"valueparam",
"=",
"[",
"]",
"for",
"v",
",",
"t",
"in",
"self",
".",
"param",
":",
"if",
"t",
"is",
"Node",
":",
"valueparam",
".",
"append",
"(",
"parser",
".",
"rule_nodes",
"[",
"v",
"]",
")",
"elif",
"type",
"(",
"v",
")",
"is",
"t",
":",
"valueparam",
".",
"append",
"(",
"v",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Type mismatch expected {} got {}\"",
".",
"format",
"(",
"t",
",",
"type",
"(",
"v",
")",
")",
")",
"if",
"not",
"self",
".",
"checkParam",
"(",
"self",
".",
"decorator_class",
",",
"valueparam",
")",
":",
"return",
"False",
"decorator",
"=",
"self",
".",
"decorator_class",
"(",
"*",
"valueparam",
")",
"global",
"_decorators",
"_decorators",
".",
"append",
"(",
"decorator",
")",
"res",
"=",
"self",
".",
"pt",
"(",
"parser",
")",
"_decorators",
".",
"pop",
"(",
")",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Fun.internal_name | Return the unique internal name | pyrser/type_system/fun.py | def internal_name(self):
"""
Return the unique internal name
"""
unq = 'f_' + super().internal_name()
if self.tparams is not None:
unq += "_" + "_".join(self.tparams)
if self.tret is not None:
unq += "_" + self.tret
return unq | def internal_name(self):
"""
Return the unique internal name
"""
unq = 'f_' + super().internal_name()
if self.tparams is not None:
unq += "_" + "_".join(self.tparams)
if self.tret is not None:
unq += "_" + self.tret
return unq | [
"Return",
"the",
"unique",
"internal",
"name"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/fun.py#L57-L66 | [
"def",
"internal_name",
"(",
"self",
")",
":",
"unq",
"=",
"'f_'",
"+",
"super",
"(",
")",
".",
"internal_name",
"(",
")",
"if",
"self",
".",
"tparams",
"is",
"not",
"None",
":",
"unq",
"+=",
"\"_\"",
"+",
"\"_\"",
".",
"join",
"(",
"self",
".",
"tparams",
")",
"if",
"self",
".",
"tret",
"is",
"not",
"None",
":",
"unq",
"+=",
"\"_\"",
"+",
"self",
".",
"tret",
"return",
"unq"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | HitClusterizer.set_hit_fields | Tell the clusterizer the meaning of the field names.
The hit_fields parameter is a dict, e.g., {"new field name": "standard field name"}.
If None default mapping is set.
Example:
--------
Internally, the clusterizer uses the hit fields names "column"/"row". If the name of the hits fields are "x"/"y", call:
set_hit_fields(hit_fields={'x': 'column',
'y': 'row'}) | pixel_clusterizer/clusterizer.py | def set_hit_fields(self, hit_fields):
''' Tell the clusterizer the meaning of the field names.
The hit_fields parameter is a dict, e.g., {"new field name": "standard field name"}.
If None default mapping is set.
Example:
--------
Internally, the clusterizer uses the hit fields names "column"/"row". If the name of the hits fields are "x"/"y", call:
set_hit_fields(hit_fields={'x': 'column',
'y': 'row'})
'''
if not hit_fields:
hit_fields_mapping_inverse = {}
hit_fields_mapping = {}
else:
# Create also the inverse dictionary for faster lookup
hit_fields_mapping_inverse = dict((k, v) for k, v in hit_fields.items())
hit_fields_mapping = dict((v, k) for k, v in hit_fields.items())
for old_name, new_name in self._default_hit_fields_mapping.items():
if old_name not in hit_fields_mapping:
hit_fields_mapping[old_name] = new_name
hit_fields_mapping_inverse[new_name] = old_name
self._hit_fields_mapping = hit_fields_mapping
self._hit_fields_mapping_inverse = hit_fields_mapping_inverse | def set_hit_fields(self, hit_fields):
''' Tell the clusterizer the meaning of the field names.
The hit_fields parameter is a dict, e.g., {"new field name": "standard field name"}.
If None default mapping is set.
Example:
--------
Internally, the clusterizer uses the hit fields names "column"/"row". If the name of the hits fields are "x"/"y", call:
set_hit_fields(hit_fields={'x': 'column',
'y': 'row'})
'''
if not hit_fields:
hit_fields_mapping_inverse = {}
hit_fields_mapping = {}
else:
# Create also the inverse dictionary for faster lookup
hit_fields_mapping_inverse = dict((k, v) for k, v in hit_fields.items())
hit_fields_mapping = dict((v, k) for k, v in hit_fields.items())
for old_name, new_name in self._default_hit_fields_mapping.items():
if old_name not in hit_fields_mapping:
hit_fields_mapping[old_name] = new_name
hit_fields_mapping_inverse[new_name] = old_name
self._hit_fields_mapping = hit_fields_mapping
self._hit_fields_mapping_inverse = hit_fields_mapping_inverse | [
"Tell",
"the",
"clusterizer",
"the",
"meaning",
"of",
"the",
"field",
"names",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L140-L167 | [
"def",
"set_hit_fields",
"(",
"self",
",",
"hit_fields",
")",
":",
"if",
"not",
"hit_fields",
":",
"hit_fields_mapping_inverse",
"=",
"{",
"}",
"hit_fields_mapping",
"=",
"{",
"}",
"else",
":",
"# Create also the inverse dictionary for faster lookup",
"hit_fields_mapping_inverse",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"hit_fields",
".",
"items",
"(",
")",
")",
"hit_fields_mapping",
"=",
"dict",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"hit_fields",
".",
"items",
"(",
")",
")",
"for",
"old_name",
",",
"new_name",
"in",
"self",
".",
"_default_hit_fields_mapping",
".",
"items",
"(",
")",
":",
"if",
"old_name",
"not",
"in",
"hit_fields_mapping",
":",
"hit_fields_mapping",
"[",
"old_name",
"]",
"=",
"new_name",
"hit_fields_mapping_inverse",
"[",
"new_name",
"]",
"=",
"old_name",
"self",
".",
"_hit_fields_mapping",
"=",
"hit_fields_mapping",
"self",
".",
"_hit_fields_mapping_inverse",
"=",
"hit_fields_mapping_inverse"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.set_cluster_fields | Tell the clusterizer the meaning of the field names.
The cluster_fields parameter is a dict, e.g., {"new filed name": "standard field name"}. | pixel_clusterizer/clusterizer.py | def set_cluster_fields(self, cluster_fields):
''' Tell the clusterizer the meaning of the field names.
The cluster_fields parameter is a dict, e.g., {"new filed name": "standard field name"}.
'''
if not cluster_fields:
cluster_fields_mapping_inverse = {}
cluster_fields_mapping = {}
else:
# Create also the inverse dictionary for faster lookup
cluster_fields_mapping_inverse = dict((k, v) for k, v in cluster_fields.items())
cluster_fields_mapping = dict((v, k) for k, v in cluster_fields.items())
for old_name, new_name in self._default_cluster_fields_mapping.items():
if old_name not in cluster_fields_mapping:
cluster_fields_mapping[old_name] = new_name
cluster_fields_mapping_inverse[new_name] = old_name
self._cluster_fields_mapping = cluster_fields_mapping
self._cluster_fields_mapping_inverse = cluster_fields_mapping_inverse | def set_cluster_fields(self, cluster_fields):
''' Tell the clusterizer the meaning of the field names.
The cluster_fields parameter is a dict, e.g., {"new filed name": "standard field name"}.
'''
if not cluster_fields:
cluster_fields_mapping_inverse = {}
cluster_fields_mapping = {}
else:
# Create also the inverse dictionary for faster lookup
cluster_fields_mapping_inverse = dict((k, v) for k, v in cluster_fields.items())
cluster_fields_mapping = dict((v, k) for k, v in cluster_fields.items())
for old_name, new_name in self._default_cluster_fields_mapping.items():
if old_name not in cluster_fields_mapping:
cluster_fields_mapping[old_name] = new_name
cluster_fields_mapping_inverse[new_name] = old_name
self._cluster_fields_mapping = cluster_fields_mapping
self._cluster_fields_mapping_inverse = cluster_fields_mapping_inverse | [
"Tell",
"the",
"clusterizer",
"the",
"meaning",
"of",
"the",
"field",
"names",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L169-L188 | [
"def",
"set_cluster_fields",
"(",
"self",
",",
"cluster_fields",
")",
":",
"if",
"not",
"cluster_fields",
":",
"cluster_fields_mapping_inverse",
"=",
"{",
"}",
"cluster_fields_mapping",
"=",
"{",
"}",
"else",
":",
"# Create also the inverse dictionary for faster lookup",
"cluster_fields_mapping_inverse",
"=",
"dict",
"(",
"(",
"k",
",",
"v",
")",
"for",
"k",
",",
"v",
"in",
"cluster_fields",
".",
"items",
"(",
")",
")",
"cluster_fields_mapping",
"=",
"dict",
"(",
"(",
"v",
",",
"k",
")",
"for",
"k",
",",
"v",
"in",
"cluster_fields",
".",
"items",
"(",
")",
")",
"for",
"old_name",
",",
"new_name",
"in",
"self",
".",
"_default_cluster_fields_mapping",
".",
"items",
"(",
")",
":",
"if",
"old_name",
"not",
"in",
"cluster_fields_mapping",
":",
"cluster_fields_mapping",
"[",
"old_name",
"]",
"=",
"new_name",
"cluster_fields_mapping_inverse",
"[",
"new_name",
"]",
"=",
"old_name",
"self",
".",
"_cluster_fields_mapping",
"=",
"cluster_fields_mapping",
"self",
".",
"_cluster_fields_mapping_inverse",
"=",
"cluster_fields_mapping_inverse"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.set_hit_dtype | Set the data type of the hits.
Fields that are not mentioned here are NOT copied into the clustered hits array.
Clusterizer has to know the hit data type to produce the clustered hit result with the same data types.
Parameters:
-----------
hit_dtype : numpy.dtype or equivalent
Defines the dtype of the hit array.
Example:
--------
hit_dtype = [("column", np.uint16), ("row", np.uint16)], where
"column", "row" is the field name of the input hit array. | pixel_clusterizer/clusterizer.py | def set_hit_dtype(self, hit_dtype):
''' Set the data type of the hits.
Fields that are not mentioned here are NOT copied into the clustered hits array.
Clusterizer has to know the hit data type to produce the clustered hit result with the same data types.
Parameters:
-----------
hit_dtype : numpy.dtype or equivalent
Defines the dtype of the hit array.
Example:
--------
hit_dtype = [("column", np.uint16), ("row", np.uint16)], where
"column", "row" is the field name of the input hit array.
'''
if not hit_dtype:
hit_dtype = np.dtype([])
else:
hit_dtype = np.dtype(hit_dtype)
cluster_hits_descr = hit_dtype.descr
# Add default back to description
for dtype_name, dtype in self._default_cluster_hits_descr:
if self._hit_fields_mapping[dtype_name] not in hit_dtype.fields:
cluster_hits_descr.append((dtype_name, dtype))
self._cluster_hits_descr = cluster_hits_descr
self._init_arrays(size=0) | def set_hit_dtype(self, hit_dtype):
''' Set the data type of the hits.
Fields that are not mentioned here are NOT copied into the clustered hits array.
Clusterizer has to know the hit data type to produce the clustered hit result with the same data types.
Parameters:
-----------
hit_dtype : numpy.dtype or equivalent
Defines the dtype of the hit array.
Example:
--------
hit_dtype = [("column", np.uint16), ("row", np.uint16)], where
"column", "row" is the field name of the input hit array.
'''
if not hit_dtype:
hit_dtype = np.dtype([])
else:
hit_dtype = np.dtype(hit_dtype)
cluster_hits_descr = hit_dtype.descr
# Add default back to description
for dtype_name, dtype in self._default_cluster_hits_descr:
if self._hit_fields_mapping[dtype_name] not in hit_dtype.fields:
cluster_hits_descr.append((dtype_name, dtype))
self._cluster_hits_descr = cluster_hits_descr
self._init_arrays(size=0) | [
"Set",
"the",
"data",
"type",
"of",
"the",
"hits",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L190-L218 | [
"def",
"set_hit_dtype",
"(",
"self",
",",
"hit_dtype",
")",
":",
"if",
"not",
"hit_dtype",
":",
"hit_dtype",
"=",
"np",
".",
"dtype",
"(",
"[",
"]",
")",
"else",
":",
"hit_dtype",
"=",
"np",
".",
"dtype",
"(",
"hit_dtype",
")",
"cluster_hits_descr",
"=",
"hit_dtype",
".",
"descr",
"# Add default back to description",
"for",
"dtype_name",
",",
"dtype",
"in",
"self",
".",
"_default_cluster_hits_descr",
":",
"if",
"self",
".",
"_hit_fields_mapping",
"[",
"dtype_name",
"]",
"not",
"in",
"hit_dtype",
".",
"fields",
":",
"cluster_hits_descr",
".",
"append",
"(",
"(",
"dtype_name",
",",
"dtype",
")",
")",
"self",
".",
"_cluster_hits_descr",
"=",
"cluster_hits_descr",
"self",
".",
"_init_arrays",
"(",
"size",
"=",
"0",
")"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.set_cluster_dtype | Set the data type of the cluster.
Parameters:
-----------
cluster_dtype : numpy.dtype or equivalent
Defines the dtype of the cluster array. | pixel_clusterizer/clusterizer.py | def set_cluster_dtype(self, cluster_dtype):
''' Set the data type of the cluster.
Parameters:
-----------
cluster_dtype : numpy.dtype or equivalent
Defines the dtype of the cluster array.
'''
if not cluster_dtype:
cluster_dtype = np.dtype([])
else:
cluster_dtype = np.dtype(cluster_dtype)
cluster_descr = cluster_dtype.descr
for dtype_name, dtype in self._default_cluster_descr:
if self._cluster_fields_mapping[dtype_name] not in cluster_dtype.fields:
cluster_descr.append((dtype_name, dtype))
self._cluster_descr = cluster_descr
self._init_arrays(size=0) | def set_cluster_dtype(self, cluster_dtype):
''' Set the data type of the cluster.
Parameters:
-----------
cluster_dtype : numpy.dtype or equivalent
Defines the dtype of the cluster array.
'''
if not cluster_dtype:
cluster_dtype = np.dtype([])
else:
cluster_dtype = np.dtype(cluster_dtype)
cluster_descr = cluster_dtype.descr
for dtype_name, dtype in self._default_cluster_descr:
if self._cluster_fields_mapping[dtype_name] not in cluster_dtype.fields:
cluster_descr.append((dtype_name, dtype))
self._cluster_descr = cluster_descr
self._init_arrays(size=0) | [
"Set",
"the",
"data",
"type",
"of",
"the",
"cluster",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L220-L239 | [
"def",
"set_cluster_dtype",
"(",
"self",
",",
"cluster_dtype",
")",
":",
"if",
"not",
"cluster_dtype",
":",
"cluster_dtype",
"=",
"np",
".",
"dtype",
"(",
"[",
"]",
")",
"else",
":",
"cluster_dtype",
"=",
"np",
".",
"dtype",
"(",
"cluster_dtype",
")",
"cluster_descr",
"=",
"cluster_dtype",
".",
"descr",
"for",
"dtype_name",
",",
"dtype",
"in",
"self",
".",
"_default_cluster_descr",
":",
"if",
"self",
".",
"_cluster_fields_mapping",
"[",
"dtype_name",
"]",
"not",
"in",
"cluster_dtype",
".",
"fields",
":",
"cluster_descr",
".",
"append",
"(",
"(",
"dtype_name",
",",
"dtype",
")",
")",
"self",
".",
"_cluster_descr",
"=",
"cluster_descr",
"self",
".",
"_init_arrays",
"(",
"size",
"=",
"0",
")"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.add_cluster_field | Adds a field or a list of fields to the cluster result array. Has to be defined as a numpy dtype entry, e.g.: ('parameter', '<i4') | pixel_clusterizer/clusterizer.py | def add_cluster_field(self, description):
''' Adds a field or a list of fields to the cluster result array. Has to be defined as a numpy dtype entry, e.g.: ('parameter', '<i4') '''
if isinstance(description, list):
for item in description:
if len(item) != 2:
raise TypeError("Description needs to be a list of 2-tuples of a string and a dtype.")
self._cluster_descr.append(item)
else:
if len(description) != 2:
raise TypeError("Description needs to be a 2-tuple of a string and a dtype.")
self._cluster_descr.append(description)
self._init_arrays(size=0) | def add_cluster_field(self, description):
''' Adds a field or a list of fields to the cluster result array. Has to be defined as a numpy dtype entry, e.g.: ('parameter', '<i4') '''
if isinstance(description, list):
for item in description:
if len(item) != 2:
raise TypeError("Description needs to be a list of 2-tuples of a string and a dtype.")
self._cluster_descr.append(item)
else:
if len(description) != 2:
raise TypeError("Description needs to be a 2-tuple of a string and a dtype.")
self._cluster_descr.append(description)
self._init_arrays(size=0) | [
"Adds",
"a",
"field",
"or",
"a",
"list",
"of",
"fields",
"to",
"the",
"cluster",
"result",
"array",
".",
"Has",
"to",
"be",
"defined",
"as",
"a",
"numpy",
"dtype",
"entry",
"e",
".",
"g",
".",
":",
"(",
"parameter",
"<i4",
")"
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L241-L252 | [
"def",
"add_cluster_field",
"(",
"self",
",",
"description",
")",
":",
"if",
"isinstance",
"(",
"description",
",",
"list",
")",
":",
"for",
"item",
"in",
"description",
":",
"if",
"len",
"(",
"item",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"\"Description needs to be a list of 2-tuples of a string and a dtype.\"",
")",
"self",
".",
"_cluster_descr",
".",
"append",
"(",
"item",
")",
"else",
":",
"if",
"len",
"(",
"description",
")",
"!=",
"2",
":",
"raise",
"TypeError",
"(",
"\"Description needs to be a 2-tuple of a string and a dtype.\"",
")",
"self",
".",
"_cluster_descr",
".",
"append",
"(",
"description",
")",
"self",
".",
"_init_arrays",
"(",
"size",
"=",
"0",
")"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.set_end_of_cluster_function | Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing. | pixel_clusterizer/clusterizer.py | def set_end_of_cluster_function(self, function):
''' Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing.
'''
self.cluster_functions._end_of_cluster_function = self._jitted(function)
self._end_of_cluster_function = function | def set_end_of_cluster_function(self, function):
''' Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing.
'''
self.cluster_functions._end_of_cluster_function = self._jitted(function)
self._end_of_cluster_function = function | [
"Adding",
"function",
"to",
"module",
".",
"This",
"is",
"maybe",
"the",
"only",
"way",
"to",
"make",
"the",
"clusterizer",
"to",
"work",
"with",
"multiprocessing",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L254-L259 | [
"def",
"set_end_of_cluster_function",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"cluster_functions",
".",
"_end_of_cluster_function",
"=",
"self",
".",
"_jitted",
"(",
"function",
")",
"self",
".",
"_end_of_cluster_function",
"=",
"function"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.set_end_of_event_function | Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing. | pixel_clusterizer/clusterizer.py | def set_end_of_event_function(self, function):
''' Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing.
'''
self.cluster_functions._end_of_event_function = self._jitted(function)
self._end_of_event_function = function | def set_end_of_event_function(self, function):
''' Adding function to module.
This is maybe the only way to make the clusterizer to work with multiprocessing.
'''
self.cluster_functions._end_of_event_function = self._jitted(function)
self._end_of_event_function = function | [
"Adding",
"function",
"to",
"module",
".",
"This",
"is",
"maybe",
"the",
"only",
"way",
"to",
"make",
"the",
"clusterizer",
"to",
"work",
"with",
"multiprocessing",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L261-L266 | [
"def",
"set_end_of_event_function",
"(",
"self",
",",
"function",
")",
":",
"self",
".",
"cluster_functions",
".",
"_end_of_event_function",
"=",
"self",
".",
"_jitted",
"(",
"function",
")",
"self",
".",
"_end_of_event_function",
"=",
"function"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer.cluster_hits | Cluster given hit array.
The noisy_pixels and disabled_pixels parameters are iterables of column/row index pairs, e.g. [[column_1, row_1], [column_2, row_2], ...].
The noisy_pixels parameter allows for removing clusters that consist of a single noisy pixels. Clusters with 2 or more noisy pixels are not removed.
The disabled_pixels parameter allows for ignoring pixels. | pixel_clusterizer/clusterizer.py | def cluster_hits(self, hits, noisy_pixels=None, disabled_pixels=None):
''' Cluster given hit array.
The noisy_pixels and disabled_pixels parameters are iterables of column/row index pairs, e.g. [[column_1, row_1], [column_2, row_2], ...].
The noisy_pixels parameter allows for removing clusters that consist of a single noisy pixels. Clusters with 2 or more noisy pixels are not removed.
The disabled_pixels parameter allows for ignoring pixels.
'''
# Jitting a second time to workaround different bahavior of the installation methods on different platforms (pip install vs. python setup.py).
# In some circumstances, the Numba compiler can't compile functions that were pickled previously.
self.cluster_functions._end_of_cluster_function = self._jitted(self._end_of_cluster_function)
self.cluster_functions._end_of_event_function = self._jitted(self._end_of_event_function)
n_hits = hits.shape[0] # Set n_hits to new size
if (n_hits < int(0.5 * self._cluster_hits.size)) or (n_hits > self._cluster_hits.size):
self._init_arrays(size=int(1.1 * n_hits)) # oversize buffer slightly to reduce allocations
else:
self._assigned_hit_array.fill(0) # The hit indices of the actual cluster, 0 means not assigned
self._cluster_hit_indices.fill(-1) # The hit indices of the actual cluster, -1 means not assigned
self._clusters.dtype.names = self._unmap_cluster_field_names(self._clusters.dtype.names) # Reset the data fields from previous renaming
self._cluster_hits.dtype.names = self._unmap_hit_field_names(self._cluster_hits.dtype.names) # Reset the data fields from previous renaming
self._check_struct_compatibility(hits)
# The hit info is extended by the cluster info; this is only possible by creating a new hit info array and copy data
for field_name in hits.dtype.fields:
if field_name in self._hit_fields_mapping_inverse:
cluster_hits_field_name = self._hit_fields_mapping_inverse[field_name]
else:
cluster_hits_field_name = field_name
if cluster_hits_field_name in self._cluster_hits.dtype.fields:
self._cluster_hits[cluster_hits_field_name][:n_hits] = hits[field_name]
noisy_pixels_array = np.array([]) if noisy_pixels is None else np.array(noisy_pixels)
if noisy_pixels_array.shape[0] != 0:
noisy_pixels_max_range = np.array([max(0, np.max(noisy_pixels_array[:, 0])), max(0, np.max(noisy_pixels_array[:, 1]))])
noisy_pixels = np.zeros(noisy_pixels_max_range + 1, dtype=np.bool)
noisy_pixels[noisy_pixels_array[:, 0], noisy_pixels_array[:, 1]] = 1
else:
noisy_pixels = np.zeros((0, 0), dtype=np.bool)
disabled_pixels_array = np.array([]) if disabled_pixels is None else np.array(disabled_pixels)
if disabled_pixels_array.shape[0] != 0:
disabled_pixels_max_range = np.array([np.max(disabled_pixels_array[:, 0]), np.max(disabled_pixels_array[:, 1])])
disabled_pixels = np.zeros(disabled_pixels_max_range + 1, dtype=np.bool)
disabled_pixels[disabled_pixels_array[:, 0], disabled_pixels_array[:, 1]] = 1
else:
disabled_pixels = np.zeros((0, 0), dtype=np.bool)
# col_dtype = self._cluster_hits.dtype.fields["column"][0]
# row_dtype = self._cluster_hits.dtype.fields["row"][0]
# mask_dtype = {"names": ["column", "row"],
# "formats": [col_dtype, row_dtype]}
# noisy_pixels = np.recarray(noisy_pixels_array.shape[0], dtype=mask_dtype)
# noisy_pixels[:] = [(item[0], item[1]) for item in noisy_pixels_array]
# disabled_pixels = np.recarray(disabled_pixels_array.shape[0], dtype=mask_dtype)
# disabled_pixels[:] = [(item[0], item[1]) for item in disabled_pixels_array]
n_clusters = self.cluster_functions._cluster_hits( # Set n_clusters to new size
hits=self._cluster_hits[:n_hits],
clusters=self._clusters[:n_hits],
assigned_hit_array=self._assigned_hit_array[:n_hits],
cluster_hit_indices=self._cluster_hit_indices[:n_hits],
column_cluster_distance=self._column_cluster_distance,
row_cluster_distance=self._row_cluster_distance,
frame_cluster_distance=self._frame_cluster_distance,
min_hit_charge=self._min_hit_charge,
max_hit_charge=self._max_hit_charge,
ignore_same_hits=self._ignore_same_hits,
noisy_pixels=noisy_pixels,
disabled_pixels=disabled_pixels)
self._cluster_hits.dtype.names = self._map_hit_field_names(self._cluster_hits.dtype.names) # Rename the data fields for the result
self._clusters.dtype.names = self._map_cluster_field_names(self._clusters.dtype.names) # Rename the data fields for the result
return self._cluster_hits[:n_hits], self._clusters[:n_clusters] | def cluster_hits(self, hits, noisy_pixels=None, disabled_pixels=None):
''' Cluster given hit array.
The noisy_pixels and disabled_pixels parameters are iterables of column/row index pairs, e.g. [[column_1, row_1], [column_2, row_2], ...].
The noisy_pixels parameter allows for removing clusters that consist of a single noisy pixels. Clusters with 2 or more noisy pixels are not removed.
The disabled_pixels parameter allows for ignoring pixels.
'''
# Jitting a second time to workaround different bahavior of the installation methods on different platforms (pip install vs. python setup.py).
# In some circumstances, the Numba compiler can't compile functions that were pickled previously.
self.cluster_functions._end_of_cluster_function = self._jitted(self._end_of_cluster_function)
self.cluster_functions._end_of_event_function = self._jitted(self._end_of_event_function)
n_hits = hits.shape[0] # Set n_hits to new size
if (n_hits < int(0.5 * self._cluster_hits.size)) or (n_hits > self._cluster_hits.size):
self._init_arrays(size=int(1.1 * n_hits)) # oversize buffer slightly to reduce allocations
else:
self._assigned_hit_array.fill(0) # The hit indices of the actual cluster, 0 means not assigned
self._cluster_hit_indices.fill(-1) # The hit indices of the actual cluster, -1 means not assigned
self._clusters.dtype.names = self._unmap_cluster_field_names(self._clusters.dtype.names) # Reset the data fields from previous renaming
self._cluster_hits.dtype.names = self._unmap_hit_field_names(self._cluster_hits.dtype.names) # Reset the data fields from previous renaming
self._check_struct_compatibility(hits)
# The hit info is extended by the cluster info; this is only possible by creating a new hit info array and copy data
for field_name in hits.dtype.fields:
if field_name in self._hit_fields_mapping_inverse:
cluster_hits_field_name = self._hit_fields_mapping_inverse[field_name]
else:
cluster_hits_field_name = field_name
if cluster_hits_field_name in self._cluster_hits.dtype.fields:
self._cluster_hits[cluster_hits_field_name][:n_hits] = hits[field_name]
noisy_pixels_array = np.array([]) if noisy_pixels is None else np.array(noisy_pixels)
if noisy_pixels_array.shape[0] != 0:
noisy_pixels_max_range = np.array([max(0, np.max(noisy_pixels_array[:, 0])), max(0, np.max(noisy_pixels_array[:, 1]))])
noisy_pixels = np.zeros(noisy_pixels_max_range + 1, dtype=np.bool)
noisy_pixels[noisy_pixels_array[:, 0], noisy_pixels_array[:, 1]] = 1
else:
noisy_pixels = np.zeros((0, 0), dtype=np.bool)
disabled_pixels_array = np.array([]) if disabled_pixels is None else np.array(disabled_pixels)
if disabled_pixels_array.shape[0] != 0:
disabled_pixels_max_range = np.array([np.max(disabled_pixels_array[:, 0]), np.max(disabled_pixels_array[:, 1])])
disabled_pixels = np.zeros(disabled_pixels_max_range + 1, dtype=np.bool)
disabled_pixels[disabled_pixels_array[:, 0], disabled_pixels_array[:, 1]] = 1
else:
disabled_pixels = np.zeros((0, 0), dtype=np.bool)
# col_dtype = self._cluster_hits.dtype.fields["column"][0]
# row_dtype = self._cluster_hits.dtype.fields["row"][0]
# mask_dtype = {"names": ["column", "row"],
# "formats": [col_dtype, row_dtype]}
# noisy_pixels = np.recarray(noisy_pixels_array.shape[0], dtype=mask_dtype)
# noisy_pixels[:] = [(item[0], item[1]) for item in noisy_pixels_array]
# disabled_pixels = np.recarray(disabled_pixels_array.shape[0], dtype=mask_dtype)
# disabled_pixels[:] = [(item[0], item[1]) for item in disabled_pixels_array]
n_clusters = self.cluster_functions._cluster_hits( # Set n_clusters to new size
hits=self._cluster_hits[:n_hits],
clusters=self._clusters[:n_hits],
assigned_hit_array=self._assigned_hit_array[:n_hits],
cluster_hit_indices=self._cluster_hit_indices[:n_hits],
column_cluster_distance=self._column_cluster_distance,
row_cluster_distance=self._row_cluster_distance,
frame_cluster_distance=self._frame_cluster_distance,
min_hit_charge=self._min_hit_charge,
max_hit_charge=self._max_hit_charge,
ignore_same_hits=self._ignore_same_hits,
noisy_pixels=noisy_pixels,
disabled_pixels=disabled_pixels)
self._cluster_hits.dtype.names = self._map_hit_field_names(self._cluster_hits.dtype.names) # Rename the data fields for the result
self._clusters.dtype.names = self._map_cluster_field_names(self._clusters.dtype.names) # Rename the data fields for the result
return self._cluster_hits[:n_hits], self._clusters[:n_clusters] | [
"Cluster",
"given",
"hit",
"array",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L302-L377 | [
"def",
"cluster_hits",
"(",
"self",
",",
"hits",
",",
"noisy_pixels",
"=",
"None",
",",
"disabled_pixels",
"=",
"None",
")",
":",
"# Jitting a second time to workaround different bahavior of the installation methods on different platforms (pip install vs. python setup.py).",
"# In some circumstances, the Numba compiler can't compile functions that were pickled previously.",
"self",
".",
"cluster_functions",
".",
"_end_of_cluster_function",
"=",
"self",
".",
"_jitted",
"(",
"self",
".",
"_end_of_cluster_function",
")",
"self",
".",
"cluster_functions",
".",
"_end_of_event_function",
"=",
"self",
".",
"_jitted",
"(",
"self",
".",
"_end_of_event_function",
")",
"n_hits",
"=",
"hits",
".",
"shape",
"[",
"0",
"]",
"# Set n_hits to new size",
"if",
"(",
"n_hits",
"<",
"int",
"(",
"0.5",
"*",
"self",
".",
"_cluster_hits",
".",
"size",
")",
")",
"or",
"(",
"n_hits",
">",
"self",
".",
"_cluster_hits",
".",
"size",
")",
":",
"self",
".",
"_init_arrays",
"(",
"size",
"=",
"int",
"(",
"1.1",
"*",
"n_hits",
")",
")",
"# oversize buffer slightly to reduce allocations",
"else",
":",
"self",
".",
"_assigned_hit_array",
".",
"fill",
"(",
"0",
")",
"# The hit indices of the actual cluster, 0 means not assigned",
"self",
".",
"_cluster_hit_indices",
".",
"fill",
"(",
"-",
"1",
")",
"# The hit indices of the actual cluster, -1 means not assigned",
"self",
".",
"_clusters",
".",
"dtype",
".",
"names",
"=",
"self",
".",
"_unmap_cluster_field_names",
"(",
"self",
".",
"_clusters",
".",
"dtype",
".",
"names",
")",
"# Reset the data fields from previous renaming",
"self",
".",
"_cluster_hits",
".",
"dtype",
".",
"names",
"=",
"self",
".",
"_unmap_hit_field_names",
"(",
"self",
".",
"_cluster_hits",
".",
"dtype",
".",
"names",
")",
"# Reset the data fields from previous renaming",
"self",
".",
"_check_struct_compatibility",
"(",
"hits",
")",
"# The hit info is extended by the cluster info; this is only possible by creating a new hit info array and copy data",
"for",
"field_name",
"in",
"hits",
".",
"dtype",
".",
"fields",
":",
"if",
"field_name",
"in",
"self",
".",
"_hit_fields_mapping_inverse",
":",
"cluster_hits_field_name",
"=",
"self",
".",
"_hit_fields_mapping_inverse",
"[",
"field_name",
"]",
"else",
":",
"cluster_hits_field_name",
"=",
"field_name",
"if",
"cluster_hits_field_name",
"in",
"self",
".",
"_cluster_hits",
".",
"dtype",
".",
"fields",
":",
"self",
".",
"_cluster_hits",
"[",
"cluster_hits_field_name",
"]",
"[",
":",
"n_hits",
"]",
"=",
"hits",
"[",
"field_name",
"]",
"noisy_pixels_array",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"noisy_pixels",
"is",
"None",
"else",
"np",
".",
"array",
"(",
"noisy_pixels",
")",
"if",
"noisy_pixels_array",
".",
"shape",
"[",
"0",
"]",
"!=",
"0",
":",
"noisy_pixels_max_range",
"=",
"np",
".",
"array",
"(",
"[",
"max",
"(",
"0",
",",
"np",
".",
"max",
"(",
"noisy_pixels_array",
"[",
":",
",",
"0",
"]",
")",
")",
",",
"max",
"(",
"0",
",",
"np",
".",
"max",
"(",
"noisy_pixels_array",
"[",
":",
",",
"1",
"]",
")",
")",
"]",
")",
"noisy_pixels",
"=",
"np",
".",
"zeros",
"(",
"noisy_pixels_max_range",
"+",
"1",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"noisy_pixels",
"[",
"noisy_pixels_array",
"[",
":",
",",
"0",
"]",
",",
"noisy_pixels_array",
"[",
":",
",",
"1",
"]",
"]",
"=",
"1",
"else",
":",
"noisy_pixels",
"=",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"disabled_pixels_array",
"=",
"np",
".",
"array",
"(",
"[",
"]",
")",
"if",
"disabled_pixels",
"is",
"None",
"else",
"np",
".",
"array",
"(",
"disabled_pixels",
")",
"if",
"disabled_pixels_array",
".",
"shape",
"[",
"0",
"]",
"!=",
"0",
":",
"disabled_pixels_max_range",
"=",
"np",
".",
"array",
"(",
"[",
"np",
".",
"max",
"(",
"disabled_pixels_array",
"[",
":",
",",
"0",
"]",
")",
",",
"np",
".",
"max",
"(",
"disabled_pixels_array",
"[",
":",
",",
"1",
"]",
")",
"]",
")",
"disabled_pixels",
"=",
"np",
".",
"zeros",
"(",
"disabled_pixels_max_range",
"+",
"1",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"disabled_pixels",
"[",
"disabled_pixels_array",
"[",
":",
",",
"0",
"]",
",",
"disabled_pixels_array",
"[",
":",
",",
"1",
"]",
"]",
"=",
"1",
"else",
":",
"disabled_pixels",
"=",
"np",
".",
"zeros",
"(",
"(",
"0",
",",
"0",
")",
",",
"dtype",
"=",
"np",
".",
"bool",
")",
"# col_dtype = self._cluster_hits.dtype.fields[\"column\"][0]",
"# row_dtype = self._cluster_hits.dtype.fields[\"row\"][0]",
"# mask_dtype = {\"names\": [\"column\", \"row\"],",
"# \"formats\": [col_dtype, row_dtype]}",
"# noisy_pixels = np.recarray(noisy_pixels_array.shape[0], dtype=mask_dtype)",
"# noisy_pixels[:] = [(item[0], item[1]) for item in noisy_pixels_array]",
"# disabled_pixels = np.recarray(disabled_pixels_array.shape[0], dtype=mask_dtype)",
"# disabled_pixels[:] = [(item[0], item[1]) for item in disabled_pixels_array]",
"n_clusters",
"=",
"self",
".",
"cluster_functions",
".",
"_cluster_hits",
"(",
"# Set n_clusters to new size",
"hits",
"=",
"self",
".",
"_cluster_hits",
"[",
":",
"n_hits",
"]",
",",
"clusters",
"=",
"self",
".",
"_clusters",
"[",
":",
"n_hits",
"]",
",",
"assigned_hit_array",
"=",
"self",
".",
"_assigned_hit_array",
"[",
":",
"n_hits",
"]",
",",
"cluster_hit_indices",
"=",
"self",
".",
"_cluster_hit_indices",
"[",
":",
"n_hits",
"]",
",",
"column_cluster_distance",
"=",
"self",
".",
"_column_cluster_distance",
",",
"row_cluster_distance",
"=",
"self",
".",
"_row_cluster_distance",
",",
"frame_cluster_distance",
"=",
"self",
".",
"_frame_cluster_distance",
",",
"min_hit_charge",
"=",
"self",
".",
"_min_hit_charge",
",",
"max_hit_charge",
"=",
"self",
".",
"_max_hit_charge",
",",
"ignore_same_hits",
"=",
"self",
".",
"_ignore_same_hits",
",",
"noisy_pixels",
"=",
"noisy_pixels",
",",
"disabled_pixels",
"=",
"disabled_pixels",
")",
"self",
".",
"_cluster_hits",
".",
"dtype",
".",
"names",
"=",
"self",
".",
"_map_hit_field_names",
"(",
"self",
".",
"_cluster_hits",
".",
"dtype",
".",
"names",
")",
"# Rename the data fields for the result",
"self",
".",
"_clusters",
".",
"dtype",
".",
"names",
"=",
"self",
".",
"_map_cluster_field_names",
"(",
"self",
".",
"_clusters",
".",
"dtype",
".",
"names",
")",
"# Rename the data fields for the result",
"return",
"self",
".",
"_cluster_hits",
"[",
":",
"n_hits",
"]",
",",
"self",
".",
"_clusters",
"[",
":",
"n_clusters",
"]"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | HitClusterizer._check_struct_compatibility | Takes the hit array and checks if the important data fields have the same data type than the hit clustered array and that the field names are correct. | pixel_clusterizer/clusterizer.py | def _check_struct_compatibility(self, hits):
''' Takes the hit array and checks if the important data fields have the same data type than the hit clustered array and that the field names are correct.'''
for key, _ in self._cluster_hits_descr:
if key in self._hit_fields_mapping_inverse:
mapped_key = self._hit_fields_mapping_inverse[key]
else:
mapped_key = key
# Only check hit fields that contain hit information
if mapped_key in ['cluster_ID', 'is_seed', 'cluster_size', 'n_cluster']:
continue
if key not in hits.dtype.names:
raise TypeError('Required hit field "%s" not found.' % key)
if self._cluster_hits.dtype[mapped_key] != hits.dtype[key]:
raise TypeError('The dtype for hit data field "%s" does not match. Got/expected: %s/%s.' % (key, hits.dtype[key], self._cluster_hits.dtype[mapped_key]))
additional_hit_fields = set(hits.dtype.names) - set([key for key, val in self._cluster_hits_descr])
if additional_hit_fields:
logging.warning('Found additional hit fields: %s' % ", ".join(additional_hit_fields)) | def _check_struct_compatibility(self, hits):
''' Takes the hit array and checks if the important data fields have the same data type than the hit clustered array and that the field names are correct.'''
for key, _ in self._cluster_hits_descr:
if key in self._hit_fields_mapping_inverse:
mapped_key = self._hit_fields_mapping_inverse[key]
else:
mapped_key = key
# Only check hit fields that contain hit information
if mapped_key in ['cluster_ID', 'is_seed', 'cluster_size', 'n_cluster']:
continue
if key not in hits.dtype.names:
raise TypeError('Required hit field "%s" not found.' % key)
if self._cluster_hits.dtype[mapped_key] != hits.dtype[key]:
raise TypeError('The dtype for hit data field "%s" does not match. Got/expected: %s/%s.' % (key, hits.dtype[key], self._cluster_hits.dtype[mapped_key]))
additional_hit_fields = set(hits.dtype.names) - set([key for key, val in self._cluster_hits_descr])
if additional_hit_fields:
logging.warning('Found additional hit fields: %s' % ", ".join(additional_hit_fields)) | [
"Takes",
"the",
"hit",
"array",
"and",
"checks",
"if",
"the",
"important",
"data",
"fields",
"have",
"the",
"same",
"data",
"type",
"than",
"the",
"hit",
"clustered",
"array",
"and",
"that",
"the",
"field",
"names",
"are",
"correct",
"."
] | SiLab-Bonn/pixel_clusterizer | python | https://github.com/SiLab-Bonn/pixel_clusterizer/blob/d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d/pixel_clusterizer/clusterizer.py#L422-L438 | [
"def",
"_check_struct_compatibility",
"(",
"self",
",",
"hits",
")",
":",
"for",
"key",
",",
"_",
"in",
"self",
".",
"_cluster_hits_descr",
":",
"if",
"key",
"in",
"self",
".",
"_hit_fields_mapping_inverse",
":",
"mapped_key",
"=",
"self",
".",
"_hit_fields_mapping_inverse",
"[",
"key",
"]",
"else",
":",
"mapped_key",
"=",
"key",
"# Only check hit fields that contain hit information",
"if",
"mapped_key",
"in",
"[",
"'cluster_ID'",
",",
"'is_seed'",
",",
"'cluster_size'",
",",
"'n_cluster'",
"]",
":",
"continue",
"if",
"key",
"not",
"in",
"hits",
".",
"dtype",
".",
"names",
":",
"raise",
"TypeError",
"(",
"'Required hit field \"%s\" not found.'",
"%",
"key",
")",
"if",
"self",
".",
"_cluster_hits",
".",
"dtype",
"[",
"mapped_key",
"]",
"!=",
"hits",
".",
"dtype",
"[",
"key",
"]",
":",
"raise",
"TypeError",
"(",
"'The dtype for hit data field \"%s\" does not match. Got/expected: %s/%s.'",
"%",
"(",
"key",
",",
"hits",
".",
"dtype",
"[",
"key",
"]",
",",
"self",
".",
"_cluster_hits",
".",
"dtype",
"[",
"mapped_key",
"]",
")",
")",
"additional_hit_fields",
"=",
"set",
"(",
"hits",
".",
"dtype",
".",
"names",
")",
"-",
"set",
"(",
"[",
"key",
"for",
"key",
",",
"val",
"in",
"self",
".",
"_cluster_hits_descr",
"]",
")",
"if",
"additional_hit_fields",
":",
"logging",
".",
"warning",
"(",
"'Found additional hit fields: %s'",
"%",
"\", \"",
".",
"join",
"(",
"additional_hit_fields",
")",
")"
] | d2c8c3072fb03ebb7c6a3e8c57350fbbe38efd4d |
test | add_mod | Create a tree.{Complement, LookAhead, Neg, Until} | pyrser/dsl.py | def add_mod(self, seq, mod):
"""Create a tree.{Complement, LookAhead, Neg, Until}"""
modstr = self.value(mod)
if modstr == '~':
seq.parser_tree = parsing.Complement(seq.parser_tree)
elif modstr == '!!':
seq.parser_tree = parsing.LookAhead(seq.parser_tree)
elif modstr == '!':
seq.parser_tree = parsing.Neg(seq.parser_tree)
elif modstr == '->':
seq.parser_tree = parsing.Until(seq.parser_tree)
return True | def add_mod(self, seq, mod):
"""Create a tree.{Complement, LookAhead, Neg, Until}"""
modstr = self.value(mod)
if modstr == '~':
seq.parser_tree = parsing.Complement(seq.parser_tree)
elif modstr == '!!':
seq.parser_tree = parsing.LookAhead(seq.parser_tree)
elif modstr == '!':
seq.parser_tree = parsing.Neg(seq.parser_tree)
elif modstr == '->':
seq.parser_tree = parsing.Until(seq.parser_tree)
return True | [
"Create",
"a",
"tree",
".",
"{",
"Complement",
"LookAhead",
"Neg",
"Until",
"}"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L495-L506 | [
"def",
"add_mod",
"(",
"self",
",",
"seq",
",",
"mod",
")",
":",
"modstr",
"=",
"self",
".",
"value",
"(",
"mod",
")",
"if",
"modstr",
"==",
"'~'",
":",
"seq",
".",
"parser_tree",
"=",
"parsing",
".",
"Complement",
"(",
"seq",
".",
"parser_tree",
")",
"elif",
"modstr",
"==",
"'!!'",
":",
"seq",
".",
"parser_tree",
"=",
"parsing",
".",
"LookAhead",
"(",
"seq",
".",
"parser_tree",
")",
"elif",
"modstr",
"==",
"'!'",
":",
"seq",
".",
"parser_tree",
"=",
"parsing",
".",
"Neg",
"(",
"seq",
".",
"parser_tree",
")",
"elif",
"modstr",
"==",
"'->'",
":",
"seq",
".",
"parser_tree",
"=",
"parsing",
".",
"Until",
"(",
"seq",
".",
"parser_tree",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_ruleclause_name | Create a tree.Rule | pyrser/dsl.py | def add_ruleclause_name(self, ns_name, rid) -> bool:
"""Create a tree.Rule"""
ns_name.parser_tree = parsing.Rule(self.value(rid))
return True | def add_ruleclause_name(self, ns_name, rid) -> bool:
"""Create a tree.Rule"""
ns_name.parser_tree = parsing.Rule(self.value(rid))
return True | [
"Create",
"a",
"tree",
".",
"Rule"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L510-L513 | [
"def",
"add_ruleclause_name",
"(",
"self",
",",
"ns_name",
",",
"rid",
")",
"->",
"bool",
":",
"ns_name",
".",
"parser_tree",
"=",
"parsing",
".",
"Rule",
"(",
"self",
".",
"value",
"(",
"rid",
")",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_rules | Attach a parser tree to the dict of rules | pyrser/dsl.py | def add_rules(self, bnf, r) -> bool:
"""Attach a parser tree to the dict of rules"""
bnf[r.rulename] = r.parser_tree
return True | def add_rules(self, bnf, r) -> bool:
"""Attach a parser tree to the dict of rules"""
bnf[r.rulename] = r.parser_tree
return True | [
"Attach",
"a",
"parser",
"tree",
"to",
"the",
"dict",
"of",
"rules"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L517-L520 | [
"def",
"add_rules",
"(",
"self",
",",
"bnf",
",",
"r",
")",
"->",
"bool",
":",
"bnf",
"[",
"r",
".",
"rulename",
"]",
"=",
"r",
".",
"parser_tree",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_rule | Add the rule name | pyrser/dsl.py | def add_rule(self, rule, rn, alts) -> bool:
"""Add the rule name"""
rule.rulename = self.value(rn)
rule.parser_tree = alts.parser_tree
return True | def add_rule(self, rule, rn, alts) -> bool:
"""Add the rule name"""
rule.rulename = self.value(rn)
rule.parser_tree = alts.parser_tree
return True | [
"Add",
"the",
"rule",
"name"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L524-L528 | [
"def",
"add_rule",
"(",
"self",
",",
"rule",
",",
"rn",
",",
"alts",
")",
"->",
"bool",
":",
"rule",
".",
"rulename",
"=",
"self",
".",
"value",
"(",
"rn",
")",
"rule",
".",
"parser_tree",
"=",
"alts",
".",
"parser_tree",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_sequences | Create a tree.Seq | pyrser/dsl.py | def add_sequences(self, sequences, cla) -> bool:
"""Create a tree.Seq"""
if not hasattr(sequences, 'parser_tree'):
# forward sublevel of sequence as is
sequences.parser_tree = cla.parser_tree
else:
oldnode = sequences
if isinstance(oldnode.parser_tree, parsing.Seq):
oldpt = list(oldnode.parser_tree.ptlist)
else:
oldpt = [oldnode.parser_tree]
oldpt.append(cla.parser_tree)
sequences.parser_tree = parsing.Seq(*tuple(oldpt))
return True | def add_sequences(self, sequences, cla) -> bool:
"""Create a tree.Seq"""
if not hasattr(sequences, 'parser_tree'):
# forward sublevel of sequence as is
sequences.parser_tree = cla.parser_tree
else:
oldnode = sequences
if isinstance(oldnode.parser_tree, parsing.Seq):
oldpt = list(oldnode.parser_tree.ptlist)
else:
oldpt = [oldnode.parser_tree]
oldpt.append(cla.parser_tree)
sequences.parser_tree = parsing.Seq(*tuple(oldpt))
return True | [
"Create",
"a",
"tree",
".",
"Seq"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L532-L545 | [
"def",
"add_sequences",
"(",
"self",
",",
"sequences",
",",
"cla",
")",
"->",
"bool",
":",
"if",
"not",
"hasattr",
"(",
"sequences",
",",
"'parser_tree'",
")",
":",
"# forward sublevel of sequence as is",
"sequences",
".",
"parser_tree",
"=",
"cla",
".",
"parser_tree",
"else",
":",
"oldnode",
"=",
"sequences",
"if",
"isinstance",
"(",
"oldnode",
".",
"parser_tree",
",",
"parsing",
".",
"Seq",
")",
":",
"oldpt",
"=",
"list",
"(",
"oldnode",
".",
"parser_tree",
".",
"ptlist",
")",
"else",
":",
"oldpt",
"=",
"[",
"oldnode",
".",
"parser_tree",
"]",
"oldpt",
".",
"append",
"(",
"cla",
".",
"parser_tree",
")",
"sequences",
".",
"parser_tree",
"=",
"parsing",
".",
"Seq",
"(",
"*",
"tuple",
"(",
"oldpt",
")",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_alt | Create a tree.Alt | pyrser/dsl.py | def add_alt(self, alternatives, alt) -> bool:
"""Create a tree.Alt"""
if not hasattr(alternatives, 'parser_tree'):
# forward sublevel of alt as is
if hasattr(alt, 'parser_tree'):
alternatives.parser_tree = alt.parser_tree
else:
alternatives.parser_tree = alt
else:
oldnode = alternatives
if isinstance(oldnode.parser_tree, parsing.Alt):
oldpt = list(oldnode.parser_tree.ptlist)
else:
oldpt = [oldnode.parser_tree]
oldpt.append(alt.parser_tree)
alternatives.parser_tree = parsing.Alt(*tuple(oldpt))
return True | def add_alt(self, alternatives, alt) -> bool:
"""Create a tree.Alt"""
if not hasattr(alternatives, 'parser_tree'):
# forward sublevel of alt as is
if hasattr(alt, 'parser_tree'):
alternatives.parser_tree = alt.parser_tree
else:
alternatives.parser_tree = alt
else:
oldnode = alternatives
if isinstance(oldnode.parser_tree, parsing.Alt):
oldpt = list(oldnode.parser_tree.ptlist)
else:
oldpt = [oldnode.parser_tree]
oldpt.append(alt.parser_tree)
alternatives.parser_tree = parsing.Alt(*tuple(oldpt))
return True | [
"Create",
"a",
"tree",
".",
"Alt"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L549-L565 | [
"def",
"add_alt",
"(",
"self",
",",
"alternatives",
",",
"alt",
")",
"->",
"bool",
":",
"if",
"not",
"hasattr",
"(",
"alternatives",
",",
"'parser_tree'",
")",
":",
"# forward sublevel of alt as is",
"if",
"hasattr",
"(",
"alt",
",",
"'parser_tree'",
")",
":",
"alternatives",
".",
"parser_tree",
"=",
"alt",
".",
"parser_tree",
"else",
":",
"alternatives",
".",
"parser_tree",
"=",
"alt",
"else",
":",
"oldnode",
"=",
"alternatives",
"if",
"isinstance",
"(",
"oldnode",
".",
"parser_tree",
",",
"parsing",
".",
"Alt",
")",
":",
"oldpt",
"=",
"list",
"(",
"oldnode",
".",
"parser_tree",
".",
"ptlist",
")",
"else",
":",
"oldpt",
"=",
"[",
"oldnode",
".",
"parser_tree",
"]",
"oldpt",
".",
"append",
"(",
"alt",
".",
"parser_tree",
")",
"alternatives",
".",
"parser_tree",
"=",
"parsing",
".",
"Alt",
"(",
"*",
"tuple",
"(",
"oldpt",
")",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_read_sqstring | Add a read_char/read_text primitive from simple quote string | pyrser/dsl.py | def add_read_sqstring(self, sequence, s):
"""Add a read_char/read_text primitive from simple quote string"""
v = self.value(s).strip("'")
if len(v) > 1:
sequence.parser_tree = parsing.Text(v)
return True
sequence.parser_tree = parsing.Char(v)
return True | def add_read_sqstring(self, sequence, s):
"""Add a read_char/read_text primitive from simple quote string"""
v = self.value(s).strip("'")
if len(v) > 1:
sequence.parser_tree = parsing.Text(v)
return True
sequence.parser_tree = parsing.Char(v)
return True | [
"Add",
"a",
"read_char",
"/",
"read_text",
"primitive",
"from",
"simple",
"quote",
"string"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L569-L576 | [
"def",
"add_read_sqstring",
"(",
"self",
",",
"sequence",
",",
"s",
")",
":",
"v",
"=",
"self",
".",
"value",
"(",
"s",
")",
".",
"strip",
"(",
"\"'\"",
")",
"if",
"len",
"(",
"v",
")",
">",
"1",
":",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Text",
"(",
"v",
")",
"return",
"True",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Char",
"(",
"v",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_range | Add a read_range primitive | pyrser/dsl.py | def add_range(self, sequence, begin, end):
"""Add a read_range primitive"""
sequence.parser_tree = parsing.Range(self.value(begin).strip("'"),
self.value(end).strip("'"))
return True | def add_range(self, sequence, begin, end):
"""Add a read_range primitive"""
sequence.parser_tree = parsing.Range(self.value(begin).strip("'"),
self.value(end).strip("'"))
return True | [
"Add",
"a",
"read_range",
"primitive"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L591-L595 | [
"def",
"add_range",
"(",
"self",
",",
"sequence",
",",
"begin",
",",
"end",
")",
":",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Range",
"(",
"self",
".",
"value",
"(",
"begin",
")",
".",
"strip",
"(",
"\"'\"",
")",
",",
"self",
".",
"value",
"(",
"end",
")",
".",
"strip",
"(",
"\"'\"",
")",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_rpt | Add a repeater to the previous sequence | pyrser/dsl.py | def add_rpt(self, sequence, mod, pt):
"""Add a repeater to the previous sequence"""
modstr = self.value(mod)
if modstr == '!!':
# cursor on the REPEATER
self._stream.restore_context()
# log the error
self.diagnostic.notify(
error.Severity.ERROR,
"Cannot repeat a lookahead rule",
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
if modstr == '!':
# cursor on the REPEATER
self._stream.restore_context()
# log the error
self.diagnostic.notify(
error.Severity.ERROR,
"Cannot repeat a negated rule",
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
oldnode = sequence
sequence.parser_tree = pt.functor(oldnode.parser_tree)
return True | def add_rpt(self, sequence, mod, pt):
"""Add a repeater to the previous sequence"""
modstr = self.value(mod)
if modstr == '!!':
# cursor on the REPEATER
self._stream.restore_context()
# log the error
self.diagnostic.notify(
error.Severity.ERROR,
"Cannot repeat a lookahead rule",
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
if modstr == '!':
# cursor on the REPEATER
self._stream.restore_context()
# log the error
self.diagnostic.notify(
error.Severity.ERROR,
"Cannot repeat a negated rule",
error.LocationInfo.from_stream(self._stream, is_error=True)
)
raise self.diagnostic
oldnode = sequence
sequence.parser_tree = pt.functor(oldnode.parser_tree)
return True | [
"Add",
"a",
"repeater",
"to",
"the",
"previous",
"sequence"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L599-L624 | [
"def",
"add_rpt",
"(",
"self",
",",
"sequence",
",",
"mod",
",",
"pt",
")",
":",
"modstr",
"=",
"self",
".",
"value",
"(",
"mod",
")",
"if",
"modstr",
"==",
"'!!'",
":",
"# cursor on the REPEATER",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")",
"# log the error",
"self",
".",
"diagnostic",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Cannot repeat a lookahead rule\"",
",",
"error",
".",
"LocationInfo",
".",
"from_stream",
"(",
"self",
".",
"_stream",
",",
"is_error",
"=",
"True",
")",
")",
"raise",
"self",
".",
"diagnostic",
"if",
"modstr",
"==",
"'!'",
":",
"# cursor on the REPEATER",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")",
"# log the error",
"self",
".",
"diagnostic",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Cannot repeat a negated rule\"",
",",
"error",
".",
"LocationInfo",
".",
"from_stream",
"(",
"self",
".",
"_stream",
",",
"is_error",
"=",
"True",
")",
")",
"raise",
"self",
".",
"diagnostic",
"oldnode",
"=",
"sequence",
"sequence",
".",
"parser_tree",
"=",
"pt",
".",
"functor",
"(",
"oldnode",
".",
"parser_tree",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_capture | Create a tree.Capture | pyrser/dsl.py | def add_capture(self, sequence, cpt):
"""Create a tree.Capture"""
cpt_value = self.value(cpt)
sequence.parser_tree = parsing.Capture(cpt_value, sequence.parser_tree)
return True | def add_capture(self, sequence, cpt):
"""Create a tree.Capture"""
cpt_value = self.value(cpt)
sequence.parser_tree = parsing.Capture(cpt_value, sequence.parser_tree)
return True | [
"Create",
"a",
"tree",
".",
"Capture"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L628-L632 | [
"def",
"add_capture",
"(",
"self",
",",
"sequence",
",",
"cpt",
")",
":",
"cpt_value",
"=",
"self",
".",
"value",
"(",
"cpt",
")",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Capture",
"(",
"cpt_value",
",",
"sequence",
".",
"parser_tree",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_bind | Create a tree.Bind | pyrser/dsl.py | def add_bind(self, sequence, cpt):
"""Create a tree.Bind"""
cpt_value = self.value(cpt)
sequence.parser_tree = parsing.Bind(cpt_value, sequence.parser_tree)
return True | def add_bind(self, sequence, cpt):
"""Create a tree.Bind"""
cpt_value = self.value(cpt)
sequence.parser_tree = parsing.Bind(cpt_value, sequence.parser_tree)
return True | [
"Create",
"a",
"tree",
".",
"Bind"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L636-L640 | [
"def",
"add_bind",
"(",
"self",
",",
"sequence",
",",
"cpt",
")",
":",
"cpt_value",
"=",
"self",
".",
"value",
"(",
"cpt",
")",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Bind",
"(",
"cpt_value",
",",
"sequence",
".",
"parser_tree",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_hook | Create a tree.Hook | pyrser/dsl.py | def add_hook(self, sequence, h):
"""Create a tree.Hook"""
sequence.parser_tree = parsing.Hook(h.name, h.listparam)
return True | def add_hook(self, sequence, h):
"""Create a tree.Hook"""
sequence.parser_tree = parsing.Hook(h.name, h.listparam)
return True | [
"Create",
"a",
"tree",
".",
"Hook"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L672-L675 | [
"def",
"add_hook",
"(",
"self",
",",
"sequence",
",",
"h",
")",
":",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Hook",
"(",
"h",
".",
"name",
",",
"h",
".",
"listparam",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | param_num | Parse a int in parameter list | pyrser/dsl.py | def param_num(self, param, n):
"""Parse a int in parameter list"""
param.pair = (int(self.value(n)), int)
return True | def param_num(self, param, n):
"""Parse a int in parameter list"""
param.pair = (int(self.value(n)), int)
return True | [
"Parse",
"a",
"int",
"in",
"parameter",
"list"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L679-L682 | [
"def",
"param_num",
"(",
"self",
",",
"param",
",",
"n",
")",
":",
"param",
".",
"pair",
"=",
"(",
"int",
"(",
"self",
".",
"value",
"(",
"n",
")",
")",
",",
"int",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | param_str | Parse a str in parameter list | pyrser/dsl.py | def param_str(self, param, s):
"""Parse a str in parameter list"""
param.pair = (self.value(s).strip('"'), str)
return True | def param_str(self, param, s):
"""Parse a str in parameter list"""
param.pair = (self.value(s).strip('"'), str)
return True | [
"Parse",
"a",
"str",
"in",
"parameter",
"list"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L686-L689 | [
"def",
"param_str",
"(",
"self",
",",
"param",
",",
"s",
")",
":",
"param",
".",
"pair",
"=",
"(",
"self",
".",
"value",
"(",
"s",
")",
".",
"strip",
"(",
"'\"'",
")",
",",
"str",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | param_char | Parse a char in parameter list | pyrser/dsl.py | def param_char(self, param, c):
"""Parse a char in parameter list"""
param.pair = (self.value(c).strip("'"), str)
return True | def param_char(self, param, c):
"""Parse a char in parameter list"""
param.pair = (self.value(c).strip("'"), str)
return True | [
"Parse",
"a",
"char",
"in",
"parameter",
"list"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L693-L696 | [
"def",
"param_char",
"(",
"self",
",",
"param",
",",
"c",
")",
":",
"param",
".",
"pair",
"=",
"(",
"self",
".",
"value",
"(",
"c",
")",
".",
"strip",
"(",
"\"'\"",
")",
",",
"str",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | param_id | Parse a node name in parameter list | pyrser/dsl.py | def param_id(self, param, i):
"""Parse a node name in parameter list"""
param.pair = (self.value(i), parsing.Node)
return True | def param_id(self, param, i):
"""Parse a node name in parameter list"""
param.pair = (self.value(i), parsing.Node)
return True | [
"Parse",
"a",
"node",
"name",
"in",
"parameter",
"list"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L700-L703 | [
"def",
"param_id",
"(",
"self",
",",
"param",
",",
"i",
")",
":",
"param",
".",
"pair",
"=",
"(",
"self",
".",
"value",
"(",
"i",
")",
",",
"parsing",
".",
"Node",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | hook_name | Parse a hook name | pyrser/dsl.py | def hook_name(self, hook, n):
"""Parse a hook name"""
hook.name = self.value(n)
hook.listparam = []
return True | def hook_name(self, hook, n):
"""Parse a hook name"""
hook.name = self.value(n)
hook.listparam = []
return True | [
"Parse",
"a",
"hook",
"name"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L707-L711 | [
"def",
"hook_name",
"(",
"self",
",",
"hook",
",",
"n",
")",
":",
"hook",
".",
"name",
"=",
"self",
".",
"value",
"(",
"n",
")",
"hook",
".",
"listparam",
"=",
"[",
"]",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | hook_param | Parse a hook parameter | pyrser/dsl.py | def hook_param(self, hook, p):
"""Parse a hook parameter"""
hook.listparam.append(p.pair)
return True | def hook_param(self, hook, p):
"""Parse a hook parameter"""
hook.listparam.append(p.pair)
return True | [
"Parse",
"a",
"hook",
"parameter"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L715-L718 | [
"def",
"hook_param",
"(",
"self",
",",
"hook",
",",
"p",
")",
":",
"hook",
".",
"listparam",
".",
"append",
"(",
"p",
".",
"pair",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_directive2 | Add a directive in the sequence | pyrser/dsl.py | def add_directive2(self, sequence, d, s):
"""Add a directive in the sequence"""
sequence.parser_tree = parsing.Directive2(
d.name,
d.listparam,
s.parser_tree
)
return True | def add_directive2(self, sequence, d, s):
"""Add a directive in the sequence"""
sequence.parser_tree = parsing.Directive2(
d.name,
d.listparam,
s.parser_tree
)
return True | [
"Add",
"a",
"directive",
"in",
"the",
"sequence"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L722-L729 | [
"def",
"add_directive2",
"(",
"self",
",",
"sequence",
",",
"d",
",",
"s",
")",
":",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Directive2",
"(",
"d",
".",
"name",
",",
"d",
".",
"listparam",
",",
"s",
".",
"parser_tree",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | add_directive | Add a directive in the sequence | pyrser/dsl.py | def add_directive(self, sequence, d, s):
"""Add a directive in the sequence"""
if d.name in meta._directives:
the_class = meta._directives[d.name]
sequence.parser_tree = parsing.Directive(the_class(), d.listparam,
s.parser_tree)
elif d.name in meta._decorators:
the_class = meta._decorators[d.name]
sequence.parser_tree = parsing.Decorator(the_class, d.listparam,
s.parser_tree)
else:
raise TypeError("Unkown directive or decorator %s" % d.name)
return True | def add_directive(self, sequence, d, s):
"""Add a directive in the sequence"""
if d.name in meta._directives:
the_class = meta._directives[d.name]
sequence.parser_tree = parsing.Directive(the_class(), d.listparam,
s.parser_tree)
elif d.name in meta._decorators:
the_class = meta._decorators[d.name]
sequence.parser_tree = parsing.Decorator(the_class, d.listparam,
s.parser_tree)
else:
raise TypeError("Unkown directive or decorator %s" % d.name)
return True | [
"Add",
"a",
"directive",
"in",
"the",
"sequence"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L733-L745 | [
"def",
"add_directive",
"(",
"self",
",",
"sequence",
",",
"d",
",",
"s",
")",
":",
"if",
"d",
".",
"name",
"in",
"meta",
".",
"_directives",
":",
"the_class",
"=",
"meta",
".",
"_directives",
"[",
"d",
".",
"name",
"]",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Directive",
"(",
"the_class",
"(",
")",
",",
"d",
".",
"listparam",
",",
"s",
".",
"parser_tree",
")",
"elif",
"d",
".",
"name",
"in",
"meta",
".",
"_decorators",
":",
"the_class",
"=",
"meta",
".",
"_decorators",
"[",
"d",
".",
"name",
"]",
"sequence",
".",
"parser_tree",
"=",
"parsing",
".",
"Decorator",
"(",
"the_class",
",",
"d",
".",
"listparam",
",",
"s",
".",
"parser_tree",
")",
"else",
":",
"raise",
"TypeError",
"(",
"\"Unkown directive or decorator %s\"",
"%",
"d",
".",
"name",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | EBNF.get_rules | Parse the DSL and provide a dictionnaries of all resulting rules.
Call by the MetaGrammar class.
TODO: could be done in the rules property of parsing.BasicParser??? | pyrser/dsl.py | def get_rules(self) -> parsing.Node:
"""
Parse the DSL and provide a dictionnaries of all resulting rules.
Call by the MetaGrammar class.
TODO: could be done in the rules property of parsing.BasicParser???
"""
res = None
try:
res = self.eval_rule('bnf_dsl')
if not res:
# we fail to parse, but error is not set
self.diagnostic.notify(
error.Severity.ERROR,
"Parse error in '%s' in EBNF bnf" % self._lastRule,
error.LocationInfo.from_maxstream(self._stream)
)
raise self.diagnostic
except error.Diagnostic as d:
d.notify(
error.Severity.ERROR,
"Parse error in '%s' in EBNF bnf" % self._lastRule
)
raise d
return res | def get_rules(self) -> parsing.Node:
"""
Parse the DSL and provide a dictionnaries of all resulting rules.
Call by the MetaGrammar class.
TODO: could be done in the rules property of parsing.BasicParser???
"""
res = None
try:
res = self.eval_rule('bnf_dsl')
if not res:
# we fail to parse, but error is not set
self.diagnostic.notify(
error.Severity.ERROR,
"Parse error in '%s' in EBNF bnf" % self._lastRule,
error.LocationInfo.from_maxstream(self._stream)
)
raise self.diagnostic
except error.Diagnostic as d:
d.notify(
error.Severity.ERROR,
"Parse error in '%s' in EBNF bnf" % self._lastRule
)
raise d
return res | [
"Parse",
"the",
"DSL",
"and",
"provide",
"a",
"dictionnaries",
"of",
"all",
"resulting",
"rules",
".",
"Call",
"by",
"the",
"MetaGrammar",
"class",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/dsl.py#L15-L39 | [
"def",
"get_rules",
"(",
"self",
")",
"->",
"parsing",
".",
"Node",
":",
"res",
"=",
"None",
"try",
":",
"res",
"=",
"self",
".",
"eval_rule",
"(",
"'bnf_dsl'",
")",
"if",
"not",
"res",
":",
"# we fail to parse, but error is not set",
"self",
".",
"diagnostic",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Parse error in '%s' in EBNF bnf\"",
"%",
"self",
".",
"_lastRule",
",",
"error",
".",
"LocationInfo",
".",
"from_maxstream",
"(",
"self",
".",
"_stream",
")",
")",
"raise",
"self",
".",
"diagnostic",
"except",
"error",
".",
"Diagnostic",
"as",
"d",
":",
"d",
".",
"notify",
"(",
"error",
".",
"Severity",
".",
"ERROR",
",",
"\"Parse error in '%s' in EBNF bnf\"",
"%",
"self",
".",
"_lastRule",
")",
"raise",
"d",
"return",
"res"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | to_yml | Allow to get the YML string representation of a Node.::
from pyrser.passes import to_yml
t = Node()
...
print(str(t.to_yml())) | pyrser/passes/to_yml.py | def to_yml(self):
"""
Allow to get the YML string representation of a Node.::
from pyrser.passes import to_yml
t = Node()
...
print(str(t.to_yml()))
"""
pp = fmt.tab([])
to_yml_item(self, pp.lsdata, "")
return str(pp) | def to_yml(self):
"""
Allow to get the YML string representation of a Node.::
from pyrser.passes import to_yml
t = Node()
...
print(str(t.to_yml()))
"""
pp = fmt.tab([])
to_yml_item(self, pp.lsdata, "")
return str(pp) | [
"Allow",
"to",
"get",
"the",
"YML",
"string",
"representation",
"of",
"a",
"Node",
".",
"::"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/to_yml.py#L11-L23 | [
"def",
"to_yml",
"(",
"self",
")",
":",
"pp",
"=",
"fmt",
".",
"tab",
"(",
"[",
"]",
")",
"to_yml_item",
"(",
"self",
",",
"pp",
".",
"lsdata",
",",
"\"\"",
")",
"return",
"str",
"(",
"pp",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | ignore_cxx | Consume comments and whitespace characters. | pyrser/directives/ignore.py | def ignore_cxx(self) -> bool:
"""Consume comments and whitespace characters."""
self._stream.save_context()
while not self.read_eof():
idxref = self._stream.index
if self._stream.peek_char in " \t\v\f\r\n":
while (not self.read_eof()
and self._stream.peek_char in " \t\v\f\r\n"):
self._stream.incpos()
if self.peek_text("//"):
while not self.read_eof() and not self.peek_char("\n"):
self._stream.incpos()
if not self.read_char("\n") and self.read_eof():
return self._stream.validate_context()
if self.peek_text("/*"):
while not self.read_eof() and not self.peek_text("*/"):
self._stream.incpos()
if not self.read_text("*/") and self.read_eof():
return self._stream.restore_context()
if idxref == self._stream.index:
break
return self._stream.validate_context() | def ignore_cxx(self) -> bool:
"""Consume comments and whitespace characters."""
self._stream.save_context()
while not self.read_eof():
idxref = self._stream.index
if self._stream.peek_char in " \t\v\f\r\n":
while (not self.read_eof()
and self._stream.peek_char in " \t\v\f\r\n"):
self._stream.incpos()
if self.peek_text("//"):
while not self.read_eof() and not self.peek_char("\n"):
self._stream.incpos()
if not self.read_char("\n") and self.read_eof():
return self._stream.validate_context()
if self.peek_text("/*"):
while not self.read_eof() and not self.peek_text("*/"):
self._stream.incpos()
if not self.read_text("*/") and self.read_eof():
return self._stream.restore_context()
if idxref == self._stream.index:
break
return self._stream.validate_context() | [
"Consume",
"comments",
"and",
"whitespace",
"characters",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/directives/ignore.py#L5-L26 | [
"def",
"ignore_cxx",
"(",
"self",
")",
"->",
"bool",
":",
"self",
".",
"_stream",
".",
"save_context",
"(",
")",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
":",
"idxref",
"=",
"self",
".",
"_stream",
".",
"index",
"if",
"self",
".",
"_stream",
".",
"peek_char",
"in",
"\" \\t\\v\\f\\r\\n\"",
":",
"while",
"(",
"not",
"self",
".",
"read_eof",
"(",
")",
"and",
"self",
".",
"_stream",
".",
"peek_char",
"in",
"\" \\t\\v\\f\\r\\n\"",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"if",
"self",
".",
"peek_text",
"(",
"\"//\"",
")",
":",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
"and",
"not",
"self",
".",
"peek_char",
"(",
"\"\\n\"",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"if",
"not",
"self",
".",
"read_char",
"(",
"\"\\n\"",
")",
"and",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")",
"if",
"self",
".",
"peek_text",
"(",
"\"/*\"",
")",
":",
"while",
"not",
"self",
".",
"read_eof",
"(",
")",
"and",
"not",
"self",
".",
"peek_text",
"(",
"\"*/\"",
")",
":",
"self",
".",
"_stream",
".",
"incpos",
"(",
")",
"if",
"not",
"self",
".",
"read_text",
"(",
"\"*/\"",
")",
"and",
"self",
".",
"read_eof",
"(",
")",
":",
"return",
"self",
".",
"_stream",
".",
"restore_context",
"(",
")",
"if",
"idxref",
"==",
"self",
".",
"_stream",
".",
"index",
":",
"break",
"return",
"self",
".",
"_stream",
".",
"validate_context",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | StateRegister.add_state | all state in the register have a uid | pyrser/ast/state.py | def add_state(self, s: State):
"""
all state in the register have a uid
"""
ids = id(s)
uid = len(self.states)
if ids not in self.states:
self.states[ids] = (uid, s) | def add_state(self, s: State):
"""
all state in the register have a uid
"""
ids = id(s)
uid = len(self.states)
if ids not in self.states:
self.states[ids] = (uid, s) | [
"all",
"state",
"in",
"the",
"register",
"have",
"a",
"uid"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L47-L54 | [
"def",
"add_state",
"(",
"self",
",",
"s",
":",
"State",
")",
":",
"ids",
"=",
"id",
"(",
"s",
")",
"uid",
"=",
"len",
"(",
"self",
".",
"states",
")",
"if",
"ids",
"not",
"in",
"self",
".",
"states",
":",
"self",
".",
"states",
"[",
"ids",
"]",
"=",
"(",
"uid",
",",
"s",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | StateRegister.to_dot | Provide a '.dot' representation of all State in the register. | pyrser/ast/state.py | def to_dot(self) -> str:
"""
Provide a '.dot' representation of all State in the register.
"""
txt = ""
txt += "digraph S%d {\n" % id(self)
if self.label is not None:
txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l')
txt += "\trankdir=LR;\n"
#txt += '\tlabelloc="t";\n'
txt += '\tgraph [labeljust=l, labelloc=t, nojustify=true];\n'
txt += "\tesep=1;\n"
txt += '\tranksep="equally";\n'
txt += "\tnode [shape = circle];\n"
txt += "\tsplines = ortho;\n"
for s in self.states.values():
txt += s[1].to_dot()
txt += "}\n"
return txt | def to_dot(self) -> str:
"""
Provide a '.dot' representation of all State in the register.
"""
txt = ""
txt += "digraph S%d {\n" % id(self)
if self.label is not None:
txt += '\tlabel="%s";\n' % (self.label + '\l').replace('\n', '\l')
txt += "\trankdir=LR;\n"
#txt += '\tlabelloc="t";\n'
txt += '\tgraph [labeljust=l, labelloc=t, nojustify=true];\n'
txt += "\tesep=1;\n"
txt += '\tranksep="equally";\n'
txt += "\tnode [shape = circle];\n"
txt += "\tsplines = ortho;\n"
for s in self.states.values():
txt += s[1].to_dot()
txt += "}\n"
return txt | [
"Provide",
"a",
".",
"dot",
"representation",
"of",
"all",
"State",
"in",
"the",
"register",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L65-L83 | [
"def",
"to_dot",
"(",
"self",
")",
"->",
"str",
":",
"txt",
"=",
"\"\"",
"txt",
"+=",
"\"digraph S%d {\\n\"",
"%",
"id",
"(",
"self",
")",
"if",
"self",
".",
"label",
"is",
"not",
"None",
":",
"txt",
"+=",
"'\\tlabel=\"%s\";\\n'",
"%",
"(",
"self",
".",
"label",
"+",
"'\\l'",
")",
".",
"replace",
"(",
"'\\n'",
",",
"'\\l'",
")",
"txt",
"+=",
"\"\\trankdir=LR;\\n\"",
"#txt += '\\tlabelloc=\"t\";\\n'",
"txt",
"+=",
"'\\tgraph [labeljust=l, labelloc=t, nojustify=true];\\n'",
"txt",
"+=",
"\"\\tesep=1;\\n\"",
"txt",
"+=",
"'\\tranksep=\"equally\";\\n'",
"txt",
"+=",
"\"\\tnode [shape = circle];\\n\"",
"txt",
"+=",
"\"\\tsplines = ortho;\\n\"",
"for",
"s",
"in",
"self",
".",
"states",
".",
"values",
"(",
")",
":",
"txt",
"+=",
"s",
"[",
"1",
"]",
".",
"to_dot",
"(",
")",
"txt",
"+=",
"\"}\\n\"",
"return",
"txt"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | StateRegister.to_dot_file | write a '.dot' file. | pyrser/ast/state.py | def to_dot_file(self, fname: str):
"""
write a '.dot' file.
"""
with open(fname, 'w') as f:
f.write(self.to_dot()) | def to_dot_file(self, fname: str):
"""
write a '.dot' file.
"""
with open(fname, 'w') as f:
f.write(self.to_dot()) | [
"write",
"a",
".",
"dot",
"file",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L85-L90 | [
"def",
"to_dot_file",
"(",
"self",
",",
"fname",
":",
"str",
")",
":",
"with",
"open",
"(",
"fname",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"to_dot",
"(",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | StateRegister.to_png_file | write a '.png' file. | pyrser/ast/state.py | def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
f.write(self.to_dot()) | def to_png_file(self, fname: str):
"""
write a '.png' file.
"""
cmd = pipes.Template()
cmd.append('dot -Tpng > %s' % fname, '-.')
with cmd.open('pipefile', 'w') as f:
f.write(self.to_dot()) | [
"write",
"a",
".",
"png",
"file",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L92-L99 | [
"def",
"to_png_file",
"(",
"self",
",",
"fname",
":",
"str",
")",
":",
"cmd",
"=",
"pipes",
".",
"Template",
"(",
")",
"cmd",
".",
"append",
"(",
"'dot -Tpng > %s'",
"%",
"fname",
",",
"'-.'",
")",
"with",
"cmd",
".",
"open",
"(",
"'pipefile'",
",",
"'w'",
")",
"as",
"f",
":",
"f",
".",
"write",
"(",
"self",
".",
"to_dot",
"(",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | StateRegister.to_fmt | Provide a useful representation of the register. | pyrser/ast/state.py | def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
infos.lsdata.append("events:" + repr(self.events))
infos.lsdata.append(
"named_events:" + repr(list(self.named_events.keys()))
)
infos.lsdata.append("uid_events:" + repr(list(self.uid_events.keys())))
return infos | def to_fmt(self) -> str:
"""
Provide a useful representation of the register.
"""
infos = fmt.end(";\n", [])
s = fmt.sep(', ', [])
for ids in sorted(self.states.keys()):
s.lsdata.append(str(ids))
infos.lsdata.append(fmt.block('(', ')', [s]))
infos.lsdata.append("events:" + repr(self.events))
infos.lsdata.append(
"named_events:" + repr(list(self.named_events.keys()))
)
infos.lsdata.append("uid_events:" + repr(list(self.uid_events.keys())))
return infos | [
"Provide",
"a",
"useful",
"representation",
"of",
"the",
"register",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L101-L115 | [
"def",
"to_fmt",
"(",
"self",
")",
"->",
"str",
":",
"infos",
"=",
"fmt",
".",
"end",
"(",
"\";\\n\"",
",",
"[",
"]",
")",
"s",
"=",
"fmt",
".",
"sep",
"(",
"', '",
",",
"[",
"]",
")",
"for",
"ids",
"in",
"sorted",
"(",
"self",
".",
"states",
".",
"keys",
"(",
")",
")",
":",
"s",
".",
"lsdata",
".",
"append",
"(",
"str",
"(",
"ids",
")",
")",
"infos",
".",
"lsdata",
".",
"append",
"(",
"fmt",
".",
"block",
"(",
"'('",
",",
"')'",
",",
"[",
"s",
"]",
")",
")",
"infos",
".",
"lsdata",
".",
"append",
"(",
"\"events:\"",
"+",
"repr",
"(",
"self",
".",
"events",
")",
")",
"infos",
".",
"lsdata",
".",
"append",
"(",
"\"named_events:\"",
"+",
"repr",
"(",
"list",
"(",
"self",
".",
"named_events",
".",
"keys",
"(",
")",
")",
")",
")",
"infos",
".",
"lsdata",
".",
"append",
"(",
"\"uid_events:\"",
"+",
"repr",
"(",
"list",
"(",
"self",
".",
"uid_events",
".",
"keys",
"(",
")",
")",
")",
")",
"return",
"infos"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | State.nextstate | Manage transition of state. | pyrser/ast/state.py | def nextstate(self, newstate, treenode=None, user_data=None):
"""
Manage transition of state.
"""
if newstate is None:
return self
if isinstance(newstate, State) and id(newstate) != id(self):
return newstate
elif isinstance(newstate, StateEvent):
self.state_register.named_events[newstate.name] = True
return newstate.st
elif isinstance(newstate, StatePrecond):
return newstate.st
elif isinstance(newstate, StateHook):
# final API using PSL
newstate.call(treenode, user_data)
return newstate.st
return self | def nextstate(self, newstate, treenode=None, user_data=None):
"""
Manage transition of state.
"""
if newstate is None:
return self
if isinstance(newstate, State) and id(newstate) != id(self):
return newstate
elif isinstance(newstate, StateEvent):
self.state_register.named_events[newstate.name] = True
return newstate.st
elif isinstance(newstate, StatePrecond):
return newstate.st
elif isinstance(newstate, StateHook):
# final API using PSL
newstate.call(treenode, user_data)
return newstate.st
return self | [
"Manage",
"transition",
"of",
"state",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L288-L305 | [
"def",
"nextstate",
"(",
"self",
",",
"newstate",
",",
"treenode",
"=",
"None",
",",
"user_data",
"=",
"None",
")",
":",
"if",
"newstate",
"is",
"None",
":",
"return",
"self",
"if",
"isinstance",
"(",
"newstate",
",",
"State",
")",
"and",
"id",
"(",
"newstate",
")",
"!=",
"id",
"(",
"self",
")",
":",
"return",
"newstate",
"elif",
"isinstance",
"(",
"newstate",
",",
"StateEvent",
")",
":",
"self",
".",
"state_register",
".",
"named_events",
"[",
"newstate",
".",
"name",
"]",
"=",
"True",
"return",
"newstate",
".",
"st",
"elif",
"isinstance",
"(",
"newstate",
",",
"StatePrecond",
")",
":",
"return",
"newstate",
".",
"st",
"elif",
"isinstance",
"(",
"newstate",
",",
"StateHook",
")",
":",
"# final API using PSL",
"newstate",
".",
"call",
"(",
"treenode",
",",
"user_data",
")",
"return",
"newstate",
".",
"st",
"return",
"self"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | State.checkValue | the str() of Values are stored internally for convenience | pyrser/ast/state.py | def checkValue(self, v) -> State:
"""the str() of Values are stored internally for convenience"""
if self.wild_value:
return self.nextstate(self.values['*'])
elif str(v) in self.values:
return self.nextstate(self.values[str(v)])
return self | def checkValue(self, v) -> State:
"""the str() of Values are stored internally for convenience"""
if self.wild_value:
return self.nextstate(self.values['*'])
elif str(v) in self.values:
return self.nextstate(self.values[str(v)])
return self | [
"the",
"str",
"()",
"of",
"Values",
"are",
"stored",
"internally",
"for",
"convenience"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L399-L405 | [
"def",
"checkValue",
"(",
"self",
",",
"v",
")",
"->",
"State",
":",
"if",
"self",
".",
"wild_value",
":",
"return",
"self",
".",
"nextstate",
"(",
"self",
".",
"values",
"[",
"'*'",
"]",
")",
"elif",
"str",
"(",
"v",
")",
"in",
"self",
".",
"values",
":",
"return",
"self",
".",
"nextstate",
"(",
"self",
".",
"values",
"[",
"str",
"(",
"v",
")",
"]",
")",
"return",
"self"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | LivingContext.resetLivingState | Only one Living State on the S0 of each StateRegister | pyrser/ast/state.py | def resetLivingState(self):
"""Only one Living State on the S0 of each StateRegister"""
# TODO: add some test to control number of instanciation of LivingState
# clean all living state on S0
must_delete = []
l = len(self.ls)
for idx, ls in zip(range(l), self.ls):
# TODO: alive by default on False, change to True on the first match
ids = id(ls[1].thestate())
if ids == id(ls[0]) and (ls[1].have_finish or not ls[1].alive):
must_delete.append(idx)
elif ls[1].alive:
ls[1].alive = False
for delete in reversed(must_delete):
self.ls.pop(delete)
self.init_all() | def resetLivingState(self):
"""Only one Living State on the S0 of each StateRegister"""
# TODO: add some test to control number of instanciation of LivingState
# clean all living state on S0
must_delete = []
l = len(self.ls)
for idx, ls in zip(range(l), self.ls):
# TODO: alive by default on False, change to True on the first match
ids = id(ls[1].thestate())
if ids == id(ls[0]) and (ls[1].have_finish or not ls[1].alive):
must_delete.append(idx)
elif ls[1].alive:
ls[1].alive = False
for delete in reversed(must_delete):
self.ls.pop(delete)
self.init_all() | [
"Only",
"one",
"Living",
"State",
"on",
"the",
"S0",
"of",
"each",
"StateRegister"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/ast/state.py#L990-L1005 | [
"def",
"resetLivingState",
"(",
"self",
")",
":",
"# TODO: add some test to control number of instanciation of LivingState",
"# clean all living state on S0",
"must_delete",
"=",
"[",
"]",
"l",
"=",
"len",
"(",
"self",
".",
"ls",
")",
"for",
"idx",
",",
"ls",
"in",
"zip",
"(",
"range",
"(",
"l",
")",
",",
"self",
".",
"ls",
")",
":",
"# TODO: alive by default on False, change to True on the first match",
"ids",
"=",
"id",
"(",
"ls",
"[",
"1",
"]",
".",
"thestate",
"(",
")",
")",
"if",
"ids",
"==",
"id",
"(",
"ls",
"[",
"0",
"]",
")",
"and",
"(",
"ls",
"[",
"1",
"]",
".",
"have_finish",
"or",
"not",
"ls",
"[",
"1",
"]",
".",
"alive",
")",
":",
"must_delete",
".",
"append",
"(",
"idx",
")",
"elif",
"ls",
"[",
"1",
"]",
".",
"alive",
":",
"ls",
"[",
"1",
"]",
".",
"alive",
"=",
"False",
"for",
"delete",
"in",
"reversed",
"(",
"must_delete",
")",
":",
"self",
".",
"ls",
".",
"pop",
"(",
"delete",
")",
"self",
".",
"init_all",
"(",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.infer_type | Do inference. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self. | pyrser/type_system/inference.py | def infer_type(self, init_scope: Scope=None, diagnostic=None):
"""
Do inference. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self.
"""
# create the first .infer_node
if not hasattr(self, 'infer_node'):
self.infer_node = InferNode(init_scope)
elif init_scope is not None:
# only change the root scope
self.infer_node.scope_node = init_scope
# get algo
type_algo = self.type_algos()
if diagnostic is None and hasattr(self, 'diagnostic'):
diagnostic = self.diagnostic
type_algo[0](type_algo[1], diagnostic) | def infer_type(self, init_scope: Scope=None, diagnostic=None):
"""
Do inference. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self.
"""
# create the first .infer_node
if not hasattr(self, 'infer_node'):
self.infer_node = InferNode(init_scope)
elif init_scope is not None:
# only change the root scope
self.infer_node.scope_node = init_scope
# get algo
type_algo = self.type_algos()
if diagnostic is None and hasattr(self, 'diagnostic'):
diagnostic = self.diagnostic
type_algo[0](type_algo[1], diagnostic) | [
"Do",
"inference",
".",
"Write",
"infos",
"into",
"diagnostic",
"object",
"if",
"this",
"parameter",
"is",
"not",
"provide",
"and",
"self",
"is",
"a",
"AST",
"(",
"has",
"is",
"own",
"diagnostic",
"object",
")",
"use",
"the",
"diagnostic",
"of",
"self",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L45-L61 | [
"def",
"infer_type",
"(",
"self",
",",
"init_scope",
":",
"Scope",
"=",
"None",
",",
"diagnostic",
"=",
"None",
")",
":",
"# create the first .infer_node",
"if",
"not",
"hasattr",
"(",
"self",
",",
"'infer_node'",
")",
":",
"self",
".",
"infer_node",
"=",
"InferNode",
"(",
"init_scope",
")",
"elif",
"init_scope",
"is",
"not",
"None",
":",
"# only change the root scope",
"self",
".",
"infer_node",
".",
"scope_node",
"=",
"init_scope",
"# get algo",
"type_algo",
"=",
"self",
".",
"type_algos",
"(",
")",
"if",
"diagnostic",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'diagnostic'",
")",
":",
"diagnostic",
"=",
"self",
".",
"diagnostic",
"type_algo",
"[",
"0",
"]",
"(",
"type_algo",
"[",
"1",
"]",
",",
"diagnostic",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.feedback | Do feedback. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self. | pyrser/type_system/inference.py | def feedback(self, diagnostic=None):
"""
Do feedback. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self.
"""
# get algo
type_algo = self.type_algos()
if diagnostic is None and hasattr(self, 'diagnostic'):
diagnostic = self.diagnostic
type_algo[2](diagnostic) | def feedback(self, diagnostic=None):
"""
Do feedback. Write infos into diagnostic object, if this parameter
is not provide and self is a AST (has is own diagnostic object),
use the diagnostic of self.
"""
# get algo
type_algo = self.type_algos()
if diagnostic is None and hasattr(self, 'diagnostic'):
diagnostic = self.diagnostic
type_algo[2](diagnostic) | [
"Do",
"feedback",
".",
"Write",
"infos",
"into",
"diagnostic",
"object",
"if",
"this",
"parameter",
"is",
"not",
"provide",
"and",
"self",
"is",
"a",
"AST",
"(",
"has",
"is",
"own",
"diagnostic",
"object",
")",
"use",
"the",
"diagnostic",
"of",
"self",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L63-L73 | [
"def",
"feedback",
"(",
"self",
",",
"diagnostic",
"=",
"None",
")",
":",
"# get algo",
"type_algo",
"=",
"self",
".",
"type_algos",
"(",
")",
"if",
"diagnostic",
"is",
"None",
"and",
"hasattr",
"(",
"self",
",",
"'diagnostic'",
")",
":",
"diagnostic",
"=",
"self",
".",
"diagnostic",
"type_algo",
"[",
"2",
"]",
"(",
"diagnostic",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.infer_block | Infer type on block is to type each of is sub-element | pyrser/type_system/inference.py | def infer_block(self, body, diagnostic=None):
"""
Infer type on block is to type each of is sub-element
"""
# RootBlockStmt has his own .infer_node (created via infer_type)
for e in body:
e.infer_node = InferNode(parent=self.infer_node)
e.infer_type(diagnostic=diagnostic) | def infer_block(self, body, diagnostic=None):
"""
Infer type on block is to type each of is sub-element
"""
# RootBlockStmt has his own .infer_node (created via infer_type)
for e in body:
e.infer_node = InferNode(parent=self.infer_node)
e.infer_type(diagnostic=diagnostic) | [
"Infer",
"type",
"on",
"block",
"is",
"to",
"type",
"each",
"of",
"is",
"sub",
"-",
"element"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L77-L84 | [
"def",
"infer_block",
"(",
"self",
",",
"body",
",",
"diagnostic",
"=",
"None",
")",
":",
"# RootBlockStmt has his own .infer_node (created via infer_type)",
"for",
"e",
"in",
"body",
":",
"e",
".",
"infer_node",
"=",
"InferNode",
"(",
"parent",
"=",
"self",
".",
"infer_node",
")",
"e",
".",
"infer_type",
"(",
"diagnostic",
"=",
"diagnostic",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.infer_subexpr | Infer type on the subexpr | pyrser/type_system/inference.py | def infer_subexpr(self, expr, diagnostic=None):
"""
Infer type on the subexpr
"""
expr.infer_node = InferNode(parent=self.infer_node)
expr.infer_type(diagnostic=diagnostic) | def infer_subexpr(self, expr, diagnostic=None):
"""
Infer type on the subexpr
"""
expr.infer_node = InferNode(parent=self.infer_node)
expr.infer_type(diagnostic=diagnostic) | [
"Infer",
"type",
"on",
"the",
"subexpr"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L87-L92 | [
"def",
"infer_subexpr",
"(",
"self",
",",
"expr",
",",
"diagnostic",
"=",
"None",
")",
":",
"expr",
".",
"infer_node",
"=",
"InferNode",
"(",
"parent",
"=",
"self",
".",
"infer_node",
")",
"expr",
".",
"infer_type",
"(",
"diagnostic",
"=",
"diagnostic",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.infer_id | Infer type from an ID!
- check if ID is declarated in the scope
- if no ID is polymorphic type | pyrser/type_system/inference.py | def infer_id(self, ident, diagnostic=None):
"""
Infer type from an ID!
- check if ID is declarated in the scope
- if no ID is polymorphic type
"""
# check if ID is declared
#defined = self.type_node.get_by_symbol_name(ident)
defined = self.infer_node.scope_node.get_by_symbol_name(ident)
if len(defined) > 0:
# set from matchings declarations
#self.type_node.update(defined)
self.infer_node.scope_node.update(defined)
else:
diagnostic.notify(
Severity.ERROR,
"%s never declared" % self.value,
self.info
) | def infer_id(self, ident, diagnostic=None):
"""
Infer type from an ID!
- check if ID is declarated in the scope
- if no ID is polymorphic type
"""
# check if ID is declared
#defined = self.type_node.get_by_symbol_name(ident)
defined = self.infer_node.scope_node.get_by_symbol_name(ident)
if len(defined) > 0:
# set from matchings declarations
#self.type_node.update(defined)
self.infer_node.scope_node.update(defined)
else:
diagnostic.notify(
Severity.ERROR,
"%s never declared" % self.value,
self.info
) | [
"Infer",
"type",
"from",
"an",
"ID!",
"-",
"check",
"if",
"ID",
"is",
"declarated",
"in",
"the",
"scope",
"-",
"if",
"no",
"ID",
"is",
"polymorphic",
"type"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L228-L246 | [
"def",
"infer_id",
"(",
"self",
",",
"ident",
",",
"diagnostic",
"=",
"None",
")",
":",
"# check if ID is declared",
"#defined = self.type_node.get_by_symbol_name(ident)",
"defined",
"=",
"self",
".",
"infer_node",
".",
"scope_node",
".",
"get_by_symbol_name",
"(",
"ident",
")",
"if",
"len",
"(",
"defined",
")",
">",
"0",
":",
"# set from matchings declarations",
"#self.type_node.update(defined)",
"self",
".",
"infer_node",
".",
"scope_node",
".",
"update",
"(",
"defined",
")",
"else",
":",
"diagnostic",
".",
"notify",
"(",
"Severity",
".",
"ERROR",
",",
"\"%s never declared\"",
"%",
"self",
".",
"value",
",",
"self",
".",
"info",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | Inference.infer_literal | Infer type from an LITERAL!
Type of literal depend of language.
We adopt a basic convention | pyrser/type_system/inference.py | def infer_literal(self, args, diagnostic=None):
"""
Infer type from an LITERAL!
Type of literal depend of language.
We adopt a basic convention
"""
literal, t = args
#self.type_node.add(EvalCtx.from_sig(Val(literal, t)))
self.infer_node.scope_node.add(EvalCtx.from_sig(Val(literal, t))) | def infer_literal(self, args, diagnostic=None):
"""
Infer type from an LITERAL!
Type of literal depend of language.
We adopt a basic convention
"""
literal, t = args
#self.type_node.add(EvalCtx.from_sig(Val(literal, t)))
self.infer_node.scope_node.add(EvalCtx.from_sig(Val(literal, t))) | [
"Infer",
"type",
"from",
"an",
"LITERAL!",
"Type",
"of",
"literal",
"depend",
"of",
"language",
".",
"We",
"adopt",
"a",
"basic",
"convention"
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/type_system/inference.py#L267-L275 | [
"def",
"infer_literal",
"(",
"self",
",",
"args",
",",
"diagnostic",
"=",
"None",
")",
":",
"literal",
",",
"t",
"=",
"args",
"#self.type_node.add(EvalCtx.from_sig(Val(literal, t)))",
"self",
".",
"infer_node",
".",
"scope_node",
".",
"add",
"(",
"EvalCtx",
".",
"from_sig",
"(",
"Val",
"(",
"literal",
",",
"t",
")",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | dump_nodes | Dump tag,rule,id and value cache. For debug.
example::
R = [
#dump_nodes
] | pyrser/hooks/dump_nodes.py | def dump_nodes(self):
"""
Dump tag,rule,id and value cache. For debug.
example::
R = [
#dump_nodes
]
"""
print("DUMP NODE LOCAL INFOS")
try:
print("map Id->node name")
for k, v in self.id_cache.items():
print("[%d]=%s" % (k, v))
print("map tag->capture infos")
for k, v in self.tag_cache.items():
print("[%s]=%s" % (k, v))
print("map nodes->tag resolution")
for k, v in self.rule_nodes.items():
txt = "['%s']=%d" % (k, id(v))
if k in self.tag_cache:
tag = self.tag_cache[k]
txt += " tag <%s>" % tag
k = "%d:%d" % (tag._begin, tag._end)
if k in self._stream.value_cache:
txt += " cache <%s>" % self._stream.value_cache[k]
print(txt)
except Exception as err:
print("RECV Exception %s" % err)
import sys
sys.stdout.flush()
return True | def dump_nodes(self):
"""
Dump tag,rule,id and value cache. For debug.
example::
R = [
#dump_nodes
]
"""
print("DUMP NODE LOCAL INFOS")
try:
print("map Id->node name")
for k, v in self.id_cache.items():
print("[%d]=%s" % (k, v))
print("map tag->capture infos")
for k, v in self.tag_cache.items():
print("[%s]=%s" % (k, v))
print("map nodes->tag resolution")
for k, v in self.rule_nodes.items():
txt = "['%s']=%d" % (k, id(v))
if k in self.tag_cache:
tag = self.tag_cache[k]
txt += " tag <%s>" % tag
k = "%d:%d" % (tag._begin, tag._end)
if k in self._stream.value_cache:
txt += " cache <%s>" % self._stream.value_cache[k]
print(txt)
except Exception as err:
print("RECV Exception %s" % err)
import sys
sys.stdout.flush()
return True | [
"Dump",
"tag",
"rule",
"id",
"and",
"value",
"cache",
".",
"For",
"debug",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/hooks/dump_nodes.py#L6-L39 | [
"def",
"dump_nodes",
"(",
"self",
")",
":",
"print",
"(",
"\"DUMP NODE LOCAL INFOS\"",
")",
"try",
":",
"print",
"(",
"\"map Id->node name\"",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"id_cache",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"[%d]=%s\"",
"%",
"(",
"k",
",",
"v",
")",
")",
"print",
"(",
"\"map tag->capture infos\"",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"tag_cache",
".",
"items",
"(",
")",
":",
"print",
"(",
"\"[%s]=%s\"",
"%",
"(",
"k",
",",
"v",
")",
")",
"print",
"(",
"\"map nodes->tag resolution\"",
")",
"for",
"k",
",",
"v",
"in",
"self",
".",
"rule_nodes",
".",
"items",
"(",
")",
":",
"txt",
"=",
"\"['%s']=%d\"",
"%",
"(",
"k",
",",
"id",
"(",
"v",
")",
")",
"if",
"k",
"in",
"self",
".",
"tag_cache",
":",
"tag",
"=",
"self",
".",
"tag_cache",
"[",
"k",
"]",
"txt",
"+=",
"\" tag <%s>\"",
"%",
"tag",
"k",
"=",
"\"%d:%d\"",
"%",
"(",
"tag",
".",
"_begin",
",",
"tag",
".",
"_end",
")",
"if",
"k",
"in",
"self",
".",
"_stream",
".",
"value_cache",
":",
"txt",
"+=",
"\" cache <%s>\"",
"%",
"self",
".",
"_stream",
".",
"value_cache",
"[",
"k",
"]",
"print",
"(",
"txt",
")",
"except",
"Exception",
"as",
"err",
":",
"print",
"(",
"\"RECV Exception %s\"",
"%",
"err",
")",
"import",
"sys",
"sys",
".",
"stdout",
".",
"flush",
"(",
")",
"return",
"True"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | S3StorageBroker.list_dataset_uris | Return list containing URIs with base URI. | dtool_s3/storagebroker.py | def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
uri_list = []
parse_result = generous_parse_uri(base_uri)
bucket_name = parse_result.netloc
bucket = boto3.resource('s3').Bucket(bucket_name)
for obj in bucket.objects.filter(Prefix='dtool').all():
uuid = obj.key.split('-', 1)[1]
uri = cls.generate_uri(None, uuid, base_uri)
storage_broker = cls(uri, config_path)
if storage_broker.has_admin_metadata():
uri_list.append(uri)
return uri_list | def list_dataset_uris(cls, base_uri, config_path):
"""Return list containing URIs with base URI."""
uri_list = []
parse_result = generous_parse_uri(base_uri)
bucket_name = parse_result.netloc
bucket = boto3.resource('s3').Bucket(bucket_name)
for obj in bucket.objects.filter(Prefix='dtool').all():
uuid = obj.key.split('-', 1)[1]
uri = cls.generate_uri(None, uuid, base_uri)
storage_broker = cls(uri, config_path)
if storage_broker.has_admin_metadata():
uri_list.append(uri)
return uri_list | [
"Return",
"list",
"containing",
"URIs",
"with",
"base",
"URI",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L175-L191 | [
"def",
"list_dataset_uris",
"(",
"cls",
",",
"base_uri",
",",
"config_path",
")",
":",
"uri_list",
"=",
"[",
"]",
"parse_result",
"=",
"generous_parse_uri",
"(",
"base_uri",
")",
"bucket_name",
"=",
"parse_result",
".",
"netloc",
"bucket",
"=",
"boto3",
".",
"resource",
"(",
"'s3'",
")",
".",
"Bucket",
"(",
"bucket_name",
")",
"for",
"obj",
"in",
"bucket",
".",
"objects",
".",
"filter",
"(",
"Prefix",
"=",
"'dtool'",
")",
".",
"all",
"(",
")",
":",
"uuid",
"=",
"obj",
".",
"key",
".",
"split",
"(",
"'-'",
",",
"1",
")",
"[",
"1",
"]",
"uri",
"=",
"cls",
".",
"generate_uri",
"(",
"None",
",",
"uuid",
",",
"base_uri",
")",
"storage_broker",
"=",
"cls",
"(",
"uri",
",",
"config_path",
")",
"if",
"storage_broker",
".",
"has_admin_metadata",
"(",
")",
":",
"uri_list",
".",
"append",
"(",
"uri",
")",
"return",
"uri_list"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | S3StorageBroker.get_item_abspath | Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed | dtool_s3/storagebroker.py | def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metadata["uuid"]
# Create directory for the specific dataset.
dataset_cache_abspath = os.path.join(self._s3_cache_abspath, uuid)
mkdir_parents(dataset_cache_abspath)
bucket_fpath = self.data_key_prefix + identifier
obj = self.s3resource.Object(self.bucket, bucket_fpath)
relpath = obj.get()['Metadata']['handle']
_, ext = os.path.splitext(relpath)
local_item_abspath = os.path.join(
dataset_cache_abspath,
identifier + ext
)
if not os.path.isfile(local_item_abspath):
tmp_local_item_abspath = local_item_abspath + ".tmp"
self.s3resource.Bucket(self.bucket).download_file(
bucket_fpath,
tmp_local_item_abspath
)
os.rename(tmp_local_item_abspath, local_item_abspath)
return local_item_abspath | def get_item_abspath(self, identifier):
"""Return absolute path at which item content can be accessed.
:param identifier: item identifier
:returns: absolute path from which the item content can be accessed
"""
admin_metadata = self.get_admin_metadata()
uuid = admin_metadata["uuid"]
# Create directory for the specific dataset.
dataset_cache_abspath = os.path.join(self._s3_cache_abspath, uuid)
mkdir_parents(dataset_cache_abspath)
bucket_fpath = self.data_key_prefix + identifier
obj = self.s3resource.Object(self.bucket, bucket_fpath)
relpath = obj.get()['Metadata']['handle']
_, ext = os.path.splitext(relpath)
local_item_abspath = os.path.join(
dataset_cache_abspath,
identifier + ext
)
if not os.path.isfile(local_item_abspath):
tmp_local_item_abspath = local_item_abspath + ".tmp"
self.s3resource.Bucket(self.bucket).download_file(
bucket_fpath,
tmp_local_item_abspath
)
os.rename(tmp_local_item_abspath, local_item_abspath)
return local_item_abspath | [
"Return",
"absolute",
"path",
"at",
"which",
"item",
"content",
"can",
"be",
"accessed",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L298-L328 | [
"def",
"get_item_abspath",
"(",
"self",
",",
"identifier",
")",
":",
"admin_metadata",
"=",
"self",
".",
"get_admin_metadata",
"(",
")",
"uuid",
"=",
"admin_metadata",
"[",
"\"uuid\"",
"]",
"# Create directory for the specific dataset.",
"dataset_cache_abspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_s3_cache_abspath",
",",
"uuid",
")",
"mkdir_parents",
"(",
"dataset_cache_abspath",
")",
"bucket_fpath",
"=",
"self",
".",
"data_key_prefix",
"+",
"identifier",
"obj",
"=",
"self",
".",
"s3resource",
".",
"Object",
"(",
"self",
".",
"bucket",
",",
"bucket_fpath",
")",
"relpath",
"=",
"obj",
".",
"get",
"(",
")",
"[",
"'Metadata'",
"]",
"[",
"'handle'",
"]",
"_",
",",
"ext",
"=",
"os",
".",
"path",
".",
"splitext",
"(",
"relpath",
")",
"local_item_abspath",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dataset_cache_abspath",
",",
"identifier",
"+",
"ext",
")",
"if",
"not",
"os",
".",
"path",
".",
"isfile",
"(",
"local_item_abspath",
")",
":",
"tmp_local_item_abspath",
"=",
"local_item_abspath",
"+",
"\".tmp\"",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"self",
".",
"bucket",
")",
".",
"download_file",
"(",
"bucket_fpath",
",",
"tmp_local_item_abspath",
")",
"os",
".",
"rename",
"(",
"tmp_local_item_abspath",
",",
"local_item_abspath",
")",
"return",
"local_item_abspath"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | S3StorageBroker.list_overlay_names | Return list of overlay names. | dtool_s3/storagebroker.py | def list_overlay_names(self):
"""Return list of overlay names."""
bucket = self.s3resource.Bucket(self.bucket)
overlay_names = []
for obj in bucket.objects.filter(
Prefix=self.overlays_key_prefix
).all():
overlay_file = obj.key.rsplit('/', 1)[-1]
overlay_name, ext = overlay_file.split('.')
overlay_names.append(overlay_name)
return overlay_names | def list_overlay_names(self):
"""Return list of overlay names."""
bucket = self.s3resource.Bucket(self.bucket)
overlay_names = []
for obj in bucket.objects.filter(
Prefix=self.overlays_key_prefix
).all():
overlay_file = obj.key.rsplit('/', 1)[-1]
overlay_name, ext = overlay_file.split('.')
overlay_names.append(overlay_name)
return overlay_names | [
"Return",
"list",
"of",
"overlay",
"names",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L330-L344 | [
"def",
"list_overlay_names",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"self",
".",
"bucket",
")",
"overlay_names",
"=",
"[",
"]",
"for",
"obj",
"in",
"bucket",
".",
"objects",
".",
"filter",
"(",
"Prefix",
"=",
"self",
".",
"overlays_key_prefix",
")",
".",
"all",
"(",
")",
":",
"overlay_file",
"=",
"obj",
".",
"key",
".",
"rsplit",
"(",
"'/'",
",",
"1",
")",
"[",
"-",
"1",
"]",
"overlay_name",
",",
"ext",
"=",
"overlay_file",
".",
"split",
"(",
"'.'",
")",
"overlay_names",
".",
"append",
"(",
"overlay_name",
")",
"return",
"overlay_names"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | S3StorageBroker.add_item_metadata | Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value | dtool_s3/storagebroker.py | def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
identifier = generate_identifier(handle)
suffix = '{}.{}.json'.format(identifier, key)
bucket_fpath = self.fragments_key_prefix + suffix
self.s3resource.Object(self.bucket, bucket_fpath).put(
Body=json.dumps(value)
) | def add_item_metadata(self, handle, key, value):
"""Store the given key:value pair for the item associated with handle.
:param handle: handle for accessing an item before the dataset is
frozen
:param key: metadata key
:param value: metadata value
"""
identifier = generate_identifier(handle)
suffix = '{}.{}.json'.format(identifier, key)
bucket_fpath = self.fragments_key_prefix + suffix
self.s3resource.Object(self.bucket, bucket_fpath).put(
Body=json.dumps(value)
) | [
"Store",
"the",
"given",
"key",
":",
"value",
"pair",
"for",
"the",
"item",
"associated",
"with",
"handle",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L370-L385 | [
"def",
"add_item_metadata",
"(",
"self",
",",
"handle",
",",
"key",
",",
"value",
")",
":",
"identifier",
"=",
"generate_identifier",
"(",
"handle",
")",
"suffix",
"=",
"'{}.{}.json'",
".",
"format",
"(",
"identifier",
",",
"key",
")",
"bucket_fpath",
"=",
"self",
".",
"fragments_key_prefix",
"+",
"suffix",
"self",
".",
"s3resource",
".",
"Object",
"(",
"self",
".",
"bucket",
",",
"bucket_fpath",
")",
".",
"put",
"(",
"Body",
"=",
"json",
".",
"dumps",
"(",
"value",
")",
")"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | S3StorageBroker.iter_item_handles | Return iterator over item handles. | dtool_s3/storagebroker.py | def iter_item_handles(self):
"""Return iterator over item handles."""
bucket = self.s3resource.Bucket(self.bucket)
for obj in bucket.objects.filter(Prefix=self.data_key_prefix).all():
relpath = obj.get()['Metadata']['handle']
yield relpath | def iter_item_handles(self):
"""Return iterator over item handles."""
bucket = self.s3resource.Bucket(self.bucket)
for obj in bucket.objects.filter(Prefix=self.data_key_prefix).all():
relpath = obj.get()['Metadata']['handle']
yield relpath | [
"Return",
"iterator",
"over",
"item",
"handles",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L387-L395 | [
"def",
"iter_item_handles",
"(",
"self",
")",
":",
"bucket",
"=",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"self",
".",
"bucket",
")",
"for",
"obj",
"in",
"bucket",
".",
"objects",
".",
"filter",
"(",
"Prefix",
"=",
"self",
".",
"data_key_prefix",
")",
".",
"all",
"(",
")",
":",
"relpath",
"=",
"obj",
".",
"get",
"(",
")",
"[",
"'Metadata'",
"]",
"[",
"'handle'",
"]",
"yield",
"relpath"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | S3StorageBroker.get_item_metadata | Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata | dtool_s3/storagebroker.py | def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata
"""
bucket = self.s3resource.Bucket(self.bucket)
metadata = {}
identifier = generate_identifier(handle)
prefix = self.fragments_key_prefix + '{}'.format(identifier)
for obj in bucket.objects.filter(Prefix=prefix).all():
metadata_key = obj.key.split('.')[-2]
response = obj.get()
value_as_string = response['Body'].read().decode('utf-8')
value = json.loads(value_as_string)
metadata[metadata_key] = value
return metadata | def get_item_metadata(self, handle):
"""Return dictionary containing all metadata associated with handle.
In other words all the metadata added using the ``add_item_metadata``
method.
:param handle: handle for accessing an item before the dataset is
frozen
:returns: dictionary containing item metadata
"""
bucket = self.s3resource.Bucket(self.bucket)
metadata = {}
identifier = generate_identifier(handle)
prefix = self.fragments_key_prefix + '{}'.format(identifier)
for obj in bucket.objects.filter(Prefix=prefix).all():
metadata_key = obj.key.split('.')[-2]
response = obj.get()
value_as_string = response['Body'].read().decode('utf-8')
value = json.loads(value_as_string)
metadata[metadata_key] = value
return metadata | [
"Return",
"dictionary",
"containing",
"all",
"metadata",
"associated",
"with",
"handle",
"."
] | jic-dtool/dtool-s3 | python | https://github.com/jic-dtool/dtool-s3/blob/b92aca9b557797bb99390463982521a557a2e704/dtool_s3/storagebroker.py#L424-L449 | [
"def",
"get_item_metadata",
"(",
"self",
",",
"handle",
")",
":",
"bucket",
"=",
"self",
".",
"s3resource",
".",
"Bucket",
"(",
"self",
".",
"bucket",
")",
"metadata",
"=",
"{",
"}",
"identifier",
"=",
"generate_identifier",
"(",
"handle",
")",
"prefix",
"=",
"self",
".",
"fragments_key_prefix",
"+",
"'{}'",
".",
"format",
"(",
"identifier",
")",
"for",
"obj",
"in",
"bucket",
".",
"objects",
".",
"filter",
"(",
"Prefix",
"=",
"prefix",
")",
".",
"all",
"(",
")",
":",
"metadata_key",
"=",
"obj",
".",
"key",
".",
"split",
"(",
"'.'",
")",
"[",
"-",
"2",
"]",
"response",
"=",
"obj",
".",
"get",
"(",
")",
"value_as_string",
"=",
"response",
"[",
"'Body'",
"]",
".",
"read",
"(",
")",
".",
"decode",
"(",
"'utf-8'",
")",
"value",
"=",
"json",
".",
"loads",
"(",
"value_as_string",
")",
"metadata",
"[",
"metadata_key",
"]",
"=",
"value",
"return",
"metadata"
] | b92aca9b557797bb99390463982521a557a2e704 |
test | parserrule_topython | Generates code for a rule.
def rulename(self):
<code for the rule>
return True | pyrser/passes/topython.py | def parserrule_topython(parser: parsing.BasicParser,
rulename: str) -> ast.FunctionDef:
"""Generates code for a rule.
def rulename(self):
<code for the rule>
return True
"""
visitor = RuleVisitor()
rule = parser._rules[rulename]
fn_args = ast.arguments([ast.arg('self', None)], None, None, [], None,
None, [], [])
body = visitor._clause(rule_topython(rule))
body.append(ast.Return(ast.Name('True', ast.Load())))
return ast.FunctionDef(rulename, fn_args, body, [], None) | def parserrule_topython(parser: parsing.BasicParser,
rulename: str) -> ast.FunctionDef:
"""Generates code for a rule.
def rulename(self):
<code for the rule>
return True
"""
visitor = RuleVisitor()
rule = parser._rules[rulename]
fn_args = ast.arguments([ast.arg('self', None)], None, None, [], None,
None, [], [])
body = visitor._clause(rule_topython(rule))
body.append(ast.Return(ast.Name('True', ast.Load())))
return ast.FunctionDef(rulename, fn_args, body, [], None) | [
"Generates",
"code",
"for",
"a",
"rule",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L267-L281 | [
"def",
"parserrule_topython",
"(",
"parser",
":",
"parsing",
".",
"BasicParser",
",",
"rulename",
":",
"str",
")",
"->",
"ast",
".",
"FunctionDef",
":",
"visitor",
"=",
"RuleVisitor",
"(",
")",
"rule",
"=",
"parser",
".",
"_rules",
"[",
"rulename",
"]",
"fn_args",
"=",
"ast",
".",
"arguments",
"(",
"[",
"ast",
".",
"arg",
"(",
"'self'",
",",
"None",
")",
"]",
",",
"None",
",",
"None",
",",
"[",
"]",
",",
"None",
",",
"None",
",",
"[",
"]",
",",
"[",
"]",
")",
"body",
"=",
"visitor",
".",
"_clause",
"(",
"rule_topython",
"(",
"rule",
")",
")",
"body",
".",
"append",
"(",
"ast",
".",
"Return",
"(",
"ast",
".",
"Name",
"(",
"'True'",
",",
"ast",
".",
"Load",
"(",
")",
")",
")",
")",
"return",
"ast",
".",
"FunctionDef",
"(",
"rulename",
",",
"fn_args",
",",
"body",
",",
"[",
"]",
",",
"None",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.__exit_scope | Create the appropriate scope exiting statement.
The documentation only shows one level and always uses
'return False' in examples.
'raise AltFalse()' within a try.
'break' within a loop.
'return False' otherwise. | pyrser/passes/topython.py | def __exit_scope(self) -> ast.stmt:
"""Create the appropriate scope exiting statement.
The documentation only shows one level and always uses
'return False' in examples.
'raise AltFalse()' within a try.
'break' within a loop.
'return False' otherwise.
"""
if self.in_optional:
return ast.Pass()
if self.in_try:
return ast.Raise(
ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
None)
if self.in_loop:
return ast.Break()
return ast.Return(ast.Name('False', ast.Load())) | def __exit_scope(self) -> ast.stmt:
"""Create the appropriate scope exiting statement.
The documentation only shows one level and always uses
'return False' in examples.
'raise AltFalse()' within a try.
'break' within a loop.
'return False' otherwise.
"""
if self.in_optional:
return ast.Pass()
if self.in_try:
return ast.Raise(
ast.Call(ast.Name('AltFalse', ast.Load()), [], [], None, None),
None)
if self.in_loop:
return ast.Break()
return ast.Return(ast.Name('False', ast.Load())) | [
"Create",
"the",
"appropriate",
"scope",
"exiting",
"statement",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L14-L32 | [
"def",
"__exit_scope",
"(",
"self",
")",
"->",
"ast",
".",
"stmt",
":",
"if",
"self",
".",
"in_optional",
":",
"return",
"ast",
".",
"Pass",
"(",
")",
"if",
"self",
".",
"in_try",
":",
"return",
"ast",
".",
"Raise",
"(",
"ast",
".",
"Call",
"(",
"ast",
".",
"Name",
"(",
"'AltFalse'",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"[",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")",
",",
"None",
")",
"if",
"self",
".",
"in_loop",
":",
"return",
"ast",
".",
"Break",
"(",
")",
"return",
"ast",
".",
"Return",
"(",
"ast",
".",
"Name",
"(",
"'False'",
",",
"ast",
".",
"Load",
"(",
")",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor._clause | Normalize a test expression into a statements list.
Statements list are returned as-is.
Expression is packaged as:
if not expr:
return False | pyrser/passes/topython.py | def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]:
"""Normalize a test expression into a statements list.
Statements list are returned as-is.
Expression is packaged as:
if not expr:
return False
"""
if isinstance(pt, list):
return pt
return [ast.If(ast.UnaryOp(ast.Not(), pt),
[self.__exit_scope()],
[])] | def _clause(self, pt: parsing.ParserTree) -> [ast.stmt]:
"""Normalize a test expression into a statements list.
Statements list are returned as-is.
Expression is packaged as:
if not expr:
return False
"""
if isinstance(pt, list):
return pt
return [ast.If(ast.UnaryOp(ast.Not(), pt),
[self.__exit_scope()],
[])] | [
"Normalize",
"a",
"test",
"expression",
"into",
"a",
"statements",
"list",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L35-L47 | [
"def",
"_clause",
"(",
"self",
",",
"pt",
":",
"parsing",
".",
"ParserTree",
")",
"->",
"[",
"ast",
".",
"stmt",
"]",
":",
"if",
"isinstance",
"(",
"pt",
",",
"list",
")",
":",
"return",
"pt",
"return",
"[",
"ast",
".",
"If",
"(",
"ast",
".",
"UnaryOp",
"(",
"ast",
".",
"Not",
"(",
")",
",",
"pt",
")",
",",
"[",
"self",
".",
"__exit_scope",
"(",
")",
"]",
",",
"[",
"]",
")",
"]"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_Call | Generates python code calling the function.
fn(*args) | pyrser/passes/topython.py | def visit_Call(self, node: parsing.Call) -> ast.expr:
"""Generates python code calling the function.
fn(*args)
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load),
node.callObject.__name__,
ast.Load()),
[ast.Str(param) for param in node.params],
[],
None,
None) | def visit_Call(self, node: parsing.Call) -> ast.expr:
"""Generates python code calling the function.
fn(*args)
"""
return ast.Call(
ast.Attribute(
ast.Name('self', ast.Load),
node.callObject.__name__,
ast.Load()),
[ast.Str(param) for param in node.params],
[],
None,
None) | [
"Generates",
"python",
"code",
"calling",
"the",
"function",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L49-L62 | [
"def",
"visit_Call",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"Call",
")",
"->",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Call",
"(",
"ast",
".",
"Attribute",
"(",
"ast",
".",
"Name",
"(",
"'self'",
",",
"ast",
".",
"Load",
")",
",",
"node",
".",
"callObject",
".",
"__name__",
",",
"ast",
".",
"Load",
"(",
")",
")",
",",
"[",
"ast",
".",
"Str",
"(",
"param",
")",
"for",
"param",
"in",
"node",
".",
"params",
"]",
",",
"[",
"]",
",",
"None",
",",
"None",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
test | RuleVisitor.visit_CallTrue | Generates python code calling the function and returning True.
lambda: fn(*args) or True | pyrser/passes/topython.py | def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
"""Generates python code calling the function and returning True.
lambda: fn(*args) or True
"""
return ast.Lambda(
ast.arguments([], None, None, [], None, None, [], []),
ast.BoolOp(
ast.Or(),
[
self.visit_Call(node),
ast.Name('True', ast.Load())])) | def visit_CallTrue(self, node: parsing.CallTrue) -> ast.expr:
"""Generates python code calling the function and returning True.
lambda: fn(*args) or True
"""
return ast.Lambda(
ast.arguments([], None, None, [], None, None, [], []),
ast.BoolOp(
ast.Or(),
[
self.visit_Call(node),
ast.Name('True', ast.Load())])) | [
"Generates",
"python",
"code",
"calling",
"the",
"function",
"and",
"returning",
"True",
"."
] | LionelAuroux/pyrser | python | https://github.com/LionelAuroux/pyrser/blob/f153a97ef2b6bf915a1ed468c0252a9a59b754d5/pyrser/passes/topython.py#L64-L75 | [
"def",
"visit_CallTrue",
"(",
"self",
",",
"node",
":",
"parsing",
".",
"CallTrue",
")",
"->",
"ast",
".",
"expr",
":",
"return",
"ast",
".",
"Lambda",
"(",
"ast",
".",
"arguments",
"(",
"[",
"]",
",",
"None",
",",
"None",
",",
"[",
"]",
",",
"None",
",",
"None",
",",
"[",
"]",
",",
"[",
"]",
")",
",",
"ast",
".",
"BoolOp",
"(",
"ast",
".",
"Or",
"(",
")",
",",
"[",
"self",
".",
"visit_Call",
"(",
"node",
")",
",",
"ast",
".",
"Name",
"(",
"'True'",
",",
"ast",
".",
"Load",
"(",
")",
")",
"]",
")",
")"
] | f153a97ef2b6bf915a1ed468c0252a9a59b754d5 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.