id
int32 0
252k
| repo
stringlengths 7
55
| path
stringlengths 4
127
| func_name
stringlengths 1
88
| original_string
stringlengths 75
19.8k
| language
stringclasses 1
value | code
stringlengths 75
19.8k
| code_tokens
sequence | docstring
stringlengths 3
17.3k
| docstring_tokens
sequence | sha
stringlengths 40
40
| url
stringlengths 87
242
|
---|---|---|---|---|---|---|---|---|---|---|---|
2,400 | crate/crash | src/crate/crash/outputs.py | _transform_field | def _transform_field(field):
"""transform field for displaying"""
if isinstance(field, bool):
return TRUE if field else FALSE
elif isinstance(field, (list, dict)):
return json.dumps(field, sort_keys=True, ensure_ascii=False)
else:
return field | python | def _transform_field(field):
"""transform field for displaying"""
if isinstance(field, bool):
return TRUE if field else FALSE
elif isinstance(field, (list, dict)):
return json.dumps(field, sort_keys=True, ensure_ascii=False)
else:
return field | [
"def",
"_transform_field",
"(",
"field",
")",
":",
"if",
"isinstance",
"(",
"field",
",",
"bool",
")",
":",
"return",
"TRUE",
"if",
"field",
"else",
"FALSE",
"elif",
"isinstance",
"(",
"field",
",",
"(",
"list",
",",
"dict",
")",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"field",
",",
"sort_keys",
"=",
"True",
",",
"ensure_ascii",
"=",
"False",
")",
"else",
":",
"return",
"field"
] | transform field for displaying | [
"transform",
"field",
"for",
"displaying"
] | 32d3ddc78fd2f7848ed2b99d9cd8889e322528d9 | https://github.com/crate/crash/blob/32d3ddc78fd2f7848ed2b99d9cd8889e322528d9/src/crate/crash/outputs.py#L42-L49 |
2,401 | supermihi/pytaglib | src/pyprinttags.py | script | def script():
"""Run the command-line script."""
parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
parser.add_argument("file", nargs="+", help="file(s) to print tags of")
args = parser.parse_args()
for filename in args.file:
if isinstance(filename, bytes):
filename = filename.decode(sys.getfilesystemencoding())
line = "TAGS OF '{0}'".format(os.path.basename(filename))
print("*" * len(line))
print(line)
print("*" * len(line))
audioFile = taglib.File(filename)
tags = audioFile.tags
if len(tags) > 0:
maxKeyLen = max(len(key) for key in tags.keys())
for key, values in tags.items():
for value in values:
print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
if len(audioFile.unsupported) > 0:
print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
if sys.version_info[0] == 2:
inputFunction = raw_input
else:
inputFunction = input
if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]:
audioFile.removeUnsupportedProperties(audioFile.unsupported)
audioFile.save() | python | def script():
"""Run the command-line script."""
parser = argparse.ArgumentParser(description="Print all textual tags of one or more audio files.")
parser.add_argument("-b", "--batch", help="disable user interaction", action="store_true")
parser.add_argument("file", nargs="+", help="file(s) to print tags of")
args = parser.parse_args()
for filename in args.file:
if isinstance(filename, bytes):
filename = filename.decode(sys.getfilesystemencoding())
line = "TAGS OF '{0}'".format(os.path.basename(filename))
print("*" * len(line))
print(line)
print("*" * len(line))
audioFile = taglib.File(filename)
tags = audioFile.tags
if len(tags) > 0:
maxKeyLen = max(len(key) for key in tags.keys())
for key, values in tags.items():
for value in values:
print(('{0:' + str(maxKeyLen) + '} = {1}').format(key, value))
if len(audioFile.unsupported) > 0:
print('Unsupported tag elements: ' + "; ".join(audioFile.unsupported))
if sys.version_info[0] == 2:
inputFunction = raw_input
else:
inputFunction = input
if not args.batch and inputFunction("remove unsupported properties? [yN] ").lower() in ["y", "yes"]:
audioFile.removeUnsupportedProperties(audioFile.unsupported)
audioFile.save() | [
"def",
"script",
"(",
")",
":",
"parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"description",
"=",
"\"Print all textual tags of one or more audio files.\"",
")",
"parser",
".",
"add_argument",
"(",
"\"-b\"",
",",
"\"--batch\"",
",",
"help",
"=",
"\"disable user interaction\"",
",",
"action",
"=",
"\"store_true\"",
")",
"parser",
".",
"add_argument",
"(",
"\"file\"",
",",
"nargs",
"=",
"\"+\"",
",",
"help",
"=",
"\"file(s) to print tags of\"",
")",
"args",
"=",
"parser",
".",
"parse_args",
"(",
")",
"for",
"filename",
"in",
"args",
".",
"file",
":",
"if",
"isinstance",
"(",
"filename",
",",
"bytes",
")",
":",
"filename",
"=",
"filename",
".",
"decode",
"(",
"sys",
".",
"getfilesystemencoding",
"(",
")",
")",
"line",
"=",
"\"TAGS OF '{0}'\"",
".",
"format",
"(",
"os",
".",
"path",
".",
"basename",
"(",
"filename",
")",
")",
"print",
"(",
"\"*\"",
"*",
"len",
"(",
"line",
")",
")",
"print",
"(",
"line",
")",
"print",
"(",
"\"*\"",
"*",
"len",
"(",
"line",
")",
")",
"audioFile",
"=",
"taglib",
".",
"File",
"(",
"filename",
")",
"tags",
"=",
"audioFile",
".",
"tags",
"if",
"len",
"(",
"tags",
")",
">",
"0",
":",
"maxKeyLen",
"=",
"max",
"(",
"len",
"(",
"key",
")",
"for",
"key",
"in",
"tags",
".",
"keys",
"(",
")",
")",
"for",
"key",
",",
"values",
"in",
"tags",
".",
"items",
"(",
")",
":",
"for",
"value",
"in",
"values",
":",
"print",
"(",
"(",
"'{0:'",
"+",
"str",
"(",
"maxKeyLen",
")",
"+",
"'} = {1}'",
")",
".",
"format",
"(",
"key",
",",
"value",
")",
")",
"if",
"len",
"(",
"audioFile",
".",
"unsupported",
")",
">",
"0",
":",
"print",
"(",
"'Unsupported tag elements: '",
"+",
"\"; \"",
".",
"join",
"(",
"audioFile",
".",
"unsupported",
")",
")",
"if",
"sys",
".",
"version_info",
"[",
"0",
"]",
"==",
"2",
":",
"inputFunction",
"=",
"raw_input",
"else",
":",
"inputFunction",
"=",
"input",
"if",
"not",
"args",
".",
"batch",
"and",
"inputFunction",
"(",
"\"remove unsupported properties? [yN] \"",
")",
".",
"lower",
"(",
")",
"in",
"[",
"\"y\"",
",",
"\"yes\"",
"]",
":",
"audioFile",
".",
"removeUnsupportedProperties",
"(",
"audioFile",
".",
"unsupported",
")",
"audioFile",
".",
"save",
"(",
")"
] | Run the command-line script. | [
"Run",
"the",
"command",
"-",
"line",
"script",
"."
] | 719224d4fdfee09925b865335f2af510ccdcad58 | https://github.com/supermihi/pytaglib/blob/719224d4fdfee09925b865335f2af510ccdcad58/src/pyprinttags.py#L23-L51 |
2,402 | adafruit/Adafruit_CircuitPython_seesaw | adafruit_seesaw/seesaw.py | Seesaw.sw_reset | def sw_reset(self):
"""Trigger a software reset of the SeeSaw chip"""
self.write8(_STATUS_BASE, _STATUS_SWRST, 0xFF)
time.sleep(.500)
chip_id = self.read8(_STATUS_BASE, _STATUS_HW_ID)
if chip_id != _HW_ID_CODE:
raise RuntimeError("Seesaw hardware ID returned (0x{:x}) is not "
"correct! Expected 0x{:x}. Please check your wiring."
.format(chip_id, _HW_ID_CODE))
pid = self.get_version() >> 16
if pid == _CRICKIT_PID:
from adafruit_seesaw.crickit import Crickit_Pinmap
self.pin_mapping = Crickit_Pinmap
elif pid == _ROBOHATMM1_PID:
from adafruit_seesaw.robohat import MM1_Pinmap
self.pin_mapping = MM1_Pinmap
else:
from adafruit_seesaw.samd09 import SAMD09_Pinmap
self.pin_mapping = SAMD09_Pinmap | python | def sw_reset(self):
"""Trigger a software reset of the SeeSaw chip"""
self.write8(_STATUS_BASE, _STATUS_SWRST, 0xFF)
time.sleep(.500)
chip_id = self.read8(_STATUS_BASE, _STATUS_HW_ID)
if chip_id != _HW_ID_CODE:
raise RuntimeError("Seesaw hardware ID returned (0x{:x}) is not "
"correct! Expected 0x{:x}. Please check your wiring."
.format(chip_id, _HW_ID_CODE))
pid = self.get_version() >> 16
if pid == _CRICKIT_PID:
from adafruit_seesaw.crickit import Crickit_Pinmap
self.pin_mapping = Crickit_Pinmap
elif pid == _ROBOHATMM1_PID:
from adafruit_seesaw.robohat import MM1_Pinmap
self.pin_mapping = MM1_Pinmap
else:
from adafruit_seesaw.samd09 import SAMD09_Pinmap
self.pin_mapping = SAMD09_Pinmap | [
"def",
"sw_reset",
"(",
"self",
")",
":",
"self",
".",
"write8",
"(",
"_STATUS_BASE",
",",
"_STATUS_SWRST",
",",
"0xFF",
")",
"time",
".",
"sleep",
"(",
".500",
")",
"chip_id",
"=",
"self",
".",
"read8",
"(",
"_STATUS_BASE",
",",
"_STATUS_HW_ID",
")",
"if",
"chip_id",
"!=",
"_HW_ID_CODE",
":",
"raise",
"RuntimeError",
"(",
"\"Seesaw hardware ID returned (0x{:x}) is not \"",
"\"correct! Expected 0x{:x}. Please check your wiring.\"",
".",
"format",
"(",
"chip_id",
",",
"_HW_ID_CODE",
")",
")",
"pid",
"=",
"self",
".",
"get_version",
"(",
")",
">>",
"16",
"if",
"pid",
"==",
"_CRICKIT_PID",
":",
"from",
"adafruit_seesaw",
".",
"crickit",
"import",
"Crickit_Pinmap",
"self",
".",
"pin_mapping",
"=",
"Crickit_Pinmap",
"elif",
"pid",
"==",
"_ROBOHATMM1_PID",
":",
"from",
"adafruit_seesaw",
".",
"robohat",
"import",
"MM1_Pinmap",
"self",
".",
"pin_mapping",
"=",
"MM1_Pinmap",
"else",
":",
"from",
"adafruit_seesaw",
".",
"samd09",
"import",
"SAMD09_Pinmap",
"self",
".",
"pin_mapping",
"=",
"SAMD09_Pinmap"
] | Trigger a software reset of the SeeSaw chip | [
"Trigger",
"a",
"software",
"reset",
"of",
"the",
"SeeSaw",
"chip"
] | 3f55058dbdfcfde8cb5ce8708c0a37aacde9b313 | https://github.com/adafruit/Adafruit_CircuitPython_seesaw/blob/3f55058dbdfcfde8cb5ce8708c0a37aacde9b313/adafruit_seesaw/seesaw.py#L144-L165 |
2,403 | lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_default_cache_file_path | def _get_default_cache_file_path(self):
"""
Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str
"""
default_list_path = os.path.join(
self._get_default_cache_dir(), self._CACHE_FILE_NAME)
if not os.access(default_list_path, os.F_OK):
raise CacheFileError(
"Default cache file does not exist "
"'{}'!".format(default_list_path)
)
return default_list_path | python | def _get_default_cache_file_path(self):
"""
Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str
"""
default_list_path = os.path.join(
self._get_default_cache_dir(), self._CACHE_FILE_NAME)
if not os.access(default_list_path, os.F_OK):
raise CacheFileError(
"Default cache file does not exist "
"'{}'!".format(default_list_path)
)
return default_list_path | [
"def",
"_get_default_cache_file_path",
"(",
"self",
")",
":",
"default_list_path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"self",
".",
"_get_default_cache_dir",
"(",
")",
",",
"self",
".",
"_CACHE_FILE_NAME",
")",
"if",
"not",
"os",
".",
"access",
"(",
"default_list_path",
",",
"os",
".",
"F_OK",
")",
":",
"raise",
"CacheFileError",
"(",
"\"Default cache file does not exist \"",
"\"'{}'!\"",
".",
"format",
"(",
"default_list_path",
")",
")",
"return",
"default_list_path"
] | Returns default cache file path
:return: default cache file path (to data directory)
:rtype: str | [
"Returns",
"default",
"cache",
"file",
"path"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L77-L94 |
2,404 | lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_writable_cache_dir | def _get_writable_cache_dir(self):
"""
Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str
"""
dir_path_data = self._get_default_cache_dir()
if os.access(dir_path_data, os.W_OK):
self._default_cache_file = True
return dir_path_data
dir_path_user = user_cache_dir(self._URLEXTRACT_NAME)
if not os.path.exists(dir_path_user):
os.makedirs(dir_path_user, exist_ok=True)
if os.access(dir_path_user, os.W_OK):
return dir_path_user
dir_path_temp = tempfile.gettempdir()
if os.access(dir_path_temp, os.W_OK):
return dir_path_temp
raise CacheFileError("Cache directories are not writable.") | python | def _get_writable_cache_dir(self):
"""
Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str
"""
dir_path_data = self._get_default_cache_dir()
if os.access(dir_path_data, os.W_OK):
self._default_cache_file = True
return dir_path_data
dir_path_user = user_cache_dir(self._URLEXTRACT_NAME)
if not os.path.exists(dir_path_user):
os.makedirs(dir_path_user, exist_ok=True)
if os.access(dir_path_user, os.W_OK):
return dir_path_user
dir_path_temp = tempfile.gettempdir()
if os.access(dir_path_temp, os.W_OK):
return dir_path_temp
raise CacheFileError("Cache directories are not writable.") | [
"def",
"_get_writable_cache_dir",
"(",
"self",
")",
":",
"dir_path_data",
"=",
"self",
".",
"_get_default_cache_dir",
"(",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_data",
",",
"os",
".",
"W_OK",
")",
":",
"self",
".",
"_default_cache_file",
"=",
"True",
"return",
"dir_path_data",
"dir_path_user",
"=",
"user_cache_dir",
"(",
"self",
".",
"_URLEXTRACT_NAME",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"dir_path_user",
")",
":",
"os",
".",
"makedirs",
"(",
"dir_path_user",
",",
"exist_ok",
"=",
"True",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_user",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"dir_path_user",
"dir_path_temp",
"=",
"tempfile",
".",
"gettempdir",
"(",
")",
"if",
"os",
".",
"access",
"(",
"dir_path_temp",
",",
"os",
".",
"W_OK",
")",
":",
"return",
"dir_path_temp",
"raise",
"CacheFileError",
"(",
"\"Cache directories are not writable.\"",
")"
] | Get writable cache directory with fallback to user's cache directory
and global temp directory
:raises: CacheFileError when cached directory is not writable for user
:return: path to cache directory
:rtype: str | [
"Get",
"writable",
"cache",
"directory",
"with",
"fallback",
"to",
"user",
"s",
"cache",
"directory",
"and",
"global",
"temp",
"directory"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L96-L122 |
2,405 | lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_cache_file_path | def _get_cache_file_path(self, cache_dir=None):
"""
Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str
"""
if cache_dir is None:
# Tries to get writable cache dir with fallback to users data dir
# and temp directory
cache_dir = self._get_writable_cache_dir()
else:
if not os.access(cache_dir, os.W_OK):
raise CacheFileError("None of cache directories is writable.")
# get directory for cached file
return os.path.join(cache_dir, self._CACHE_FILE_NAME) | python | def _get_cache_file_path(self, cache_dir=None):
"""
Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str
"""
if cache_dir is None:
# Tries to get writable cache dir with fallback to users data dir
# and temp directory
cache_dir = self._get_writable_cache_dir()
else:
if not os.access(cache_dir, os.W_OK):
raise CacheFileError("None of cache directories is writable.")
# get directory for cached file
return os.path.join(cache_dir, self._CACHE_FILE_NAME) | [
"def",
"_get_cache_file_path",
"(",
"self",
",",
"cache_dir",
"=",
"None",
")",
":",
"if",
"cache_dir",
"is",
"None",
":",
"# Tries to get writable cache dir with fallback to users data dir",
"# and temp directory",
"cache_dir",
"=",
"self",
".",
"_get_writable_cache_dir",
"(",
")",
"else",
":",
"if",
"not",
"os",
".",
"access",
"(",
"cache_dir",
",",
"os",
".",
"W_OK",
")",
":",
"raise",
"CacheFileError",
"(",
"\"None of cache directories is writable.\"",
")",
"# get directory for cached file",
"return",
"os",
".",
"path",
".",
"join",
"(",
"cache_dir",
",",
"self",
".",
"_CACHE_FILE_NAME",
")"
] | Get path for cache file
:param str cache_dir: base path for TLD cache, defaults to data dir
:raises: CacheFileError when cached directory is not writable for user
:return: Full path to cached file with TLDs
:rtype: str | [
"Get",
"path",
"for",
"cache",
"file"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L124-L142 |
2,406 | lipoja/URLExtract | urlextract/cachefile.py | CacheFile._load_cached_tlds | def _load_cached_tlds(self):
"""
Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set
"""
# check if cached file is readable
if not os.access(self._tld_list_path, os.R_OK):
self._logger.error("Cached file is not readable for current "
"user. ({})".format(self._tld_list_path))
raise CacheFileError(
"Cached file is not readable for current user."
)
set_of_tlds = set()
with open(self._tld_list_path, 'r') as f_cache_tld:
for line in f_cache_tld:
tld = line.strip().lower()
# skip empty lines
if not tld:
continue
# skip comments
if tld[0] == '#':
continue
set_of_tlds.add("." + tld)
set_of_tlds.add("." + idna.decode(tld))
return set_of_tlds | python | def _load_cached_tlds(self):
"""
Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set
"""
# check if cached file is readable
if not os.access(self._tld_list_path, os.R_OK):
self._logger.error("Cached file is not readable for current "
"user. ({})".format(self._tld_list_path))
raise CacheFileError(
"Cached file is not readable for current user."
)
set_of_tlds = set()
with open(self._tld_list_path, 'r') as f_cache_tld:
for line in f_cache_tld:
tld = line.strip().lower()
# skip empty lines
if not tld:
continue
# skip comments
if tld[0] == '#':
continue
set_of_tlds.add("." + tld)
set_of_tlds.add("." + idna.decode(tld))
return set_of_tlds | [
"def",
"_load_cached_tlds",
"(",
"self",
")",
":",
"# check if cached file is readable",
"if",
"not",
"os",
".",
"access",
"(",
"self",
".",
"_tld_list_path",
",",
"os",
".",
"R_OK",
")",
":",
"self",
".",
"_logger",
".",
"error",
"(",
"\"Cached file is not readable for current \"",
"\"user. ({})\"",
".",
"format",
"(",
"self",
".",
"_tld_list_path",
")",
")",
"raise",
"CacheFileError",
"(",
"\"Cached file is not readable for current user.\"",
")",
"set_of_tlds",
"=",
"set",
"(",
")",
"with",
"open",
"(",
"self",
".",
"_tld_list_path",
",",
"'r'",
")",
"as",
"f_cache_tld",
":",
"for",
"line",
"in",
"f_cache_tld",
":",
"tld",
"=",
"line",
".",
"strip",
"(",
")",
".",
"lower",
"(",
")",
"# skip empty lines",
"if",
"not",
"tld",
":",
"continue",
"# skip comments",
"if",
"tld",
"[",
"0",
"]",
"==",
"'#'",
":",
"continue",
"set_of_tlds",
".",
"add",
"(",
"\".\"",
"+",
"tld",
")",
"set_of_tlds",
".",
"add",
"(",
"\".\"",
"+",
"idna",
".",
"decode",
"(",
"tld",
")",
")",
"return",
"set_of_tlds"
] | Loads TLDs from cached file to set.
:return: Set of current TLDs
:rtype: set | [
"Loads",
"TLDs",
"from",
"cached",
"file",
"to",
"set",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L190-L220 |
2,407 | lipoja/URLExtract | urlextract/cachefile.py | CacheFile._get_last_cachefile_modification | def _get_last_cachefile_modification(self):
"""
Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None
"""
try:
mtime = os.path.getmtime(self._tld_list_path)
except OSError:
return None
return datetime.fromtimestamp(mtime) | python | def _get_last_cachefile_modification(self):
"""
Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None
"""
try:
mtime = os.path.getmtime(self._tld_list_path)
except OSError:
return None
return datetime.fromtimestamp(mtime) | [
"def",
"_get_last_cachefile_modification",
"(",
"self",
")",
":",
"try",
":",
"mtime",
"=",
"os",
".",
"path",
".",
"getmtime",
"(",
"self",
".",
"_tld_list_path",
")",
"except",
"OSError",
":",
"return",
"None",
"return",
"datetime",
".",
"fromtimestamp",
"(",
"mtime",
")"
] | Get last modification of cache file with TLDs.
:return: Date and time of last modification or
None when file does not exist
:rtype: datetime|None | [
"Get",
"last",
"modification",
"of",
"cache",
"file",
"with",
"TLDs",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/cachefile.py#L222-L236 |
2,408 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._get_after_tld_chars | def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?', ':', '.', ','}
# get left enclosure characters
_, right_enclosure = zip(*self._enclosure)
# add right enclosure characters to be valid after TLD
# for correct parsing of URL e.g. (example.com)
after_tld_chars |= set(right_enclosure)
return after_tld_chars | python | def _get_after_tld_chars(self):
"""
Initialize after tld characters
"""
after_tld_chars = set(string.whitespace)
after_tld_chars |= {'/', '\"', '\'', '<', '>', '?', ':', '.', ','}
# get left enclosure characters
_, right_enclosure = zip(*self._enclosure)
# add right enclosure characters to be valid after TLD
# for correct parsing of URL e.g. (example.com)
after_tld_chars |= set(right_enclosure)
return after_tld_chars | [
"def",
"_get_after_tld_chars",
"(",
"self",
")",
":",
"after_tld_chars",
"=",
"set",
"(",
"string",
".",
"whitespace",
")",
"after_tld_chars",
"|=",
"{",
"'/'",
",",
"'\\\"'",
",",
"'\\''",
",",
"'<'",
",",
"'>'",
",",
"'?'",
",",
"':'",
",",
"'.'",
",",
"','",
"}",
"# get left enclosure characters",
"_",
",",
"right_enclosure",
"=",
"zip",
"(",
"*",
"self",
".",
"_enclosure",
")",
"# add right enclosure characters to be valid after TLD",
"# for correct parsing of URL e.g. (example.com)",
"after_tld_chars",
"|=",
"set",
"(",
"right_enclosure",
")",
"return",
"after_tld_chars"
] | Initialize after tld characters | [
"Initialize",
"after",
"tld",
"characters"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L91-L103 |
2,409 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.update_when_older | def update_when_older(self, days):
"""
Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool
"""
last_cache = self._get_last_cachefile_modification()
if last_cache is None:
return self.update()
time_to_update = last_cache + timedelta(days=days)
if datetime.now() >= time_to_update:
return self.update()
return True | python | def update_when_older(self, days):
"""
Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool
"""
last_cache = self._get_last_cachefile_modification()
if last_cache is None:
return self.update()
time_to_update = last_cache + timedelta(days=days)
if datetime.now() >= time_to_update:
return self.update()
return True | [
"def",
"update_when_older",
"(",
"self",
",",
"days",
")",
":",
"last_cache",
"=",
"self",
".",
"_get_last_cachefile_modification",
"(",
")",
"if",
"last_cache",
"is",
"None",
":",
"return",
"self",
".",
"update",
"(",
")",
"time_to_update",
"=",
"last_cache",
"+",
"timedelta",
"(",
"days",
"=",
"days",
")",
"if",
"datetime",
".",
"now",
"(",
")",
">=",
"time_to_update",
":",
"return",
"self",
".",
"update",
"(",
")",
"return",
"True"
] | Update TLD list cache file if the list is older than
number of days given in parameter `days` or if does not exist.
:param int days: number of days from last change
:return: True if update was successful, False otherwise
:rtype: bool | [
"Update",
"TLD",
"list",
"cache",
"file",
"if",
"the",
"list",
"is",
"older",
"than",
"number",
"of",
"days",
"given",
"in",
"parameter",
"days",
"or",
"if",
"does",
"not",
"exist",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L129-L148 |
2,410 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.set_stop_chars | def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.warn("Method set_stop_chars is deprecated, "
"use `set_stop_chars_left` or "
"`set_stop_chars_right` instead", DeprecationWarning)
self._stop_chars = set(stop_chars)
self._stop_chars_left = self._stop_chars
self._stop_chars_right = self._stop_chars | python | def set_stop_chars(self, stop_chars):
"""
Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters
"""
warnings.warn("Method set_stop_chars is deprecated, "
"use `set_stop_chars_left` or "
"`set_stop_chars_right` instead", DeprecationWarning)
self._stop_chars = set(stop_chars)
self._stop_chars_left = self._stop_chars
self._stop_chars_right = self._stop_chars | [
"def",
"set_stop_chars",
"(",
"self",
",",
"stop_chars",
")",
":",
"warnings",
".",
"warn",
"(",
"\"Method set_stop_chars is deprecated, \"",
"\"use `set_stop_chars_left` or \"",
"\"`set_stop_chars_right` instead\"",
",",
"DeprecationWarning",
")",
"self",
".",
"_stop_chars",
"=",
"set",
"(",
"stop_chars",
")",
"self",
".",
"_stop_chars_left",
"=",
"self",
".",
"_stop_chars",
"self",
".",
"_stop_chars_right",
"=",
"self",
".",
"_stop_chars"
] | Set stop characters used when determining end of URL.
.. deprecated:: 0.7
Use :func:`set_stop_chars_left` or :func:`set_stop_chars_right`
instead.
:param list stop_chars: list of characters | [
"Set",
"stop",
"characters",
"used",
"when",
"determining",
"end",
"of",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L196-L212 |
2,411 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.set_stop_chars_left | def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
raise TypeError("stop_chars should be type set "
"but {} was given".format(type(stop_chars)))
self._stop_chars_left = stop_chars
self._stop_chars = self._stop_chars_left | self._stop_chars_right | python | def set_stop_chars_left(self, stop_chars):
"""
Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError
"""
if not isinstance(stop_chars, set):
raise TypeError("stop_chars should be type set "
"but {} was given".format(type(stop_chars)))
self._stop_chars_left = stop_chars
self._stop_chars = self._stop_chars_left | self._stop_chars_right | [
"def",
"set_stop_chars_left",
"(",
"self",
",",
"stop_chars",
")",
":",
"if",
"not",
"isinstance",
"(",
"stop_chars",
",",
"set",
")",
":",
"raise",
"TypeError",
"(",
"\"stop_chars should be type set \"",
"\"but {} was given\"",
".",
"format",
"(",
"type",
"(",
"stop_chars",
")",
")",
")",
"self",
".",
"_stop_chars_left",
"=",
"stop_chars",
"self",
".",
"_stop_chars",
"=",
"self",
".",
"_stop_chars_left",
"|",
"self",
".",
"_stop_chars_right"
] | Set stop characters for text on left from TLD.
Stop characters are used when determining end of URL.
:param set stop_chars: set of characters
:raises: TypeError | [
"Set",
"stop",
"characters",
"for",
"text",
"on",
"left",
"from",
"TLD",
".",
"Stop",
"characters",
"are",
"used",
"when",
"determining",
"end",
"of",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L223-L236 |
2,412 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.add_enclosure | def add_enclosure(self, left_char, right_char):
"""
Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
self._enclosure.add((left_char, right_char))
self._after_tld_chars = self._get_after_tld_chars() | python | def add_enclosure(self, left_char, right_char):
"""
Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
self._enclosure.add((left_char, right_char))
self._after_tld_chars = self._get_after_tld_chars() | [
"def",
"add_enclosure",
"(",
"self",
",",
"left_char",
",",
"right_char",
")",
":",
"assert",
"len",
"(",
"left_char",
")",
"==",
"1",
",",
"\"Parameter left_char must be character not string\"",
"assert",
"len",
"(",
"right_char",
")",
"==",
"1",
",",
"\"Parameter right_char must be character not string\"",
"self",
".",
"_enclosure",
".",
"add",
"(",
"(",
"left_char",
",",
"right_char",
")",
")",
"self",
".",
"_after_tld_chars",
"=",
"self",
".",
"_get_after_tld_chars",
"(",
")"
] | Add new enclosure pair of characters. That and should be removed
when their presence is detected at beginning and end of found URL
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")" | [
"Add",
"new",
"enclosure",
"pair",
"of",
"characters",
".",
"That",
"and",
"should",
"be",
"removed",
"when",
"their",
"presence",
"is",
"detected",
"at",
"beginning",
"and",
"end",
"of",
"found",
"URL"
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L272-L286 |
2,413 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.remove_enclosure | def remove_enclosure(self, left_char, right_char):
"""
Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
rm_enclosure = (left_char, right_char)
if rm_enclosure in self._enclosure:
self._enclosure.remove(rm_enclosure)
self._after_tld_chars = self._get_after_tld_chars() | python | def remove_enclosure(self, left_char, right_char):
"""
Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")"
"""
assert len(left_char) == 1, \
"Parameter left_char must be character not string"
assert len(right_char) == 1, \
"Parameter right_char must be character not string"
rm_enclosure = (left_char, right_char)
if rm_enclosure in self._enclosure:
self._enclosure.remove(rm_enclosure)
self._after_tld_chars = self._get_after_tld_chars() | [
"def",
"remove_enclosure",
"(",
"self",
",",
"left_char",
",",
"right_char",
")",
":",
"assert",
"len",
"(",
"left_char",
")",
"==",
"1",
",",
"\"Parameter left_char must be character not string\"",
"assert",
"len",
"(",
"right_char",
")",
"==",
"1",
",",
"\"Parameter right_char must be character not string\"",
"rm_enclosure",
"=",
"(",
"left_char",
",",
"right_char",
")",
"if",
"rm_enclosure",
"in",
"self",
".",
"_enclosure",
":",
"self",
".",
"_enclosure",
".",
"remove",
"(",
"rm_enclosure",
")",
"self",
".",
"_after_tld_chars",
"=",
"self",
".",
"_get_after_tld_chars",
"(",
")"
] | Remove enclosure pair from set of enclosures.
:param str left_char: left character of enclosure pair - e.g. "("
:param str right_char: right character of enclosure pair - e.g. ")" | [
"Remove",
"enclosure",
"pair",
"from",
"set",
"of",
"enclosures",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L288-L303 |
2,414 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._complete_url | def _complete_url(self, text, tld_pos, tld):
"""
Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str
"""
left_ok = True
right_ok = True
max_len = len(text) - 1
end_pos = tld_pos
start_pos = tld_pos
while left_ok or right_ok:
if left_ok:
if start_pos <= 0:
left_ok = False
else:
if text[start_pos - 1] not in self._stop_chars_left:
start_pos -= 1
else:
left_ok = False
if right_ok:
if end_pos >= max_len:
right_ok = False
else:
if text[end_pos + 1] not in self._stop_chars_right:
end_pos += 1
else:
right_ok = False
complete_url = text[start_pos:end_pos + 1].lstrip('/')
# remove last character from url
# when it is allowed character right after TLD (e.g. dot, comma)
temp_tlds = {tld + c for c in self._after_tld_chars}
# get only dot+tld+one_char and compare
if complete_url[len(complete_url)-len(tld)-1:] in temp_tlds:
complete_url = complete_url[:-1]
complete_url = self._split_markdown(complete_url, tld_pos-start_pos)
complete_url = self._remove_enclosure_from_url(
complete_url, tld_pos-start_pos, tld)
if not self._is_domain_valid(complete_url, tld):
return ""
return complete_url | python | def _complete_url(self, text, tld_pos, tld):
"""
Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str
"""
left_ok = True
right_ok = True
max_len = len(text) - 1
end_pos = tld_pos
start_pos = tld_pos
while left_ok or right_ok:
if left_ok:
if start_pos <= 0:
left_ok = False
else:
if text[start_pos - 1] not in self._stop_chars_left:
start_pos -= 1
else:
left_ok = False
if right_ok:
if end_pos >= max_len:
right_ok = False
else:
if text[end_pos + 1] not in self._stop_chars_right:
end_pos += 1
else:
right_ok = False
complete_url = text[start_pos:end_pos + 1].lstrip('/')
# remove last character from url
# when it is allowed character right after TLD (e.g. dot, comma)
temp_tlds = {tld + c for c in self._after_tld_chars}
# get only dot+tld+one_char and compare
if complete_url[len(complete_url)-len(tld)-1:] in temp_tlds:
complete_url = complete_url[:-1]
complete_url = self._split_markdown(complete_url, tld_pos-start_pos)
complete_url = self._remove_enclosure_from_url(
complete_url, tld_pos-start_pos, tld)
if not self._is_domain_valid(complete_url, tld):
return ""
return complete_url | [
"def",
"_complete_url",
"(",
"self",
",",
"text",
",",
"tld_pos",
",",
"tld",
")",
":",
"left_ok",
"=",
"True",
"right_ok",
"=",
"True",
"max_len",
"=",
"len",
"(",
"text",
")",
"-",
"1",
"end_pos",
"=",
"tld_pos",
"start_pos",
"=",
"tld_pos",
"while",
"left_ok",
"or",
"right_ok",
":",
"if",
"left_ok",
":",
"if",
"start_pos",
"<=",
"0",
":",
"left_ok",
"=",
"False",
"else",
":",
"if",
"text",
"[",
"start_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"start_pos",
"-=",
"1",
"else",
":",
"left_ok",
"=",
"False",
"if",
"right_ok",
":",
"if",
"end_pos",
">=",
"max_len",
":",
"right_ok",
"=",
"False",
"else",
":",
"if",
"text",
"[",
"end_pos",
"+",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_right",
":",
"end_pos",
"+=",
"1",
"else",
":",
"right_ok",
"=",
"False",
"complete_url",
"=",
"text",
"[",
"start_pos",
":",
"end_pos",
"+",
"1",
"]",
".",
"lstrip",
"(",
"'/'",
")",
"# remove last character from url",
"# when it is allowed character right after TLD (e.g. dot, comma)",
"temp_tlds",
"=",
"{",
"tld",
"+",
"c",
"for",
"c",
"in",
"self",
".",
"_after_tld_chars",
"}",
"# get only dot+tld+one_char and compare",
"if",
"complete_url",
"[",
"len",
"(",
"complete_url",
")",
"-",
"len",
"(",
"tld",
")",
"-",
"1",
":",
"]",
"in",
"temp_tlds",
":",
"complete_url",
"=",
"complete_url",
"[",
":",
"-",
"1",
"]",
"complete_url",
"=",
"self",
".",
"_split_markdown",
"(",
"complete_url",
",",
"tld_pos",
"-",
"start_pos",
")",
"complete_url",
"=",
"self",
".",
"_remove_enclosure_from_url",
"(",
"complete_url",
",",
"tld_pos",
"-",
"start_pos",
",",
"tld",
")",
"if",
"not",
"self",
".",
"_is_domain_valid",
"(",
"complete_url",
",",
"tld",
")",
":",
"return",
"\"\"",
"return",
"complete_url"
] | Expand string in both sides to match whole URL.
:param str text: text where we want to find URL
:param int tld_pos: position of TLD
:param str tld: matched TLD which should be in text
:return: returns URL
:rtype: str | [
"Expand",
"string",
"in",
"both",
"sides",
"to",
"match",
"whole",
"URL",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L305-L354 |
2,415 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._validate_tld_match | def _validate_tld_match(self, text, matched_tld, tld_pos):
"""
Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool
"""
if tld_pos > len(text):
return False
right_tld_pos = tld_pos + len(matched_tld)
if len(text) > right_tld_pos:
if text[right_tld_pos] in self._after_tld_chars:
if tld_pos > 0 and text[tld_pos - 1] \
not in self._stop_chars_left:
return True
else:
if tld_pos > 0 and text[tld_pos - 1] not in self._stop_chars_left:
return True
return False | python | def _validate_tld_match(self, text, matched_tld, tld_pos):
"""
Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool
"""
if tld_pos > len(text):
return False
right_tld_pos = tld_pos + len(matched_tld)
if len(text) > right_tld_pos:
if text[right_tld_pos] in self._after_tld_chars:
if tld_pos > 0 and text[tld_pos - 1] \
not in self._stop_chars_left:
return True
else:
if tld_pos > 0 and text[tld_pos - 1] not in self._stop_chars_left:
return True
return False | [
"def",
"_validate_tld_match",
"(",
"self",
",",
"text",
",",
"matched_tld",
",",
"tld_pos",
")",
":",
"if",
"tld_pos",
">",
"len",
"(",
"text",
")",
":",
"return",
"False",
"right_tld_pos",
"=",
"tld_pos",
"+",
"len",
"(",
"matched_tld",
")",
"if",
"len",
"(",
"text",
")",
">",
"right_tld_pos",
":",
"if",
"text",
"[",
"right_tld_pos",
"]",
"in",
"self",
".",
"_after_tld_chars",
":",
"if",
"tld_pos",
">",
"0",
"and",
"text",
"[",
"tld_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"return",
"True",
"else",
":",
"if",
"tld_pos",
">",
"0",
"and",
"text",
"[",
"tld_pos",
"-",
"1",
"]",
"not",
"in",
"self",
".",
"_stop_chars_left",
":",
"return",
"True",
"return",
"False"
] | Validate TLD match - tells if at found position is really TLD.
:param str text: text where we want to find URLs
:param str matched_tld: matched TLD
:param int tld_pos: position of matched TLD
:return: True if match is valid, False otherwise
:rtype: bool | [
"Validate",
"TLD",
"match",
"-",
"tells",
"if",
"at",
"found",
"position",
"is",
"really",
"TLD",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L356-L379 |
2,416 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract._split_markdown | def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str
"""
# Markdown url can looks like:
# [http://example.com/](http://example.com/status/210)
left_bracket_pos = text_url.find('[')
# subtract 3 because URL is never shorter than 3 characters
if left_bracket_pos > tld_pos-3:
return text_url
right_bracket_pos = text_url.find(')')
if right_bracket_pos < tld_pos:
return text_url
middle_pos = text_url.rfind("](")
if middle_pos > tld_pos:
return text_url[left_bracket_pos+1:middle_pos]
return text_url | python | def _split_markdown(text_url, tld_pos):
"""
Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str
"""
# Markdown url can looks like:
# [http://example.com/](http://example.com/status/210)
left_bracket_pos = text_url.find('[')
# subtract 3 because URL is never shorter than 3 characters
if left_bracket_pos > tld_pos-3:
return text_url
right_bracket_pos = text_url.find(')')
if right_bracket_pos < tld_pos:
return text_url
middle_pos = text_url.rfind("](")
if middle_pos > tld_pos:
return text_url[left_bracket_pos+1:middle_pos]
return text_url | [
"def",
"_split_markdown",
"(",
"text_url",
",",
"tld_pos",
")",
":",
"# Markdown url can looks like:",
"# [http://example.com/](http://example.com/status/210)",
"left_bracket_pos",
"=",
"text_url",
".",
"find",
"(",
"'['",
")",
"# subtract 3 because URL is never shorter than 3 characters",
"if",
"left_bracket_pos",
">",
"tld_pos",
"-",
"3",
":",
"return",
"text_url",
"right_bracket_pos",
"=",
"text_url",
".",
"find",
"(",
"')'",
")",
"if",
"right_bracket_pos",
"<",
"tld_pos",
":",
"return",
"text_url",
"middle_pos",
"=",
"text_url",
".",
"rfind",
"(",
"\"](\"",
")",
"if",
"middle_pos",
">",
"tld_pos",
":",
"return",
"text_url",
"[",
"left_bracket_pos",
"+",
"1",
":",
"middle_pos",
"]",
"return",
"text_url"
] | Split markdown URL. There is an issue wen Markdown URL is found.
Parsing of the URL does not stop on right place so wrongly found URL
has to be split.
:param str text_url: URL that we want to extract from enclosure
:param int tld_pos: position of TLD
:return: URL that has removed enclosure
:rtype: str | [
"Split",
"markdown",
"URL",
".",
"There",
"is",
"an",
"issue",
"wen",
"Markdown",
"URL",
"is",
"found",
".",
"Parsing",
"of",
"the",
"URL",
"does",
"not",
"stop",
"on",
"right",
"place",
"so",
"wrongly",
"found",
"URL",
"has",
"to",
"be",
"split",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L497-L523 |
2,417 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.gen_urls | def gen_urls(self, text):
"""
Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str
"""
tld_pos = 0
matched_tlds = self._tlds_re.findall(text)
for tld in matched_tlds:
tmp_text = text[tld_pos:]
offset = tld_pos
tld_pos = tmp_text.find(tld)
validated = self._validate_tld_match(text, tld, offset + tld_pos)
if tld_pos != -1 and validated:
tmp_url = self._complete_url(text, offset + tld_pos, tld)
if tmp_url:
yield tmp_url
# do not search for TLD in already extracted URL
tld_pos_url = tmp_url.find(tld)
# move cursor right after found TLD
tld_pos += len(tld) + offset
# move cursor after end of found URL
tld_pos += len(tmp_url[tld_pos_url+len(tld):])
continue
# move cursor right after found TLD
tld_pos += len(tld) + offset | python | def gen_urls(self, text):
"""
Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str
"""
tld_pos = 0
matched_tlds = self._tlds_re.findall(text)
for tld in matched_tlds:
tmp_text = text[tld_pos:]
offset = tld_pos
tld_pos = tmp_text.find(tld)
validated = self._validate_tld_match(text, tld, offset + tld_pos)
if tld_pos != -1 and validated:
tmp_url = self._complete_url(text, offset + tld_pos, tld)
if tmp_url:
yield tmp_url
# do not search for TLD in already extracted URL
tld_pos_url = tmp_url.find(tld)
# move cursor right after found TLD
tld_pos += len(tld) + offset
# move cursor after end of found URL
tld_pos += len(tmp_url[tld_pos_url+len(tld):])
continue
# move cursor right after found TLD
tld_pos += len(tld) + offset | [
"def",
"gen_urls",
"(",
"self",
",",
"text",
")",
":",
"tld_pos",
"=",
"0",
"matched_tlds",
"=",
"self",
".",
"_tlds_re",
".",
"findall",
"(",
"text",
")",
"for",
"tld",
"in",
"matched_tlds",
":",
"tmp_text",
"=",
"text",
"[",
"tld_pos",
":",
"]",
"offset",
"=",
"tld_pos",
"tld_pos",
"=",
"tmp_text",
".",
"find",
"(",
"tld",
")",
"validated",
"=",
"self",
".",
"_validate_tld_match",
"(",
"text",
",",
"tld",
",",
"offset",
"+",
"tld_pos",
")",
"if",
"tld_pos",
"!=",
"-",
"1",
"and",
"validated",
":",
"tmp_url",
"=",
"self",
".",
"_complete_url",
"(",
"text",
",",
"offset",
"+",
"tld_pos",
",",
"tld",
")",
"if",
"tmp_url",
":",
"yield",
"tmp_url",
"# do not search for TLD in already extracted URL",
"tld_pos_url",
"=",
"tmp_url",
".",
"find",
"(",
"tld",
")",
"# move cursor right after found TLD",
"tld_pos",
"+=",
"len",
"(",
"tld",
")",
"+",
"offset",
"# move cursor after end of found URL",
"tld_pos",
"+=",
"len",
"(",
"tmp_url",
"[",
"tld_pos_url",
"+",
"len",
"(",
"tld",
")",
":",
"]",
")",
"continue",
"# move cursor right after found TLD",
"tld_pos",
"+=",
"len",
"(",
"tld",
")",
"+",
"offset"
] | Creates generator over found URLs in given text.
:param str text: text where we want to find URLs
:yields: URL found in text or empty string if no found
:rtype: str | [
"Creates",
"generator",
"over",
"found",
"URLs",
"in",
"given",
"text",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L525-L555 |
2,418 | lipoja/URLExtract | urlextract/urlextract_core.py | URLExtract.find_urls | def find_urls(self, text, only_unique=False):
"""
Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list
"""
urls = self.gen_urls(text)
urls = OrderedDict.fromkeys(urls) if only_unique else urls
return list(urls) | python | def find_urls(self, text, only_unique=False):
"""
Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list
"""
urls = self.gen_urls(text)
urls = OrderedDict.fromkeys(urls) if only_unique else urls
return list(urls) | [
"def",
"find_urls",
"(",
"self",
",",
"text",
",",
"only_unique",
"=",
"False",
")",
":",
"urls",
"=",
"self",
".",
"gen_urls",
"(",
"text",
")",
"urls",
"=",
"OrderedDict",
".",
"fromkeys",
"(",
"urls",
")",
"if",
"only_unique",
"else",
"urls",
"return",
"list",
"(",
"urls",
")"
] | Find all URLs in given text.
:param str text: text where we want to find URLs
:param bool only_unique: return only unique URLs
:return: list of URLs found in text
:rtype: list | [
"Find",
"all",
"URLs",
"in",
"given",
"text",
"."
] | b53fd2adfaed3cd23a811aed4d277b0ade7b4640 | https://github.com/lipoja/URLExtract/blob/b53fd2adfaed3cd23a811aed4d277b0ade7b4640/urlextract/urlextract_core.py#L557-L568 |
2,419 | pinax/pinax-badges | pinax/badges/base.py | Badge.possibly_award | def possibly_award(self, **state):
"""
Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding.
"""
assert "user" in state
if self.async:
from .tasks import AsyncBadgeAward
state = self.freeze(**state)
AsyncBadgeAward.delay(self, state)
return
self.actually_possibly_award(**state) | python | def possibly_award(self, **state):
"""
Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding.
"""
assert "user" in state
if self.async:
from .tasks import AsyncBadgeAward
state = self.freeze(**state)
AsyncBadgeAward.delay(self, state)
return
self.actually_possibly_award(**state) | [
"def",
"possibly_award",
"(",
"self",
",",
"*",
"*",
"state",
")",
":",
"assert",
"\"user\"",
"in",
"state",
"if",
"self",
".",
"async",
":",
"from",
".",
"tasks",
"import",
"AsyncBadgeAward",
"state",
"=",
"self",
".",
"freeze",
"(",
"*",
"*",
"state",
")",
"AsyncBadgeAward",
".",
"delay",
"(",
"self",
",",
"state",
")",
"return",
"self",
".",
"actually_possibly_award",
"(",
"*",
"*",
"state",
")"
] | Will see if the user should be awarded a badge. If this badge is
asynchronous it just queues up the badge awarding. | [
"Will",
"see",
"if",
"the",
"user",
"should",
"be",
"awarded",
"a",
"badge",
".",
"If",
"this",
"badge",
"is",
"asynchronous",
"it",
"just",
"queues",
"up",
"the",
"badge",
"awarding",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L26-L37 |
2,420 | pinax/pinax-badges | pinax/badges/base.py | Badge.actually_possibly_award | def actually_possibly_award(self, **state):
"""
Does the actual work of possibly awarding a badge.
"""
user = state["user"]
force_timestamp = state.pop("force_timestamp", None)
awarded = self.award(**state)
if awarded is None:
return
if awarded.level is None:
assert len(self.levels) == 1
awarded.level = 1
# awarded levels are 1 indexed, for conveineince
awarded = awarded.level - 1
assert awarded < len(self.levels)
if (
not self.multiple and
BadgeAward.objects.filter(user=user, slug=self.slug, level=awarded)
):
return
extra_kwargs = {}
if force_timestamp is not None:
extra_kwargs["awarded_at"] = force_timestamp
badge = BadgeAward.objects.create(
user=user,
slug=self.slug,
level=awarded,
**extra_kwargs
)
self.send_badge_messages(badge)
badge_awarded.send(sender=self, badge_award=badge) | python | def actually_possibly_award(self, **state):
"""
Does the actual work of possibly awarding a badge.
"""
user = state["user"]
force_timestamp = state.pop("force_timestamp", None)
awarded = self.award(**state)
if awarded is None:
return
if awarded.level is None:
assert len(self.levels) == 1
awarded.level = 1
# awarded levels are 1 indexed, for conveineince
awarded = awarded.level - 1
assert awarded < len(self.levels)
if (
not self.multiple and
BadgeAward.objects.filter(user=user, slug=self.slug, level=awarded)
):
return
extra_kwargs = {}
if force_timestamp is not None:
extra_kwargs["awarded_at"] = force_timestamp
badge = BadgeAward.objects.create(
user=user,
slug=self.slug,
level=awarded,
**extra_kwargs
)
self.send_badge_messages(badge)
badge_awarded.send(sender=self, badge_award=badge) | [
"def",
"actually_possibly_award",
"(",
"self",
",",
"*",
"*",
"state",
")",
":",
"user",
"=",
"state",
"[",
"\"user\"",
"]",
"force_timestamp",
"=",
"state",
".",
"pop",
"(",
"\"force_timestamp\"",
",",
"None",
")",
"awarded",
"=",
"self",
".",
"award",
"(",
"*",
"*",
"state",
")",
"if",
"awarded",
"is",
"None",
":",
"return",
"if",
"awarded",
".",
"level",
"is",
"None",
":",
"assert",
"len",
"(",
"self",
".",
"levels",
")",
"==",
"1",
"awarded",
".",
"level",
"=",
"1",
"# awarded levels are 1 indexed, for conveineince",
"awarded",
"=",
"awarded",
".",
"level",
"-",
"1",
"assert",
"awarded",
"<",
"len",
"(",
"self",
".",
"levels",
")",
"if",
"(",
"not",
"self",
".",
"multiple",
"and",
"BadgeAward",
".",
"objects",
".",
"filter",
"(",
"user",
"=",
"user",
",",
"slug",
"=",
"self",
".",
"slug",
",",
"level",
"=",
"awarded",
")",
")",
":",
"return",
"extra_kwargs",
"=",
"{",
"}",
"if",
"force_timestamp",
"is",
"not",
"None",
":",
"extra_kwargs",
"[",
"\"awarded_at\"",
"]",
"=",
"force_timestamp",
"badge",
"=",
"BadgeAward",
".",
"objects",
".",
"create",
"(",
"user",
"=",
"user",
",",
"slug",
"=",
"self",
".",
"slug",
",",
"level",
"=",
"awarded",
",",
"*",
"*",
"extra_kwargs",
")",
"self",
".",
"send_badge_messages",
"(",
"badge",
")",
"badge_awarded",
".",
"send",
"(",
"sender",
"=",
"self",
",",
"badge_award",
"=",
"badge",
")"
] | Does the actual work of possibly awarding a badge. | [
"Does",
"the",
"actual",
"work",
"of",
"possibly",
"awarding",
"a",
"badge",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L39-L69 |
2,421 | pinax/pinax-badges | pinax/badges/base.py | Badge.send_badge_messages | def send_badge_messages(self, badge_award):
"""
If the Badge class defines a message, send it to the user who was just
awarded the badge.
"""
user_message = getattr(badge_award.badge, "user_message", None)
if callable(user_message):
message = user_message(badge_award)
else:
message = user_message
if message is not None:
badge_award.user.message_set.create(message=message) | python | def send_badge_messages(self, badge_award):
"""
If the Badge class defines a message, send it to the user who was just
awarded the badge.
"""
user_message = getattr(badge_award.badge, "user_message", None)
if callable(user_message):
message = user_message(badge_award)
else:
message = user_message
if message is not None:
badge_award.user.message_set.create(message=message) | [
"def",
"send_badge_messages",
"(",
"self",
",",
"badge_award",
")",
":",
"user_message",
"=",
"getattr",
"(",
"badge_award",
".",
"badge",
",",
"\"user_message\"",
",",
"None",
")",
"if",
"callable",
"(",
"user_message",
")",
":",
"message",
"=",
"user_message",
"(",
"badge_award",
")",
"else",
":",
"message",
"=",
"user_message",
"if",
"message",
"is",
"not",
"None",
":",
"badge_award",
".",
"user",
".",
"message_set",
".",
"create",
"(",
"message",
"=",
"message",
")"
] | If the Badge class defines a message, send it to the user who was just
awarded the badge. | [
"If",
"the",
"Badge",
"class",
"defines",
"a",
"message",
"send",
"it",
"to",
"the",
"user",
"who",
"was",
"just",
"awarded",
"the",
"badge",
"."
] | 0921c388088e7c7a77098dc7d0eea393b4707ce5 | https://github.com/pinax/pinax-badges/blob/0921c388088e7c7a77098dc7d0eea393b4707ce5/pinax/badges/base.py#L71-L82 |
2,422 | JBKahn/flake8-print | flake8_print.py | PrintFinder.visit_Print | def visit_Print(self, node):
"""Only exists in python 2."""
self.prints_used[(node.lineno, node.col_offset)] = VIOLATIONS["found"][PRINT_FUNCTION_NAME] | python | def visit_Print(self, node):
"""Only exists in python 2."""
self.prints_used[(node.lineno, node.col_offset)] = VIOLATIONS["found"][PRINT_FUNCTION_NAME] | [
"def",
"visit_Print",
"(",
"self",
",",
"node",
")",
":",
"self",
".",
"prints_used",
"[",
"(",
"node",
".",
"lineno",
",",
"node",
".",
"col_offset",
")",
"]",
"=",
"VIOLATIONS",
"[",
"\"found\"",
"]",
"[",
"PRINT_FUNCTION_NAME",
"]"
] | Only exists in python 2. | [
"Only",
"exists",
"in",
"python",
"2",
"."
] | e5d3812c4c93628ed804e9ecf74c2d31780627e5 | https://github.com/JBKahn/flake8-print/blob/e5d3812c4c93628ed804e9ecf74c2d31780627e5/flake8_print.py#L30-L32 |
2,423 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.create_lockfile | def create_lockfile(self):
"""
Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it.
"""
process = subprocess.Popen(
self.pin_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
if process.returncode == 0:
self.fix_lockfile()
else:
logger.critical("ERROR executing %s", ' '.join(self.pin_command))
logger.critical("Exit code: %s", process.returncode)
logger.critical(stdout.decode('utf-8'))
logger.critical(stderr.decode('utf-8'))
raise RuntimeError("Failed to pip-compile {0}".format(self.infile)) | python | def create_lockfile(self):
"""
Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it.
"""
process = subprocess.Popen(
self.pin_command,
stdout=subprocess.PIPE,
stderr=subprocess.PIPE,
)
stdout, stderr = process.communicate()
if process.returncode == 0:
self.fix_lockfile()
else:
logger.critical("ERROR executing %s", ' '.join(self.pin_command))
logger.critical("Exit code: %s", process.returncode)
logger.critical(stdout.decode('utf-8'))
logger.critical(stderr.decode('utf-8'))
raise RuntimeError("Failed to pip-compile {0}".format(self.infile)) | [
"def",
"create_lockfile",
"(",
"self",
")",
":",
"process",
"=",
"subprocess",
".",
"Popen",
"(",
"self",
".",
"pin_command",
",",
"stdout",
"=",
"subprocess",
".",
"PIPE",
",",
"stderr",
"=",
"subprocess",
".",
"PIPE",
",",
")",
"stdout",
",",
"stderr",
"=",
"process",
".",
"communicate",
"(",
")",
"if",
"process",
".",
"returncode",
"==",
"0",
":",
"self",
".",
"fix_lockfile",
"(",
")",
"else",
":",
"logger",
".",
"critical",
"(",
"\"ERROR executing %s\"",
",",
"' '",
".",
"join",
"(",
"self",
".",
"pin_command",
")",
")",
"logger",
".",
"critical",
"(",
"\"Exit code: %s\"",
",",
"process",
".",
"returncode",
")",
"logger",
".",
"critical",
"(",
"stdout",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"logger",
".",
"critical",
"(",
"stderr",
".",
"decode",
"(",
"'utf-8'",
")",
")",
"raise",
"RuntimeError",
"(",
"\"Failed to pip-compile {0}\"",
".",
"format",
"(",
"self",
".",
"infile",
")",
")"
] | Write recursive dependencies list to outfile
with hard-pinned versions.
Then fix it. | [
"Write",
"recursive",
"dependencies",
"list",
"to",
"outfile",
"with",
"hard",
"-",
"pinned",
"versions",
".",
"Then",
"fix",
"it",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L31-L50 |
2,424 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.infile | def infile(self):
"""Path of the input file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['in_ext'])) | python | def infile(self):
"""Path of the input file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['in_ext'])) | [
"def",
"infile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'{0}.{1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"OPTIONS",
"[",
"'in_ext'",
"]",
")",
")"
] | Path of the input file | [
"Path",
"of",
"the",
"input",
"file"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L74-L77 |
2,425 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.outfile | def outfile(self):
"""Path of the output file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['out_ext'])) | python | def outfile(self):
"""Path of the output file"""
return os.path.join(OPTIONS['base_dir'],
'{0}.{1}'.format(self.name, OPTIONS['out_ext'])) | [
"def",
"outfile",
"(",
"self",
")",
":",
"return",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'{0}.{1}'",
".",
"format",
"(",
"self",
".",
"name",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
")"
] | Path of the output file | [
"Path",
"of",
"the",
"output",
"file"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L80-L83 |
2,426 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.pin_command | def pin_command(self):
"""Compose pip-compile shell command"""
parts = [
'pip-compile',
'--no-header',
'--verbose',
'--rebuild',
'--no-index',
'--output-file', self.outfile,
self.infile,
]
if OPTIONS['upgrade']:
parts.insert(3, '--upgrade')
if self.add_hashes:
parts.insert(1, '--generate-hashes')
return parts | python | def pin_command(self):
"""Compose pip-compile shell command"""
parts = [
'pip-compile',
'--no-header',
'--verbose',
'--rebuild',
'--no-index',
'--output-file', self.outfile,
self.infile,
]
if OPTIONS['upgrade']:
parts.insert(3, '--upgrade')
if self.add_hashes:
parts.insert(1, '--generate-hashes')
return parts | [
"def",
"pin_command",
"(",
"self",
")",
":",
"parts",
"=",
"[",
"'pip-compile'",
",",
"'--no-header'",
",",
"'--verbose'",
",",
"'--rebuild'",
",",
"'--no-index'",
",",
"'--output-file'",
",",
"self",
".",
"outfile",
",",
"self",
".",
"infile",
",",
"]",
"if",
"OPTIONS",
"[",
"'upgrade'",
"]",
":",
"parts",
".",
"insert",
"(",
"3",
",",
"'--upgrade'",
")",
"if",
"self",
".",
"add_hashes",
":",
"parts",
".",
"insert",
"(",
"1",
",",
"'--generate-hashes'",
")",
"return",
"parts"
] | Compose pip-compile shell command | [
"Compose",
"pip",
"-",
"compile",
"shell",
"command"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L86-L101 |
2,427 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.fix_lockfile | def fix_lockfile(self):
"""Run each line of outfile through fix_pin"""
with open(self.outfile, 'rt') as fp:
lines = [
self.fix_pin(line)
for line in self.concatenated(fp)
]
with open(self.outfile, 'wt') as fp:
fp.writelines([
line + '\n'
for line in lines
if line is not None
]) | python | def fix_lockfile(self):
"""Run each line of outfile through fix_pin"""
with open(self.outfile, 'rt') as fp:
lines = [
self.fix_pin(line)
for line in self.concatenated(fp)
]
with open(self.outfile, 'wt') as fp:
fp.writelines([
line + '\n'
for line in lines
if line is not None
]) | [
"def",
"fix_lockfile",
"(",
"self",
")",
":",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"lines",
"=",
"[",
"self",
".",
"fix_pin",
"(",
"line",
")",
"for",
"line",
"in",
"self",
".",
"concatenated",
"(",
"fp",
")",
"]",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"writelines",
"(",
"[",
"line",
"+",
"'\\n'",
"for",
"line",
"in",
"lines",
"if",
"line",
"is",
"not",
"None",
"]",
")"
] | Run each line of outfile through fix_pin | [
"Run",
"each",
"line",
"of",
"outfile",
"through",
"fix_pin"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L103-L115 |
2,428 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.fix_pin | def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package in self.ignore:
ignored_version = self.ignore[dep.package]
if ignored_version is not None:
# ignored_version can be None to disable conflict detection
if dep.version and dep.version != ignored_version:
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
dep.package, dep.version, ignored_version,
)
raise RuntimeError(
"Please add constraints for the package "
"version listed above"
)
return None
self.packages[dep.package] = dep.version
if self.forbid_post or dep.is_compatible:
# Always drop post for internal packages
dep.drop_post()
return dep.serialize()
return line.strip() | python | def fix_pin(self, line):
"""
Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set
"""
dep = Dependency(line)
if dep.valid:
if dep.package in self.ignore:
ignored_version = self.ignore[dep.package]
if ignored_version is not None:
# ignored_version can be None to disable conflict detection
if dep.version and dep.version != ignored_version:
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
dep.package, dep.version, ignored_version,
)
raise RuntimeError(
"Please add constraints for the package "
"version listed above"
)
return None
self.packages[dep.package] = dep.version
if self.forbid_post or dep.is_compatible:
# Always drop post for internal packages
dep.drop_post()
return dep.serialize()
return line.strip() | [
"def",
"fix_pin",
"(",
"self",
",",
"line",
")",
":",
"dep",
"=",
"Dependency",
"(",
"line",
")",
"if",
"dep",
".",
"valid",
":",
"if",
"dep",
".",
"package",
"in",
"self",
".",
"ignore",
":",
"ignored_version",
"=",
"self",
".",
"ignore",
"[",
"dep",
".",
"package",
"]",
"if",
"ignored_version",
"is",
"not",
"None",
":",
"# ignored_version can be None to disable conflict detection",
"if",
"dep",
".",
"version",
"and",
"dep",
".",
"version",
"!=",
"ignored_version",
":",
"logger",
".",
"error",
"(",
"\"Package %s was resolved to different \"",
"\"versions in different environments: %s and %s\"",
",",
"dep",
".",
"package",
",",
"dep",
".",
"version",
",",
"ignored_version",
",",
")",
"raise",
"RuntimeError",
"(",
"\"Please add constraints for the package \"",
"\"version listed above\"",
")",
"return",
"None",
"self",
".",
"packages",
"[",
"dep",
".",
"package",
"]",
"=",
"dep",
".",
"version",
"if",
"self",
".",
"forbid_post",
"or",
"dep",
".",
"is_compatible",
":",
"# Always drop post for internal packages",
"dep",
".",
"drop_post",
"(",
")",
"return",
"dep",
".",
"serialize",
"(",
")",
"return",
"line",
".",
"strip",
"(",
")"
] | Fix dependency by removing post-releases from versions
and loosing constraints on internal packages.
Drop packages from ignore set
Also populate packages set | [
"Fix",
"dependency",
"by",
"removing",
"post",
"-",
"releases",
"from",
"versions",
"and",
"loosing",
"constraints",
"on",
"internal",
"packages",
".",
"Drop",
"packages",
"from",
"ignore",
"set"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L133-L163 |
2,429 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.add_references | def add_references(self, other_names):
"""Add references to other_names in outfile"""
if not other_names:
# Skip on empty list
return
with open(self.outfile, 'rt') as fp:
header, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.writelines(header)
fp.writelines(
'-r {0}.{1}\n'.format(other_name, OPTIONS['out_ext'])
for other_name in sorted(other_names)
)
fp.writelines(body) | python | def add_references(self, other_names):
"""Add references to other_names in outfile"""
if not other_names:
# Skip on empty list
return
with open(self.outfile, 'rt') as fp:
header, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.writelines(header)
fp.writelines(
'-r {0}.{1}\n'.format(other_name, OPTIONS['out_ext'])
for other_name in sorted(other_names)
)
fp.writelines(body) | [
"def",
"add_references",
"(",
"self",
",",
"other_names",
")",
":",
"if",
"not",
"other_names",
":",
"# Skip on empty list",
"return",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"header",
",",
"body",
"=",
"self",
".",
"split_header",
"(",
"fp",
")",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"writelines",
"(",
"header",
")",
"fp",
".",
"writelines",
"(",
"'-r {0}.{1}\\n'",
".",
"format",
"(",
"other_name",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
"for",
"other_name",
"in",
"sorted",
"(",
"other_names",
")",
")",
"fp",
".",
"writelines",
"(",
"body",
")"
] | Add references to other_names in outfile | [
"Add",
"references",
"to",
"other_names",
"in",
"outfile"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L165-L178 |
2,430 | peterdemin/pip-compile-multi | pipcompilemulti/environment.py | Environment.replace_header | def replace_header(self, header_text):
"""Replace pip-compile header with custom text"""
with open(self.outfile, 'rt') as fp:
_, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.write(header_text)
fp.writelines(body) | python | def replace_header(self, header_text):
"""Replace pip-compile header with custom text"""
with open(self.outfile, 'rt') as fp:
_, body = self.split_header(fp)
with open(self.outfile, 'wt') as fp:
fp.write(header_text)
fp.writelines(body) | [
"def",
"replace_header",
"(",
"self",
",",
"header_text",
")",
":",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'rt'",
")",
"as",
"fp",
":",
"_",
",",
"body",
"=",
"self",
".",
"split_header",
"(",
"fp",
")",
"with",
"open",
"(",
"self",
".",
"outfile",
",",
"'wt'",
")",
"as",
"fp",
":",
"fp",
".",
"write",
"(",
"header_text",
")",
"fp",
".",
"writelines",
"(",
"body",
")"
] | Replace pip-compile header with custom text | [
"Replace",
"pip",
"-",
"compile",
"header",
"with",
"custom",
"text"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/environment.py#L197-L203 |
2,431 | peterdemin/pip-compile-multi | pipcompilemulti/discover.py | order_by_refs | def order_by_refs(envs):
"""
Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references.
"""
topology = {
env['name']: set(env['refs'])
for env in envs
}
by_name = {
env['name']: env
for env in envs
}
return [
by_name[name]
for name in toposort_flatten(topology)
] | python | def order_by_refs(envs):
"""
Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references.
"""
topology = {
env['name']: set(env['refs'])
for env in envs
}
by_name = {
env['name']: env
for env in envs
}
return [
by_name[name]
for name in toposort_flatten(topology)
] | [
"def",
"order_by_refs",
"(",
"envs",
")",
":",
"topology",
"=",
"{",
"env",
"[",
"'name'",
"]",
":",
"set",
"(",
"env",
"[",
"'refs'",
"]",
")",
"for",
"env",
"in",
"envs",
"}",
"by_name",
"=",
"{",
"env",
"[",
"'name'",
"]",
":",
"env",
"for",
"env",
"in",
"envs",
"}",
"return",
"[",
"by_name",
"[",
"name",
"]",
"for",
"name",
"in",
"toposort_flatten",
"(",
"topology",
")",
"]"
] | Return topologicaly sorted list of environments.
I.e. all referenced environments are placed before their references. | [
"Return",
"topologicaly",
"sorted",
"list",
"of",
"environments",
".",
"I",
".",
"e",
".",
"all",
"referenced",
"environments",
"are",
"placed",
"before",
"their",
"references",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/discover.py#L46-L62 |
2,432 | peterdemin/pip-compile-multi | pipcompilemulti/dependency.py | Dependency.is_compatible | def is_compatible(self):
"""Check if package name is matched by compatible_patterns"""
for pattern in OPTIONS['compatible_patterns']:
if fnmatch(self.package.lower(), pattern):
return True
return False | python | def is_compatible(self):
"""Check if package name is matched by compatible_patterns"""
for pattern in OPTIONS['compatible_patterns']:
if fnmatch(self.package.lower(), pattern):
return True
return False | [
"def",
"is_compatible",
"(",
"self",
")",
":",
"for",
"pattern",
"in",
"OPTIONS",
"[",
"'compatible_patterns'",
"]",
":",
"if",
"fnmatch",
"(",
"self",
".",
"package",
".",
"lower",
"(",
")",
",",
"pattern",
")",
":",
"return",
"True",
"return",
"False"
] | Check if package name is matched by compatible_patterns | [
"Check",
"if",
"package",
"name",
"is",
"matched",
"by",
"compatible_patterns"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/dependency.py#L104-L109 |
2,433 | peterdemin/pip-compile-multi | pipcompilemulti/dependency.py | Dependency.drop_post | def drop_post(self):
"""Remove .postXXXX postfix from version"""
post_index = self.version.find('.post')
if post_index >= 0:
self.version = self.version[:post_index] | python | def drop_post(self):
"""Remove .postXXXX postfix from version"""
post_index = self.version.find('.post')
if post_index >= 0:
self.version = self.version[:post_index] | [
"def",
"drop_post",
"(",
"self",
")",
":",
"post_index",
"=",
"self",
".",
"version",
".",
"find",
"(",
"'.post'",
")",
"if",
"post_index",
">=",
"0",
":",
"self",
".",
"version",
"=",
"self",
".",
"version",
"[",
":",
"post_index",
"]"
] | Remove .postXXXX postfix from version | [
"Remove",
".",
"postXXXX",
"postfix",
"from",
"version"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/dependency.py#L111-L115 |
2,434 | peterdemin/pip-compile-multi | pipcompilemulti/verify.py | verify_environments | def verify_environments():
"""
For each environment verify hash comments and report failures.
If any failure occured, exit with code 1.
"""
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
)
)
success = True
for conf in env_confs:
env = Environment(name=conf['name'])
current_comment = generate_hash_comment(env.infile)
existing_comment = parse_hash_comment(env.outfile)
if current_comment == existing_comment:
logger.info("OK - %s was generated from %s.",
env.outfile, env.infile)
else:
logger.error("ERROR! %s was not regenerated after changes in %s.",
env.outfile, env.infile)
logger.error("Expecting: %s", current_comment.strip())
logger.error("Found: %s", existing_comment.strip())
success = False
return success | python | def verify_environments():
"""
For each environment verify hash comments and report failures.
If any failure occured, exit with code 1.
"""
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
)
)
success = True
for conf in env_confs:
env = Environment(name=conf['name'])
current_comment = generate_hash_comment(env.infile)
existing_comment = parse_hash_comment(env.outfile)
if current_comment == existing_comment:
logger.info("OK - %s was generated from %s.",
env.outfile, env.infile)
else:
logger.error("ERROR! %s was not regenerated after changes in %s.",
env.outfile, env.infile)
logger.error("Expecting: %s", current_comment.strip())
logger.error("Found: %s", existing_comment.strip())
success = False
return success | [
"def",
"verify_environments",
"(",
")",
":",
"env_confs",
"=",
"discover",
"(",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'*.'",
"+",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
")",
")",
"success",
"=",
"True",
"for",
"conf",
"in",
"env_confs",
":",
"env",
"=",
"Environment",
"(",
"name",
"=",
"conf",
"[",
"'name'",
"]",
")",
"current_comment",
"=",
"generate_hash_comment",
"(",
"env",
".",
"infile",
")",
"existing_comment",
"=",
"parse_hash_comment",
"(",
"env",
".",
"outfile",
")",
"if",
"current_comment",
"==",
"existing_comment",
":",
"logger",
".",
"info",
"(",
"\"OK - %s was generated from %s.\"",
",",
"env",
".",
"outfile",
",",
"env",
".",
"infile",
")",
"else",
":",
"logger",
".",
"error",
"(",
"\"ERROR! %s was not regenerated after changes in %s.\"",
",",
"env",
".",
"outfile",
",",
"env",
".",
"infile",
")",
"logger",
".",
"error",
"(",
"\"Expecting: %s\"",
",",
"current_comment",
".",
"strip",
"(",
")",
")",
"logger",
".",
"error",
"(",
"\"Found: %s\"",
",",
"existing_comment",
".",
"strip",
"(",
")",
")",
"success",
"=",
"False",
"return",
"success"
] | For each environment verify hash comments and report failures.
If any failure occured, exit with code 1. | [
"For",
"each",
"environment",
"verify",
"hash",
"comments",
"and",
"report",
"failures",
".",
"If",
"any",
"failure",
"occured",
"exit",
"with",
"code",
"1",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/verify.py#L15-L40 |
2,435 | peterdemin/pip-compile-multi | pipcompilemulti/verify.py | generate_hash_comment | def generate_hash_comment(file_path):
"""
Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash
"""
with open(file_path, 'rb') as fp:
hexdigest = hashlib.sha1(fp.read().strip()).hexdigest()
return "# SHA1:{0}\n".format(hexdigest) | python | def generate_hash_comment(file_path):
"""
Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash
"""
with open(file_path, 'rb') as fp:
hexdigest = hashlib.sha1(fp.read().strip()).hexdigest()
return "# SHA1:{0}\n".format(hexdigest) | [
"def",
"generate_hash_comment",
"(",
"file_path",
")",
":",
"with",
"open",
"(",
"file_path",
",",
"'rb'",
")",
"as",
"fp",
":",
"hexdigest",
"=",
"hashlib",
".",
"sha1",
"(",
"fp",
".",
"read",
"(",
")",
".",
"strip",
"(",
")",
")",
".",
"hexdigest",
"(",
")",
"return",
"\"# SHA1:{0}\\n\"",
".",
"format",
"(",
"hexdigest",
")"
] | Read file with given file_path and return string of format
# SHA1:da39a3ee5e6b4b0d3255bfef95601890afd80709
which is hex representation of SHA1 file content hash | [
"Read",
"file",
"with",
"given",
"file_path",
"and",
"return",
"string",
"of",
"format"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/verify.py#L43-L53 |
2,436 | peterdemin/pip-compile-multi | pipcompilemulti/config.py | parse_value | def parse_value(key, value):
"""Parse value as comma-delimited list if default value for it is list"""
default = OPTIONS.get(key)
if isinstance(default, collections.Iterable):
if not isinstance(default, six.string_types):
return [item.strip()
for item in value.split(',')]
return value | python | def parse_value(key, value):
"""Parse value as comma-delimited list if default value for it is list"""
default = OPTIONS.get(key)
if isinstance(default, collections.Iterable):
if not isinstance(default, six.string_types):
return [item.strip()
for item in value.split(',')]
return value | [
"def",
"parse_value",
"(",
"key",
",",
"value",
")",
":",
"default",
"=",
"OPTIONS",
".",
"get",
"(",
"key",
")",
"if",
"isinstance",
"(",
"default",
",",
"collections",
".",
"Iterable",
")",
":",
"if",
"not",
"isinstance",
"(",
"default",
",",
"six",
".",
"string_types",
")",
":",
"return",
"[",
"item",
".",
"strip",
"(",
")",
"for",
"item",
"in",
"value",
".",
"split",
"(",
"','",
")",
"]",
"return",
"value"
] | Parse value as comma-delimited list if default value for it is list | [
"Parse",
"value",
"as",
"comma",
"-",
"delimited",
"list",
"if",
"default",
"value",
"for",
"it",
"is",
"list"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/config.py#L53-L60 |
2,437 | peterdemin/pip-compile-multi | pipcompilemulti/config.py | python_version_matchers | def python_version_matchers():
"""Return set of string representations of current python version"""
version = sys.version_info
patterns = [
"{0}",
"{0}{1}",
"{0}.{1}",
]
matchers = [
pattern.format(*version)
for pattern in patterns
] + [None]
return set(matchers) | python | def python_version_matchers():
"""Return set of string representations of current python version"""
version = sys.version_info
patterns = [
"{0}",
"{0}{1}",
"{0}.{1}",
]
matchers = [
pattern.format(*version)
for pattern in patterns
] + [None]
return set(matchers) | [
"def",
"python_version_matchers",
"(",
")",
":",
"version",
"=",
"sys",
".",
"version_info",
"patterns",
"=",
"[",
"\"{0}\"",
",",
"\"{0}{1}\"",
",",
"\"{0}.{1}\"",
",",
"]",
"matchers",
"=",
"[",
"pattern",
".",
"format",
"(",
"*",
"version",
")",
"for",
"pattern",
"in",
"patterns",
"]",
"+",
"[",
"None",
"]",
"return",
"set",
"(",
"matchers",
")"
] | Return set of string representations of current python version | [
"Return",
"set",
"of",
"string",
"representations",
"of",
"current",
"python",
"version"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/config.py#L63-L75 |
2,438 | peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | verify | def verify(ctx):
"""Upgrade locked dependency versions"""
oks = run_configurations(
skipper(verify_environments),
read_sections,
)
ctx.exit(0
if False not in oks
else 1) | python | def verify(ctx):
"""Upgrade locked dependency versions"""
oks = run_configurations(
skipper(verify_environments),
read_sections,
)
ctx.exit(0
if False not in oks
else 1) | [
"def",
"verify",
"(",
"ctx",
")",
":",
"oks",
"=",
"run_configurations",
"(",
"skipper",
"(",
"verify_environments",
")",
",",
"read_sections",
",",
")",
"ctx",
".",
"exit",
"(",
"0",
"if",
"False",
"not",
"in",
"oks",
"else",
"1",
")"
] | Upgrade locked dependency versions | [
"Upgrade",
"locked",
"dependency",
"versions"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L38-L46 |
2,439 | peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | skipper | def skipper(func):
"""Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates."""
@functools.wraps(func)
def wrapped():
"""Dummy docstring to make pylint happy."""
key = (OPTIONS['base_dir'], OPTIONS['in_ext'], OPTIONS['out_ext'])
if key not in seen:
seen[key] = func()
return seen[key]
seen = {}
return wrapped | python | def skipper(func):
"""Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates."""
@functools.wraps(func)
def wrapped():
"""Dummy docstring to make pylint happy."""
key = (OPTIONS['base_dir'], OPTIONS['in_ext'], OPTIONS['out_ext'])
if key not in seen:
seen[key] = func()
return seen[key]
seen = {}
return wrapped | [
"def",
"skipper",
"(",
"func",
")",
":",
"@",
"functools",
".",
"wraps",
"(",
"func",
")",
"def",
"wrapped",
"(",
")",
":",
"\"\"\"Dummy docstring to make pylint happy.\"\"\"",
"key",
"=",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
"OPTIONS",
"[",
"'out_ext'",
"]",
")",
"if",
"key",
"not",
"in",
"seen",
":",
"seen",
"[",
"key",
"]",
"=",
"func",
"(",
")",
"return",
"seen",
"[",
"key",
"]",
"seen",
"=",
"{",
"}",
"return",
"wrapped"
] | Decorator that memorizes base_dir, in_ext and out_ext from OPTIONS
and skips execution for duplicates. | [
"Decorator",
"that",
"memorizes",
"base_dir",
"in_ext",
"and",
"out_ext",
"from",
"OPTIONS",
"and",
"skips",
"execution",
"for",
"duplicates",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L49-L60 |
2,440 | peterdemin/pip-compile-multi | pipcompilemulti/cli_v2.py | run_configurations | def run_configurations(callback, sections_reader):
"""Parse configurations and execute callback for matching."""
base = dict(OPTIONS)
sections = sections_reader()
if sections is None:
logger.info("Configuration not found in .ini files. "
"Running with default settings")
recompile()
elif sections == []:
logger.info("Configuration does not match current runtime. "
"Exiting")
results = []
for section, options in sections:
OPTIONS.clear()
OPTIONS.update(base)
OPTIONS.update(options)
logger.debug("Running configuration from section \"%s\". OPTIONS: %r",
section, OPTIONS)
results.append(callback())
return results | python | def run_configurations(callback, sections_reader):
"""Parse configurations and execute callback for matching."""
base = dict(OPTIONS)
sections = sections_reader()
if sections is None:
logger.info("Configuration not found in .ini files. "
"Running with default settings")
recompile()
elif sections == []:
logger.info("Configuration does not match current runtime. "
"Exiting")
results = []
for section, options in sections:
OPTIONS.clear()
OPTIONS.update(base)
OPTIONS.update(options)
logger.debug("Running configuration from section \"%s\". OPTIONS: %r",
section, OPTIONS)
results.append(callback())
return results | [
"def",
"run_configurations",
"(",
"callback",
",",
"sections_reader",
")",
":",
"base",
"=",
"dict",
"(",
"OPTIONS",
")",
"sections",
"=",
"sections_reader",
"(",
")",
"if",
"sections",
"is",
"None",
":",
"logger",
".",
"info",
"(",
"\"Configuration not found in .ini files. \"",
"\"Running with default settings\"",
")",
"recompile",
"(",
")",
"elif",
"sections",
"==",
"[",
"]",
":",
"logger",
".",
"info",
"(",
"\"Configuration does not match current runtime. \"",
"\"Exiting\"",
")",
"results",
"=",
"[",
"]",
"for",
"section",
",",
"options",
"in",
"sections",
":",
"OPTIONS",
".",
"clear",
"(",
")",
"OPTIONS",
".",
"update",
"(",
"base",
")",
"OPTIONS",
".",
"update",
"(",
"options",
")",
"logger",
".",
"debug",
"(",
"\"Running configuration from section \\\"%s\\\". OPTIONS: %r\"",
",",
"section",
",",
"OPTIONS",
")",
"results",
".",
"append",
"(",
"callback",
"(",
")",
")",
"return",
"results"
] | Parse configurations and execute callback for matching. | [
"Parse",
"configurations",
"and",
"execute",
"callback",
"for",
"matching",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/cli_v2.py#L63-L82 |
2,441 | peterdemin/pip-compile-multi | pipcompilemulti/actions.py | recompile | def recompile():
"""
Compile requirements files for all environments.
"""
pinned_packages = {}
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
),
)
if OPTIONS['header_file']:
with open(OPTIONS['header_file']) as fp:
base_header_text = fp.read()
else:
base_header_text = DEFAULT_HEADER
hashed_by_reference = set()
for name in OPTIONS['add_hashes']:
hashed_by_reference.update(
reference_cluster(env_confs, name)
)
included_and_refs = set(OPTIONS['include_names'])
for name in set(included_and_refs):
included_and_refs.update(
recursive_refs(env_confs, name)
)
for conf in env_confs:
if included_and_refs:
if conf['name'] not in included_and_refs:
# Skip envs that are not included or referenced by included:
continue
rrefs = recursive_refs(env_confs, conf['name'])
add_hashes = conf['name'] in hashed_by_reference
env = Environment(
name=conf['name'],
ignore=merged_packages(pinned_packages, rrefs),
forbid_post=conf['name'] in OPTIONS['forbid_post'],
add_hashes=add_hashes,
)
logger.info("Locking %s to %s. References: %r",
env.infile, env.outfile, sorted(rrefs))
env.create_lockfile()
header_text = generate_hash_comment(env.infile) + base_header_text
env.replace_header(header_text)
env.add_references(conf['refs'])
pinned_packages[conf['name']] = env.packages | python | def recompile():
"""
Compile requirements files for all environments.
"""
pinned_packages = {}
env_confs = discover(
os.path.join(
OPTIONS['base_dir'],
'*.' + OPTIONS['in_ext'],
),
)
if OPTIONS['header_file']:
with open(OPTIONS['header_file']) as fp:
base_header_text = fp.read()
else:
base_header_text = DEFAULT_HEADER
hashed_by_reference = set()
for name in OPTIONS['add_hashes']:
hashed_by_reference.update(
reference_cluster(env_confs, name)
)
included_and_refs = set(OPTIONS['include_names'])
for name in set(included_and_refs):
included_and_refs.update(
recursive_refs(env_confs, name)
)
for conf in env_confs:
if included_and_refs:
if conf['name'] not in included_and_refs:
# Skip envs that are not included or referenced by included:
continue
rrefs = recursive_refs(env_confs, conf['name'])
add_hashes = conf['name'] in hashed_by_reference
env = Environment(
name=conf['name'],
ignore=merged_packages(pinned_packages, rrefs),
forbid_post=conf['name'] in OPTIONS['forbid_post'],
add_hashes=add_hashes,
)
logger.info("Locking %s to %s. References: %r",
env.infile, env.outfile, sorted(rrefs))
env.create_lockfile()
header_text = generate_hash_comment(env.infile) + base_header_text
env.replace_header(header_text)
env.add_references(conf['refs'])
pinned_packages[conf['name']] = env.packages | [
"def",
"recompile",
"(",
")",
":",
"pinned_packages",
"=",
"{",
"}",
"env_confs",
"=",
"discover",
"(",
"os",
".",
"path",
".",
"join",
"(",
"OPTIONS",
"[",
"'base_dir'",
"]",
",",
"'*.'",
"+",
"OPTIONS",
"[",
"'in_ext'",
"]",
",",
")",
",",
")",
"if",
"OPTIONS",
"[",
"'header_file'",
"]",
":",
"with",
"open",
"(",
"OPTIONS",
"[",
"'header_file'",
"]",
")",
"as",
"fp",
":",
"base_header_text",
"=",
"fp",
".",
"read",
"(",
")",
"else",
":",
"base_header_text",
"=",
"DEFAULT_HEADER",
"hashed_by_reference",
"=",
"set",
"(",
")",
"for",
"name",
"in",
"OPTIONS",
"[",
"'add_hashes'",
"]",
":",
"hashed_by_reference",
".",
"update",
"(",
"reference_cluster",
"(",
"env_confs",
",",
"name",
")",
")",
"included_and_refs",
"=",
"set",
"(",
"OPTIONS",
"[",
"'include_names'",
"]",
")",
"for",
"name",
"in",
"set",
"(",
"included_and_refs",
")",
":",
"included_and_refs",
".",
"update",
"(",
"recursive_refs",
"(",
"env_confs",
",",
"name",
")",
")",
"for",
"conf",
"in",
"env_confs",
":",
"if",
"included_and_refs",
":",
"if",
"conf",
"[",
"'name'",
"]",
"not",
"in",
"included_and_refs",
":",
"# Skip envs that are not included or referenced by included:",
"continue",
"rrefs",
"=",
"recursive_refs",
"(",
"env_confs",
",",
"conf",
"[",
"'name'",
"]",
")",
"add_hashes",
"=",
"conf",
"[",
"'name'",
"]",
"in",
"hashed_by_reference",
"env",
"=",
"Environment",
"(",
"name",
"=",
"conf",
"[",
"'name'",
"]",
",",
"ignore",
"=",
"merged_packages",
"(",
"pinned_packages",
",",
"rrefs",
")",
",",
"forbid_post",
"=",
"conf",
"[",
"'name'",
"]",
"in",
"OPTIONS",
"[",
"'forbid_post'",
"]",
",",
"add_hashes",
"=",
"add_hashes",
",",
")",
"logger",
".",
"info",
"(",
"\"Locking %s to %s. References: %r\"",
",",
"env",
".",
"infile",
",",
"env",
".",
"outfile",
",",
"sorted",
"(",
"rrefs",
")",
")",
"env",
".",
"create_lockfile",
"(",
")",
"header_text",
"=",
"generate_hash_comment",
"(",
"env",
".",
"infile",
")",
"+",
"base_header_text",
"env",
".",
"replace_header",
"(",
"header_text",
")",
"env",
".",
"add_references",
"(",
"conf",
"[",
"'refs'",
"]",
")",
"pinned_packages",
"[",
"conf",
"[",
"'name'",
"]",
"]",
"=",
"env",
".",
"packages"
] | Compile requirements files for all environments. | [
"Compile",
"requirements",
"files",
"for",
"all",
"environments",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/actions.py#L17-L62 |
2,442 | peterdemin/pip-compile-multi | pipcompilemulti/actions.py | merged_packages | def merged_packages(env_packages, names):
"""
Return union set of environment packages with given names
>>> sorted(merged_packages(
... {
... 'a': {'x': 1, 'y': 2},
... 'b': {'y': 2, 'z': 3},
... 'c': {'z': 3, 'w': 4}
... },
... ['a', 'b']
... ).items())
[('x', 1), ('y', 2), ('z', 3)]
"""
combined_packages = sorted(itertools.chain.from_iterable(
env_packages[name].items()
for name in names
))
result = {}
errors = set()
for name, version in combined_packages:
if name in result:
if result[name] != version:
errors.add((name, version, result[name]))
else:
result[name] = version
if errors:
for error in sorted(errors):
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
error[0], error[1], error[2],
)
raise RuntimeError(
"Please add constraints for the package version listed above"
)
return result | python | def merged_packages(env_packages, names):
"""
Return union set of environment packages with given names
>>> sorted(merged_packages(
... {
... 'a': {'x': 1, 'y': 2},
... 'b': {'y': 2, 'z': 3},
... 'c': {'z': 3, 'w': 4}
... },
... ['a', 'b']
... ).items())
[('x', 1), ('y', 2), ('z', 3)]
"""
combined_packages = sorted(itertools.chain.from_iterable(
env_packages[name].items()
for name in names
))
result = {}
errors = set()
for name, version in combined_packages:
if name in result:
if result[name] != version:
errors.add((name, version, result[name]))
else:
result[name] = version
if errors:
for error in sorted(errors):
logger.error(
"Package %s was resolved to different "
"versions in different environments: %s and %s",
error[0], error[1], error[2],
)
raise RuntimeError(
"Please add constraints for the package version listed above"
)
return result | [
"def",
"merged_packages",
"(",
"env_packages",
",",
"names",
")",
":",
"combined_packages",
"=",
"sorted",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"env_packages",
"[",
"name",
"]",
".",
"items",
"(",
")",
"for",
"name",
"in",
"names",
")",
")",
"result",
"=",
"{",
"}",
"errors",
"=",
"set",
"(",
")",
"for",
"name",
",",
"version",
"in",
"combined_packages",
":",
"if",
"name",
"in",
"result",
":",
"if",
"result",
"[",
"name",
"]",
"!=",
"version",
":",
"errors",
".",
"add",
"(",
"(",
"name",
",",
"version",
",",
"result",
"[",
"name",
"]",
")",
")",
"else",
":",
"result",
"[",
"name",
"]",
"=",
"version",
"if",
"errors",
":",
"for",
"error",
"in",
"sorted",
"(",
"errors",
")",
":",
"logger",
".",
"error",
"(",
"\"Package %s was resolved to different \"",
"\"versions in different environments: %s and %s\"",
",",
"error",
"[",
"0",
"]",
",",
"error",
"[",
"1",
"]",
",",
"error",
"[",
"2",
"]",
",",
")",
"raise",
"RuntimeError",
"(",
"\"Please add constraints for the package version listed above\"",
")",
"return",
"result"
] | Return union set of environment packages with given names
>>> sorted(merged_packages(
... {
... 'a': {'x': 1, 'y': 2},
... 'b': {'y': 2, 'z': 3},
... 'c': {'z': 3, 'w': 4}
... },
... ['a', 'b']
... ).items())
[('x', 1), ('y', 2), ('z', 3)] | [
"Return",
"union",
"set",
"of",
"environment",
"packages",
"with",
"given",
"names"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/actions.py#L65-L101 |
2,443 | peterdemin/pip-compile-multi | pipcompilemulti/actions.py | recursive_refs | def recursive_refs(envs, name):
"""
Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ['base', 'test']
True
"""
refs_by_name = {
env['name']: set(env['refs'])
for env in envs
}
refs = refs_by_name[name]
if refs:
indirect_refs = set(itertools.chain.from_iterable([
recursive_refs(envs, ref)
for ref in refs
]))
else:
indirect_refs = set()
return set.union(refs, indirect_refs) | python | def recursive_refs(envs, name):
"""
Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ['base', 'test']
True
"""
refs_by_name = {
env['name']: set(env['refs'])
for env in envs
}
refs = refs_by_name[name]
if refs:
indirect_refs = set(itertools.chain.from_iterable([
recursive_refs(envs, ref)
for ref in refs
]))
else:
indirect_refs = set()
return set.union(refs, indirect_refs) | [
"def",
"recursive_refs",
"(",
"envs",
",",
"name",
")",
":",
"refs_by_name",
"=",
"{",
"env",
"[",
"'name'",
"]",
":",
"set",
"(",
"env",
"[",
"'refs'",
"]",
")",
"for",
"env",
"in",
"envs",
"}",
"refs",
"=",
"refs_by_name",
"[",
"name",
"]",
"if",
"refs",
":",
"indirect_refs",
"=",
"set",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"recursive_refs",
"(",
"envs",
",",
"ref",
")",
"for",
"ref",
"in",
"refs",
"]",
")",
")",
"else",
":",
"indirect_refs",
"=",
"set",
"(",
")",
"return",
"set",
".",
"union",
"(",
"refs",
",",
"indirect_refs",
")"
] | Return set of recursive refs for given env name
>>> local_refs = sorted(recursive_refs([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'local'))
>>> local_refs == ['base', 'test']
True | [
"Return",
"set",
"of",
"recursive",
"refs",
"for",
"given",
"env",
"name"
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/actions.py#L104-L128 |
2,444 | peterdemin/pip-compile-multi | pipcompilemulti/actions.py | reference_cluster | def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'test'))
>>> cluster == ['base', 'local', 'test']
True
"""
edges = [
set([env['name'], ref])
for env in envs
for ref in env['refs']
]
prev, cluster = set(), set([name])
while prev != cluster:
# While cluster grows
prev = set(cluster)
to_visit = []
for edge in edges:
if cluster & edge:
# Add adjacent nodes:
cluster |= edge
else:
# Leave only edges that are out
# of cluster for the next round:
to_visit.append(edge)
edges = to_visit
return cluster | python | def reference_cluster(envs, name):
"""
Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'test'))
>>> cluster == ['base', 'local', 'test']
True
"""
edges = [
set([env['name'], ref])
for env in envs
for ref in env['refs']
]
prev, cluster = set(), set([name])
while prev != cluster:
# While cluster grows
prev = set(cluster)
to_visit = []
for edge in edges:
if cluster & edge:
# Add adjacent nodes:
cluster |= edge
else:
# Leave only edges that are out
# of cluster for the next round:
to_visit.append(edge)
edges = to_visit
return cluster | [
"def",
"reference_cluster",
"(",
"envs",
",",
"name",
")",
":",
"edges",
"=",
"[",
"set",
"(",
"[",
"env",
"[",
"'name'",
"]",
",",
"ref",
"]",
")",
"for",
"env",
"in",
"envs",
"for",
"ref",
"in",
"env",
"[",
"'refs'",
"]",
"]",
"prev",
",",
"cluster",
"=",
"set",
"(",
")",
",",
"set",
"(",
"[",
"name",
"]",
")",
"while",
"prev",
"!=",
"cluster",
":",
"# While cluster grows",
"prev",
"=",
"set",
"(",
"cluster",
")",
"to_visit",
"=",
"[",
"]",
"for",
"edge",
"in",
"edges",
":",
"if",
"cluster",
"&",
"edge",
":",
"# Add adjacent nodes:",
"cluster",
"|=",
"edge",
"else",
":",
"# Leave only edges that are out",
"# of cluster for the next round:",
"to_visit",
".",
"append",
"(",
"edge",
")",
"edges",
"=",
"to_visit",
"return",
"cluster"
] | Return set of all env names referencing or
referenced by given name.
>>> cluster = sorted(reference_cluster([
... {'name': 'base', 'refs': []},
... {'name': 'test', 'refs': ['base']},
... {'name': 'local', 'refs': ['test']},
... ], 'test'))
>>> cluster == ['base', 'local', 'test']
True | [
"Return",
"set",
"of",
"all",
"env",
"names",
"referencing",
"or",
"referenced",
"by",
"given",
"name",
"."
] | 7bd1968c424dd7ce3236885b4b3e4e28523e6915 | https://github.com/peterdemin/pip-compile-multi/blob/7bd1968c424dd7ce3236885b4b3e4e28523e6915/pipcompilemulti/actions.py#L131-L163 |
2,445 | oceanprotocol/squid-py | squid_py/http_requests/requests_session.py | get_requests_session | def get_requests_session():
"""
Set connection pool maxsize and block value to avoid `connection pool full` warnings.
:return: requests session
"""
session = requests.sessions.Session()
session.mount('http://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))
session.mount('https://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))
return session | python | def get_requests_session():
"""
Set connection pool maxsize and block value to avoid `connection pool full` warnings.
:return: requests session
"""
session = requests.sessions.Session()
session.mount('http://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))
session.mount('https://', HTTPAdapter(pool_connections=25, pool_maxsize=25, pool_block=True))
return session | [
"def",
"get_requests_session",
"(",
")",
":",
"session",
"=",
"requests",
".",
"sessions",
".",
"Session",
"(",
")",
"session",
".",
"mount",
"(",
"'http://'",
",",
"HTTPAdapter",
"(",
"pool_connections",
"=",
"25",
",",
"pool_maxsize",
"=",
"25",
",",
"pool_block",
"=",
"True",
")",
")",
"session",
".",
"mount",
"(",
"'https://'",
",",
"HTTPAdapter",
"(",
"pool_connections",
"=",
"25",
",",
"pool_maxsize",
"=",
"25",
",",
"pool_block",
"=",
"True",
")",
")",
"return",
"session"
] | Set connection pool maxsize and block value to avoid `connection pool full` warnings.
:return: requests session | [
"Set",
"connection",
"pool",
"maxsize",
"and",
"block",
"value",
"to",
"avoid",
"connection",
"pool",
"full",
"warnings",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/http_requests/requests_session.py#L5-L14 |
2,446 | oceanprotocol/squid-py | squid_py/keeper/dispenser.py | Dispenser.request_tokens | def request_tokens(self, amount, account):
"""
Request an amount of tokens for a particular address.
This transaction has gas cost
:param amount: Amount of tokens, int
:param account: Account instance
:raise OceanInvalidTransaction: Transaction failed
:return: bool
"""
address = account.address
try:
tx_hash = self.send_transaction(
'requestTokens',
(amount,),
transact={'from': address,
'passphrase': account.password}
)
logging.debug(f'{address} requests {amount} tokens, returning receipt')
try:
receipt = Web3Provider.get_web3().eth.waitForTransactionReceipt(
tx_hash, timeout=20)
logging.debug(f'requestTokens receipt: {receipt}')
except Timeout:
receipt = None
if not receipt:
return False
if receipt.status == 0:
logging.warning(f'request tokens failed: Tx-receipt={receipt}')
logging.warning(f'request tokens failed: account {address}')
return False
# check for emitted events:
rfe = EventFilter(
'RequestFrequencyExceeded',
self.events.RequestFrequencyExceeded,
argument_filters={'requester': Web3Provider.get_web3().toBytes(hexstr=address)},
from_block='latest',
to_block='latest',
)
logs = rfe.get_all_entries(max_tries=5)
if logs:
logging.warning(f'request tokens failed RequestFrequencyExceeded')
logging.info(f'RequestFrequencyExceeded event logs: {logs}')
return False
rle = EventFilter(
'RequestLimitExceeded',
self.events.RequestLimitExceeded,
argument_filters={'requester': Web3Provider.get_web3().toBytes(hexstr=address)},
from_block='latest',
to_block='latest',
)
logs = rle.get_all_entries(max_tries=5)
if logs:
logging.warning(f'request tokens failed RequestLimitExceeded')
logging.info(f'RequestLimitExceeded event logs: {logs}')
return False
return True
except ValueError as err:
raise OceanInvalidTransaction(
f'Requesting {amount} tokens'
f' to {address} failed with error: {err}'
) | python | def request_tokens(self, amount, account):
"""
Request an amount of tokens for a particular address.
This transaction has gas cost
:param amount: Amount of tokens, int
:param account: Account instance
:raise OceanInvalidTransaction: Transaction failed
:return: bool
"""
address = account.address
try:
tx_hash = self.send_transaction(
'requestTokens',
(amount,),
transact={'from': address,
'passphrase': account.password}
)
logging.debug(f'{address} requests {amount} tokens, returning receipt')
try:
receipt = Web3Provider.get_web3().eth.waitForTransactionReceipt(
tx_hash, timeout=20)
logging.debug(f'requestTokens receipt: {receipt}')
except Timeout:
receipt = None
if not receipt:
return False
if receipt.status == 0:
logging.warning(f'request tokens failed: Tx-receipt={receipt}')
logging.warning(f'request tokens failed: account {address}')
return False
# check for emitted events:
rfe = EventFilter(
'RequestFrequencyExceeded',
self.events.RequestFrequencyExceeded,
argument_filters={'requester': Web3Provider.get_web3().toBytes(hexstr=address)},
from_block='latest',
to_block='latest',
)
logs = rfe.get_all_entries(max_tries=5)
if logs:
logging.warning(f'request tokens failed RequestFrequencyExceeded')
logging.info(f'RequestFrequencyExceeded event logs: {logs}')
return False
rle = EventFilter(
'RequestLimitExceeded',
self.events.RequestLimitExceeded,
argument_filters={'requester': Web3Provider.get_web3().toBytes(hexstr=address)},
from_block='latest',
to_block='latest',
)
logs = rle.get_all_entries(max_tries=5)
if logs:
logging.warning(f'request tokens failed RequestLimitExceeded')
logging.info(f'RequestLimitExceeded event logs: {logs}')
return False
return True
except ValueError as err:
raise OceanInvalidTransaction(
f'Requesting {amount} tokens'
f' to {address} failed with error: {err}'
) | [
"def",
"request_tokens",
"(",
"self",
",",
"amount",
",",
"account",
")",
":",
"address",
"=",
"account",
".",
"address",
"try",
":",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'requestTokens'",
",",
"(",
"amount",
",",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")",
"logging",
".",
"debug",
"(",
"f'{address} requests {amount} tokens, returning receipt'",
")",
"try",
":",
"receipt",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"eth",
".",
"waitForTransactionReceipt",
"(",
"tx_hash",
",",
"timeout",
"=",
"20",
")",
"logging",
".",
"debug",
"(",
"f'requestTokens receipt: {receipt}'",
")",
"except",
"Timeout",
":",
"receipt",
"=",
"None",
"if",
"not",
"receipt",
":",
"return",
"False",
"if",
"receipt",
".",
"status",
"==",
"0",
":",
"logging",
".",
"warning",
"(",
"f'request tokens failed: Tx-receipt={receipt}'",
")",
"logging",
".",
"warning",
"(",
"f'request tokens failed: account {address}'",
")",
"return",
"False",
"# check for emitted events:",
"rfe",
"=",
"EventFilter",
"(",
"'RequestFrequencyExceeded'",
",",
"self",
".",
"events",
".",
"RequestFrequencyExceeded",
",",
"argument_filters",
"=",
"{",
"'requester'",
":",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toBytes",
"(",
"hexstr",
"=",
"address",
")",
"}",
",",
"from_block",
"=",
"'latest'",
",",
"to_block",
"=",
"'latest'",
",",
")",
"logs",
"=",
"rfe",
".",
"get_all_entries",
"(",
"max_tries",
"=",
"5",
")",
"if",
"logs",
":",
"logging",
".",
"warning",
"(",
"f'request tokens failed RequestFrequencyExceeded'",
")",
"logging",
".",
"info",
"(",
"f'RequestFrequencyExceeded event logs: {logs}'",
")",
"return",
"False",
"rle",
"=",
"EventFilter",
"(",
"'RequestLimitExceeded'",
",",
"self",
".",
"events",
".",
"RequestLimitExceeded",
",",
"argument_filters",
"=",
"{",
"'requester'",
":",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toBytes",
"(",
"hexstr",
"=",
"address",
")",
"}",
",",
"from_block",
"=",
"'latest'",
",",
"to_block",
"=",
"'latest'",
",",
")",
"logs",
"=",
"rle",
".",
"get_all_entries",
"(",
"max_tries",
"=",
"5",
")",
"if",
"logs",
":",
"logging",
".",
"warning",
"(",
"f'request tokens failed RequestLimitExceeded'",
")",
"logging",
".",
"info",
"(",
"f'RequestLimitExceeded event logs: {logs}'",
")",
"return",
"False",
"return",
"True",
"except",
"ValueError",
"as",
"err",
":",
"raise",
"OceanInvalidTransaction",
"(",
"f'Requesting {amount} tokens'",
"f' to {address} failed with error: {err}'",
")"
] | Request an amount of tokens for a particular address.
This transaction has gas cost
:param amount: Amount of tokens, int
:param account: Account instance
:raise OceanInvalidTransaction: Transaction failed
:return: bool | [
"Request",
"an",
"amount",
"of",
"tokens",
"for",
"a",
"particular",
"address",
".",
"This",
"transaction",
"has",
"gas",
"cost"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/dispenser.py#L20-L87 |
2,447 | oceanprotocol/squid-py | squid_py/keeper/keeper.py | Keeper.get_network_name | def get_network_name(network_id):
"""
Return the keeper network name based on the current ethereum network id.
Return `development` for every network id that is not mapped.
:param network_id: Network id, int
:return: Network name, str
"""
if os.environ.get('KEEPER_NETWORK_NAME'):
logging.debug('keeper network name overridden by an environment variable: {}'.format(
os.environ.get('KEEPER_NETWORK_NAME')))
return os.environ.get('KEEPER_NETWORK_NAME')
return Keeper._network_name_map.get(network_id, Keeper.DEFAULT_NETWORK_NAME) | python | def get_network_name(network_id):
"""
Return the keeper network name based on the current ethereum network id.
Return `development` for every network id that is not mapped.
:param network_id: Network id, int
:return: Network name, str
"""
if os.environ.get('KEEPER_NETWORK_NAME'):
logging.debug('keeper network name overridden by an environment variable: {}'.format(
os.environ.get('KEEPER_NETWORK_NAME')))
return os.environ.get('KEEPER_NETWORK_NAME')
return Keeper._network_name_map.get(network_id, Keeper.DEFAULT_NETWORK_NAME) | [
"def",
"get_network_name",
"(",
"network_id",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"'KEEPER_NETWORK_NAME'",
")",
":",
"logging",
".",
"debug",
"(",
"'keeper network name overridden by an environment variable: {}'",
".",
"format",
"(",
"os",
".",
"environ",
".",
"get",
"(",
"'KEEPER_NETWORK_NAME'",
")",
")",
")",
"return",
"os",
".",
"environ",
".",
"get",
"(",
"'KEEPER_NETWORK_NAME'",
")",
"return",
"Keeper",
".",
"_network_name_map",
".",
"get",
"(",
"network_id",
",",
"Keeper",
".",
"DEFAULT_NETWORK_NAME",
")"
] | Return the keeper network name based on the current ethereum network id.
Return `development` for every network id that is not mapped.
:param network_id: Network id, int
:return: Network name, str | [
"Return",
"the",
"keeper",
"network",
"name",
"based",
"on",
"the",
"current",
"ethereum",
"network",
"id",
".",
"Return",
"development",
"for",
"every",
"network",
"id",
"that",
"is",
"not",
"mapped",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/keeper.py#L68-L81 |
2,448 | oceanprotocol/squid-py | squid_py/keeper/keeper.py | Keeper.unlock_account | def unlock_account(account):
"""
Unlock the account.
:param account: Account
:return:
"""
return Web3Provider.get_web3().personal.unlockAccount(account.address, account.password) | python | def unlock_account(account):
"""
Unlock the account.
:param account: Account
:return:
"""
return Web3Provider.get_web3().personal.unlockAccount(account.address, account.password) | [
"def",
"unlock_account",
"(",
"account",
")",
":",
"return",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"personal",
".",
"unlockAccount",
"(",
"account",
".",
"address",
",",
"account",
".",
"password",
")"
] | Unlock the account.
:param account: Account
:return: | [
"Unlock",
"the",
"account",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/keeper.py#L114-L121 |
2,449 | oceanprotocol/squid-py | squid_py/keeper/keeper.py | Keeper.get_condition_name_by_address | def get_condition_name_by_address(self, address):
"""Return the condition name for a given address."""
if self.lock_reward_condition.address == address:
return 'lockReward'
elif self.access_secret_store_condition.address == address:
return 'accessSecretStore'
elif self.escrow_reward_condition.address == address:
return 'escrowReward'
else:
logging.error(f'The current address {address} is not a condition address') | python | def get_condition_name_by_address(self, address):
"""Return the condition name for a given address."""
if self.lock_reward_condition.address == address:
return 'lockReward'
elif self.access_secret_store_condition.address == address:
return 'accessSecretStore'
elif self.escrow_reward_condition.address == address:
return 'escrowReward'
else:
logging.error(f'The current address {address} is not a condition address') | [
"def",
"get_condition_name_by_address",
"(",
"self",
",",
"address",
")",
":",
"if",
"self",
".",
"lock_reward_condition",
".",
"address",
"==",
"address",
":",
"return",
"'lockReward'",
"elif",
"self",
".",
"access_secret_store_condition",
".",
"address",
"==",
"address",
":",
"return",
"'accessSecretStore'",
"elif",
"self",
".",
"escrow_reward_condition",
".",
"address",
"==",
"address",
":",
"return",
"'escrowReward'",
"else",
":",
"logging",
".",
"error",
"(",
"f'The current address {address} is not a condition address'",
")"
] | Return the condition name for a given address. | [
"Return",
"the",
"condition",
"name",
"for",
"a",
"given",
"address",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/keeper.py#L133-L142 |
2,450 | oceanprotocol/squid-py | squid_py/brizo/brizo.py | Brizo.consume_service | def consume_service(service_agreement_id, service_endpoint, account, files,
destination_folder, index=None):
"""
Call the brizo endpoint to get access to the different files that form the asset.
:param service_agreement_id: Service Agreement Id, str
:param service_endpoint: Url to consume, str
:param account: Account instance of the consumer signing this agreement, hex-str
:param files: List containing the files to be consumed, list
:param index: Index of the document that is going to be downloaded, int
:param destination_folder: Path, str
:return: True if was downloaded, bool
"""
signature = Keeper.get_instance().sign_hash(service_agreement_id, account)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
assert index < len(files), logger.error(
'index can not be bigger than the number of files')
consume_url = Brizo._create_consume_url(service_endpoint, service_agreement_id, account,
None, signature, index)
logger.info(f'invoke consume endpoint with this url: {consume_url}')
response = Brizo._http_client.get(consume_url, stream=True)
file_name = Brizo._get_file_name(response)
Brizo.write_file(response, destination_folder, file_name)
else:
for i, _file in enumerate(files):
consume_url = Brizo._create_consume_url(service_endpoint, service_agreement_id,
account, _file,
signature, i)
logger.info(f'invoke consume endpoint with this url: {consume_url}')
response = Brizo._http_client.get(consume_url, stream=True)
file_name = Brizo._get_file_name(response)
Brizo.write_file(response, destination_folder, file_name) | python | def consume_service(service_agreement_id, service_endpoint, account, files,
destination_folder, index=None):
"""
Call the brizo endpoint to get access to the different files that form the asset.
:param service_agreement_id: Service Agreement Id, str
:param service_endpoint: Url to consume, str
:param account: Account instance of the consumer signing this agreement, hex-str
:param files: List containing the files to be consumed, list
:param index: Index of the document that is going to be downloaded, int
:param destination_folder: Path, str
:return: True if was downloaded, bool
"""
signature = Keeper.get_instance().sign_hash(service_agreement_id, account)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
assert index < len(files), logger.error(
'index can not be bigger than the number of files')
consume_url = Brizo._create_consume_url(service_endpoint, service_agreement_id, account,
None, signature, index)
logger.info(f'invoke consume endpoint with this url: {consume_url}')
response = Brizo._http_client.get(consume_url, stream=True)
file_name = Brizo._get_file_name(response)
Brizo.write_file(response, destination_folder, file_name)
else:
for i, _file in enumerate(files):
consume_url = Brizo._create_consume_url(service_endpoint, service_agreement_id,
account, _file,
signature, i)
logger.info(f'invoke consume endpoint with this url: {consume_url}')
response = Brizo._http_client.get(consume_url, stream=True)
file_name = Brizo._get_file_name(response)
Brizo.write_file(response, destination_folder, file_name) | [
"def",
"consume_service",
"(",
"service_agreement_id",
",",
"service_endpoint",
",",
"account",
",",
"files",
",",
"destination_folder",
",",
"index",
"=",
"None",
")",
":",
"signature",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"sign_hash",
"(",
"service_agreement_id",
",",
"account",
")",
"if",
"index",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
",",
"logger",
".",
"error",
"(",
"'index has to be an integer.'",
")",
"assert",
"index",
">=",
"0",
",",
"logger",
".",
"error",
"(",
"'index has to be 0 or a positive integer.'",
")",
"assert",
"index",
"<",
"len",
"(",
"files",
")",
",",
"logger",
".",
"error",
"(",
"'index can not be bigger than the number of files'",
")",
"consume_url",
"=",
"Brizo",
".",
"_create_consume_url",
"(",
"service_endpoint",
",",
"service_agreement_id",
",",
"account",
",",
"None",
",",
"signature",
",",
"index",
")",
"logger",
".",
"info",
"(",
"f'invoke consume endpoint with this url: {consume_url}'",
")",
"response",
"=",
"Brizo",
".",
"_http_client",
".",
"get",
"(",
"consume_url",
",",
"stream",
"=",
"True",
")",
"file_name",
"=",
"Brizo",
".",
"_get_file_name",
"(",
"response",
")",
"Brizo",
".",
"write_file",
"(",
"response",
",",
"destination_folder",
",",
"file_name",
")",
"else",
":",
"for",
"i",
",",
"_file",
"in",
"enumerate",
"(",
"files",
")",
":",
"consume_url",
"=",
"Brizo",
".",
"_create_consume_url",
"(",
"service_endpoint",
",",
"service_agreement_id",
",",
"account",
",",
"_file",
",",
"signature",
",",
"i",
")",
"logger",
".",
"info",
"(",
"f'invoke consume endpoint with this url: {consume_url}'",
")",
"response",
"=",
"Brizo",
".",
"_http_client",
".",
"get",
"(",
"consume_url",
",",
"stream",
"=",
"True",
")",
"file_name",
"=",
"Brizo",
".",
"_get_file_name",
"(",
"response",
")",
"Brizo",
".",
"write_file",
"(",
"response",
",",
"destination_folder",
",",
"file_name",
")"
] | Call the brizo endpoint to get access to the different files that form the asset.
:param service_agreement_id: Service Agreement Id, str
:param service_endpoint: Url to consume, str
:param account: Account instance of the consumer signing this agreement, hex-str
:param files: List containing the files to be consumed, list
:param index: Index of the document that is going to be downloaded, int
:param destination_folder: Path, str
:return: True if was downloaded, bool | [
"Call",
"the",
"brizo",
"endpoint",
"to",
"get",
"access",
"to",
"the",
"different",
"files",
"that",
"form",
"the",
"asset",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/brizo/brizo.py#L99-L132 |
2,451 | oceanprotocol/squid-py | squid_py/brizo/brizo.py | Brizo._prepare_consume_payload | def _prepare_consume_payload(did, service_agreement_id, service_definition_id, signature,
consumer_address):
"""Prepare a payload to send to `Brizo`.
:param did: DID, str
:param service_agreement_id: Service Agreement Id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
service in the DDO (DID document)
:param signature: the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement, str
:param consumer_address: ethereum address of the consumer signing this agreement, hex-str
:return: dict
"""
return json.dumps({
'did': did,
'serviceAgreementId': service_agreement_id,
ServiceAgreement.SERVICE_DEFINITION_ID: service_definition_id,
'signature': signature,
'consumerAddress': consumer_address
}) | python | def _prepare_consume_payload(did, service_agreement_id, service_definition_id, signature,
consumer_address):
"""Prepare a payload to send to `Brizo`.
:param did: DID, str
:param service_agreement_id: Service Agreement Id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
service in the DDO (DID document)
:param signature: the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement, str
:param consumer_address: ethereum address of the consumer signing this agreement, hex-str
:return: dict
"""
return json.dumps({
'did': did,
'serviceAgreementId': service_agreement_id,
ServiceAgreement.SERVICE_DEFINITION_ID: service_definition_id,
'signature': signature,
'consumerAddress': consumer_address
}) | [
"def",
"_prepare_consume_payload",
"(",
"did",
",",
"service_agreement_id",
",",
"service_definition_id",
",",
"signature",
",",
"consumer_address",
")",
":",
"return",
"json",
".",
"dumps",
"(",
"{",
"'did'",
":",
"did",
",",
"'serviceAgreementId'",
":",
"service_agreement_id",
",",
"ServiceAgreement",
".",
"SERVICE_DEFINITION_ID",
":",
"service_definition_id",
",",
"'signature'",
":",
"signature",
",",
"'consumerAddress'",
":",
"consumer_address",
"}",
")"
] | Prepare a payload to send to `Brizo`.
:param did: DID, str
:param service_agreement_id: Service Agreement Id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
service in the DDO (DID document)
:param signature: the signed agreement message hash which includes
conditions and their parameters values and other details of the agreement, str
:param consumer_address: ethereum address of the consumer signing this agreement, hex-str
:return: dict | [
"Prepare",
"a",
"payload",
"to",
"send",
"to",
"Brizo",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/brizo/brizo.py#L135-L154 |
2,452 | oceanprotocol/squid-py | squid_py/brizo/brizo.py | Brizo.get_brizo_url | def get_brizo_url(config):
"""
Return the Brizo component url.
:param config: Config
:return: Url, str
"""
brizo_url = 'http://localhost:8030'
if config.has_option('resources', 'brizo.url'):
brizo_url = config.get('resources', 'brizo.url') or brizo_url
brizo_path = '/api/v1/brizo'
return f'{brizo_url}{brizo_path}' | python | def get_brizo_url(config):
"""
Return the Brizo component url.
:param config: Config
:return: Url, str
"""
brizo_url = 'http://localhost:8030'
if config.has_option('resources', 'brizo.url'):
brizo_url = config.get('resources', 'brizo.url') or brizo_url
brizo_path = '/api/v1/brizo'
return f'{brizo_url}{brizo_path}' | [
"def",
"get_brizo_url",
"(",
"config",
")",
":",
"brizo_url",
"=",
"'http://localhost:8030'",
"if",
"config",
".",
"has_option",
"(",
"'resources'",
",",
"'brizo.url'",
")",
":",
"brizo_url",
"=",
"config",
".",
"get",
"(",
"'resources'",
",",
"'brizo.url'",
")",
"or",
"brizo_url",
"brizo_path",
"=",
"'/api/v1/brizo'",
"return",
"f'{brizo_url}{brizo_path}'"
] | Return the Brizo component url.
:param config: Config
:return: Url, str | [
"Return",
"the",
"Brizo",
"component",
"url",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/brizo/brizo.py#L157-L169 |
2,453 | oceanprotocol/squid-py | squid_py/ddo/metadata.py | Metadata.validate | def validate(metadata):
"""Validator of the metadata composition
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: bool
"""
# validate required sections and their sub items
for section_key in Metadata.REQUIRED_SECTIONS:
if section_key not in metadata or not metadata[section_key] or not isinstance(
metadata[section_key], dict):
return False
section = Metadata.MAIN_SECTIONS[section_key]
section_metadata = metadata[section_key]
for subkey in section.REQUIRED_VALUES_KEYS:
if subkey not in section_metadata or section_metadata[subkey] is None:
return False
return True | python | def validate(metadata):
"""Validator of the metadata composition
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: bool
"""
# validate required sections and their sub items
for section_key in Metadata.REQUIRED_SECTIONS:
if section_key not in metadata or not metadata[section_key] or not isinstance(
metadata[section_key], dict):
return False
section = Metadata.MAIN_SECTIONS[section_key]
section_metadata = metadata[section_key]
for subkey in section.REQUIRED_VALUES_KEYS:
if subkey not in section_metadata or section_metadata[subkey] is None:
return False
return True | [
"def",
"validate",
"(",
"metadata",
")",
":",
"# validate required sections and their sub items",
"for",
"section_key",
"in",
"Metadata",
".",
"REQUIRED_SECTIONS",
":",
"if",
"section_key",
"not",
"in",
"metadata",
"or",
"not",
"metadata",
"[",
"section_key",
"]",
"or",
"not",
"isinstance",
"(",
"metadata",
"[",
"section_key",
"]",
",",
"dict",
")",
":",
"return",
"False",
"section",
"=",
"Metadata",
".",
"MAIN_SECTIONS",
"[",
"section_key",
"]",
"section_metadata",
"=",
"metadata",
"[",
"section_key",
"]",
"for",
"subkey",
"in",
"section",
".",
"REQUIRED_VALUES_KEYS",
":",
"if",
"subkey",
"not",
"in",
"section_metadata",
"or",
"section_metadata",
"[",
"subkey",
"]",
"is",
"None",
":",
"return",
"False",
"return",
"True"
] | Validator of the metadata composition
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: bool | [
"Validator",
"of",
"the",
"metadata",
"composition"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/metadata.py#L127-L145 |
2,454 | oceanprotocol/squid-py | squid_py/ddo/metadata.py | Metadata.get_example | def get_example():
"""Retrieve an example of the metadata"""
example = dict()
for section_key, section in Metadata.MAIN_SECTIONS.items():
example[section_key] = section.EXAMPLE.copy()
return example | python | def get_example():
"""Retrieve an example of the metadata"""
example = dict()
for section_key, section in Metadata.MAIN_SECTIONS.items():
example[section_key] = section.EXAMPLE.copy()
return example | [
"def",
"get_example",
"(",
")",
":",
"example",
"=",
"dict",
"(",
")",
"for",
"section_key",
",",
"section",
"in",
"Metadata",
".",
"MAIN_SECTIONS",
".",
"items",
"(",
")",
":",
"example",
"[",
"section_key",
"]",
"=",
"section",
".",
"EXAMPLE",
".",
"copy",
"(",
")",
"return",
"example"
] | Retrieve an example of the metadata | [
"Retrieve",
"an",
"example",
"of",
"the",
"metadata"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/metadata.py#L148-L154 |
2,455 | oceanprotocol/squid-py | squid_py/secret_store/secret_store.py | SecretStore.encrypt_document | def encrypt_document(self, document_id, content, threshold=0):
"""
encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for encryption session
:param content: str to be encrypted
:param threshold: int
:return:
None -- if encryption failed
hex str -- the encrypted document
"""
return self._secret_store_client(self._account).publish_document(
remove_0x_prefix(document_id), content, threshold
) | python | def encrypt_document(self, document_id, content, threshold=0):
"""
encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for encryption session
:param content: str to be encrypted
:param threshold: int
:return:
None -- if encryption failed
hex str -- the encrypted document
"""
return self._secret_store_client(self._account).publish_document(
remove_0x_prefix(document_id), content, threshold
) | [
"def",
"encrypt_document",
"(",
"self",
",",
"document_id",
",",
"content",
",",
"threshold",
"=",
"0",
")",
":",
"return",
"self",
".",
"_secret_store_client",
"(",
"self",
".",
"_account",
")",
".",
"publish_document",
"(",
"remove_0x_prefix",
"(",
"document_id",
")",
",",
"content",
",",
"threshold",
")"
] | encrypt string data using the DID as an secret store id,
if secret store is enabled then return the result from secret store encryption
None for no encryption performed
:param document_id: hex str id of document to use for encryption session
:param content: str to be encrypted
:param threshold: int
:return:
None -- if encryption failed
hex str -- the encrypted document | [
"encrypt",
"string",
"data",
"using",
"the",
"DID",
"as",
"an",
"secret",
"store",
"id",
"if",
"secret",
"store",
"is",
"enabled",
"then",
"return",
"the",
"result",
"from",
"secret",
"store",
"encryption"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/secret_store/secret_store.py#L50-L66 |
2,456 | oceanprotocol/squid-py | squid_py/assets/asset_consumer.py | AssetConsumer.download | def download(service_agreement_id, service_definition_id, ddo, consumer_account, destination,
brizo, secret_store, index=None):
"""
Download asset data files or result files from a compute job.
:param service_agreement_id: Service agreement id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param ddo: DDO
:param consumer_account: Account instance of the consumer
:param destination: Path, str
:param brizo: Brizo instance
:param secret_store: SecretStore instance
:param index: Index of the document that is going to be downloaded, int
:return: Asset folder path, str
"""
did = ddo.did
encrypted_files = ddo.metadata['base']['encryptedFiles']
encrypted_files = (
encrypted_files if isinstance(encrypted_files, str)
else encrypted_files[0]
)
sa = ServiceAgreement.from_ddo(service_definition_id, ddo)
consume_url = sa.consume_endpoint
if not consume_url:
logger.error(
'Consume asset failed, service definition is missing the "serviceEndpoint".')
raise AssertionError(
'Consume asset failed, service definition is missing the "serviceEndpoint".')
if ddo.get_service('Authorization'):
secret_store_service = ddo.get_service(service_type=ServiceTypes.AUTHORIZATION)
secret_store_url = secret_store_service.endpoints.service
secret_store.set_secret_store_url(secret_store_url)
# decrypt the contentUrls
decrypted_content_urls = json.loads(
secret_store.decrypt_document(did_to_id(did), encrypted_files)
)
if isinstance(decrypted_content_urls, str):
decrypted_content_urls = [decrypted_content_urls]
logger.debug(f'got decrypted contentUrls: {decrypted_content_urls}')
if not os.path.isabs(destination):
destination = os.path.abspath(destination)
if not os.path.exists(destination):
os.mkdir(destination)
asset_folder = os.path.join(destination,
f'datafile.{did_to_id(did)}.{sa.service_definition_id}')
if not os.path.exists(asset_folder):
os.mkdir(asset_folder)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
assert index < len(decrypted_content_urls), logger.error(
'index can not be bigger than the number of files')
brizo.consume_service(
service_agreement_id,
consume_url,
consumer_account,
decrypted_content_urls,
asset_folder,
index
)
return asset_folder | python | def download(service_agreement_id, service_definition_id, ddo, consumer_account, destination,
brizo, secret_store, index=None):
"""
Download asset data files or result files from a compute job.
:param service_agreement_id: Service agreement id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param ddo: DDO
:param consumer_account: Account instance of the consumer
:param destination: Path, str
:param brizo: Brizo instance
:param secret_store: SecretStore instance
:param index: Index of the document that is going to be downloaded, int
:return: Asset folder path, str
"""
did = ddo.did
encrypted_files = ddo.metadata['base']['encryptedFiles']
encrypted_files = (
encrypted_files if isinstance(encrypted_files, str)
else encrypted_files[0]
)
sa = ServiceAgreement.from_ddo(service_definition_id, ddo)
consume_url = sa.consume_endpoint
if not consume_url:
logger.error(
'Consume asset failed, service definition is missing the "serviceEndpoint".')
raise AssertionError(
'Consume asset failed, service definition is missing the "serviceEndpoint".')
if ddo.get_service('Authorization'):
secret_store_service = ddo.get_service(service_type=ServiceTypes.AUTHORIZATION)
secret_store_url = secret_store_service.endpoints.service
secret_store.set_secret_store_url(secret_store_url)
# decrypt the contentUrls
decrypted_content_urls = json.loads(
secret_store.decrypt_document(did_to_id(did), encrypted_files)
)
if isinstance(decrypted_content_urls, str):
decrypted_content_urls = [decrypted_content_urls]
logger.debug(f'got decrypted contentUrls: {decrypted_content_urls}')
if not os.path.isabs(destination):
destination = os.path.abspath(destination)
if not os.path.exists(destination):
os.mkdir(destination)
asset_folder = os.path.join(destination,
f'datafile.{did_to_id(did)}.{sa.service_definition_id}')
if not os.path.exists(asset_folder):
os.mkdir(asset_folder)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
assert index < len(decrypted_content_urls), logger.error(
'index can not be bigger than the number of files')
brizo.consume_service(
service_agreement_id,
consume_url,
consumer_account,
decrypted_content_urls,
asset_folder,
index
)
return asset_folder | [
"def",
"download",
"(",
"service_agreement_id",
",",
"service_definition_id",
",",
"ddo",
",",
"consumer_account",
",",
"destination",
",",
"brizo",
",",
"secret_store",
",",
"index",
"=",
"None",
")",
":",
"did",
"=",
"ddo",
".",
"did",
"encrypted_files",
"=",
"ddo",
".",
"metadata",
"[",
"'base'",
"]",
"[",
"'encryptedFiles'",
"]",
"encrypted_files",
"=",
"(",
"encrypted_files",
"if",
"isinstance",
"(",
"encrypted_files",
",",
"str",
")",
"else",
"encrypted_files",
"[",
"0",
"]",
")",
"sa",
"=",
"ServiceAgreement",
".",
"from_ddo",
"(",
"service_definition_id",
",",
"ddo",
")",
"consume_url",
"=",
"sa",
".",
"consume_endpoint",
"if",
"not",
"consume_url",
":",
"logger",
".",
"error",
"(",
"'Consume asset failed, service definition is missing the \"serviceEndpoint\".'",
")",
"raise",
"AssertionError",
"(",
"'Consume asset failed, service definition is missing the \"serviceEndpoint\".'",
")",
"if",
"ddo",
".",
"get_service",
"(",
"'Authorization'",
")",
":",
"secret_store_service",
"=",
"ddo",
".",
"get_service",
"(",
"service_type",
"=",
"ServiceTypes",
".",
"AUTHORIZATION",
")",
"secret_store_url",
"=",
"secret_store_service",
".",
"endpoints",
".",
"service",
"secret_store",
".",
"set_secret_store_url",
"(",
"secret_store_url",
")",
"# decrypt the contentUrls",
"decrypted_content_urls",
"=",
"json",
".",
"loads",
"(",
"secret_store",
".",
"decrypt_document",
"(",
"did_to_id",
"(",
"did",
")",
",",
"encrypted_files",
")",
")",
"if",
"isinstance",
"(",
"decrypted_content_urls",
",",
"str",
")",
":",
"decrypted_content_urls",
"=",
"[",
"decrypted_content_urls",
"]",
"logger",
".",
"debug",
"(",
"f'got decrypted contentUrls: {decrypted_content_urls}'",
")",
"if",
"not",
"os",
".",
"path",
".",
"isabs",
"(",
"destination",
")",
":",
"destination",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"destination",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"destination",
")",
":",
"os",
".",
"mkdir",
"(",
"destination",
")",
"asset_folder",
"=",
"os",
".",
"path",
".",
"join",
"(",
"destination",
",",
"f'datafile.{did_to_id(did)}.{sa.service_definition_id}'",
")",
"if",
"not",
"os",
".",
"path",
".",
"exists",
"(",
"asset_folder",
")",
":",
"os",
".",
"mkdir",
"(",
"asset_folder",
")",
"if",
"index",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
",",
"logger",
".",
"error",
"(",
"'index has to be an integer.'",
")",
"assert",
"index",
">=",
"0",
",",
"logger",
".",
"error",
"(",
"'index has to be 0 or a positive integer.'",
")",
"assert",
"index",
"<",
"len",
"(",
"decrypted_content_urls",
")",
",",
"logger",
".",
"error",
"(",
"'index can not be bigger than the number of files'",
")",
"brizo",
".",
"consume_service",
"(",
"service_agreement_id",
",",
"consume_url",
",",
"consumer_account",
",",
"decrypted_content_urls",
",",
"asset_folder",
",",
"index",
")",
"return",
"asset_folder"
] | Download asset data files or result files from a compute job.
:param service_agreement_id: Service agreement id, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param ddo: DDO
:param consumer_account: Account instance of the consumer
:param destination: Path, str
:param brizo: Brizo instance
:param secret_store: SecretStore instance
:param index: Index of the document that is going to be downloaded, int
:return: Asset folder path, str | [
"Download",
"asset",
"data",
"files",
"or",
"result",
"files",
"from",
"a",
"compute",
"job",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/assets/asset_consumer.py#L20-L85 |
2,457 | oceanprotocol/squid-py | squid_py/ddo/public_key_base.py | PublicKeyBase.set_key_value | def set_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):
"""Set the key value based on it's storage type."""
if isinstance(value, dict):
if PUBLIC_KEY_STORE_TYPE_HEX in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_HEX], PUBLIC_KEY_STORE_TYPE_HEX)
elif PUBLIC_KEY_STORE_TYPE_BASE64 in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_BASE64],
PUBLIC_KEY_STORE_TYPE_BASE64)
elif PUBLIC_KEY_STORE_TYPE_BASE85 in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_BASE85],
PUBLIC_KEY_STORE_TYPE_BASE85)
elif PUBLIC_KEY_STORE_TYPE_JWK in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_JWK], PUBLIC_KEY_STORE_TYPE_JWK)
elif PUBLIC_KEY_STORE_TYPE_PEM in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_PEM], PUBLIC_KEY_STORE_TYPE_PEM)
else:
self._value = value
self._store_type = store_type | python | def set_key_value(self, value, store_type=PUBLIC_KEY_STORE_TYPE_BASE64):
"""Set the key value based on it's storage type."""
if isinstance(value, dict):
if PUBLIC_KEY_STORE_TYPE_HEX in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_HEX], PUBLIC_KEY_STORE_TYPE_HEX)
elif PUBLIC_KEY_STORE_TYPE_BASE64 in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_BASE64],
PUBLIC_KEY_STORE_TYPE_BASE64)
elif PUBLIC_KEY_STORE_TYPE_BASE85 in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_BASE85],
PUBLIC_KEY_STORE_TYPE_BASE85)
elif PUBLIC_KEY_STORE_TYPE_JWK in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_JWK], PUBLIC_KEY_STORE_TYPE_JWK)
elif PUBLIC_KEY_STORE_TYPE_PEM in value:
self.set_key_value(value[PUBLIC_KEY_STORE_TYPE_PEM], PUBLIC_KEY_STORE_TYPE_PEM)
else:
self._value = value
self._store_type = store_type | [
"def",
"set_key_value",
"(",
"self",
",",
"value",
",",
"store_type",
"=",
"PUBLIC_KEY_STORE_TYPE_BASE64",
")",
":",
"if",
"isinstance",
"(",
"value",
",",
"dict",
")",
":",
"if",
"PUBLIC_KEY_STORE_TYPE_HEX",
"in",
"value",
":",
"self",
".",
"set_key_value",
"(",
"value",
"[",
"PUBLIC_KEY_STORE_TYPE_HEX",
"]",
",",
"PUBLIC_KEY_STORE_TYPE_HEX",
")",
"elif",
"PUBLIC_KEY_STORE_TYPE_BASE64",
"in",
"value",
":",
"self",
".",
"set_key_value",
"(",
"value",
"[",
"PUBLIC_KEY_STORE_TYPE_BASE64",
"]",
",",
"PUBLIC_KEY_STORE_TYPE_BASE64",
")",
"elif",
"PUBLIC_KEY_STORE_TYPE_BASE85",
"in",
"value",
":",
"self",
".",
"set_key_value",
"(",
"value",
"[",
"PUBLIC_KEY_STORE_TYPE_BASE85",
"]",
",",
"PUBLIC_KEY_STORE_TYPE_BASE85",
")",
"elif",
"PUBLIC_KEY_STORE_TYPE_JWK",
"in",
"value",
":",
"self",
".",
"set_key_value",
"(",
"value",
"[",
"PUBLIC_KEY_STORE_TYPE_JWK",
"]",
",",
"PUBLIC_KEY_STORE_TYPE_JWK",
")",
"elif",
"PUBLIC_KEY_STORE_TYPE_PEM",
"in",
"value",
":",
"self",
".",
"set_key_value",
"(",
"value",
"[",
"PUBLIC_KEY_STORE_TYPE_PEM",
"]",
",",
"PUBLIC_KEY_STORE_TYPE_PEM",
")",
"else",
":",
"self",
".",
"_value",
"=",
"value",
"self",
".",
"_store_type",
"=",
"store_type"
] | Set the key value based on it's storage type. | [
"Set",
"the",
"key",
"value",
"based",
"on",
"it",
"s",
"storage",
"type",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_base.py#L61-L78 |
2,458 | oceanprotocol/squid-py | squid_py/ddo/public_key_base.py | PublicKeyBase.set_encode_key_value | def set_encode_key_value(self, value, store_type):
"""Save the key value base on it's storage type."""
self._store_type = store_type
if store_type == PUBLIC_KEY_STORE_TYPE_HEX:
self._value = value.hex()
elif store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
self._value = b64encode(value).decode()
elif store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
self._value = b85encode(value).decode()
elif store_type == PUBLIC_KEY_STORE_TYPE_JWK:
# TODO: need to decide on which jwk library to import?
raise NotImplementedError
else:
self._value = value
return value | python | def set_encode_key_value(self, value, store_type):
"""Save the key value base on it's storage type."""
self._store_type = store_type
if store_type == PUBLIC_KEY_STORE_TYPE_HEX:
self._value = value.hex()
elif store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
self._value = b64encode(value).decode()
elif store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
self._value = b85encode(value).decode()
elif store_type == PUBLIC_KEY_STORE_TYPE_JWK:
# TODO: need to decide on which jwk library to import?
raise NotImplementedError
else:
self._value = value
return value | [
"def",
"set_encode_key_value",
"(",
"self",
",",
"value",
",",
"store_type",
")",
":",
"self",
".",
"_store_type",
"=",
"store_type",
"if",
"store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_HEX",
":",
"self",
".",
"_value",
"=",
"value",
".",
"hex",
"(",
")",
"elif",
"store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_BASE64",
":",
"self",
".",
"_value",
"=",
"b64encode",
"(",
"value",
")",
".",
"decode",
"(",
")",
"elif",
"store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_BASE85",
":",
"self",
".",
"_value",
"=",
"b85encode",
"(",
"value",
")",
".",
"decode",
"(",
")",
"elif",
"store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_JWK",
":",
"# TODO: need to decide on which jwk library to import?",
"raise",
"NotImplementedError",
"else",
":",
"self",
".",
"_value",
"=",
"value",
"return",
"value"
] | Save the key value base on it's storage type. | [
"Save",
"the",
"key",
"value",
"base",
"on",
"it",
"s",
"storage",
"type",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_base.py#L80-L94 |
2,459 | oceanprotocol/squid-py | squid_py/ddo/public_key_base.py | PublicKeyBase.get_decode_value | def get_decode_value(self):
"""Return the key value based on it's storage type."""
if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:
value = bytes.fromhex(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
value = b64decode(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
value = b85decode(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_JWK:
# TODO: need to decide on which jwk library to import?
raise NotImplementedError
else:
value = self._value
return value | python | def get_decode_value(self):
"""Return the key value based on it's storage type."""
if self._store_type == PUBLIC_KEY_STORE_TYPE_HEX:
value = bytes.fromhex(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE64:
value = b64decode(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_BASE85:
value = b85decode(self._value)
elif self._store_type == PUBLIC_KEY_STORE_TYPE_JWK:
# TODO: need to decide on which jwk library to import?
raise NotImplementedError
else:
value = self._value
return value | [
"def",
"get_decode_value",
"(",
"self",
")",
":",
"if",
"self",
".",
"_store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_HEX",
":",
"value",
"=",
"bytes",
".",
"fromhex",
"(",
"self",
".",
"_value",
")",
"elif",
"self",
".",
"_store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_BASE64",
":",
"value",
"=",
"b64decode",
"(",
"self",
".",
"_value",
")",
"elif",
"self",
".",
"_store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_BASE85",
":",
"value",
"=",
"b85decode",
"(",
"self",
".",
"_value",
")",
"elif",
"self",
".",
"_store_type",
"==",
"PUBLIC_KEY_STORE_TYPE_JWK",
":",
"# TODO: need to decide on which jwk library to import?",
"raise",
"NotImplementedError",
"else",
":",
"value",
"=",
"self",
".",
"_value",
"return",
"value"
] | Return the key value based on it's storage type. | [
"Return",
"the",
"key",
"value",
"based",
"on",
"it",
"s",
"storage",
"type",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_base.py#L96-L109 |
2,460 | oceanprotocol/squid-py | squid_py/ddo/public_key_base.py | PublicKeyBase.as_text | def as_text(self, is_pretty=False):
"""Return the key as JSON text."""
values = {'id': self._id, 'type': self._type}
if self._owner:
values['owner'] = self._owner
if is_pretty:
return json.dumps(values, indent=4, separators=(',', ': '))
return json.dumps(values) | python | def as_text(self, is_pretty=False):
"""Return the key as JSON text."""
values = {'id': self._id, 'type': self._type}
if self._owner:
values['owner'] = self._owner
if is_pretty:
return json.dumps(values, indent=4, separators=(',', ': '))
return json.dumps(values) | [
"def",
"as_text",
"(",
"self",
",",
"is_pretty",
"=",
"False",
")",
":",
"values",
"=",
"{",
"'id'",
":",
"self",
".",
"_id",
",",
"'type'",
":",
"self",
".",
"_type",
"}",
"if",
"self",
".",
"_owner",
":",
"values",
"[",
"'owner'",
"]",
"=",
"self",
".",
"_owner",
"if",
"is_pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"values",
",",
"indent",
"=",
"4",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"values",
")"
] | Return the key as JSON text. | [
"Return",
"the",
"key",
"as",
"JSON",
"text",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_base.py#L115-L124 |
2,461 | oceanprotocol/squid-py | squid_py/ddo/public_key_base.py | PublicKeyBase.as_dictionary | def as_dictionary(self):
"""Return the key as a python dictionary."""
values = {
'id': self._id,
'type': self._type
}
if self._owner:
values['owner'] = self._owner
return values | python | def as_dictionary(self):
"""Return the key as a python dictionary."""
values = {
'id': self._id,
'type': self._type
}
if self._owner:
values['owner'] = self._owner
return values | [
"def",
"as_dictionary",
"(",
"self",
")",
":",
"values",
"=",
"{",
"'id'",
":",
"self",
".",
"_id",
",",
"'type'",
":",
"self",
".",
"_type",
"}",
"if",
"self",
".",
"_owner",
":",
"values",
"[",
"'owner'",
"]",
"=",
"self",
".",
"_owner",
"return",
"values"
] | Return the key as a python dictionary. | [
"Return",
"the",
"key",
"as",
"a",
"python",
"dictionary",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/public_key_base.py#L126-L135 |
2,462 | oceanprotocol/squid-py | squid_py/keeper/agreements/agreement_manager.py | AgreementStoreManager.get_agreement | def get_agreement(self, agreement_id):
"""
Retrieve the agreement for a agreement_id.
:param agreement_id: id of the agreement, hex str
:return: the agreement attributes.
"""
agreement = self.contract_concise.getAgreement(agreement_id)
if agreement and len(agreement) == 6:
agreement = AgreementValues(*agreement)
did = add_0x_prefix(agreement.did.hex())
cond_ids = [add_0x_prefix(_id.hex()) for _id in agreement.condition_ids]
return AgreementValues(
did,
agreement.owner,
agreement.template_id,
cond_ids,
agreement.updated_by,
agreement.block_number_updated
)
return None | python | def get_agreement(self, agreement_id):
"""
Retrieve the agreement for a agreement_id.
:param agreement_id: id of the agreement, hex str
:return: the agreement attributes.
"""
agreement = self.contract_concise.getAgreement(agreement_id)
if agreement and len(agreement) == 6:
agreement = AgreementValues(*agreement)
did = add_0x_prefix(agreement.did.hex())
cond_ids = [add_0x_prefix(_id.hex()) for _id in agreement.condition_ids]
return AgreementValues(
did,
agreement.owner,
agreement.template_id,
cond_ids,
agreement.updated_by,
agreement.block_number_updated
)
return None | [
"def",
"get_agreement",
"(",
"self",
",",
"agreement_id",
")",
":",
"agreement",
"=",
"self",
".",
"contract_concise",
".",
"getAgreement",
"(",
"agreement_id",
")",
"if",
"agreement",
"and",
"len",
"(",
"agreement",
")",
"==",
"6",
":",
"agreement",
"=",
"AgreementValues",
"(",
"*",
"agreement",
")",
"did",
"=",
"add_0x_prefix",
"(",
"agreement",
".",
"did",
".",
"hex",
"(",
")",
")",
"cond_ids",
"=",
"[",
"add_0x_prefix",
"(",
"_id",
".",
"hex",
"(",
")",
")",
"for",
"_id",
"in",
"agreement",
".",
"condition_ids",
"]",
"return",
"AgreementValues",
"(",
"did",
",",
"agreement",
".",
"owner",
",",
"agreement",
".",
"template_id",
",",
"cond_ids",
",",
"agreement",
".",
"updated_by",
",",
"agreement",
".",
"block_number_updated",
")",
"return",
"None"
] | Retrieve the agreement for a agreement_id.
:param agreement_id: id of the agreement, hex str
:return: the agreement attributes. | [
"Retrieve",
"the",
"agreement",
"for",
"a",
"agreement_id",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/agreements/agreement_manager.py#L48-L70 |
2,463 | oceanprotocol/squid-py | squid_py/keeper/contract_handler.py | ContractHandler._load | def _load(contract_name):
"""Retrieve the contract instance for `contract_name` that represent the smart
contract in the keeper network.
:param contract_name: str name of the solidity keeper contract without the network name.
:return: web3.eth.Contract instance
"""
contract_definition = ContractHandler.get_contract_dict_by_name(contract_name)
address = Web3Provider.get_web3().toChecksumAddress(contract_definition['address'])
abi = contract_definition['abi']
contract = Web3Provider.get_web3().eth.contract(address=address, abi=abi)
ContractHandler._contracts[contract_name] = (contract, ConciseContract(contract))
return ContractHandler._contracts[contract_name] | python | def _load(contract_name):
"""Retrieve the contract instance for `contract_name` that represent the smart
contract in the keeper network.
:param contract_name: str name of the solidity keeper contract without the network name.
:return: web3.eth.Contract instance
"""
contract_definition = ContractHandler.get_contract_dict_by_name(contract_name)
address = Web3Provider.get_web3().toChecksumAddress(contract_definition['address'])
abi = contract_definition['abi']
contract = Web3Provider.get_web3().eth.contract(address=address, abi=abi)
ContractHandler._contracts[contract_name] = (contract, ConciseContract(contract))
return ContractHandler._contracts[contract_name] | [
"def",
"_load",
"(",
"contract_name",
")",
":",
"contract_definition",
"=",
"ContractHandler",
".",
"get_contract_dict_by_name",
"(",
"contract_name",
")",
"address",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toChecksumAddress",
"(",
"contract_definition",
"[",
"'address'",
"]",
")",
"abi",
"=",
"contract_definition",
"[",
"'abi'",
"]",
"contract",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"eth",
".",
"contract",
"(",
"address",
"=",
"address",
",",
"abi",
"=",
"abi",
")",
"ContractHandler",
".",
"_contracts",
"[",
"contract_name",
"]",
"=",
"(",
"contract",
",",
"ConciseContract",
"(",
"contract",
")",
")",
"return",
"ContractHandler",
".",
"_contracts",
"[",
"contract_name",
"]"
] | Retrieve the contract instance for `contract_name` that represent the smart
contract in the keeper network.
:param contract_name: str name of the solidity keeper contract without the network name.
:return: web3.eth.Contract instance | [
"Retrieve",
"the",
"contract",
"instance",
"for",
"contract_name",
"that",
"represent",
"the",
"smart",
"contract",
"in",
"the",
"keeper",
"network",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_handler.py#L70-L82 |
2,464 | oceanprotocol/squid-py | squid_py/keeper/contract_handler.py | ContractHandler.get_contract_dict_by_name | def get_contract_dict_by_name(contract_name):
"""
Retrieve the Contract instance for a given contract name.
:param contract_name: str
:return: the smart contract's definition from the json abi file, dict
"""
network_name = Keeper.get_network_name(Keeper.get_network_id()).lower()
artifacts_path = ConfigProvider.get_config().keeper_path
# file_name = '{}.{}.json'.format(contract_name, network_name)
# path = os.path.join(keeper.artifacts_path, file_name)
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, network_name)
if not (path and os.path.exists(path)):
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, network_name.lower())
if not (path and os.path.exists(path)):
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, Keeper.DEFAULT_NETWORK_NAME)
if not (path and os.path.exists(path)):
raise FileNotFoundError(
f'Keeper contract {contract_name} file '
f'not found in {artifacts_path} '
f'using network name {network_name}'
)
with open(path) as f:
contract_dict = json.loads(f.read())
return contract_dict | python | def get_contract_dict_by_name(contract_name):
"""
Retrieve the Contract instance for a given contract name.
:param contract_name: str
:return: the smart contract's definition from the json abi file, dict
"""
network_name = Keeper.get_network_name(Keeper.get_network_id()).lower()
artifacts_path = ConfigProvider.get_config().keeper_path
# file_name = '{}.{}.json'.format(contract_name, network_name)
# path = os.path.join(keeper.artifacts_path, file_name)
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, network_name)
if not (path and os.path.exists(path)):
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, network_name.lower())
if not (path and os.path.exists(path)):
path = ContractHandler._get_contract_file_path(
artifacts_path, contract_name, Keeper.DEFAULT_NETWORK_NAME)
if not (path and os.path.exists(path)):
raise FileNotFoundError(
f'Keeper contract {contract_name} file '
f'not found in {artifacts_path} '
f'using network name {network_name}'
)
with open(path) as f:
contract_dict = json.loads(f.read())
return contract_dict | [
"def",
"get_contract_dict_by_name",
"(",
"contract_name",
")",
":",
"network_name",
"=",
"Keeper",
".",
"get_network_name",
"(",
"Keeper",
".",
"get_network_id",
"(",
")",
")",
".",
"lower",
"(",
")",
"artifacts_path",
"=",
"ConfigProvider",
".",
"get_config",
"(",
")",
".",
"keeper_path",
"# file_name = '{}.{}.json'.format(contract_name, network_name)",
"# path = os.path.join(keeper.artifacts_path, file_name)",
"path",
"=",
"ContractHandler",
".",
"_get_contract_file_path",
"(",
"artifacts_path",
",",
"contract_name",
",",
"network_name",
")",
"if",
"not",
"(",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"path",
"=",
"ContractHandler",
".",
"_get_contract_file_path",
"(",
"artifacts_path",
",",
"contract_name",
",",
"network_name",
".",
"lower",
"(",
")",
")",
"if",
"not",
"(",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"path",
"=",
"ContractHandler",
".",
"_get_contract_file_path",
"(",
"artifacts_path",
",",
"contract_name",
",",
"Keeper",
".",
"DEFAULT_NETWORK_NAME",
")",
"if",
"not",
"(",
"path",
"and",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
")",
":",
"raise",
"FileNotFoundError",
"(",
"f'Keeper contract {contract_name} file '",
"f'not found in {artifacts_path} '",
"f'using network name {network_name}'",
")",
"with",
"open",
"(",
"path",
")",
"as",
"f",
":",
"contract_dict",
"=",
"json",
".",
"loads",
"(",
"f",
".",
"read",
"(",
")",
")",
"return",
"contract_dict"
] | Retrieve the Contract instance for a given contract name.
:param contract_name: str
:return: the smart contract's definition from the json abi file, dict | [
"Retrieve",
"the",
"Contract",
"instance",
"for",
"a",
"given",
"contract",
"name",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/contract_handler.py#L94-L126 |
2,465 | oceanprotocol/squid-py | examples/buy_asset.py | buy_asset | def buy_asset():
"""
Requires all ocean services running.
"""
ConfigProvider.set_config(ExampleConfig.get_config())
config = ConfigProvider.get_config()
# make ocean instance
ocn = Ocean()
acc = get_publisher_account(config)
if not acc:
acc = ([acc for acc in ocn.accounts.list() if acc.password] or ocn.accounts.list())[0]
# Register ddo
ddo = ocn.assets.create(Metadata.get_example(), acc, providers=[acc.address], use_secret_store=False)
logging.info(f'registered ddo: {ddo.did}')
# ocn here will be used only to publish the asset. Handling the asset by the publisher
# will be performed by the Brizo server running locally
keeper = Keeper.get_instance()
if 'TEST_LOCAL_NILE' in os.environ and os.environ['TEST_LOCAL_NILE'] == '1':
provider = keeper.did_registry.to_checksum_address(
'0x413c9ba0a05b8a600899b41b0c62dd661e689354'
)
keeper.did_registry.add_provider(ddo.asset_id, provider, acc)
logging.debug(f'is did provider: '
f'{keeper.did_registry.is_did_provider(ddo.asset_id, provider)}')
cons_ocn = Ocean()
consumer_account = get_account_from_config(config, 'parity.address1', 'parity.password1')
# sign agreement using the registered asset did above
service = ddo.get_service(service_type=ServiceTypes.ASSET_ACCESS)
# This will send the order request to Brizo which in turn will execute the agreement on-chain
cons_ocn.accounts.request_tokens(consumer_account, 100)
sa = ServiceAgreement.from_service_dict(service.as_dictionary())
agreement_id = cons_ocn.assets.order(
ddo.did, sa.service_definition_id, consumer_account)
logging.info('placed order: %s, %s', ddo.did, agreement_id)
i = 0
while ocn.agreements.is_access_granted(
agreement_id, ddo.did, consumer_account.address) is not True and i < 30:
time.sleep(1)
i += 1
assert ocn.agreements.is_access_granted(agreement_id, ddo.did, consumer_account.address)
ocn.assets.consume(
agreement_id,
ddo.did,
sa.service_definition_id,
consumer_account,
config.downloads_path)
logging.info('Success buying asset.') | python | def buy_asset():
"""
Requires all ocean services running.
"""
ConfigProvider.set_config(ExampleConfig.get_config())
config = ConfigProvider.get_config()
# make ocean instance
ocn = Ocean()
acc = get_publisher_account(config)
if not acc:
acc = ([acc for acc in ocn.accounts.list() if acc.password] or ocn.accounts.list())[0]
# Register ddo
ddo = ocn.assets.create(Metadata.get_example(), acc, providers=[acc.address], use_secret_store=False)
logging.info(f'registered ddo: {ddo.did}')
# ocn here will be used only to publish the asset. Handling the asset by the publisher
# will be performed by the Brizo server running locally
keeper = Keeper.get_instance()
if 'TEST_LOCAL_NILE' in os.environ and os.environ['TEST_LOCAL_NILE'] == '1':
provider = keeper.did_registry.to_checksum_address(
'0x413c9ba0a05b8a600899b41b0c62dd661e689354'
)
keeper.did_registry.add_provider(ddo.asset_id, provider, acc)
logging.debug(f'is did provider: '
f'{keeper.did_registry.is_did_provider(ddo.asset_id, provider)}')
cons_ocn = Ocean()
consumer_account = get_account_from_config(config, 'parity.address1', 'parity.password1')
# sign agreement using the registered asset did above
service = ddo.get_service(service_type=ServiceTypes.ASSET_ACCESS)
# This will send the order request to Brizo which in turn will execute the agreement on-chain
cons_ocn.accounts.request_tokens(consumer_account, 100)
sa = ServiceAgreement.from_service_dict(service.as_dictionary())
agreement_id = cons_ocn.assets.order(
ddo.did, sa.service_definition_id, consumer_account)
logging.info('placed order: %s, %s', ddo.did, agreement_id)
i = 0
while ocn.agreements.is_access_granted(
agreement_id, ddo.did, consumer_account.address) is not True and i < 30:
time.sleep(1)
i += 1
assert ocn.agreements.is_access_granted(agreement_id, ddo.did, consumer_account.address)
ocn.assets.consume(
agreement_id,
ddo.did,
sa.service_definition_id,
consumer_account,
config.downloads_path)
logging.info('Success buying asset.') | [
"def",
"buy_asset",
"(",
")",
":",
"ConfigProvider",
".",
"set_config",
"(",
"ExampleConfig",
".",
"get_config",
"(",
")",
")",
"config",
"=",
"ConfigProvider",
".",
"get_config",
"(",
")",
"# make ocean instance",
"ocn",
"=",
"Ocean",
"(",
")",
"acc",
"=",
"get_publisher_account",
"(",
"config",
")",
"if",
"not",
"acc",
":",
"acc",
"=",
"(",
"[",
"acc",
"for",
"acc",
"in",
"ocn",
".",
"accounts",
".",
"list",
"(",
")",
"if",
"acc",
".",
"password",
"]",
"or",
"ocn",
".",
"accounts",
".",
"list",
"(",
")",
")",
"[",
"0",
"]",
"# Register ddo",
"ddo",
"=",
"ocn",
".",
"assets",
".",
"create",
"(",
"Metadata",
".",
"get_example",
"(",
")",
",",
"acc",
",",
"providers",
"=",
"[",
"acc",
".",
"address",
"]",
",",
"use_secret_store",
"=",
"False",
")",
"logging",
".",
"info",
"(",
"f'registered ddo: {ddo.did}'",
")",
"# ocn here will be used only to publish the asset. Handling the asset by the publisher",
"# will be performed by the Brizo server running locally",
"keeper",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
"if",
"'TEST_LOCAL_NILE'",
"in",
"os",
".",
"environ",
"and",
"os",
".",
"environ",
"[",
"'TEST_LOCAL_NILE'",
"]",
"==",
"'1'",
":",
"provider",
"=",
"keeper",
".",
"did_registry",
".",
"to_checksum_address",
"(",
"'0x413c9ba0a05b8a600899b41b0c62dd661e689354'",
")",
"keeper",
".",
"did_registry",
".",
"add_provider",
"(",
"ddo",
".",
"asset_id",
",",
"provider",
",",
"acc",
")",
"logging",
".",
"debug",
"(",
"f'is did provider: '",
"f'{keeper.did_registry.is_did_provider(ddo.asset_id, provider)}'",
")",
"cons_ocn",
"=",
"Ocean",
"(",
")",
"consumer_account",
"=",
"get_account_from_config",
"(",
"config",
",",
"'parity.address1'",
",",
"'parity.password1'",
")",
"# sign agreement using the registered asset did above",
"service",
"=",
"ddo",
".",
"get_service",
"(",
"service_type",
"=",
"ServiceTypes",
".",
"ASSET_ACCESS",
")",
"# This will send the order request to Brizo which in turn will execute the agreement on-chain",
"cons_ocn",
".",
"accounts",
".",
"request_tokens",
"(",
"consumer_account",
",",
"100",
")",
"sa",
"=",
"ServiceAgreement",
".",
"from_service_dict",
"(",
"service",
".",
"as_dictionary",
"(",
")",
")",
"agreement_id",
"=",
"cons_ocn",
".",
"assets",
".",
"order",
"(",
"ddo",
".",
"did",
",",
"sa",
".",
"service_definition_id",
",",
"consumer_account",
")",
"logging",
".",
"info",
"(",
"'placed order: %s, %s'",
",",
"ddo",
".",
"did",
",",
"agreement_id",
")",
"i",
"=",
"0",
"while",
"ocn",
".",
"agreements",
".",
"is_access_granted",
"(",
"agreement_id",
",",
"ddo",
".",
"did",
",",
"consumer_account",
".",
"address",
")",
"is",
"not",
"True",
"and",
"i",
"<",
"30",
":",
"time",
".",
"sleep",
"(",
"1",
")",
"i",
"+=",
"1",
"assert",
"ocn",
".",
"agreements",
".",
"is_access_granted",
"(",
"agreement_id",
",",
"ddo",
".",
"did",
",",
"consumer_account",
".",
"address",
")",
"ocn",
".",
"assets",
".",
"consume",
"(",
"agreement_id",
",",
"ddo",
".",
"did",
",",
"sa",
".",
"service_definition_id",
",",
"consumer_account",
",",
"config",
".",
"downloads_path",
")",
"logging",
".",
"info",
"(",
"'Success buying asset.'",
")"
] | Requires all ocean services running. | [
"Requires",
"all",
"ocean",
"services",
"running",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/examples/buy_asset.py#L29-L83 |
2,466 | oceanprotocol/squid-py | squid_py/keeper/token.py | Token.token_approve | def token_approve(self, spender_address, price, from_account):
"""
Approve the passed address to spend the specified amount of tokens.
:param spender_address: Account address, str
:param price: Asset price, int
:param from_account: Account address, str
:return: bool
"""
if not Web3Provider.get_web3().isChecksumAddress(spender_address):
spender_address = Web3Provider.get_web3().toChecksumAddress(spender_address)
tx_hash = self.send_transaction(
'approve',
(spender_address,
price),
transact={'from': from_account.address,
'passphrase': from_account.password}
)
return self.get_tx_receipt(tx_hash).status == 1 | python | def token_approve(self, spender_address, price, from_account):
"""
Approve the passed address to spend the specified amount of tokens.
:param spender_address: Account address, str
:param price: Asset price, int
:param from_account: Account address, str
:return: bool
"""
if not Web3Provider.get_web3().isChecksumAddress(spender_address):
spender_address = Web3Provider.get_web3().toChecksumAddress(spender_address)
tx_hash = self.send_transaction(
'approve',
(spender_address,
price),
transact={'from': from_account.address,
'passphrase': from_account.password}
)
return self.get_tx_receipt(tx_hash).status == 1 | [
"def",
"token_approve",
"(",
"self",
",",
"spender_address",
",",
"price",
",",
"from_account",
")",
":",
"if",
"not",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"isChecksumAddress",
"(",
"spender_address",
")",
":",
"spender_address",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toChecksumAddress",
"(",
"spender_address",
")",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'approve'",
",",
"(",
"spender_address",
",",
"price",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"from_account",
".",
"address",
",",
"'passphrase'",
":",
"from_account",
".",
"password",
"}",
")",
"return",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")",
".",
"status",
"==",
"1"
] | Approve the passed address to spend the specified amount of tokens.
:param spender_address: Account address, str
:param price: Asset price, int
:param from_account: Account address, str
:return: bool | [
"Approve",
"the",
"passed",
"address",
"to",
"spend",
"the",
"specified",
"amount",
"of",
"tokens",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/token.py#L31-L50 |
2,467 | oceanprotocol/squid-py | squid_py/keeper/token.py | Token.transfer | def transfer(self, receiver_address, amount, from_account):
"""
Transfer tokens from one account to the receiver address.
:param receiver_address: Address of the transfer receiver, str
:param amount: Amount of tokens, int
:param from_account: Sender account, Account
:return: bool
"""
tx_hash = self.send_transaction(
'transfer',
(receiver_address,
amount),
transact={'from': from_account.address,
'passphrase': from_account.password}
)
return self.get_tx_receipt(tx_hash).status == 1 | python | def transfer(self, receiver_address, amount, from_account):
"""
Transfer tokens from one account to the receiver address.
:param receiver_address: Address of the transfer receiver, str
:param amount: Amount of tokens, int
:param from_account: Sender account, Account
:return: bool
"""
tx_hash = self.send_transaction(
'transfer',
(receiver_address,
amount),
transact={'from': from_account.address,
'passphrase': from_account.password}
)
return self.get_tx_receipt(tx_hash).status == 1 | [
"def",
"transfer",
"(",
"self",
",",
"receiver_address",
",",
"amount",
",",
"from_account",
")",
":",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'transfer'",
",",
"(",
"receiver_address",
",",
"amount",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"from_account",
".",
"address",
",",
"'passphrase'",
":",
"from_account",
".",
"password",
"}",
")",
"return",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")",
".",
"status",
"==",
"1"
] | Transfer tokens from one account to the receiver address.
:param receiver_address: Address of the transfer receiver, str
:param amount: Amount of tokens, int
:param from_account: Sender account, Account
:return: bool | [
"Transfer",
"tokens",
"from",
"one",
"account",
"to",
"the",
"receiver",
"address",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/token.py#L52-L68 |
2,468 | oceanprotocol/squid-py | squid_py/agreements/events/access_secret_store_condition.py | fulfill_access_secret_store_condition | def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreement,
consumer_address, publisher_account):
"""
Fulfill the access condition.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_account: Account instance of the publisher
"""
logger.debug(f"release reward after event {event}.")
name_to_parameter = {param.name: param for param in
service_agreement.condition_by_name['accessSecretStore'].parameters}
document_id = add_0x_prefix(name_to_parameter['_documentId'].value)
asset_id = add_0x_prefix(did_to_id(did))
assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'
try:
tx_hash = Keeper.get_instance().access_secret_store_condition.fulfill(
agreement_id, document_id, consumer_address, publisher_account
)
process_tx_receipt(
tx_hash,
Keeper.get_instance().access_secret_store_condition.FULFILLED_EVENT,
'AccessSecretStoreCondition.Fulfilled'
)
except Exception as e:
# logger.error(f'Error when calling grantAccess condition function: {e}')
raise e | python | def fulfill_access_secret_store_condition(event, agreement_id, did, service_agreement,
consumer_address, publisher_account):
"""
Fulfill the access condition.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_account: Account instance of the publisher
"""
logger.debug(f"release reward after event {event}.")
name_to_parameter = {param.name: param for param in
service_agreement.condition_by_name['accessSecretStore'].parameters}
document_id = add_0x_prefix(name_to_parameter['_documentId'].value)
asset_id = add_0x_prefix(did_to_id(did))
assert document_id == asset_id, f'document_id {document_id} <=> asset_id {asset_id} mismatch.'
try:
tx_hash = Keeper.get_instance().access_secret_store_condition.fulfill(
agreement_id, document_id, consumer_address, publisher_account
)
process_tx_receipt(
tx_hash,
Keeper.get_instance().access_secret_store_condition.FULFILLED_EVENT,
'AccessSecretStoreCondition.Fulfilled'
)
except Exception as e:
# logger.error(f'Error when calling grantAccess condition function: {e}')
raise e | [
"def",
"fulfill_access_secret_store_condition",
"(",
"event",
",",
"agreement_id",
",",
"did",
",",
"service_agreement",
",",
"consumer_address",
",",
"publisher_account",
")",
":",
"logger",
".",
"debug",
"(",
"f\"release reward after event {event}.\"",
")",
"name_to_parameter",
"=",
"{",
"param",
".",
"name",
":",
"param",
"for",
"param",
"in",
"service_agreement",
".",
"condition_by_name",
"[",
"'accessSecretStore'",
"]",
".",
"parameters",
"}",
"document_id",
"=",
"add_0x_prefix",
"(",
"name_to_parameter",
"[",
"'_documentId'",
"]",
".",
"value",
")",
"asset_id",
"=",
"add_0x_prefix",
"(",
"did_to_id",
"(",
"did",
")",
")",
"assert",
"document_id",
"==",
"asset_id",
",",
"f'document_id {document_id} <=> asset_id {asset_id} mismatch.'",
"try",
":",
"tx_hash",
"=",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"access_secret_store_condition",
".",
"fulfill",
"(",
"agreement_id",
",",
"document_id",
",",
"consumer_address",
",",
"publisher_account",
")",
"process_tx_receipt",
"(",
"tx_hash",
",",
"Keeper",
".",
"get_instance",
"(",
")",
".",
"access_secret_store_condition",
".",
"FULFILLED_EVENT",
",",
"'AccessSecretStoreCondition.Fulfilled'",
")",
"except",
"Exception",
"as",
"e",
":",
"# logger.error(f'Error when calling grantAccess condition function: {e}')",
"raise",
"e"
] | Fulfill the access condition.
:param event: AttributeDict with the event data.
:param agreement_id: id of the agreement, hex str
:param did: DID, str
:param service_agreement: ServiceAgreement instance
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_account: Account instance of the publisher | [
"Fulfill",
"the",
"access",
"condition",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/events/access_secret_store_condition.py#L16-L45 |
2,469 | oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.retire | def retire(self, did):
"""
Retire this did of Aquarius
:param did: DID, str
:return: bool
"""
try:
ddo = self.resolve(did)
metadata_service = ddo.find_service_by_type(ServiceTypes.METADATA)
self._get_aquarius(metadata_service.endpoints.service).retire_asset_ddo(did)
return True
except AquariusGenericError as err:
logger.error(err)
return False | python | def retire(self, did):
"""
Retire this did of Aquarius
:param did: DID, str
:return: bool
"""
try:
ddo = self.resolve(did)
metadata_service = ddo.find_service_by_type(ServiceTypes.METADATA)
self._get_aquarius(metadata_service.endpoints.service).retire_asset_ddo(did)
return True
except AquariusGenericError as err:
logger.error(err)
return False | [
"def",
"retire",
"(",
"self",
",",
"did",
")",
":",
"try",
":",
"ddo",
"=",
"self",
".",
"resolve",
"(",
"did",
")",
"metadata_service",
"=",
"ddo",
".",
"find_service_by_type",
"(",
"ServiceTypes",
".",
"METADATA",
")",
"self",
".",
"_get_aquarius",
"(",
"metadata_service",
".",
"endpoints",
".",
"service",
")",
".",
"retire_asset_ddo",
"(",
"did",
")",
"return",
"True",
"except",
"AquariusGenericError",
"as",
"err",
":",
"logger",
".",
"error",
"(",
"err",
")",
"return",
"False"
] | Retire this did of Aquarius
:param did: DID, str
:return: bool | [
"Retire",
"this",
"did",
"of",
"Aquarius"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L197-L211 |
2,470 | oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.search | def search(self, text, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using aquarius.
:param text: String with the value that you are searching
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query
"""
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
logger.info(f'Searching asset containing: {text}')
return [DDO(dictionary=ddo_dict) for ddo_dict in
self._get_aquarius(aquarius_url).text_search(text, sort, offset, page)['results']] | python | def search(self, text, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using aquarius.
:param text: String with the value that you are searching
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query
"""
assert page >= 1, f'Invalid page value {page}. Required page >= 1.'
logger.info(f'Searching asset containing: {text}')
return [DDO(dictionary=ddo_dict) for ddo_dict in
self._get_aquarius(aquarius_url).text_search(text, sort, offset, page)['results']] | [
"def",
"search",
"(",
"self",
",",
"text",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
",",
"aquarius_url",
"=",
"None",
")",
":",
"assert",
"page",
">=",
"1",
",",
"f'Invalid page value {page}. Required page >= 1.'",
"logger",
".",
"info",
"(",
"f'Searching asset containing: {text}'",
")",
"return",
"[",
"DDO",
"(",
"dictionary",
"=",
"ddo_dict",
")",
"for",
"ddo_dict",
"in",
"self",
".",
"_get_aquarius",
"(",
"aquarius_url",
")",
".",
"text_search",
"(",
"text",
",",
"sort",
",",
"offset",
",",
"page",
")",
"[",
"'results'",
"]",
"]"
] | Search an asset in oceanDB using aquarius.
:param text: String with the value that you are searching
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query | [
"Search",
"an",
"asset",
"in",
"oceanDB",
"using",
"aquarius",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L222-L237 |
2,471 | oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.query | def query(self, query, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using search query.
:param query: dict with query parameters
(e.g.) https://github.com/oceanprotocol/aquarius/blob/develop/docs/for_api_users/API.md
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query.
"""
logger.info(f'Searching asset query: {query}')
aquarius = self._get_aquarius(aquarius_url)
return [DDO(dictionary=ddo_dict) for ddo_dict in
aquarius.query_search(query, sort, offset, page)['results']] | python | def query(self, query, sort=None, offset=100, page=1, aquarius_url=None):
"""
Search an asset in oceanDB using search query.
:param query: dict with query parameters
(e.g.) https://github.com/oceanprotocol/aquarius/blob/develop/docs/for_api_users/API.md
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query.
"""
logger.info(f'Searching asset query: {query}')
aquarius = self._get_aquarius(aquarius_url)
return [DDO(dictionary=ddo_dict) for ddo_dict in
aquarius.query_search(query, sort, offset, page)['results']] | [
"def",
"query",
"(",
"self",
",",
"query",
",",
"sort",
"=",
"None",
",",
"offset",
"=",
"100",
",",
"page",
"=",
"1",
",",
"aquarius_url",
"=",
"None",
")",
":",
"logger",
".",
"info",
"(",
"f'Searching asset query: {query}'",
")",
"aquarius",
"=",
"self",
".",
"_get_aquarius",
"(",
"aquarius_url",
")",
"return",
"[",
"DDO",
"(",
"dictionary",
"=",
"ddo_dict",
")",
"for",
"ddo_dict",
"in",
"aquarius",
".",
"query_search",
"(",
"query",
",",
"sort",
",",
"offset",
",",
"page",
")",
"[",
"'results'",
"]",
"]"
] | Search an asset in oceanDB using search query.
:param query: dict with query parameters
(e.g.) https://github.com/oceanprotocol/aquarius/blob/develop/docs/for_api_users/API.md
:param sort: Dictionary to choose order base in some value
:param offset: Number of elements shows by page
:param page: Page number
:param aquarius_url: Url of the aquarius where you want to search. If there is not
provided take the default
:return: List of assets that match with the query. | [
"Search",
"an",
"asset",
"in",
"oceanDB",
"using",
"search",
"query",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L239-L255 |
2,472 | oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.order | def order(self, did, service_definition_id, consumer_account, auto_consume=False):
"""
Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associated with this service.
:param did: str starting with the prefix `did:op:` and followed by the asset id which is
a hex str
:param service_definition_id: str the service definition id identifying a specific
service in the DDO (DID document)
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean
:return: tuple(agreement_id, signature) the service agreement id (can be used to query
the keeper-contracts for the status of the service agreement) and signed agreement hash
"""
assert consumer_account.address in self._keeper.accounts, f'Unrecognized consumer ' \
f'address `consumer_account`'
agreement_id, signature = self._agreements.prepare(
did, service_definition_id, consumer_account
)
logger.debug(f'about to request create agreement: {agreement_id}')
self._agreements.send(
did,
agreement_id,
service_definition_id,
signature,
consumer_account,
auto_consume=auto_consume
)
return agreement_id | python | def order(self, did, service_definition_id, consumer_account, auto_consume=False):
"""
Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associated with this service.
:param did: str starting with the prefix `did:op:` and followed by the asset id which is
a hex str
:param service_definition_id: str the service definition id identifying a specific
service in the DDO (DID document)
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean
:return: tuple(agreement_id, signature) the service agreement id (can be used to query
the keeper-contracts for the status of the service agreement) and signed agreement hash
"""
assert consumer_account.address in self._keeper.accounts, f'Unrecognized consumer ' \
f'address `consumer_account`'
agreement_id, signature = self._agreements.prepare(
did, service_definition_id, consumer_account
)
logger.debug(f'about to request create agreement: {agreement_id}')
self._agreements.send(
did,
agreement_id,
service_definition_id,
signature,
consumer_account,
auto_consume=auto_consume
)
return agreement_id | [
"def",
"order",
"(",
"self",
",",
"did",
",",
"service_definition_id",
",",
"consumer_account",
",",
"auto_consume",
"=",
"False",
")",
":",
"assert",
"consumer_account",
".",
"address",
"in",
"self",
".",
"_keeper",
".",
"accounts",
",",
"f'Unrecognized consumer '",
"f'address `consumer_account`'",
"agreement_id",
",",
"signature",
"=",
"self",
".",
"_agreements",
".",
"prepare",
"(",
"did",
",",
"service_definition_id",
",",
"consumer_account",
")",
"logger",
".",
"debug",
"(",
"f'about to request create agreement: {agreement_id}'",
")",
"self",
".",
"_agreements",
".",
"send",
"(",
"did",
",",
"agreement_id",
",",
"service_definition_id",
",",
"signature",
",",
"consumer_account",
",",
"auto_consume",
"=",
"auto_consume",
")",
"return",
"agreement_id"
] | Sign service agreement.
Sign the service agreement defined in the service section identified
by `service_definition_id` in the ddo and send the signed agreement to the purchase endpoint
associated with this service.
:param did: str starting with the prefix `did:op:` and followed by the asset id which is
a hex str
:param service_definition_id: str the service definition id identifying a specific
service in the DDO (DID document)
:param consumer_account: Account instance of the consumer
:param auto_consume: boolean
:return: tuple(agreement_id, signature) the service agreement id (can be used to query
the keeper-contracts for the status of the service agreement) and signed agreement hash | [
"Sign",
"service",
"agreement",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L257-L289 |
2,473 | oceanprotocol/squid-py | squid_py/ocean/ocean_assets.py | OceanAssets.consume | def consume(self, service_agreement_id, did, service_definition_id, consumer_account,
destination, index=None):
"""
Consume the asset data.
Using the service endpoint defined in the ddo's service pointed to by service_definition_id.
Consumer's permissions is checked implicitly by the secret-store during decryption
of the contentUrls.
The service endpoint is expected to also verify the consumer's permissions to consume this
asset.
This method downloads and saves the asset datafiles to disk.
:param service_agreement_id: str
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_account: Account instance of the consumer
:param destination: str path
:param index: Index of the document that is going to be downloaded, int
:return: str path to saved files
"""
ddo = self.resolve(did)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
return self._asset_consumer.download(
service_agreement_id,
service_definition_id,
ddo,
consumer_account,
destination,
BrizoProvider.get_brizo(),
self._get_secret_store(consumer_account),
index
) | python | def consume(self, service_agreement_id, did, service_definition_id, consumer_account,
destination, index=None):
"""
Consume the asset data.
Using the service endpoint defined in the ddo's service pointed to by service_definition_id.
Consumer's permissions is checked implicitly by the secret-store during decryption
of the contentUrls.
The service endpoint is expected to also verify the consumer's permissions to consume this
asset.
This method downloads and saves the asset datafiles to disk.
:param service_agreement_id: str
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_account: Account instance of the consumer
:param destination: str path
:param index: Index of the document that is going to be downloaded, int
:return: str path to saved files
"""
ddo = self.resolve(did)
if index is not None:
assert isinstance(index, int), logger.error('index has to be an integer.')
assert index >= 0, logger.error('index has to be 0 or a positive integer.')
return self._asset_consumer.download(
service_agreement_id,
service_definition_id,
ddo,
consumer_account,
destination,
BrizoProvider.get_brizo(),
self._get_secret_store(consumer_account),
index
) | [
"def",
"consume",
"(",
"self",
",",
"service_agreement_id",
",",
"did",
",",
"service_definition_id",
",",
"consumer_account",
",",
"destination",
",",
"index",
"=",
"None",
")",
":",
"ddo",
"=",
"self",
".",
"resolve",
"(",
"did",
")",
"if",
"index",
"is",
"not",
"None",
":",
"assert",
"isinstance",
"(",
"index",
",",
"int",
")",
",",
"logger",
".",
"error",
"(",
"'index has to be an integer.'",
")",
"assert",
"index",
">=",
"0",
",",
"logger",
".",
"error",
"(",
"'index has to be 0 or a positive integer.'",
")",
"return",
"self",
".",
"_asset_consumer",
".",
"download",
"(",
"service_agreement_id",
",",
"service_definition_id",
",",
"ddo",
",",
"consumer_account",
",",
"destination",
",",
"BrizoProvider",
".",
"get_brizo",
"(",
")",
",",
"self",
".",
"_get_secret_store",
"(",
"consumer_account",
")",
",",
"index",
")"
] | Consume the asset data.
Using the service endpoint defined in the ddo's service pointed to by service_definition_id.
Consumer's permissions is checked implicitly by the secret-store during decryption
of the contentUrls.
The service endpoint is expected to also verify the consumer's permissions to consume this
asset.
This method downloads and saves the asset datafiles to disk.
:param service_agreement_id: str
:param did: DID, str
:param service_definition_id: identifier of the service inside the asset DDO, str
:param consumer_account: Account instance of the consumer
:param destination: str path
:param index: Index of the document that is going to be downloaded, int
:return: str path to saved files | [
"Consume",
"the",
"asset",
"data",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_assets.py#L291-L324 |
2,474 | oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.propose | def propose(self, template_address, account):
"""
Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool
"""
try:
proposed = self._keeper.template_manager.propose_template(template_address, account)
return proposed
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Propose template failed: {err}')
return False
if template_values.state != 1:
logger.warning(
f'Propose template failed, current state is set to {template_values.state}')
return False
return True | python | def propose(self, template_address, account):
"""
Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool
"""
try:
proposed = self._keeper.template_manager.propose_template(template_address, account)
return proposed
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Propose template failed: {err}')
return False
if template_values.state != 1:
logger.warning(
f'Propose template failed, current state is set to {template_values.state}')
return False
return True | [
"def",
"propose",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"proposed",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"propose_template",
"(",
"template_address",
",",
"account",
")",
"return",
"proposed",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Propose template failed: {err}'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"!=",
"1",
":",
"logger",
".",
"warning",
"(",
"f'Propose template failed, current state is set to {template_values.state}'",
")",
"return",
"False",
"return",
"True"
] | Propose a new template.
:param template_address: Address of the template contract, str
:param account: account proposing the template, Account
:return: bool | [
"Propose",
"a",
"new",
"template",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L18-L40 |
2,475 | oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.approve | def approve(self, template_address, account):
"""
Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool
"""
try:
approved = self._keeper.template_manager.approve_template(template_address, account)
return approved
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Approve template failed: {err}')
return False
if template_values.state == 1:
logger.warning(f'Approve template failed, this template is '
f'currently in "proposed" state.')
return False
if template_values.state == 3:
logger.warning(f'Approve template failed, this template appears to be '
f'revoked.')
return False
if template_values.state == 2:
return True
return False | python | def approve(self, template_address, account):
"""
Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool
"""
try:
approved = self._keeper.template_manager.approve_template(template_address, account)
return approved
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Approve template failed: {err}')
return False
if template_values.state == 1:
logger.warning(f'Approve template failed, this template is '
f'currently in "proposed" state.')
return False
if template_values.state == 3:
logger.warning(f'Approve template failed, this template appears to be '
f'revoked.')
return False
if template_values.state == 2:
return True
return False | [
"def",
"approve",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"approved",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"approve_template",
"(",
"template_address",
",",
"account",
")",
"return",
"approved",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed: {err}'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"1",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed, this template is '",
"f'currently in \"proposed\" state.'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"3",
":",
"logger",
".",
"warning",
"(",
"f'Approve template failed, this template appears to be '",
"f'revoked.'",
")",
"return",
"False",
"if",
"template_values",
".",
"state",
"==",
"2",
":",
"return",
"True",
"return",
"False"
] | Approve a template already proposed. The account needs to be owner of the templateManager
contract to be able of approve the template.
:param template_address: Address of the template contract, str
:param account: account approving the template, Account
:return: bool | [
"Approve",
"a",
"template",
"already",
"proposed",
".",
"The",
"account",
"needs",
"to",
"be",
"owner",
"of",
"the",
"templateManager",
"contract",
"to",
"be",
"able",
"of",
"approve",
"the",
"template",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L42-L73 |
2,476 | oceanprotocol/squid-py | squid_py/ocean/ocean_templates.py | OceanTemplates.revoke | def revoke(self, template_address, account):
"""
Revoke a template already approved. The account needs to be owner of the templateManager
contract to be able of revoke the template.
:param template_address: Address of the template contract, str
:param account: account revoking the template, Account
:return: bool
"""
try:
revoked = self._keeper.template_manager.revoke_template(template_address, account)
return revoked
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Cannot revoke template since it does not exist: {err}')
return False
logger.warning(f'Only template admin or owner can revoke a template: {err}')
return False | python | def revoke(self, template_address, account):
"""
Revoke a template already approved. The account needs to be owner of the templateManager
contract to be able of revoke the template.
:param template_address: Address of the template contract, str
:param account: account revoking the template, Account
:return: bool
"""
try:
revoked = self._keeper.template_manager.revoke_template(template_address, account)
return revoked
except ValueError as err:
template_values = self._keeper.template_manager.get_template(template_address)
if not template_values:
logger.warning(f'Cannot revoke template since it does not exist: {err}')
return False
logger.warning(f'Only template admin or owner can revoke a template: {err}')
return False | [
"def",
"revoke",
"(",
"self",
",",
"template_address",
",",
"account",
")",
":",
"try",
":",
"revoked",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"revoke_template",
"(",
"template_address",
",",
"account",
")",
"return",
"revoked",
"except",
"ValueError",
"as",
"err",
":",
"template_values",
"=",
"self",
".",
"_keeper",
".",
"template_manager",
".",
"get_template",
"(",
"template_address",
")",
"if",
"not",
"template_values",
":",
"logger",
".",
"warning",
"(",
"f'Cannot revoke template since it does not exist: {err}'",
")",
"return",
"False",
"logger",
".",
"warning",
"(",
"f'Only template admin or owner can revoke a template: {err}'",
")",
"return",
"False"
] | Revoke a template already approved. The account needs to be owner of the templateManager
contract to be able of revoke the template.
:param template_address: Address of the template contract, str
:param account: account revoking the template, Account
:return: bool | [
"Revoke",
"a",
"template",
"already",
"approved",
".",
"The",
"account",
"needs",
"to",
"be",
"owner",
"of",
"the",
"templateManager",
"contract",
"to",
"be",
"able",
"of",
"revoke",
"the",
"template",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ocean/ocean_templates.py#L75-L94 |
2,477 | oceanprotocol/squid-py | squid_py/agreements/service_agreement.py | ServiceAgreement.get_price | def get_price(self):
"""
Return the price from the conditions parameters.
:return: Int
"""
for cond in self.conditions:
for p in cond.parameters:
if p.name == '_amount':
return p.value | python | def get_price(self):
"""
Return the price from the conditions parameters.
:return: Int
"""
for cond in self.conditions:
for p in cond.parameters:
if p.name == '_amount':
return p.value | [
"def",
"get_price",
"(",
"self",
")",
":",
"for",
"cond",
"in",
"self",
".",
"conditions",
":",
"for",
"p",
"in",
"cond",
".",
"parameters",
":",
"if",
"p",
".",
"name",
"==",
"'_amount'",
":",
"return",
"p",
".",
"value"
] | Return the price from the conditions parameters.
:return: Int | [
"Return",
"the",
"price",
"from",
"the",
"conditions",
"parameters",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement.py#L47-L56 |
2,478 | oceanprotocol/squid-py | squid_py/agreements/service_agreement.py | ServiceAgreement.get_service_agreement_hash | def get_service_agreement_hash(
self, agreement_id, asset_id, consumer_address, publisher_address, keeper):
"""Return the hash of the service agreement values to be signed by a consumer.
:param agreement_id:id of the agreement, hex str
:param asset_id:
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_address: ethereum account address of publisher, hex str
:param keeper:
:return:
"""
agreement_hash = ServiceAgreement.generate_service_agreement_hash(
self.template_id,
self.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, keeper),
self.conditions_timelocks,
self.conditions_timeouts,
agreement_id
)
return agreement_hash | python | def get_service_agreement_hash(
self, agreement_id, asset_id, consumer_address, publisher_address, keeper):
"""Return the hash of the service agreement values to be signed by a consumer.
:param agreement_id:id of the agreement, hex str
:param asset_id:
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_address: ethereum account address of publisher, hex str
:param keeper:
:return:
"""
agreement_hash = ServiceAgreement.generate_service_agreement_hash(
self.template_id,
self.generate_agreement_condition_ids(
agreement_id, asset_id, consumer_address, publisher_address, keeper),
self.conditions_timelocks,
self.conditions_timeouts,
agreement_id
)
return agreement_hash | [
"def",
"get_service_agreement_hash",
"(",
"self",
",",
"agreement_id",
",",
"asset_id",
",",
"consumer_address",
",",
"publisher_address",
",",
"keeper",
")",
":",
"agreement_hash",
"=",
"ServiceAgreement",
".",
"generate_service_agreement_hash",
"(",
"self",
".",
"template_id",
",",
"self",
".",
"generate_agreement_condition_ids",
"(",
"agreement_id",
",",
"asset_id",
",",
"consumer_address",
",",
"publisher_address",
",",
"keeper",
")",
",",
"self",
".",
"conditions_timelocks",
",",
"self",
".",
"conditions_timeouts",
",",
"agreement_id",
")",
"return",
"agreement_hash"
] | Return the hash of the service agreement values to be signed by a consumer.
:param agreement_id:id of the agreement, hex str
:param asset_id:
:param consumer_address: ethereum account address of consumer, hex str
:param publisher_address: ethereum account address of publisher, hex str
:param keeper:
:return: | [
"Return",
"the",
"hash",
"of",
"the",
"service",
"agreement",
"values",
"to",
"be",
"signed",
"by",
"a",
"consumer",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/agreements/service_agreement.py#L226-L245 |
2,479 | oceanprotocol/squid-py | squid_py/config.py | Config.keeper_path | def keeper_path(self):
"""Path where the keeper-contracts artifacts are allocated."""
keeper_path_string = self.get(self._section_name, NAME_KEEPER_PATH)
path = Path(keeper_path_string).expanduser().resolve()
# TODO: Handle the default case and make default empty string
# assert path.exists(), "Can't find the keeper path: {} ({})"..format(keeper_path_string,
# path)
if os.path.exists(path):
pass
elif os.getenv('VIRTUAL_ENV'):
path = os.path.join(os.getenv('VIRTUAL_ENV'), 'artifacts')
else:
path = os.path.join(site.PREFIXES[0], 'artifacts')
return path | python | def keeper_path(self):
"""Path where the keeper-contracts artifacts are allocated."""
keeper_path_string = self.get(self._section_name, NAME_KEEPER_PATH)
path = Path(keeper_path_string).expanduser().resolve()
# TODO: Handle the default case and make default empty string
# assert path.exists(), "Can't find the keeper path: {} ({})"..format(keeper_path_string,
# path)
if os.path.exists(path):
pass
elif os.getenv('VIRTUAL_ENV'):
path = os.path.join(os.getenv('VIRTUAL_ENV'), 'artifacts')
else:
path = os.path.join(site.PREFIXES[0], 'artifacts')
return path | [
"def",
"keeper_path",
"(",
"self",
")",
":",
"keeper_path_string",
"=",
"self",
".",
"get",
"(",
"self",
".",
"_section_name",
",",
"NAME_KEEPER_PATH",
")",
"path",
"=",
"Path",
"(",
"keeper_path_string",
")",
".",
"expanduser",
"(",
")",
".",
"resolve",
"(",
")",
"# TODO: Handle the default case and make default empty string",
"# assert path.exists(), \"Can't find the keeper path: {} ({})\"..format(keeper_path_string,",
"# path)",
"if",
"os",
".",
"path",
".",
"exists",
"(",
"path",
")",
":",
"pass",
"elif",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"os",
".",
"getenv",
"(",
"'VIRTUAL_ENV'",
")",
",",
"'artifacts'",
")",
"else",
":",
"path",
"=",
"os",
".",
"path",
".",
"join",
"(",
"site",
".",
"PREFIXES",
"[",
"0",
"]",
",",
"'artifacts'",
")",
"return",
"path"
] | Path where the keeper-contracts artifacts are allocated. | [
"Path",
"where",
"the",
"keeper",
"-",
"contracts",
"artifacts",
"are",
"allocated",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/config.py#L116-L129 |
2,480 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_public_key | def add_public_key(self, did, public_key):
"""
Add a public key object to the list of public keys.
:param public_key: Public key, PublicKeyHex
"""
logger.debug(f'Adding public key {public_key} to the did {did}')
self._public_keys.append(
PublicKeyBase(did, **{"owner": public_key, "type": "EthereumECDSAKey"})) | python | def add_public_key(self, did, public_key):
"""
Add a public key object to the list of public keys.
:param public_key: Public key, PublicKeyHex
"""
logger.debug(f'Adding public key {public_key} to the did {did}')
self._public_keys.append(
PublicKeyBase(did, **{"owner": public_key, "type": "EthereumECDSAKey"})) | [
"def",
"add_public_key",
"(",
"self",
",",
"did",
",",
"public_key",
")",
":",
"logger",
".",
"debug",
"(",
"f'Adding public key {public_key} to the did {did}'",
")",
"self",
".",
"_public_keys",
".",
"append",
"(",
"PublicKeyBase",
"(",
"did",
",",
"*",
"*",
"{",
"\"owner\"",
":",
"public_key",
",",
"\"type\"",
":",
"\"EthereumECDSAKey\"",
"}",
")",
")"
] | Add a public key object to the list of public keys.
:param public_key: Public key, PublicKeyHex | [
"Add",
"a",
"public",
"key",
"object",
"to",
"the",
"list",
"of",
"public",
"keys",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L79-L87 |
2,481 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_authentication | def add_authentication(self, public_key, authentication_type=None):
"""
Add a authentication public key id and type to the list of authentications.
:param key_id: Key id, Authentication
:param authentication_type: Authentication type, str
"""
authentication = {}
if public_key:
authentication = {'type': authentication_type, 'publicKey': public_key}
logger.debug(f'Adding authentication {authentication}')
self._authentications.append(authentication) | python | def add_authentication(self, public_key, authentication_type=None):
"""
Add a authentication public key id and type to the list of authentications.
:param key_id: Key id, Authentication
:param authentication_type: Authentication type, str
"""
authentication = {}
if public_key:
authentication = {'type': authentication_type, 'publicKey': public_key}
logger.debug(f'Adding authentication {authentication}')
self._authentications.append(authentication) | [
"def",
"add_authentication",
"(",
"self",
",",
"public_key",
",",
"authentication_type",
"=",
"None",
")",
":",
"authentication",
"=",
"{",
"}",
"if",
"public_key",
":",
"authentication",
"=",
"{",
"'type'",
":",
"authentication_type",
",",
"'publicKey'",
":",
"public_key",
"}",
"logger",
".",
"debug",
"(",
"f'Adding authentication {authentication}'",
")",
"self",
".",
"_authentications",
".",
"append",
"(",
"authentication",
")"
] | Add a authentication public key id and type to the list of authentications.
:param key_id: Key id, Authentication
:param authentication_type: Authentication type, str | [
"Add",
"a",
"authentication",
"public",
"key",
"id",
"and",
"type",
"to",
"the",
"list",
"of",
"authentications",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L89-L100 |
2,482 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.add_service | def add_service(self, service_type, service_endpoint=None, values=None):
"""
Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint.
"""
if isinstance(service_type, Service):
service = service_type
else:
service = Service(service_endpoint, service_type, values, did=self._did)
logger.debug(f'Adding service with service type {service_type} with did {self._did}')
self._services.append(service) | python | def add_service(self, service_type, service_endpoint=None, values=None):
"""
Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint.
"""
if isinstance(service_type, Service):
service = service_type
else:
service = Service(service_endpoint, service_type, values, did=self._did)
logger.debug(f'Adding service with service type {service_type} with did {self._did}')
self._services.append(service) | [
"def",
"add_service",
"(",
"self",
",",
"service_type",
",",
"service_endpoint",
"=",
"None",
",",
"values",
"=",
"None",
")",
":",
"if",
"isinstance",
"(",
"service_type",
",",
"Service",
")",
":",
"service",
"=",
"service_type",
"else",
":",
"service",
"=",
"Service",
"(",
"service_endpoint",
",",
"service_type",
",",
"values",
",",
"did",
"=",
"self",
".",
"_did",
")",
"logger",
".",
"debug",
"(",
"f'Adding service with service type {service_type} with did {self._did}'",
")",
"self",
".",
"_services",
".",
"append",
"(",
"service",
")"
] | Add a service to the list of services on the DDO.
:param service_type: Service
:param service_endpoint: Service endpoint, str
:param values: Python dict with serviceDefinitionId, templateId, serviceAgreementContract,
list of conditions and consume endpoint. | [
"Add",
"a",
"service",
"to",
"the",
"list",
"of",
"services",
"on",
"the",
"DDO",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L102-L116 |
2,483 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.as_text | def as_text(self, is_proof=True, is_pretty=False):
"""Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
"""
data = self.as_dictionary(is_proof)
if is_pretty:
return json.dumps(data, indent=2, separators=(',', ': '))
return json.dumps(data) | python | def as_text(self, is_proof=True, is_pretty=False):
"""Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str
"""
data = self.as_dictionary(is_proof)
if is_pretty:
return json.dumps(data, indent=2, separators=(',', ': '))
return json.dumps(data) | [
"def",
"as_text",
"(",
"self",
",",
"is_proof",
"=",
"True",
",",
"is_pretty",
"=",
"False",
")",
":",
"data",
"=",
"self",
".",
"as_dictionary",
"(",
"is_proof",
")",
"if",
"is_pretty",
":",
"return",
"json",
".",
"dumps",
"(",
"data",
",",
"indent",
"=",
"2",
",",
"separators",
"=",
"(",
"','",
",",
"': '",
")",
")",
"return",
"json",
".",
"dumps",
"(",
"data",
")"
] | Return the DDO as a JSON text.
:param if is_proof: if False then do not include the 'proof' element.
:param is_pretty: If True return dictionary in a prettier way, bool
:return: str | [
"Return",
"the",
"DDO",
"as",
"a",
"JSON",
"text",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L118-L129 |
2,484 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.as_dictionary | def as_dictionary(self, is_proof=True):
"""
Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict
"""
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@context': DID_DDO_CONTEXT_URL,
'id': self._did,
'created': self._created,
}
if self._public_keys:
values = []
for public_key in self._public_keys:
values.append(public_key.as_dictionary())
data['publicKey'] = values
if self._authentications:
values = []
for authentication in self._authentications:
values.append(authentication)
data['authentication'] = values
if self._services:
values = []
for service in self._services:
values.append(service.as_dictionary())
data['service'] = values
if self._proof and is_proof:
data['proof'] = self._proof
return data | python | def as_dictionary(self, is_proof=True):
"""
Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict
"""
if self._created is None:
self._created = DDO._get_timestamp()
data = {
'@context': DID_DDO_CONTEXT_URL,
'id': self._did,
'created': self._created,
}
if self._public_keys:
values = []
for public_key in self._public_keys:
values.append(public_key.as_dictionary())
data['publicKey'] = values
if self._authentications:
values = []
for authentication in self._authentications:
values.append(authentication)
data['authentication'] = values
if self._services:
values = []
for service in self._services:
values.append(service.as_dictionary())
data['service'] = values
if self._proof and is_proof:
data['proof'] = self._proof
return data | [
"def",
"as_dictionary",
"(",
"self",
",",
"is_proof",
"=",
"True",
")",
":",
"if",
"self",
".",
"_created",
"is",
"None",
":",
"self",
".",
"_created",
"=",
"DDO",
".",
"_get_timestamp",
"(",
")",
"data",
"=",
"{",
"'@context'",
":",
"DID_DDO_CONTEXT_URL",
",",
"'id'",
":",
"self",
".",
"_did",
",",
"'created'",
":",
"self",
".",
"_created",
",",
"}",
"if",
"self",
".",
"_public_keys",
":",
"values",
"=",
"[",
"]",
"for",
"public_key",
"in",
"self",
".",
"_public_keys",
":",
"values",
".",
"append",
"(",
"public_key",
".",
"as_dictionary",
"(",
")",
")",
"data",
"[",
"'publicKey'",
"]",
"=",
"values",
"if",
"self",
".",
"_authentications",
":",
"values",
"=",
"[",
"]",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"values",
".",
"append",
"(",
"authentication",
")",
"data",
"[",
"'authentication'",
"]",
"=",
"values",
"if",
"self",
".",
"_services",
":",
"values",
"=",
"[",
"]",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"values",
".",
"append",
"(",
"service",
".",
"as_dictionary",
"(",
")",
")",
"data",
"[",
"'service'",
"]",
"=",
"values",
"if",
"self",
".",
"_proof",
"and",
"is_proof",
":",
"data",
"[",
"'proof'",
"]",
"=",
"self",
".",
"_proof",
"return",
"data"
] | Return the DDO as a JSON dict.
:param if is_proof: if False then do not include the 'proof' element.
:return: dict | [
"Return",
"the",
"DDO",
"as",
"a",
"JSON",
"dict",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L131-L164 |
2,485 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._read_dict | def _read_dict(self, dictionary):
"""Import a JSON dict into this DDO."""
values = dictionary
self._did = values['id']
self._created = values.get('created', None)
if 'publicKey' in values:
self._public_keys = []
for value in values['publicKey']:
if isinstance(value, str):
value = json.loads(value)
self._public_keys.append(DDO.create_public_key_from_json(value))
if 'authentication' in values:
self._authentications = []
for value in values['authentication']:
if isinstance(value, str):
value = json.loads(value)
self._authentications.append(DDO.create_authentication_from_json(value))
if 'service' in values:
self._services = []
for value in values['service']:
if isinstance(value, str):
value = json.loads(value)
service = Service.from_json(value)
service.set_did(self._did)
self._services.append(service)
if 'proof' in values:
self._proof = values['proof'] | python | def _read_dict(self, dictionary):
"""Import a JSON dict into this DDO."""
values = dictionary
self._did = values['id']
self._created = values.get('created', None)
if 'publicKey' in values:
self._public_keys = []
for value in values['publicKey']:
if isinstance(value, str):
value = json.loads(value)
self._public_keys.append(DDO.create_public_key_from_json(value))
if 'authentication' in values:
self._authentications = []
for value in values['authentication']:
if isinstance(value, str):
value = json.loads(value)
self._authentications.append(DDO.create_authentication_from_json(value))
if 'service' in values:
self._services = []
for value in values['service']:
if isinstance(value, str):
value = json.loads(value)
service = Service.from_json(value)
service.set_did(self._did)
self._services.append(service)
if 'proof' in values:
self._proof = values['proof'] | [
"def",
"_read_dict",
"(",
"self",
",",
"dictionary",
")",
":",
"values",
"=",
"dictionary",
"self",
".",
"_did",
"=",
"values",
"[",
"'id'",
"]",
"self",
".",
"_created",
"=",
"values",
".",
"get",
"(",
"'created'",
",",
"None",
")",
"if",
"'publicKey'",
"in",
"values",
":",
"self",
".",
"_public_keys",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'publicKey'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"self",
".",
"_public_keys",
".",
"append",
"(",
"DDO",
".",
"create_public_key_from_json",
"(",
"value",
")",
")",
"if",
"'authentication'",
"in",
"values",
":",
"self",
".",
"_authentications",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'authentication'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"self",
".",
"_authentications",
".",
"append",
"(",
"DDO",
".",
"create_authentication_from_json",
"(",
"value",
")",
")",
"if",
"'service'",
"in",
"values",
":",
"self",
".",
"_services",
"=",
"[",
"]",
"for",
"value",
"in",
"values",
"[",
"'service'",
"]",
":",
"if",
"isinstance",
"(",
"value",
",",
"str",
")",
":",
"value",
"=",
"json",
".",
"loads",
"(",
"value",
")",
"service",
"=",
"Service",
".",
"from_json",
"(",
"value",
")",
"service",
".",
"set_did",
"(",
"self",
".",
"_did",
")",
"self",
".",
"_services",
".",
"append",
"(",
"service",
")",
"if",
"'proof'",
"in",
"values",
":",
"self",
".",
"_proof",
"=",
"values",
"[",
"'proof'",
"]"
] | Import a JSON dict into this DDO. | [
"Import",
"a",
"JSON",
"dict",
"into",
"this",
"DDO",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L166-L192 |
2,486 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.get_public_key | def get_public_key(self, key_id, is_search_embedded=False):
"""Key_id can be a string, or int. If int then the index in the list of keys."""
if isinstance(key_id, int):
return self._public_keys[key_id]
for item in self._public_keys:
if item.get_id() == key_id:
return item
if is_search_embedded:
for authentication in self._authentications:
if authentication.get_public_key_id() == key_id:
return authentication.get_public_key()
return None | python | def get_public_key(self, key_id, is_search_embedded=False):
"""Key_id can be a string, or int. If int then the index in the list of keys."""
if isinstance(key_id, int):
return self._public_keys[key_id]
for item in self._public_keys:
if item.get_id() == key_id:
return item
if is_search_embedded:
for authentication in self._authentications:
if authentication.get_public_key_id() == key_id:
return authentication.get_public_key()
return None | [
"def",
"get_public_key",
"(",
"self",
",",
"key_id",
",",
"is_search_embedded",
"=",
"False",
")",
":",
"if",
"isinstance",
"(",
"key_id",
",",
"int",
")",
":",
"return",
"self",
".",
"_public_keys",
"[",
"key_id",
"]",
"for",
"item",
"in",
"self",
".",
"_public_keys",
":",
"if",
"item",
".",
"get_id",
"(",
")",
"==",
"key_id",
":",
"return",
"item",
"if",
"is_search_embedded",
":",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"get_public_key_id",
"(",
")",
"==",
"key_id",
":",
"return",
"authentication",
".",
"get_public_key",
"(",
")",
"return",
"None"
] | Key_id can be a string, or int. If int then the index in the list of keys. | [
"Key_id",
"can",
"be",
"a",
"string",
"or",
"int",
".",
"If",
"int",
"then",
"the",
"index",
"in",
"the",
"list",
"of",
"keys",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L211-L224 |
2,487 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._get_public_key_count | def _get_public_key_count(self):
"""Return the count of public keys in the list and embedded."""
index = len(self._public_keys)
for authentication in self._authentications:
if authentication.is_public_key():
index += 1
return index | python | def _get_public_key_count(self):
"""Return the count of public keys in the list and embedded."""
index = len(self._public_keys)
for authentication in self._authentications:
if authentication.is_public_key():
index += 1
return index | [
"def",
"_get_public_key_count",
"(",
"self",
")",
":",
"index",
"=",
"len",
"(",
"self",
".",
"_public_keys",
")",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"is_public_key",
"(",
")",
":",
"index",
"+=",
"1",
"return",
"index"
] | Return the count of public keys in the list and embedded. | [
"Return",
"the",
"count",
"of",
"public",
"keys",
"in",
"the",
"list",
"and",
"embedded",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L226-L232 |
2,488 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO._get_authentication_from_public_key_id | def _get_authentication_from_public_key_id(self, key_id):
"""Return the authentication based on it's id."""
for authentication in self._authentications:
if authentication.is_key_id(key_id):
return authentication
return None | python | def _get_authentication_from_public_key_id(self, key_id):
"""Return the authentication based on it's id."""
for authentication in self._authentications:
if authentication.is_key_id(key_id):
return authentication
return None | [
"def",
"_get_authentication_from_public_key_id",
"(",
"self",
",",
"key_id",
")",
":",
"for",
"authentication",
"in",
"self",
".",
"_authentications",
":",
"if",
"authentication",
".",
"is_key_id",
"(",
"key_id",
")",
":",
"return",
"authentication",
"return",
"None"
] | Return the authentication based on it's id. | [
"Return",
"the",
"authentication",
"based",
"on",
"it",
"s",
"id",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L234-L239 |
2,489 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.get_service | def get_service(self, service_type=None):
"""Return a service using."""
for service in self._services:
if service.type == service_type and service_type:
return service
return None | python | def get_service(self, service_type=None):
"""Return a service using."""
for service in self._services:
if service.type == service_type and service_type:
return service
return None | [
"def",
"get_service",
"(",
"self",
",",
"service_type",
"=",
"None",
")",
":",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service",
".",
"type",
"==",
"service_type",
"and",
"service_type",
":",
"return",
"service",
"return",
"None"
] | Return a service using. | [
"Return",
"a",
"service",
"using",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L241-L246 |
2,490 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.find_service_by_id | def find_service_by_id(self, service_id):
"""
Get service for a given service_id.
:param service_id: Service id, str
:return: Service
"""
service_id_key = 'serviceDefinitionId'
service_id = str(service_id)
for service in self._services:
if service_id_key in service.values and str(
service.values[service_id_key]) == service_id:
return service
try:
# If service_id is int or can be converted to int then we couldn't find it
int(service_id)
return None
except ValueError:
pass
# try to find by type
return self.find_service_by_type(service_id) | python | def find_service_by_id(self, service_id):
"""
Get service for a given service_id.
:param service_id: Service id, str
:return: Service
"""
service_id_key = 'serviceDefinitionId'
service_id = str(service_id)
for service in self._services:
if service_id_key in service.values and str(
service.values[service_id_key]) == service_id:
return service
try:
# If service_id is int or can be converted to int then we couldn't find it
int(service_id)
return None
except ValueError:
pass
# try to find by type
return self.find_service_by_type(service_id) | [
"def",
"find_service_by_id",
"(",
"self",
",",
"service_id",
")",
":",
"service_id_key",
"=",
"'serviceDefinitionId'",
"service_id",
"=",
"str",
"(",
"service_id",
")",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service_id_key",
"in",
"service",
".",
"values",
"and",
"str",
"(",
"service",
".",
"values",
"[",
"service_id_key",
"]",
")",
"==",
"service_id",
":",
"return",
"service",
"try",
":",
"# If service_id is int or can be converted to int then we couldn't find it",
"int",
"(",
"service_id",
")",
"return",
"None",
"except",
"ValueError",
":",
"pass",
"# try to find by type",
"return",
"self",
".",
"find_service_by_type",
"(",
"service_id",
")"
] | Get service for a given service_id.
:param service_id: Service id, str
:return: Service | [
"Get",
"service",
"for",
"a",
"given",
"service_id",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L248-L270 |
2,491 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.find_service_by_type | def find_service_by_type(self, service_type):
"""
Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service
"""
for service in self._services:
if service_type == service.type:
return service
return None | python | def find_service_by_type(self, service_type):
"""
Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service
"""
for service in self._services:
if service_type == service.type:
return service
return None | [
"def",
"find_service_by_type",
"(",
"self",
",",
"service_type",
")",
":",
"for",
"service",
"in",
"self",
".",
"_services",
":",
"if",
"service_type",
"==",
"service",
".",
"type",
":",
"return",
"service",
"return",
"None"
] | Get service for a given service type.
:param service_type: Service type, ServiceType
:return: Service | [
"Get",
"service",
"for",
"a",
"given",
"service",
"type",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L272-L282 |
2,492 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.create_public_key_from_json | def create_public_key_from_json(values):
"""Create a public key object based on the values from the JSON record."""
# currently we only support RSA public keys
_id = values.get('id')
if not _id:
# Make it more forgiving for now.
_id = ''
# raise ValueError('publicKey definition is missing the "id" value.')
if values.get('type') == PUBLIC_KEY_TYPE_RSA:
public_key = PublicKeyRSA(_id, owner=values.get('owner'))
else:
public_key = PublicKeyBase(_id, owner=values.get('owner'), type='EthereumECDSAKey')
public_key.set_key_value(values)
return public_key | python | def create_public_key_from_json(values):
"""Create a public key object based on the values from the JSON record."""
# currently we only support RSA public keys
_id = values.get('id')
if not _id:
# Make it more forgiving for now.
_id = ''
# raise ValueError('publicKey definition is missing the "id" value.')
if values.get('type') == PUBLIC_KEY_TYPE_RSA:
public_key = PublicKeyRSA(_id, owner=values.get('owner'))
else:
public_key = PublicKeyBase(_id, owner=values.get('owner'), type='EthereumECDSAKey')
public_key.set_key_value(values)
return public_key | [
"def",
"create_public_key_from_json",
"(",
"values",
")",
":",
"# currently we only support RSA public keys",
"_id",
"=",
"values",
".",
"get",
"(",
"'id'",
")",
"if",
"not",
"_id",
":",
"# Make it more forgiving for now.",
"_id",
"=",
"''",
"# raise ValueError('publicKey definition is missing the \"id\" value.')",
"if",
"values",
".",
"get",
"(",
"'type'",
")",
"==",
"PUBLIC_KEY_TYPE_RSA",
":",
"public_key",
"=",
"PublicKeyRSA",
"(",
"_id",
",",
"owner",
"=",
"values",
".",
"get",
"(",
"'owner'",
")",
")",
"else",
":",
"public_key",
"=",
"PublicKeyBase",
"(",
"_id",
",",
"owner",
"=",
"values",
".",
"get",
"(",
"'owner'",
")",
",",
"type",
"=",
"'EthereumECDSAKey'",
")",
"public_key",
".",
"set_key_value",
"(",
"values",
")",
"return",
"public_key"
] | Create a public key object based on the values from the JSON record. | [
"Create",
"a",
"public",
"key",
"object",
"based",
"on",
"the",
"values",
"from",
"the",
"JSON",
"record",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L295-L310 |
2,493 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.create_authentication_from_json | def create_authentication_from_json(values):
"""Create authentitaciton object from a JSON string."""
key_id = values.get('publicKey')
authentication_type = values.get('type')
if not key_id:
raise ValueError(
f'Invalid authentication definition, "publicKey" is missing: {values}')
authentication = {'type': authentication_type, 'publicKey': key_id}
return authentication | python | def create_authentication_from_json(values):
"""Create authentitaciton object from a JSON string."""
key_id = values.get('publicKey')
authentication_type = values.get('type')
if not key_id:
raise ValueError(
f'Invalid authentication definition, "publicKey" is missing: {values}')
authentication = {'type': authentication_type, 'publicKey': key_id}
return authentication | [
"def",
"create_authentication_from_json",
"(",
"values",
")",
":",
"key_id",
"=",
"values",
".",
"get",
"(",
"'publicKey'",
")",
"authentication_type",
"=",
"values",
".",
"get",
"(",
"'type'",
")",
"if",
"not",
"key_id",
":",
"raise",
"ValueError",
"(",
"f'Invalid authentication definition, \"publicKey\" is missing: {values}'",
")",
"authentication",
"=",
"{",
"'type'",
":",
"authentication_type",
",",
"'publicKey'",
":",
"key_id",
"}",
"return",
"authentication"
] | Create authentitaciton object from a JSON string. | [
"Create",
"authentitaciton",
"object",
"from",
"a",
"JSON",
"string",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L313-L323 |
2,494 | oceanprotocol/squid-py | squid_py/ddo/ddo.py | DDO.generate_checksum | def generate_checksum(did, metadata):
"""
Generation of the hash for integrity checksum.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: hex str
"""
files_checksum = ''
for file in metadata['base']['files']:
if 'checksum' in file:
files_checksum = files_checksum + file['checksum']
return hashlib.sha3_256((files_checksum +
metadata['base']['name'] +
metadata['base']['author'] +
metadata['base']['license'] +
did).encode('UTF-8')).hexdigest() | python | def generate_checksum(did, metadata):
"""
Generation of the hash for integrity checksum.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: hex str
"""
files_checksum = ''
for file in metadata['base']['files']:
if 'checksum' in file:
files_checksum = files_checksum + file['checksum']
return hashlib.sha3_256((files_checksum +
metadata['base']['name'] +
metadata['base']['author'] +
metadata['base']['license'] +
did).encode('UTF-8')).hexdigest() | [
"def",
"generate_checksum",
"(",
"did",
",",
"metadata",
")",
":",
"files_checksum",
"=",
"''",
"for",
"file",
"in",
"metadata",
"[",
"'base'",
"]",
"[",
"'files'",
"]",
":",
"if",
"'checksum'",
"in",
"file",
":",
"files_checksum",
"=",
"files_checksum",
"+",
"file",
"[",
"'checksum'",
"]",
"return",
"hashlib",
".",
"sha3_256",
"(",
"(",
"files_checksum",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'name'",
"]",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'author'",
"]",
"+",
"metadata",
"[",
"'base'",
"]",
"[",
"'license'",
"]",
"+",
"did",
")",
".",
"encode",
"(",
"'UTF-8'",
")",
")",
".",
"hexdigest",
"(",
")"
] | Generation of the hash for integrity checksum.
:param did: DID, str
:param metadata: conforming to the Metadata accepted by Ocean Protocol, dict
:return: hex str | [
"Generation",
"of",
"the",
"hash",
"for",
"integrity",
"checksum",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/ddo/ddo.py#L331-L347 |
2,495 | oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.register | def register(self, did, checksum, url, account, providers=None):
"""
Register or update a DID on the block chain using the DIDRegistry smart contract.
:param did: DID to register/update, can be a 32 byte or hexstring
:param checksum: hex str hash of TODO
:param url: URL of the resolved DID
:param account: instance of Account to use to register/update the DID
:param providers: list of addresses of providers to be allowed to serve the asset and play
a part in creating and fulfilling service agreements
:return: Receipt
"""
did_source_id = did_to_id_bytes(did)
if not did_source_id:
raise ValueError(f'{did} must be a valid DID to register')
if not urlparse(url):
raise ValueError(f'Invalid URL {url} to register for DID {did}')
if checksum is None:
checksum = Web3Provider.get_web3().toBytes(0)
if not isinstance(checksum, bytes):
raise ValueError(f'Invalid checksum value {checksum}, must be bytes or string')
if account is None:
raise ValueError('You must provide an account to use to register a DID')
transaction = self._register_attribute(
did_source_id, checksum, url, account, providers or []
)
receipt = self.get_tx_receipt(transaction)
return receipt and receipt.status == 1 | python | def register(self, did, checksum, url, account, providers=None):
"""
Register or update a DID on the block chain using the DIDRegistry smart contract.
:param did: DID to register/update, can be a 32 byte or hexstring
:param checksum: hex str hash of TODO
:param url: URL of the resolved DID
:param account: instance of Account to use to register/update the DID
:param providers: list of addresses of providers to be allowed to serve the asset and play
a part in creating and fulfilling service agreements
:return: Receipt
"""
did_source_id = did_to_id_bytes(did)
if not did_source_id:
raise ValueError(f'{did} must be a valid DID to register')
if not urlparse(url):
raise ValueError(f'Invalid URL {url} to register for DID {did}')
if checksum is None:
checksum = Web3Provider.get_web3().toBytes(0)
if not isinstance(checksum, bytes):
raise ValueError(f'Invalid checksum value {checksum}, must be bytes or string')
if account is None:
raise ValueError('You must provide an account to use to register a DID')
transaction = self._register_attribute(
did_source_id, checksum, url, account, providers or []
)
receipt = self.get_tx_receipt(transaction)
return receipt and receipt.status == 1 | [
"def",
"register",
"(",
"self",
",",
"did",
",",
"checksum",
",",
"url",
",",
"account",
",",
"providers",
"=",
"None",
")",
":",
"did_source_id",
"=",
"did_to_id_bytes",
"(",
"did",
")",
"if",
"not",
"did_source_id",
":",
"raise",
"ValueError",
"(",
"f'{did} must be a valid DID to register'",
")",
"if",
"not",
"urlparse",
"(",
"url",
")",
":",
"raise",
"ValueError",
"(",
"f'Invalid URL {url} to register for DID {did}'",
")",
"if",
"checksum",
"is",
"None",
":",
"checksum",
"=",
"Web3Provider",
".",
"get_web3",
"(",
")",
".",
"toBytes",
"(",
"0",
")",
"if",
"not",
"isinstance",
"(",
"checksum",
",",
"bytes",
")",
":",
"raise",
"ValueError",
"(",
"f'Invalid checksum value {checksum}, must be bytes or string'",
")",
"if",
"account",
"is",
"None",
":",
"raise",
"ValueError",
"(",
"'You must provide an account to use to register a DID'",
")",
"transaction",
"=",
"self",
".",
"_register_attribute",
"(",
"did_source_id",
",",
"checksum",
",",
"url",
",",
"account",
",",
"providers",
"or",
"[",
"]",
")",
"receipt",
"=",
"self",
".",
"get_tx_receipt",
"(",
"transaction",
")",
"return",
"receipt",
"and",
"receipt",
".",
"status",
"==",
"1"
] | Register or update a DID on the block chain using the DIDRegistry smart contract.
:param did: DID to register/update, can be a 32 byte or hexstring
:param checksum: hex str hash of TODO
:param url: URL of the resolved DID
:param account: instance of Account to use to register/update the DID
:param providers: list of addresses of providers to be allowed to serve the asset and play
a part in creating and fulfilling service agreements
:return: Receipt | [
"Register",
"or",
"update",
"a",
"DID",
"on",
"the",
"block",
"chain",
"using",
"the",
"DIDRegistry",
"smart",
"contract",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L29-L62 |
2,496 | oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry._register_attribute | def _register_attribute(self, did, checksum, value, account, providers):
"""Register an DID attribute as an event on the block chain.
:param did: 32 byte string/hex of the DID
:param checksum: checksum of the ddo, hex str
:param value: url for resolve the did, str
:param account: account owner of this DID registration record
:param providers: list of providers addresses
"""
assert isinstance(providers, list), ''
return self.send_transaction(
'registerAttribute',
(did,
checksum,
providers,
value),
transact={'from': account.address,
'passphrase': account.password}
) | python | def _register_attribute(self, did, checksum, value, account, providers):
"""Register an DID attribute as an event on the block chain.
:param did: 32 byte string/hex of the DID
:param checksum: checksum of the ddo, hex str
:param value: url for resolve the did, str
:param account: account owner of this DID registration record
:param providers: list of providers addresses
"""
assert isinstance(providers, list), ''
return self.send_transaction(
'registerAttribute',
(did,
checksum,
providers,
value),
transact={'from': account.address,
'passphrase': account.password}
) | [
"def",
"_register_attribute",
"(",
"self",
",",
"did",
",",
"checksum",
",",
"value",
",",
"account",
",",
"providers",
")",
":",
"assert",
"isinstance",
"(",
"providers",
",",
"list",
")",
",",
"''",
"return",
"self",
".",
"send_transaction",
"(",
"'registerAttribute'",
",",
"(",
"did",
",",
"checksum",
",",
"providers",
",",
"value",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")"
] | Register an DID attribute as an event on the block chain.
:param did: 32 byte string/hex of the DID
:param checksum: checksum of the ddo, hex str
:param value: url for resolve the did, str
:param account: account owner of this DID registration record
:param providers: list of providers addresses | [
"Register",
"an",
"DID",
"attribute",
"as",
"an",
"event",
"on",
"the",
"block",
"chain",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L64-L82 |
2,497 | oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.remove_provider | def remove_provider(self, did, provider_address, account):
"""
Remove a provider
:param did: the id of an asset on-chain, hex str
:param provider_address: ethereum account address of the provider, hex str
:param account: Account executing the action
:return:
"""
tx_hash = self.send_transaction(
'removeDIDProvider',
(did,
provider_address),
transact={'from': account.address,
'passphrase': account.password}
)
return self.get_tx_receipt(tx_hash) | python | def remove_provider(self, did, provider_address, account):
"""
Remove a provider
:param did: the id of an asset on-chain, hex str
:param provider_address: ethereum account address of the provider, hex str
:param account: Account executing the action
:return:
"""
tx_hash = self.send_transaction(
'removeDIDProvider',
(did,
provider_address),
transact={'from': account.address,
'passphrase': account.password}
)
return self.get_tx_receipt(tx_hash) | [
"def",
"remove_provider",
"(",
"self",
",",
"did",
",",
"provider_address",
",",
"account",
")",
":",
"tx_hash",
"=",
"self",
".",
"send_transaction",
"(",
"'removeDIDProvider'",
",",
"(",
"did",
",",
"provider_address",
")",
",",
"transact",
"=",
"{",
"'from'",
":",
"account",
".",
"address",
",",
"'passphrase'",
":",
"account",
".",
"password",
"}",
")",
"return",
"self",
".",
"get_tx_receipt",
"(",
"tx_hash",
")"
] | Remove a provider
:param did: the id of an asset on-chain, hex str
:param provider_address: ethereum account address of the provider, hex str
:param account: Account executing the action
:return: | [
"Remove",
"a",
"provider"
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L115-L131 |
2,498 | oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.get_did_providers | def get_did_providers(self, did):
"""
Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers
"""
register_values = self.contract_concise.getDIDRegister(did)
if register_values and len(register_values) == 5:
return DIDRegisterValues(*register_values).providers
return None | python | def get_did_providers(self, did):
"""
Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers
"""
register_values = self.contract_concise.getDIDRegister(did)
if register_values and len(register_values) == 5:
return DIDRegisterValues(*register_values).providers
return None | [
"def",
"get_did_providers",
"(",
"self",
",",
"did",
")",
":",
"register_values",
"=",
"self",
".",
"contract_concise",
".",
"getDIDRegister",
"(",
"did",
")",
"if",
"register_values",
"and",
"len",
"(",
"register_values",
")",
"==",
"5",
":",
"return",
"DIDRegisterValues",
"(",
"*",
"register_values",
")",
".",
"providers",
"return",
"None"
] | Return the list providers registered on-chain for the given did.
:param did: hex str the id of an asset on-chain
:return:
list of addresses
None if asset has no registerd providers | [
"Return",
"the",
"list",
"providers",
"registered",
"on",
"-",
"chain",
"for",
"the",
"given",
"did",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L143-L156 |
2,499 | oceanprotocol/squid-py | squid_py/keeper/didregistry.py | DIDRegistry.get_owner_asset_ids | def get_owner_asset_ids(self, address):
"""
Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return:
"""
block_filter = self._get_event_filter(owner=address)
log_items = block_filter.get_all_entries(max_tries=5)
did_list = []
for log_i in log_items:
did_list.append(id_to_did(log_i.args['_did']))
return did_list | python | def get_owner_asset_ids(self, address):
"""
Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return:
"""
block_filter = self._get_event_filter(owner=address)
log_items = block_filter.get_all_entries(max_tries=5)
did_list = []
for log_i in log_items:
did_list.append(id_to_did(log_i.args['_did']))
return did_list | [
"def",
"get_owner_asset_ids",
"(",
"self",
",",
"address",
")",
":",
"block_filter",
"=",
"self",
".",
"_get_event_filter",
"(",
"owner",
"=",
"address",
")",
"log_items",
"=",
"block_filter",
".",
"get_all_entries",
"(",
"max_tries",
"=",
"5",
")",
"did_list",
"=",
"[",
"]",
"for",
"log_i",
"in",
"log_items",
":",
"did_list",
".",
"append",
"(",
"id_to_did",
"(",
"log_i",
".",
"args",
"[",
"'_did'",
"]",
")",
")",
"return",
"did_list"
] | Get the list of assets owned by an address owner.
:param address: ethereum account address, hex str
:return: | [
"Get",
"the",
"list",
"of",
"assets",
"owned",
"by",
"an",
"address",
"owner",
"."
] | 43a5b7431627e4c9ab7382ed9eb8153e96ed4483 | https://github.com/oceanprotocol/squid-py/blob/43a5b7431627e4c9ab7382ed9eb8153e96ed4483/squid_py/keeper/didregistry.py#L158-L171 |
Subsets and Splits