Search is not available for this dataset
identifier
stringlengths
1
155
parameters
stringlengths
2
6.09k
docstring
stringlengths
11
63.4k
docstring_summary
stringlengths
0
63.4k
function
stringlengths
29
99.8k
function_tokens
list
start_point
list
end_point
list
language
stringclasses
1 value
docstring_language
stringlengths
2
7
docstring_language_predictions
stringlengths
18
23
is_langid_reliable
stringclasses
2 values
to_current_timezone
(value)
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display.
def to_current_timezone(value): """ When time zone support is enabled, convert aware datetimes to naive datetimes in the current time zone for display. """ if settings.USE_TZ and value is not None and timezone.is_aware(value): current_timezone = timezone.get_current_timezone() return...
[ "def", "to_current_timezone", "(", "value", ")", ":", "if", "settings", ".", "USE_TZ", "and", "value", "is", "not", "None", "and", "timezone", ".", "is_aware", "(", "value", ")", ":", "current_timezone", "=", "timezone", ".", "get_current_timezone", "(", ")"...
[ 184, 0 ]
[ 192, 16 ]
python
en
['en', 'error', 'th']
False
additions_for_solution
( coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int )
Checks the conditions created by CoinSolution and returns the list of all coins created
Checks the conditions created by CoinSolution and returns the list of all coins created
def additions_for_solution( coin_name: bytes32, puzzle_reveal: SerializedProgram, solution: SerializedProgram, max_cost: int ) -> List[Coin]: """ Checks the conditions created by CoinSolution and returns the list of all coins created """ err, dic, cost = conditions_dict_for_solution(puzzle_reveal, s...
[ "def", "additions_for_solution", "(", "coin_name", ":", "bytes32", ",", "puzzle_reveal", ":", "SerializedProgram", ",", "solution", ":", "SerializedProgram", ",", "max_cost", ":", "int", ")", "->", "List", "[", "Coin", "]", ":", "err", ",", "dic", ",", "cost...
[ 11, 0 ]
[ 20, 62 ]
python
en
['en', 'error', 'th']
False
walk_revctrl
(dirname='')
Find all files under revision control
Find all files under revision control
def walk_revctrl(dirname=''): """Find all files under revision control""" for ep in pkg_resources.iter_entry_points('setuptools.file_finders'): for item in ep.load()(dirname): yield item
[ "def", "walk_revctrl", "(", "dirname", "=", "''", ")", ":", "for", "ep", "in", "pkg_resources", ".", "iter_entry_points", "(", "'setuptools.file_finders'", ")", ":", "for", "item", "in", "ep", ".", "load", "(", ")", "(", "dirname", ")", ":", "yield", "it...
[ 16, 0 ]
[ 20, 22 ]
python
en
['en', 'en', 'en']
True
sdist.make_distribution
(self)
Workaround for #516
Workaround for #516
def make_distribution(self): """ Workaround for #516 """ with self._remove_os_link(): orig.sdist.make_distribution(self)
[ "def", "make_distribution", "(", "self", ")", ":", "with", "self", ".", "_remove_os_link", "(", ")", ":", "orig", ".", "sdist", ".", "make_distribution", "(", "self", ")" ]
[ 72, 4 ]
[ 77, 46 ]
python
en
['en', 'error', 'th']
False
sdist._remove_os_link
()
In a context, remove and restore os.link if it exists
In a context, remove and restore os.link if it exists
def _remove_os_link(): """ In a context, remove and restore os.link if it exists """ class NoValue: pass orig_val = getattr(os, 'link', NoValue) try: del os.link except Exception: pass try: yield fi...
[ "def", "_remove_os_link", "(", ")", ":", "class", "NoValue", ":", "pass", "orig_val", "=", "getattr", "(", "os", ",", "'link'", ",", "NoValue", ")", "try", ":", "del", "os", ".", "link", "except", "Exception", ":", "pass", "try", ":", "yield", "finally...
[ 81, 4 ]
[ 98, 45 ]
python
en
['en', 'error', 'th']
False
sdist._add_defaults_python
(self)
getting python files
getting python files
def _add_defaults_python(self): """getting python files""" if self.distribution.has_pure_modules(): build_py = self.get_finalized_command('build_py') self.filelist.extend(build_py.get_source_files()) self._add_data_files(self._safe_data_files(build_py))
[ "def", "_add_defaults_python", "(", "self", ")", ":", "if", "self", ".", "distribution", ".", "has_pure_modules", "(", ")", ":", "build_py", "=", "self", ".", "get_finalized_command", "(", "'build_py'", ")", "self", ".", "filelist", ".", "extend", "(", "buil...
[ 105, 4 ]
[ 110, 65 ]
python
en
['en', 'en', 'en']
True
sdist._safe_data_files
(self, build_py)
Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case.
Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case.
def _safe_data_files(self, build_py): """ Extracting data_files from build_py is known to cause infinite recursion errors when `include_package_data` is enabled, so suppress it in that case. """ if self.distribution.include_package_data: return () retu...
[ "def", "_safe_data_files", "(", "self", ",", "build_py", ")", ":", "if", "self", ".", "distribution", ".", "include_package_data", ":", "return", "(", ")", "return", "build_py", ".", "data_files" ]
[ 112, 4 ]
[ 120, 34 ]
python
en
['en', 'error', 'th']
False
sdist._add_data_files
(self, data_files)
Add data files as found in build_py.data_files.
Add data files as found in build_py.data_files.
def _add_data_files(self, data_files): """ Add data files as found in build_py.data_files. """ self.filelist.extend( os.path.join(src_dir, name) for _, src_dir, _, filenames in data_files for name in filenames )
[ "def", "_add_data_files", "(", "self", ",", "data_files", ")", ":", "self", ".", "filelist", ".", "extend", "(", "os", ".", "path", ".", "join", "(", "src_dir", ",", "name", ")", "for", "_", ",", "src_dir", ",", "_", ",", "filenames", "in", "data_fil...
[ 122, 4 ]
[ 130, 9 ]
python
en
['en', 'error', 'th']
False
sdist.read_manifest
(self)
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution.
def read_manifest(self): """Read the manifest file (named by 'self.manifest') and use it to fill in 'self.filelist', the list of files to include in the source distribution. """ log.info("reading manifest file '%s'", self.manifest) manifest = open(self.manifest, 'rb') ...
[ "def", "read_manifest", "(", "self", ")", ":", "log", ".", "info", "(", "\"reading manifest file '%s'\"", ",", "self", ".", "manifest", ")", "manifest", "=", "open", "(", "self", ".", "manifest", ",", "'rb'", ")", "for", "line", "in", "manifest", ":", "#...
[ 171, 4 ]
[ 190, 24 ]
python
en
['en', 'en', 'en']
True
sdist.check_license
(self)
Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'.
Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'.
def check_license(self): """Checks if license_file' or 'license_files' is configured and adds any valid paths to 'self.filelist'. """ files = ordered_set.OrderedSet() opts = self.distribution.get_option_dict('metadata') # ignore the source of the value _, licen...
[ "def", "check_license", "(", "self", ")", ":", "files", "=", "ordered_set", ".", "OrderedSet", "(", ")", "opts", "=", "self", ".", "distribution", ".", "get_option_dict", "(", "'metadata'", ")", "# ignore the source of the value", "_", ",", "license_file", "=", ...
[ 192, 4 ]
[ 221, 35 ]
python
en
['en', 'en', 'en']
True
get_metadata_for_ordering
(images)
args: images (tuple): list of image urls returns: list: of ImageMetadataForSort
args: images (tuple): list of image urls returns: list: of ImageMetadataForSort
def get_metadata_for_ordering(images): """ args: images (tuple): list of image urls returns: list: of ImageMetadataForSort """ logger.debug("Retrieving ordering metadata from accessors") l = [] for a in tkp.steps.persistence.get_accessors(images): l.append(ImageMetada...
[ "def", "get_metadata_for_ordering", "(", "images", ")", ":", "logger", ".", "debug", "(", "\"Retrieving ordering metadata from accessors\"", ")", "l", "=", "[", "]", "for", "a", "in", "tkp", ".", "steps", ".", "persistence", ".", "get_accessors", "(", "images", ...
[ 35, 0 ]
[ 47, 12 ]
python
en
['en', 'error', 'th']
False
build_safe_env
(env)
Build environment dictionary, hiding potentially sensitive information such as passwords or keys.
Build environment dictionary, hiding potentially sensitive information such as passwords or keys.
def build_safe_env(env): """ Build environment dictionary, hiding potentially sensitive information such as passwords or keys. """ hidden_re = re.compile(r'API|TOKEN|KEY|SECRET|PASS', re.I) urlpass_re = re.compile(r'^.*?://[^:]+:(.*?)@.*?$') safe_env = dict(env) for k, v in safe_env.item...
[ "def", "build_safe_env", "(", "env", ")", ":", "hidden_re", "=", "re", ".", "compile", "(", "r'API|TOKEN|KEY|SECRET|PASS'", ",", "re", ".", "I", ")", "urlpass_re", "=", "re", ".", "compile", "(", "r'^.*?://[^:]+:(.*?)@.*?$'", ")", "safe_env", "=", "dict", "(...
[ 53, 0 ]
[ 70, 19 ]
python
en
['en', 'error', 'th']
False
Credential.unique_hash
(self, display=False)
Credential exclusivity is not defined solely by the related credential type (due to vault), so this produces a hash that can be used to evaluate exclusivity
Credential exclusivity is not defined solely by the related credential type (due to vault), so this produces a hash that can be used to evaluate exclusivity
def unique_hash(self, display=False): """ Credential exclusivity is not defined solely by the related credential type (due to vault), so this produces a hash that can be used to evaluate exclusivity """ if display: type_alias = self.credential_type.name ...
[ "def", "unique_hash", "(", "self", ",", "display", "=", "False", ")", ":", "if", "display", ":", "type_alias", "=", "self", ".", "credential_type", ".", "name", "else", ":", "type_alias", "=", "self", ".", "credential_type_id", "if", "self", ".", "credenti...
[ 236, 4 ]
[ 252, 30 ]
python
en
['en', 'error', 'th']
False
Credential.get_input
(self, field_name, **kwargs)
Get an injectable and decrypted value for an input field. Retrieves the value for a given credential input field name. Return values for secret input fields are decrypted. If the credential doesn't have an input value defined for the given field name, an AttributeError is raise...
Get an injectable and decrypted value for an input field.
def get_input(self, field_name, **kwargs): """ Get an injectable and decrypted value for an input field. Retrieves the value for a given credential input field name. Return values for secret input fields are decrypted. If the credential doesn't have an input value defined for th...
[ "def", "get_input", "(", "self", ",", "field_name", ",", "*", "*", "kwargs", ")", ":", "if", "self", ".", "credential_type", ".", "kind", "!=", "'external'", "and", "field_name", "in", "self", ".", "dynamic_input_fields", ":", "return", "self", ".", "_get_...
[ 261, 4 ]
[ 292, 40 ]
python
en
['en', 'error', 'th']
False
CredentialType.inject_credential
(self, credential, env, safe_env, args, private_data_dir)
Inject credential data into the environment variables and arguments passed to `ansible-playbook` :param credential: a :class:`awx.main.models.Credential` instance :param env: a dictionary of environment variables used in the `ansible-...
Inject credential data into the environment variables and arguments passed to `ansible-playbook`
def inject_credential(self, credential, env, safe_env, args, private_data_dir): """ Inject credential data into the environment variables and arguments passed to `ansible-playbook` :param credential: a :class:`awx.main.models.Credential` instance :param env: a...
[ "def", "inject_credential", "(", "self", ",", "credential", ",", "env", ",", "safe_env", ",", "args", ",", "private_data_dir", ")", ":", "if", "not", "self", ".", "injectors", ":", "if", "self", ".", "managed", "and", "credential", ".", "credential_type", ...
[ 421, 4 ]
[ 544, 59 ]
python
en
['en', 'error', 'th']
False
TestCloudProvisioning.test_terminate_only
(self)
test is terminated only when it was started and didn't finished
test is terminated only when it was started and didn't finished
def test_terminate_only(self): """ test is terminated only when it was started and didn't finished """ self.obj.user.token = object() cls = ServiceStubCaptureHAR.__module__ + "." + ServiceStubCaptureHAR.__name__ self.configure( add_settings=False, engine_cfg={ ...
[ "def", "test_terminate_only", "(", "self", ")", ":", "self", ".", "obj", ".", "user", ".", "token", "=", "object", "(", ")", "cls", "=", "ServiceStubCaptureHAR", ".", "__module__", "+", "\".\"", "+", "ServiceStubCaptureHAR", ".", "__name__", "self", ".", "...
[ 643, 4 ]
[ 697, 113 ]
python
en
['en', 'en', 'en']
True
TestCloudProvisioning.test_cloud_paths
(self)
Test different executor/path combinations for correct return values of get_resources_files
Test different executor/path combinations for correct return values of get_resources_files
def test_cloud_paths(self): """ Test different executor/path combinations for correct return values of get_resources_files """ self.configure( add_config=False, add_settings=False, ) # upload files # FIXME: refactor this method! self.sniff_log(self.o...
[ "def", "test_cloud_paths", "(", "self", ")", ":", "self", ".", "configure", "(", "add_config", "=", "False", ",", "add_settings", "=", "False", ",", ")", "# upload files", "# FIXME: refactor this method!", "self", ".", "sniff_log", "(", "self", ".", "obj", "."...
[ 699, 4 ]
[ 822, 36 ]
python
en
['en', 'error', 'th']
False
Command.show_list
(self, connection, app_names=None)
Shows a list of all migrations on the system, or only those of some named apps.
Shows a list of all migrations on the system, or only those of some named apps.
def show_list(self, connection, app_names=None): """ Shows a list of all migrations on the system, or only those of some named apps. """ # Load migrations from disk/DB loader = MigrationLoader(connection, ignore_no_migrations=True) graph = loader.graph # I...
[ "def", "show_list", "(", "self", ",", "connection", ",", "app_names", "=", "None", ")", ":", "# Load migrations from disk/DB", "loader", "=", "MigrationLoader", "(", "connection", ",", "ignore_no_migrations", "=", "True", ")", "graph", "=", "loader", ".", "graph...
[ 57, 4 ]
[ 91, 71 ]
python
en
['en', 'error', 'th']
False
Command.show_plan
(self, connection, app_names=None)
Shows all known migrations (or only those of the specified app_names) in the order they will be applied.
Shows all known migrations (or only those of the specified app_names) in the order they will be applied.
def show_plan(self, connection, app_names=None): """ Shows all known migrations (or only those of the specified app_names) in the order they will be applied. """ # Load migrations from disk/DB loader = MigrationLoader(connection) graph = loader.graph if ap...
[ "def", "show_plan", "(", "self", ",", "connection", ",", "app_names", "=", "None", ")", ":", "# Load migrations from disk/DB", "loader", "=", "MigrationLoader", "(", "connection", ")", "graph", "=", "loader", ".", "graph", "if", "app_names", ":", "self", ".", ...
[ 93, 4 ]
[ 133, 84 ]
python
en
['en', 'error', 'th']
False
test_visible_roles
(admin_user, system_auditor, rando, organization, project)
system admin & system auditor fixtures needed to create system roles
system admin & system auditor fixtures needed to create system roles
def test_visible_roles(admin_user, system_auditor, rando, organization, project): """ system admin & system auditor fixtures needed to create system roles """ organization.auditor_role.members.add(rando) access = RoleAccess(rando) assert rando not in organization.admin_role assert access.ca...
[ "def", "test_visible_roles", "(", "admin_user", ",", "system_auditor", ",", "rando", ",", "organization", ",", "project", ")", ":", "organization", ".", "auditor_role", ".", "members", ".", "add", "(", "rando", ")", "access", "=", "RoleAccess", "(", "rando", ...
[ 37, 0 ]
[ 50, 58 ]
python
en
['en', 'error', 'th']
False
test_org_user_role_attach
(user, organization, inventory)
Org admins must not be able to add arbitrary users to their organization, because that would give them admin permission to that user
Org admins must not be able to add arbitrary users to their organization, because that would give them admin permission to that user
def test_org_user_role_attach(user, organization, inventory): """ Org admins must not be able to add arbitrary users to their organization, because that would give them admin permission to that user """ admin = user('admin') nonmember = user('nonmember') other_org = Organization.objects.crea...
[ "def", "test_org_user_role_attach", "(", "user", ",", "organization", ",", "inventory", ")", ":", "admin", "=", "user", "(", "'admin'", ")", "nonmember", "=", "user", "(", "'nonmember'", ")", "other_org", "=", "Organization", ".", "objects", ".", "create", "...
[ 55, 0 ]
[ 73, 89 ]
python
en
['en', 'error', 'th']
False
test_user_org_object_roles
(organization, org_admin, org_member)
Unlike admin & member roles, the special-purpose organization roles do not confer any permissions related to user management, Normal rules about role delegation should apply, only admin to org needed.
Unlike admin & member roles, the special-purpose organization roles do not confer any permissions related to user management, Normal rules about role delegation should apply, only admin to org needed.
def test_user_org_object_roles(organization, org_admin, org_member): """ Unlike admin & member roles, the special-purpose organization roles do not confer any permissions related to user management, Normal rules about role delegation should apply, only admin to org needed. """ assert RoleAccess(...
[ "def", "test_user_org_object_roles", "(", "organization", ",", "org_admin", ",", "org_member", ")", ":", "assert", "RoleAccess", "(", "org_admin", ")", ".", "can_attach", "(", "organization", ".", "notification_admin_role", ",", "org_member", ",", "'members'", ",", ...
[ 78, 0 ]
[ 87, 123 ]
python
en
['en', 'error', 'th']
False
test_team_org_object_roles
(organization, team, org_admin, org_member)
the special-purpose organization roles are not ancestors of any team roles, and can be delegated en masse through teams, following normal admin rules
the special-purpose organization roles are not ancestors of any team roles, and can be delegated en masse through teams, following normal admin rules
def test_team_org_object_roles(organization, team, org_admin, org_member): """ the special-purpose organization roles are not ancestors of any team roles, and can be delegated en masse through teams, following normal admin rules """ assert RoleAccess(org_admin).can_attach(organization.notificati...
[ "def", "test_team_org_object_roles", "(", "organization", ",", "team", ",", "org_admin", ",", "org_member", ")", ":", "assert", "RoleAccess", "(", "org_admin", ")", ".", "can_attach", "(", "organization", ".", "notification_admin_role", ",", "team", ",", "'member_...
[ 91, 0 ]
[ 102, 114 ]
python
en
['en', 'error', 'th']
False
test_org_superuser_role_attach
(admin_user, org_admin, organization)
Ideally, you would not add superusers to roles (particularly member_role) but it has historically been possible this checks that the situation does not grant unexpected permissions
Ideally, you would not add superusers to roles (particularly member_role) but it has historically been possible this checks that the situation does not grant unexpected permissions
def test_org_superuser_role_attach(admin_user, org_admin, organization): """ Ideally, you would not add superusers to roles (particularly member_role) but it has historically been possible this checks that the situation does not grant unexpected permissions """ organization.member_role.members.a...
[ "def", "test_org_superuser_role_attach", "(", "admin_user", ",", "org_admin", ",", "organization", ")", ":", "organization", ".", "member_role", ".", "members", ".", "add", "(", "admin_user", ")", "role_access", "=", "RoleAccess", "(", "org_admin", ")", "org_acces...
[ 107, 0 ]
[ 122, 74 ]
python
en
['en', 'error', 'th']
False
test_need_all_orgs_to_admin_user
(user)
Old behavior - org admin to ANY organization that a user is member of grants permission to admin that user New behavior enforced here - org admin to ALL organizations that a user is member of grants permission to admin that user
Old behavior - org admin to ANY organization that a user is member of grants permission to admin that user New behavior enforced here - org admin to ALL organizations that a user is member of grants permission to admin that user
def test_need_all_orgs_to_admin_user(user): """ Old behavior - org admin to ANY organization that a user is member of grants permission to admin that user New behavior enforced here - org admin to ALL organizations that a user is member of grants permission to admin that user """ org...
[ "def", "test_need_all_orgs_to_admin_user", "(", "user", ")", ":", "org1", "=", "Organization", ".", "objects", ".", "create", "(", "name", "=", "'org1'", ")", "org2", "=", "Organization", ".", "objects", ".", "create", "(", "name", "=", "'org2'", ")", "org...
[ 140, 0 ]
[ 171, 75 ]
python
en
['en', 'error', 'th']
False
test_orphaned_user_allowed
(org_admin, rando, organization, org_credential)
We still allow adoption of orphaned* users by assigning them to organization member role, but only in the situation where the org admin already posesses indirect access to all of the user's roles *orphaned means user is not a member of any organization
We still allow adoption of orphaned* users by assigning them to organization member role, but only in the situation where the org admin already posesses indirect access to all of the user's roles *orphaned means user is not a member of any organization
def test_orphaned_user_allowed(org_admin, rando, organization, org_credential): """ We still allow adoption of orphaned* users by assigning them to organization member role, but only in the situation where the org admin already posesses indirect access to all of the user's roles *orphaned means user...
[ "def", "test_orphaned_user_allowed", "(", "org_admin", ",", "rando", ",", "organization", ",", "org_credential", ")", ":", "# give a descendent role to rando, to trigger the conditional", "# where all ancestor roles of rando should be in the set of", "# org_admin roles.", "org_credenti...
[ 176, 0 ]
[ 193, 69 ]
python
en
['en', 'error', 'th']
False
dummy
()
A context manager that does nothing special.
A context manager that does nothing special.
def dummy(): """A context manager that does nothing special.""" yield
[ "def", "dummy", "(", ")", ":", "yield" ]
[ 22, 0 ]
[ 24, 9 ]
python
en
['en', 'en', 'en']
True
read_mach_header
(lib_file, seek=None)
This funcition parse mach-O header and extract information about minimal system version :param lib_file: reference to opened library file with pointer
This funcition parse mach-O header and extract information about minimal system version
def read_mach_header(lib_file, seek=None): """ This funcition parse mach-O header and extract information about minimal system version :param lib_file: reference to opened library file with pointer """ if seek is not None: lib_file.seek(seek) base_class, magic_number = get_base_clas...
[ "def", "read_mach_header", "(", "lib_file", ",", "seek", "=", "None", ")", ":", "if", "seek", "is", "not", "None", ":", "lib_file", ".", "seek", "(", "seek", ")", "base_class", ",", "magic_number", "=", "get_base_class_and_magic_number", "(", "lib_file", ")"...
[ 304, 0 ]
[ 348, 20 ]
python
en
['en', 'error', 'th']
False
calculate_macosx_platform_tag
(archive_root, platform_tag)
Calculate proper macosx platform tag basing on files which are included to wheel Example platform tag `macosx-10.14-x86_64`
Calculate proper macosx platform tag basing on files which are included to wheel
def calculate_macosx_platform_tag(archive_root, platform_tag): """ Calculate proper macosx platform tag basing on files which are included to wheel Example platform tag `macosx-10.14-x86_64` """ prefix, base_version, suffix = platform_tag.split('-') base_version = tuple([int(x) for x in base_ve...
[ "def", "calculate_macosx_platform_tag", "(", "archive_root", ",", "platform_tag", ")", ":", "prefix", ",", "base_version", ",", "suffix", "=", "platform_tag", ".", "split", "(", "'-'", ")", "base_version", "=", "tuple", "(", "[", "int", "(", "x", ")", "for",...
[ 358, 0 ]
[ 427, 23 ]
python
en
['en', 'error', 'th']
False
process_custom_climate_data
(gdir, y0=None, y1=None, output_filesuffix=None)
Processes and writes the climate data from a user-defined climate file. The input file must have a specific format (see https://github.com/OGGM/oggm-sample-data ->test-files/histalp_merged_hef.nc for an example). This is the way OGGM used to do it for HISTALP before it got automatised. Parameters...
Processes and writes the climate data from a user-defined climate file.
def process_custom_climate_data(gdir, y0=None, y1=None, output_filesuffix=None): """Processes and writes the climate data from a user-defined climate file. The input file must have a specific format (see https://github.com/OGGM/oggm-sample-data ->test-files/histalp_merged_he...
[ "def", "process_custom_climate_data", "(", "gdir", ",", "y0", "=", "None", ",", "y1", "=", "None", ",", "output_filesuffix", "=", "None", ")", ":", "if", "not", "(", "(", "'climate_file'", "in", "cfg", ".", "PATHS", ")", "and", "os", ".", "path", ".", ...
[ 43, 0 ]
[ 143, 49 ]
python
en
['en', 'en', 'en']
True
process_climate_data
(gdir, y0=None, y1=None, output_filesuffix=None, **kwargs)
Adds the selected climate data to this glacier directory. Short wrapper deciding on which task to run based on `cfg.PARAMS['baseline_climate']`. If you want to make it explicit, simply call the relevant task (e.g. oggm.shop.cru.process_cru_data). Parameters ---------- gdir : :py:class:`og...
Adds the selected climate data to this glacier directory.
def process_climate_data(gdir, y0=None, y1=None, output_filesuffix=None, **kwargs): """Adds the selected climate data to this glacier directory. Short wrapper deciding on which task to run based on `cfg.PARAMS['baseline_climate']`. If you want to make it explicit, simply call ...
[ "def", "process_climate_data", "(", "gdir", ",", "y0", "=", "None", ",", "y1", "=", "None", ",", "output_filesuffix", "=", "None", ",", "*", "*", "kwargs", ")", ":", "# Which climate should we use?", "baseline", "=", "cfg", ".", "PARAMS", "[", "'baseline_cli...
[ 147, 0 ]
[ 222, 73 ]
python
en
['en', 'en', 'en']
True
historical_delta_method
(gdir, ref_filesuffix='', hist_filesuffix='', output_filesuffix='', ref_year_range=None, delete_input_files=True, scale_stddev=True, replace_with_ref_data=True)
Applies the anomaly method to historical climate data. This function can be used to prolongate historical time series, for example by bias-correcting CERA-20C to ERA5 or ERA5-Land. The timeseries must be already available in the glacier directory Parameters ---------- gdir : :py:class:`oggm.G...
Applies the anomaly method to historical climate data.
def historical_delta_method(gdir, ref_filesuffix='', hist_filesuffix='', output_filesuffix='', ref_year_range=None, delete_input_files=True, scale_stddev=True, replace_with_ref_data=True): """Applies the anomaly method to historical...
[ "def", "historical_delta_method", "(", "gdir", ",", "ref_filesuffix", "=", "''", ",", "hist_filesuffix", "=", "''", ",", "output_filesuffix", "=", "''", ",", "ref_year_range", "=", "None", ",", "delete_input_files", "=", "True", ",", "scale_stddev", "=", "True",...
[ 226, 0 ]
[ 385, 28 ]
python
en
['en', 'en', 'en']
True
historical_climate_qc
(gdir)
Check the "quality" of the baseline climate data and correct if needed. This forces the climate data to have at least N months (``cfg.PARAMS['climate_qc_months']``) of melt per year at the terminus of the glacier (i.e. it simply shifts temperatures up until this condition is reached), and at least N mo...
Check the "quality" of the baseline climate data and correct if needed.
def historical_climate_qc(gdir): """Check the "quality" of the baseline climate data and correct if needed. This forces the climate data to have at least N months (``cfg.PARAMS['climate_qc_months']``) of melt per year at the terminus of the glacier (i.e. it simply shifts temperatures up until this ...
[ "def", "historical_climate_qc", "(", "gdir", ")", ":", "# Parameters", "temp_s", "=", "(", "cfg", ".", "PARAMS", "[", "'temp_all_liq'", "]", "+", "cfg", ".", "PARAMS", "[", "'temp_all_solid'", "]", ")", "/", "2", "temp_m", "=", "cfg", ".", "PARAMS", "[",...
[ 389, 0 ]
[ 477, 79 ]
python
en
['en', 'en', 'en']
True
mb_climate_on_height
(gdir, heights, *, time_range=None, year_range=None)
Mass-balance climate of the glacier at a specific height Reads the glacier's monthly climate data file and computes the temperature "energies" (temp above 0) and solid precipitation at the required height. All MB parameters are considered here! (i.e. melt temp, precip scaling factor, etc.) Pa...
Mass-balance climate of the glacier at a specific height
def mb_climate_on_height(gdir, heights, *, time_range=None, year_range=None): """Mass-balance climate of the glacier at a specific height Reads the glacier's monthly climate data file and computes the temperature "energies" (temp above 0) and solid precipitation at the required height. All MB para...
[ "def", "mb_climate_on_height", "(", "gdir", ",", "heights", ",", "*", ",", "time_range", "=", "None", ",", "year_range", "=", "None", ")", ":", "if", "year_range", "is", "not", "None", ":", "sm", "=", "cfg", ".", "PARAMS", "[", "'hydro_month_'", "+", "...
[ 480, 0 ]
[ 582, 39 ]
python
en
['en', 'en', 'en']
True
mb_yearly_climate_on_height
(gdir, heights, *, year_range=None, flatten=False)
Yearly mass-balance climate of the glacier at a specific height See also: mb_climate_on_height Parameters ---------- gdir : GlacierDirectory the glacier directory heights: ndarray a 1D array of the heights (in meter) where you want the data year_range : [int, int], optional ...
Yearly mass-balance climate of the glacier at a specific height
def mb_yearly_climate_on_height(gdir, heights, *, year_range=None, flatten=False): """Yearly mass-balance climate of the glacier at a specific height See also: mb_climate_on_height Parameters ---------- gdir : GlacierDirectory the glacier directory heigh...
[ "def", "mb_yearly_climate_on_height", "(", "gdir", ",", "heights", ",", "*", ",", "year_range", "=", "None", ",", "flatten", "=", "False", ")", ":", "time", ",", "temp", ",", "prcp", "=", "mb_climate_on_height", "(", "gdir", ",", "heights", ",", "year_rang...
[ 585, 0 ]
[ 641, 34 ]
python
en
['en', 'en', 'en']
True
mb_yearly_climate_on_glacier
(gdir, *, year_range=None)
Yearly mass-balance climate at all glacier heights, multiplied with the flowlines widths. (all in pix coords.) See also: mb_climate_on_height Parameters ---------- gdir : GlacierDirectory the glacier directory year_range : [int, int], optional Provide a [y0, y1] year range to g...
Yearly mass-balance climate at all glacier heights, multiplied with the flowlines widths. (all in pix coords.)
def mb_yearly_climate_on_glacier(gdir, *, year_range=None): """Yearly mass-balance climate at all glacier heights, multiplied with the flowlines widths. (all in pix coords.) See also: mb_climate_on_height Parameters ---------- gdir : GlacierDirectory the glacier directory year_rang...
[ "def", "mb_yearly_climate_on_glacier", "(", "gdir", ",", "*", ",", "year_range", "=", "None", ")", ":", "flowlines", "=", "gdir", ".", "read_pickle", "(", "'inversion_flowlines'", ")", "heights", "=", "np", ".", "array", "(", "[", "]", ")", "widths", "=", ...
[ 644, 0 ]
[ 681, 28 ]
python
en
['en', 'en', 'en']
True
glacier_mu_candidates
(gdir)
Computes the mu candidates, glacier wide. For each 31 year-period centered on the year of interest, mu is is the temperature sensitivity necessary for the glacier with its current shape to be in equilibrium with its climate. This task is just for documentation and testing! It is not used in produc...
Computes the mu candidates, glacier wide.
def glacier_mu_candidates(gdir): """Computes the mu candidates, glacier wide. For each 31 year-period centered on the year of interest, mu is is the temperature sensitivity necessary for the glacier with its current shape to be in equilibrium with its climate. This task is just for documentation a...
[ "def", "glacier_mu_candidates", "(", "gdir", ")", ":", "warnings", ".", "warn", "(", "'The task `glacier_mu_candidates` is deprecated. It should '", "'only be used for testing.'", ",", "FutureWarning", ")", "mu_hp", "=", "int", "(", "cfg", ".", "PARAMS", "[", "'mu_star_...
[ 685, 0 ]
[ 733, 50 ]
python
en
['en', 'it', 'en']
True
t_star_from_refmb
(gdir, mbdf=None, glacierwide=None, min_mu_star=None, max_mu_star=None)
Computes the ref t* for the glacier, given a series of MB measurements. Parameters ---------- gdir : oggm.GlacierDirectory mbdf: a pd.Series containing the observed MB data indexed by year if None, read automatically from the reference data Returns ------- A dict: {t_star:[], bias:...
Computes the ref t* for the glacier, given a series of MB measurements.
def t_star_from_refmb(gdir, mbdf=None, glacierwide=None, min_mu_star=None, max_mu_star=None): """Computes the ref t* for the glacier, given a series of MB measurements. Parameters ---------- gdir : oggm.GlacierDirectory mbdf: a pd.Series containing the observed MB data indexed...
[ "def", "t_star_from_refmb", "(", "gdir", ",", "mbdf", "=", "None", ",", "glacierwide", "=", "None", ",", "min_mu_star", "=", "None", ",", "max_mu_star", "=", "None", ")", ":", "from", "oggm", ".", "core", ".", "massbalance", "import", "MultipleFlowlineMassBa...
[ 737, 0 ]
[ 864, 61 ]
python
en
['en', 'en', 'en']
True
calving_mb
(gdir)
Calving mass-loss in specific MB equivalent. This is necessary to compute mu star.
Calving mass-loss in specific MB equivalent.
def calving_mb(gdir): """Calving mass-loss in specific MB equivalent. This is necessary to compute mu star. """ if not gdir.is_tidewater: return 0. # Ok. Just take the calving rate from cfg and change its units # Original units: km3 a-1, to change to mm a-1 (units of specific MB) ...
[ "def", "calving_mb", "(", "gdir", ")", ":", "if", "not", "gdir", ".", "is_tidewater", ":", "return", "0.", "# Ok. Just take the calving rate from cfg and change its units", "# Original units: km3 a-1, to change to mm a-1 (units of specific MB)", "rho", "=", "cfg", ".", "PARAM...
[ 867, 0 ]
[ 879, 69 ]
python
en
['en', 'en', 'en']
True
_fallback_local_t_star
(gdir)
A Fallback function if climate.local_t_star raises an Error. This function will still write a `local_mustar.json`, filled with NANs, if climate.local_t_star fails and cfg.PARAMS['continue_on_error'] = True. Parameters ---------- gdir : :py:class:`oggm.GlacierDirectory` the glacier director...
A Fallback function if climate.local_t_star raises an Error.
def _fallback_local_t_star(gdir): """A Fallback function if climate.local_t_star raises an Error. This function will still write a `local_mustar.json`, filled with NANs, if climate.local_t_star fails and cfg.PARAMS['continue_on_error'] = True. Parameters ---------- gdir : :py:class:`oggm.Glaci...
[ "def", "_fallback_local_t_star", "(", "gdir", ")", ":", "# Scalars in a small dict for later", "df", "=", "dict", "(", ")", "df", "[", "'rgi_id'", "]", "=", "gdir", ".", "rgi_id", "df", "[", "'t_star'", "]", "=", "np", ".", "nan", "df", "[", "'bias'", "]...
[ 882, 0 ]
[ 900, 39 ]
python
en
['en', 'en', 'en']
True
local_t_star
(gdir, *, ref_df=None, tstar=None, bias=None, clip_mu_star=None, min_mu_star=None, max_mu_star=None)
Compute the local t* and associated glacier-wide mu*. If ``tstar`` and ``bias`` are not provided, they will be interpolated from the reference t* list (``ref_df``). If none of these are provided (the default), this list be obtained from the current working directory (``ref_tstars.csv`` and associated ...
Compute the local t* and associated glacier-wide mu*.
def local_t_star(gdir, *, ref_df=None, tstar=None, bias=None, clip_mu_star=None, min_mu_star=None, max_mu_star=None): """Compute the local t* and associated glacier-wide mu*. If ``tstar`` and ``bias`` are not provided, they will be interpolated from the reference t* list (``ref_df``). ...
[ "def", "local_t_star", "(", "gdir", ",", "*", ",", "ref_df", "=", "None", ",", "tstar", "=", "None", ",", "bias", "=", "None", ",", "clip_mu_star", "=", "None", ",", "min_mu_star", "=", "None", ",", "max_mu_star", "=", "None", ")", ":", "if", "tstar"...
[ 905, 0 ]
[ 1035, 39 ]
python
en
['en', 'en', 'en']
True
_fallback_mu_star_calibration
(gdir)
A Fallback function if climate.mu_star_calibration raises an Error. This function will still read, expand and write a `local_mustar.json`, filled with NANs, if climate.mu_star_calibration fails and if cfg.PARAMS['continue_on_error'] = True. Parameters ---------- gdir : :py:class:`oggm.GlacierD...
A Fallback function if climate.mu_star_calibration raises an Error.
def _fallback_mu_star_calibration(gdir): """A Fallback function if climate.mu_star_calibration raises an Error. This function will still read, expand and write a `local_mustar.json`, filled with NANs, if climate.mu_star_calibration fails and if cfg.PARAMS['continue_on_error'] = True. Parameters ...
[ "def", "_fallback_mu_star_calibration", "(", "gdir", ")", ":", "# read json", "try", ":", "df", "=", "gdir", ".", "read_json", "(", "'local_mustar'", ")", "except", "FileNotFoundError", ":", "df", "=", "dict", "(", ")", "df", "[", "'rgi_id'", "]", "=", "gd...
[ 1169, 0 ]
[ 1195, 39 ]
python
en
['en', 'gd', 'en']
True
mu_star_calibration
(gdir, min_mu_star=None, max_mu_star=None)
Compute the flowlines' mu* and the associated apparent mass-balance. If low lying tributaries have a non-physically consistent Mass-balance this function will either filter them out or calibrate each flowline with a specific mu*. The latter is default and recommended. Parameters ---------- gdi...
Compute the flowlines' mu* and the associated apparent mass-balance.
def mu_star_calibration(gdir, min_mu_star=None, max_mu_star=None): """Compute the flowlines' mu* and the associated apparent mass-balance. If low lying tributaries have a non-physically consistent Mass-balance this function will either filter them out or calibrate each flowline with a specific mu*. The...
[ "def", "mu_star_calibration", "(", "gdir", ",", "min_mu_star", "=", "None", ",", "max_mu_star", "=", "None", ")", ":", "# Interpolated data", "df", "=", "gdir", ".", "read_json", "(", "'local_mustar'", ")", "t_star", "=", "df", "[", "'t_star'", "]", "bias", ...
[ 1200, 0 ]
[ 1296, 39 ]
python
en
['en', 'lb', 'en']
True
mu_star_calibration_from_geodetic_mb
(gdir, ref_mb=None, ref_period='', step_height_for_corr=25, max_height_change_for_corr=3000, ignore_hydro_months=Fa...
Compute the flowlines' mu* from the reference geodetic MB data. This is similar to mu_star_calibration but using the reference geodetic MB data instead, and this does NOT compute the apparent mass-balance at the same time - users need to run apparent_mb_from_any_mb separately. Currently only works for ...
Compute the flowlines' mu* from the reference geodetic MB data.
def mu_star_calibration_from_geodetic_mb(gdir, ref_mb=None, ref_period='', step_height_for_corr=25, max_height_change_for_corr=3000, ...
[ "def", "mu_star_calibration_from_geodetic_mb", "(", "gdir", ",", "ref_mb", "=", "None", ",", "ref_period", "=", "''", ",", "step_height_for_corr", "=", "25", ",", "max_height_change_for_corr", "=", "3000", ",", "ignore_hydro_months", "=", "False", ",", "min_mu_star"...
[ 1301, 0 ]
[ 1508, 39 ]
python
en
['en', 'en', 'en']
True
apparent_mb_from_linear_mb
(gdir, mb_gradient=3., ela_h=None)
Compute apparent mb from a linear mass-balance assumption (for testing). This is for testing currently, but could be used as alternative method for the inversion quite easily. Parameters ---------- gdir : :py:class:`oggm.GlacierDirectory` the glacier directory to process
Compute apparent mb from a linear mass-balance assumption (for testing).
def apparent_mb_from_linear_mb(gdir, mb_gradient=3., ela_h=None): """Compute apparent mb from a linear mass-balance assumption (for testing). This is for testing currently, but could be used as alternative method for the inversion quite easily. Parameters ---------- gdir : :py:class:`oggm.Glac...
[ "def", "apparent_mb_from_linear_mb", "(", "gdir", ",", "mb_gradient", "=", "3.", ",", "ela_h", "=", "None", ")", ":", "# Do we have a calving glacier?", "cmb", "=", "calving_mb", "(", "gdir", ")", "# Get the height and widths along the fls", "h", ",", "w", "=", "g...
[ 1512, 0 ]
[ 1566, 41 ]
python
en
['en', 'en', 'en']
True
apparent_mb_from_any_mb
(gdir, mb_model=None, mb_years=None)
Compute apparent mb from an arbitrary mass-balance profile. This searches for a mass-balance residual to add to the mass-balance profile so that the average specific MB is zero. Parameters ---------- gdir : :py:class:`oggm.GlacierDirectory` the glacier directory to process mb_model : :...
Compute apparent mb from an arbitrary mass-balance profile.
def apparent_mb_from_any_mb(gdir, mb_model=None, mb_years=None): """Compute apparent mb from an arbitrary mass-balance profile. This searches for a mass-balance residual to add to the mass-balance profile so that the average specific MB is zero. Parameters ---------- gdir : :py:class:`oggm.Gla...
[ "def", "apparent_mb_from_any_mb", "(", "gdir", ",", "mb_model", "=", "None", ",", "mb_years", "=", "None", ")", ":", "# Do we have a calving glacier?", "cmb", "=", "calving_mb", "(", "gdir", ")", "# For each flowline compute the apparent MB", "fls", "=", "gdir", "."...
[ 1570, 0 ]
[ 1646, 49 ]
python
en
['en', 'en', 'en']
True
compute_ref_t_stars
(gdirs)
Detects the best t* for the reference glaciers and writes them to disk Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects will be filtered for reference glaciers
Detects the best t* for the reference glaciers and writes them to disk
def compute_ref_t_stars(gdirs): """ Detects the best t* for the reference glaciers and writes them to disk Parameters ---------- gdirs : list of :py:class:`oggm.GlacierDirectory` objects will be filtered for reference glaciers """ if not cfg.PARAMS['run_mb_calibration']: raise ...
[ "def", "compute_ref_t_stars", "(", "gdirs", ")", ":", "if", "not", "cfg", ".", "PARAMS", "[", "'run_mb_calibration'", "]", ":", "raise", "InvalidParamsError", "(", "'Are you sure you want to calibrate the '", "'reference t*? There is a pre-calibrated '", "'version available. ...
[ 1650, 0 ]
[ 1706, 60 ]
python
en
['en', 'en', 'en']
True
do_test_spend
( puzzle_reveal: Program, solution: Program, payments: Iterable[Tuple[bytes32, int]], key_lookup: KeyTool, farm_time: CoinTimestamp = T1, spend_time: CoinTimestamp = T2, )
This method will farm a coin paid to the hash of `puzzle_reveal`, then try to spend it with `solution`, and verify that the created coins correspond to `payments`. The `key_lookup` is used to create a signed version of the `SpendBundle`, although at this time, signatures are not verified.
This method will farm a coin paid to the hash of `puzzle_reveal`, then try to spend it with `solution`, and verify that the created coins correspond to `payments`.
def do_test_spend( puzzle_reveal: Program, solution: Program, payments: Iterable[Tuple[bytes32, int]], key_lookup: KeyTool, farm_time: CoinTimestamp = T1, spend_time: CoinTimestamp = T2, ) -> SpendBundle: """ This method will farm a coin paid to the hash of `puzzle_reveal`, then try to s...
[ "def", "do_test_spend", "(", "puzzle_reveal", ":", "Program", ",", "solution", ":", "Program", ",", "payments", ":", "Iterable", "[", "Tuple", "[", "bytes32", ",", "int", "]", "]", ",", "key_lookup", ":", "KeyTool", ",", "farm_time", ":", "CoinTimestamp", ...
[ 47, 0 ]
[ 89, 87 ]
python
en
['en', 'error', 'th']
False
setup_test_logging
()
set up test logging for convenience in IDE
set up test logging for convenience in IDE
def setup_test_logging(): """ set up test logging for convenience in IDE """ if not ROOT_LOGGER.handlers: CLI.log = '' # means no log file will be created CLI.verbose = True CLI.setup_logging(CLI) else: ROOT_LOGGER.debug("Already set up logging")
[ "def", "setup_test_logging", "(", ")", ":", "if", "not", "ROOT_LOGGER", ".", "handlers", ":", "CLI", ".", "log", "=", "''", "# means no log file will be created", "CLI", ".", "verbose", "=", "True", "CLI", ".", "setup_logging", "(", "CLI", ")", "else", ":", ...
[ 27, 0 ]
[ 34, 51 ]
python
en
['en', 'en', 'en']
True
local_paths_config
()
to fix relative paths
to fix relative paths
def local_paths_config(): """ to fix relative paths """ dirname = os.path.dirname(__file__) fname = temp_file() settings = { "modules": { "jmeter": { "path": RESOURCES_DIR + "jmeter/jmeter-loader" + EXE_SUFFIX, }, "grinder": { "...
[ "def", "local_paths_config", "(", ")", ":", "dirname", "=", "os", ".", "path", ".", "dirname", "(", "__file__", ")", "fname", "=", "temp_file", "(", ")", "settings", "=", "{", "\"modules\"", ":", "{", "\"jmeter\"", ":", "{", "\"path\"", ":", "RESOURCES_D...
[ 46, 0 ]
[ 70, 16 ]
python
en
['en', 'en', 'en']
True
load
(filename)
Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read.
Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object.
def load(filename): """ Load a font file. This function loads a font object from the given bitmap font file, and returns the corresponding font object. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read. """ f = ImageFont() ...
[ "def", "load", "(", "filename", ")", ":", "f", "=", "ImageFont", "(", ")", "f", ".", "_load_pilfont", "(", "filename", ")", "return", "f" ]
[ 764, 0 ]
[ 775, 12 ]
python
en
['en', 'error', 'th']
False
truetype
(font=None, size=10, index=0, encoding="", layout_engine=None)
Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size. Pillow uses FreeType to open font files. If you are opening many fonts ...
Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given size.
def truetype(font=None, size=10, index=0, encoding="", layout_engine=None): """ Load a TrueType or OpenType font from a file or file-like object, and create a font object. This function loads a font object from the given file or file-like object, and creates a font object for a font of the given siz...
[ "def", "truetype", "(", "font", "=", "None", ",", "size", "=", "10", ",", "index", "=", "0", ",", "encoding", "=", "\"\"", ",", "layout_engine", "=", "None", ")", ":", "def", "freetype", "(", "font", ")", ":", "return", "FreeTypeFont", "(", "font", ...
[ 778, 0 ]
[ 878, 13 ]
python
en
['en', 'error', 'th']
False
load_path
(filename)
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read.
Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path.
def load_path(filename): """ Load font file. Same as :py:func:`~PIL.ImageFont.load`, but searches for a bitmap font along the Python path. :param filename: Name of font file. :return: A font object. :exception OSError: If the file could not be read. """ for directory in sys.path: ...
[ "def", "load_path", "(", "filename", ")", ":", "for", "directory", "in", "sys", ".", "path", ":", "if", "isDirectory", "(", "directory", ")", ":", "if", "not", "isinstance", "(", "filename", ",", "str", ")", ":", "filename", "=", "filename", ".", "deco...
[ 881, 0 ]
[ 898, 42 ]
python
en
['en', 'error', 'th']
False
load_default
()
Load a "better than nothing" default font. .. versionadded:: 1.1.4 :return: A font object.
Load a "better than nothing" default font.
def load_default(): """Load a "better than nothing" default font. .. versionadded:: 1.1.4 :return: A font object. """ f = ImageFont() f._load_pilfont_data( # courB08 BytesIO( base64.b64decode( b""" UElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAA...
[ "def", "load_default", "(", ")", ":", "f", "=", "ImageFont", "(", ")", "f", ".", "_load_pilfont_data", "(", "# courB08", "BytesIO", "(", "base64", ".", "b64decode", "(", "b\"\"\"\nUElMZm9udAo7Ozs7OzsxMDsKREFUQQoAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA\nAAAAAAAAAAAAAAAA...
[ 901, 0 ]
[ 1040, 12 ]
python
en
['en', 'en', 'en']
True
ImageFont.getsize
(self, text, *args, **kwargs)
Returns width and height (in pixels) of given text. :param text: Text to measure. :return: (width, height)
Returns width and height (in pixels) of given text.
def getsize(self, text, *args, **kwargs): """ Returns width and height (in pixels) of given text. :param text: Text to measure. :return: (width, height) """ return self.font.getsize(text)
[ "def", "getsize", "(", "self", ",", "text", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "font", ".", "getsize", "(", "text", ")" ]
[ 119, 4 ]
[ 127, 38 ]
python
en
['en', 'error', 'th']
False
ImageFont.getmask
(self, text, mode="", *args, **kwargs)
Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. Otherwise, it should have mode ``1``. :param text: Text to render. :param mode: Used by some graphics drivers to indicate what mode the ...
Create a bitmap for the text.
def getmask(self, text, mode="", *args, **kwargs): """ Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. Otherwise, it should have mode ``1``. :param text: Text to render. :param mode: Used by ...
[ "def", "getmask", "(", "self", ",", "text", ",", "mode", "=", "\"\"", ",", "*", "args", ",", "*", "*", "kwargs", ")", ":", "return", "self", ".", "font", ".", "getmask", "(", "text", ",", "mode", ")" ]
[ 129, 4 ]
[ 147, 44 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getname
(self)
:return: A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold)
:return: A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold)
def getname(self): """ :return: A tuple of the font family (e.g. Helvetica) and the font style (e.g. Bold) """ return self.font.family, self.font.style
[ "def", "getname", "(", "self", ")", ":", "return", "self", ".", "font", ".", "family", ",", "self", ".", "font", ".", "style" ]
[ 202, 4 ]
[ 207, 48 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getmetrics
(self)
:return: A tuple of the font ascent (the distance from the baseline to the highest outline point) and descent (the distance from the baseline to the lowest outline point, a negative value)
:return: A tuple of the font ascent (the distance from the baseline to the highest outline point) and descent (the distance from the baseline to the lowest outline point, a negative value)
def getmetrics(self): """ :return: A tuple of the font ascent (the distance from the baseline to the highest outline point) and descent (the distance from the baseline to the lowest outline point, a negative value) """ return self.font.ascent, self.font.descent
[ "def", "getmetrics", "(", "self", ")", ":", "return", "self", ".", "font", ".", "ascent", ",", "self", ".", "font", ".", "descent" ]
[ 209, 4 ]
[ 215, 50 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getlength
(self, text, mode="", direction=None, features=None, language=None)
Returns length (in pixels with 1/64 precision) of given text when rendered in font with provided direction, features, and language. This is the amount by which following text should be offset. Text bounding box may extend past the length in some fonts, e.g. when using italics o...
Returns length (in pixels with 1/64 precision) of given text when rendered in font with provided direction, features, and language.
def getlength(self, text, mode="", direction=None, features=None, language=None): """ Returns length (in pixels with 1/64 precision) of given text when rendered in font with provided direction, features, and language. This is the amount by which following text should be offset. ...
[ "def", "getlength", "(", "self", ",", "text", ",", "mode", "=", "\"\"", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ")", ":", "return", "self", ".", "font", ".", "getlength", "(", "text", ",", "mode", ...
[ 217, 4 ]
[ 292, 82 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getbbox
( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, )
Returns bounding box (in pixels) of given text relative to given anchor when rendered in font with provided direction, features, and language. Use :py:meth:`getlength()` to get the offset of following text with 1/64 pixel precision. The bounding box includes extra margins for s...
Returns bounding box (in pixels) of given text relative to given anchor when rendered in font with provided direction, features, and language.
def getbbox( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, ): """ Returns bounding box (in pixels) of given text relative to given anchor when rendered in font with provided dire...
[ "def", "getbbox", "(", "self", ",", "text", ",", "mode", "=", "\"\"", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",", "anchor", "=", "None", ",", ")", ":", "size", ",", ...
[ 294, 4 ]
[ 356, 52 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getsize
( self, text, direction=None, features=None, language=None, stroke_width=0 )
Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language. Use :py:meth:`getlength()` to measure the offset of following text with 1/64 pixel precision. Use :py:meth:`getbbox()` to get the exact bounding box based on ...
Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language.
def getsize( self, text, direction=None, features=None, language=None, stroke_width=0 ): """ Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language. Use :py:meth:`getlength()` to measure the offset of following ...
[ "def", "getsize", "(", "self", ",", "text", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ")", ":", "# vertical offset is added for historical reasons", "# see https://github.com/python-pill...
[ 358, 4 ]
[ 417, 9 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getsize_multiline
( self, text, direction=None, spacing=4, features=None, language=None, stroke_width=0, )
Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language, while respecting newline characters. :param text: Text to measure. :param direction: Direction of the text. It can be 'rtl' (right to ...
Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language, while respecting newline characters.
def getsize_multiline( self, text, direction=None, spacing=4, features=None, language=None, stroke_width=0, ): """ Returns width and height (in pixels) of given text if rendered in font with provided direction, features, and language, w...
[ "def", "getsize_multiline", "(", "self", ",", "text", ",", "direction", "=", "None", ",", "spacing", "=", "4", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",", ")", ":", "max_width", "=", "0", "lines", "...
[ 419, 4 ]
[ 477, 61 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getoffset
(self, text)
Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note that this gap is included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`. :param text: Text to measure. :return: A tuple of the x and y offset ...
Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note that this gap is included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`.
def getoffset(self, text): """ Returns the offset of given text. This is the gap between the starting coordinate and the first marking. Note that this gap is included in the result of :py:func:`~PIL.ImageFont.FreeTypeFont.getsize`. :param text: Text to measure. :return:...
[ "def", "getoffset", "(", "self", ",", "text", ")", ":", "return", "self", ".", "font", ".", "getsize", "(", "text", ")", "[", "1", "]" ]
[ 479, 4 ]
[ 489, 41 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getmask
( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, )
Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. If the font has embedded color data, the bitmap should have mode ``RGBA``. Otherwise, it should have mode ``1``. :param text: Text to render. ...
Create a bitmap for the text.
def getmask( self, text, mode="", direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, ): """ Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` a...
[ "def", "getmask", "(", "self", ",", "text", ",", "mode", "=", "\"\"", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",", "anchor", "=", "None", ",", "ink", "=", "0", ",", ...
[ 491, 4 ]
[ 572, 12 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.getmask2
( self, text, mode="", fill=Image.core.fill, direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, *args, **kwargs, )
Create a bitmap for the text. If the font uses antialiasing, the bitmap should have mode ``L`` and use a maximum value of 255. If the font has embedded color data, the bitmap should have mode ``RGBA``. Otherwise, it should have mode ``1``. :param text: Text to render. ...
Create a bitmap for the text.
def getmask2( self, text, mode="", fill=Image.core.fill, direction=None, features=None, language=None, stroke_width=0, anchor=None, ink=0, *args, **kwargs, ): """ Create a bitmap for the text. If...
[ "def", "getmask2", "(", "self", ",", "text", ",", "mode", "=", "\"\"", ",", "fill", "=", "Image", ".", "core", ".", "fill", ",", "direction", "=", "None", ",", "features", "=", "None", ",", "language", "=", "None", ",", "stroke_width", "=", "0", ",...
[ 574, 4 ]
[ 659, 25 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.font_variant
( self, font=None, size=None, index=None, encoding=None, layout_engine=None )
Create a copy of this FreeTypeFont object, using any specified arguments to override the settings. Parameters are identical to the parameters used to initialize this object. :return: A FreeTypeFont object.
Create a copy of this FreeTypeFont object, using any specified arguments to override the settings.
def font_variant( self, font=None, size=None, index=None, encoding=None, layout_engine=None ): """ Create a copy of this FreeTypeFont object, using any specified arguments to override the settings. Parameters are identical to the parameters used to initialize this ob...
[ "def", "font_variant", "(", "self", ",", "font", "=", "None", ",", "size", "=", "None", ",", "index", "=", "None", ",", "encoding", "=", "None", ",", "layout_engine", "=", "None", ")", ":", "return", "FreeTypeFont", "(", "font", "=", "self", ".", "pa...
[ 661, 4 ]
[ 679, 9 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.get_variation_names
(self)
:returns: A list of the named styles in a variation font. :exception OSError: If the font is not a variation font.
:returns: A list of the named styles in a variation font. :exception OSError: If the font is not a variation font.
def get_variation_names(self): """ :returns: A list of the named styles in a variation font. :exception OSError: If the font is not a variation font. """ try: names = self.font.getvarnames() except AttributeError as e: raise NotImplementedError("Fr...
[ "def", "get_variation_names", "(", "self", ")", ":", "try", ":", "names", "=", "self", ".", "font", ".", "getvarnames", "(", ")", "except", "AttributeError", "as", "e", ":", "raise", "NotImplementedError", "(", "\"FreeType 2.9.1 or greater is required\"", ")", "...
[ 681, 4 ]
[ 690, 61 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.set_variation_by_name
(self, name)
:param name: The name of the style. :exception OSError: If the font is not a variation font.
:param name: The name of the style. :exception OSError: If the font is not a variation font.
def set_variation_by_name(self, name): """ :param name: The name of the style. :exception OSError: If the font is not a variation font. """ names = self.get_variation_names() if not isinstance(name, bytes): name = name.encode() index = names.index(name...
[ "def", "set_variation_by_name", "(", "self", ",", "name", ")", ":", "names", "=", "self", ".", "get_variation_names", "(", ")", "if", "not", "isinstance", "(", "name", ",", "bytes", ")", ":", "name", "=", "name", ".", "encode", "(", ")", "index", "=", ...
[ 692, 4 ]
[ 709, 35 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.get_variation_axes
(self)
:returns: A list of the axes in a variation font. :exception OSError: If the font is not a variation font.
:returns: A list of the axes in a variation font. :exception OSError: If the font is not a variation font.
def get_variation_axes(self): """ :returns: A list of the axes in a variation font. :exception OSError: If the font is not a variation font. """ try: axes = self.font.getvaraxes() except AttributeError as e: raise NotImplementedError("FreeType 2.9....
[ "def", "get_variation_axes", "(", "self", ")", ":", "try", ":", "axes", "=", "self", ".", "font", ".", "getvaraxes", "(", ")", "except", "AttributeError", "as", "e", ":", "raise", "NotImplementedError", "(", "\"FreeType 2.9.1 or greater is required\"", ")", "fro...
[ 711, 4 ]
[ 722, 19 ]
python
en
['en', 'error', 'th']
False
FreeTypeFont.set_variation_by_axes
(self, axes)
:param axes: A list of values for each axis. :exception OSError: If the font is not a variation font.
:param axes: A list of values for each axis. :exception OSError: If the font is not a variation font.
def set_variation_by_axes(self, axes): """ :param axes: A list of values for each axis. :exception OSError: If the font is not a variation font. """ try: self.font.setvaraxes(axes) except AttributeError as e: raise NotImplementedError("FreeType 2.9...
[ "def", "set_variation_by_axes", "(", "self", ",", "axes", ")", ":", "try", ":", "self", ".", "font", ".", "setvaraxes", "(", "axes", ")", "except", "AttributeError", "as", "e", ":", "raise", "NotImplementedError", "(", "\"FreeType 2.9.1 or greater is required\"", ...
[ 724, 4 ]
[ 732, 85 ]
python
en
['en', 'error', 'th']
False
TransposedFont.__init__
(self, font, orientation=None)
Wrapper that creates a transposed font from any existing font object. :param font: A font object. :param orientation: An optional orientation. If given, this should be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTOM, Image.ROTATE_90, Image.ROTATE_180, or Im...
Wrapper that creates a transposed font from any existing font object.
def __init__(self, font, orientation=None): """ Wrapper that creates a transposed font from any existing font object. :param font: A font object. :param orientation: An optional orientation. If given, this should be one of Image.FLIP_LEFT_RIGHT, Image.FLIP_TOP_BOTTO...
[ "def", "__init__", "(", "self", ",", "font", ",", "orientation", "=", "None", ")", ":", "self", ".", "font", "=", "font", "self", ".", "orientation", "=", "orientation" ]
[ 738, 4 ]
[ 749, 38 ]
python
en
['en', 'error', 'th']
False
decoder
(conv_func)
The Python sqlite3 interface returns always byte strings. This function converts the received value to a regular string before passing it to the receiver function.
The Python sqlite3 interface returns always byte strings. This function converts the received value to a regular string before passing it to the receiver function.
def decoder(conv_func): """ The Python sqlite3 interface returns always byte strings. This function converts the received value to a regular string before passing it to the receiver function. """ return lambda s: conv_func(s.decode('utf-8'))
[ "def", "decoder", "(", "conv_func", ")", ":", "return", "lambda", "s", ":", "conv_func", "(", "s", ".", "decode", "(", "'utf-8'", ")", ")" ]
[ 59, 0 ]
[ 64, 49 ]
python
en
['en', 'en', 'en']
True
_sqlite_format_dtdelta
(conn, lhs, rhs)
LHS and RHS can be either: - An integer number of microseconds - A string representing a timedelta object - A string representing a datetime
LHS and RHS can be either: - An integer number of microseconds - A string representing a timedelta object - A string representing a datetime
def _sqlite_format_dtdelta(conn, lhs, rhs): """ LHS and RHS can be either: - An integer number of microseconds - A string representing a timedelta object - A string representing a datetime """ try: if isinstance(lhs, six.integer_types): lhs = str(decimal.Decim...
[ "def", "_sqlite_format_dtdelta", "(", "conn", ",", "lhs", ",", "rhs", ")", ":", "try", ":", "if", "isinstance", "(", "lhs", ",", "six", ".", "integer_types", ")", ":", "lhs", "=", "str", "(", "decimal", ".", "Decimal", "(", "lhs", ")", "/", "decimal"...
[ 444, 0 ]
[ 470, 19 ]
python
en
['en', 'error', 'th']
False
DatabaseWrapper.check_constraints
(self, table_names=None)
Checks each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered while constraint ...
Checks each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows with invalid references were entered while constraint ...
def check_constraints(self, table_names=None): """ Checks each table name in `table_names` for rows with invalid foreign key references. This method is intended to be used in conjunction with `disable_constraint_checking()` and `enable_constraint_checking()`, to determine if rows...
[ "def", "check_constraints", "(", "self", ",", "table_names", "=", "None", ")", ":", "cursor", "=", "self", ".", "cursor", "(", ")", "if", "table_names", "is", "None", ":", "table_names", "=", "self", ".", "introspection", ".", "table_names", "(", "cursor",...
[ 251, 4 ]
[ 296, 21 ]
python
en
['en', 'error', 'th']
False
DatabaseWrapper._start_transaction_under_autocommit
(self)
Start a transaction explicitly in autocommit mode. Staying in autocommit mode works around a bug of sqlite3 that breaks savepoints when autocommit is disabled.
Start a transaction explicitly in autocommit mode.
def _start_transaction_under_autocommit(self): """ Start a transaction explicitly in autocommit mode. Staying in autocommit mode works around a bug of sqlite3 that breaks savepoints when autocommit is disabled. """ self.cursor().execute("BEGIN")
[ "def", "_start_transaction_under_autocommit", "(", "self", ")", ":", "self", ".", "cursor", "(", ")", ".", "execute", "(", "\"BEGIN\"", ")" ]
[ 301, 4 ]
[ 308, 38 ]
python
en
['en', 'error', 'th']
False
Connection.__init__
(self, url: str, loop: asyncio.AbstractEventLoop, delay: int = 0)
Make connection. :arg str url: WebSocket url to connect devtool. :arg int delay: delay to wait before processing received messages.
Make connection.
def __init__(self, url: str, loop: asyncio.AbstractEventLoop, delay: int = 0) -> None: """Make connection. :arg str url: WebSocket url to connect devtool. :arg int delay: delay to wait before processing received messages. """ super().__init__() self._url...
[ "def", "__init__", "(", "self", ",", "url", ":", "str", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", ",", "delay", ":", "int", "=", "0", ")", "->", "None", ":", "super", "(", ")", ".", "__init__", "(", ")", "self", ".", "_url", "=", "ur...
[ 26, 4 ]
[ 45, 64 ]
python
en
['en', 'en', 'en']
False
Connection.url
(self)
Get connected WebSocket url.
Get connected WebSocket url.
def url(self) -> str: """Get connected WebSocket url.""" return self._url
[ "def", "url", "(", "self", ")", "->", "str", ":", "return", "self", ".", "_url" ]
[ 48, 4 ]
[ 50, 24 ]
python
en
['en', 'nl', 'en']
True
Connection.send
(self, method: str, params: dict = None)
Send message via the connection.
Send message via the connection.
def send(self, method: str, params: dict = None) -> Awaitable: """Send message via the connection.""" # Detect connection availability from the second transmission if self._lastId and not self._connected: raise ConnectionError('Connection is closed') if params is None: ...
[ "def", "send", "(", "self", ",", "method", ":", "str", ",", "params", ":", "dict", "=", "None", ")", "->", "Awaitable", ":", "# Detect connection availability from the second transmission", "if", "self", ".", "_lastId", "and", "not", "self", ".", "_connected", ...
[ 80, 4 ]
[ 100, 23 ]
python
en
['en', 'fr', 'en']
True
Connection.setClosedCallback
(self, callback: Callable[[], None])
Set closed callback.
Set closed callback.
def setClosedCallback(self, callback: Callable[[], None]) -> None: """Set closed callback.""" self._closeCallback = callback
[ "def", "setClosedCallback", "(", "self", ",", "callback", ":", "Callable", "[", "[", "]", ",", "None", "]", ")", "->", "None", ":", "self", ".", "_closeCallback", "=", "callback" ]
[ 131, 4 ]
[ 133, 38 ]
python
en
['en', 'et', 'en']
True
Connection.dispose
(self)
Close all connection.
Close all connection.
async def dispose(self) -> None: """Close all connection.""" self._connected = False await self._on_close()
[ "async", "def", "dispose", "(", "self", ")", "->", "None", ":", "self", ".", "_connected", "=", "False", "await", "self", ".", "_on_close", "(", ")" ]
[ 166, 4 ]
[ 169, 30 ]
python
en
['en', 'en', 'en']
True
Connection.createSession
(self, targetInfo: Dict)
Create new session.
Create new session.
async def createSession(self, targetInfo: Dict) -> 'CDPSession': """Create new session.""" resp = await self.send( 'Target.attachToTarget', {'targetId': targetInfo['targetId']} ) sessionId = resp.get('sessionId') session = CDPSession(self, targetInfo['type...
[ "async", "def", "createSession", "(", "self", ",", "targetInfo", ":", "Dict", ")", "->", "'CDPSession'", ":", "resp", "=", "await", "self", ".", "send", "(", "'Target.attachToTarget'", ",", "{", "'targetId'", ":", "targetInfo", "[", "'targetId'", "]", "}", ...
[ 171, 4 ]
[ 180, 22 ]
python
en
['en', 'en', 'en']
True
CDPSession.__init__
(self, connection: Union[Connection, 'CDPSession'], targetType: str, sessionId: str, loop: asyncio.AbstractEventLoop)
Make new session.
Make new session.
def __init__(self, connection: Union[Connection, 'CDPSession'], targetType: str, sessionId: str, loop: asyncio.AbstractEventLoop) -> None: """Make new session.""" super().__init__() self._lastId = 0 self._callbacks: Dict[int, asyncio.Future] = {} ...
[ "def", "__init__", "(", "self", ",", "connection", ":", "Union", "[", "Connection", ",", "'CDPSession'", "]", ",", "targetType", ":", "str", ",", "sessionId", ":", "str", ",", "loop", ":", "asyncio", ".", "AbstractEventLoop", ")", "->", "None", ":", "sup...
[ 196, 4 ]
[ 207, 25 ]
python
en
['en', 'no', 'en']
True
CDPSession.send
(self, method: str, params: dict = None)
Send message to the connected session. :arg str method: Protocol method name. :arg dict params: Optional method parameters.
Send message to the connected session.
def send(self, method: str, params: dict = None) -> Awaitable: """Send message to the connected session. :arg str method: Protocol method name. :arg dict params: Optional method parameters. """ if not self._connection: raise NetworkError( f'Protocol E...
[ "def", "send", "(", "self", ",", "method", ":", "str", ",", "params", ":", "dict", "=", "None", ")", "->", "Awaitable", ":", "if", "not", "self", ".", "_connection", ":", "raise", "NetworkError", "(", "f'Protocol Error ({method}): Session closed. Most likely the...
[ 209, 4 ]
[ 243, 23 ]
python
en
['en', 'en', 'en']
True
CDPSession.detach
(self)
Detach session from target. Once detached, session won't emit any events and can't be used to send messages.
Detach session from target.
async def detach(self) -> None: """Detach session from target. Once detached, session won't emit any events and can't be used to send messages. """ if not self._connection: raise NetworkError('Connection already closed.') await self._connection.send('Target.d...
[ "async", "def", "detach", "(", "self", ")", "->", "None", ":", "if", "not", "self", ".", "_connection", ":", "raise", "NetworkError", "(", "'Connection already closed.'", ")", "await", "self", ".", "_connection", ".", "send", "(", "'Target.detachFromTarget'", ...
[ 277, 4 ]
[ 286, 67 ]
python
en
['en', 'en', 'en']
True
WalletBlockchain.create
( block_store: WalletBlockStore, coin_store: WalletCoinStore, tx_store: WalletTransactionStore, consensus_constants: ConsensusConstants, coins_of_interest_received: Callable, # f(removals: List[Coin], additions: List[Coin], height: uint32) reorg_rollback: Callable, ...
Initializes a blockchain with the BlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config.
Initializes a blockchain with the BlockRecords from disk, assuming they have all been validated. Uses the genesis block given in override_constants, or as a fallback, in the consensus constants config.
async def create( block_store: WalletBlockStore, coin_store: WalletCoinStore, tx_store: WalletTransactionStore, consensus_constants: ConsensusConstants, coins_of_interest_received: Callable, # f(removals: List[Coin], additions: List[Coin], height: uint32) reorg_rollback:...
[ "async", "def", "create", "(", "block_store", ":", "WalletBlockStore", ",", "coin_store", ":", "WalletCoinStore", ",", "tx_store", ":", "WalletTransactionStore", ",", "consensus_constants", ":", "ConsensusConstants", ",", "coins_of_interest_received", ":", "Callable", "...
[ 79, 4 ]
[ 112, 19 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain._load_chain_from_store
(self)
Initializes the state of the Blockchain class from the database.
Initializes the state of the Blockchain class from the database.
async def _load_chain_from_store(self) -> None: """ Initializes the state of the Blockchain class from the database. """ height_to_hash, sub_epoch_summaries = await self.block_store.get_peak_heights_dicts() self.__height_to_hash = height_to_hash self.__sub_epoch_summaries...
[ "async", "def", "_load_chain_from_store", "(", "self", ")", "->", "None", ":", "height_to_hash", ",", "sub_epoch_summaries", "=", "await", "self", ".", "block_store", ".", "get_peak_heights_dicts", "(", ")", "self", ".", "__height_to_hash", "=", "height_to_hash", ...
[ 118, 4 ]
[ 138, 66 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.get_peak
(self)
Return the peak of the blockchain
Return the peak of the blockchain
def get_peak(self) -> Optional[BlockRecord]: """ Return the peak of the blockchain """ if self._peak_height is None: return None return self.height_to_block_record(self._peak_height)
[ "def", "get_peak", "(", "self", ")", "->", "Optional", "[", "BlockRecord", "]", ":", "if", "self", ".", "_peak_height", "is", "None", ":", "return", "None", "return", "self", ".", "height_to_block_record", "(", "self", ".", "_peak_height", ")" ]
[ 140, 4 ]
[ 146, 61 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.receive_block
( self, header_block_record: HeaderBlockRecord, pre_validation_result: Optional[PreValidationResult] = None, trusted: bool = False, fork_point_with_peak: Optional[uint32] = None, )
Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case...
Adds a new block into the blockchain, if it's valid and connected to the current blockchain, regardless of whether it is the child of a head, or another block. Returns a header if block is added to head. Returns an error if the block is invalid. Also returns the fork height, in the case...
async def receive_block( self, header_block_record: HeaderBlockRecord, pre_validation_result: Optional[PreValidationResult] = None, trusted: bool = False, fork_point_with_peak: Optional[uint32] = None, ) -> Tuple[ReceiveBlockResult, Optional[Err], Optional[uint32]]: "...
[ "async", "def", "receive_block", "(", "self", ",", "header_block_record", ":", "HeaderBlockRecord", ",", "pre_validation_result", ":", "Optional", "[", "PreValidationResult", "]", "=", "None", ",", "trusted", ":", "bool", "=", "False", ",", "fork_point_with_peak", ...
[ 148, 4 ]
[ 245, 69 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain._reconsider_peak
( self, block_record: BlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32] )
When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there w...
When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting blocks which are not in the heaviest chain. It returns the height of the fork between the previous chain and the new chain, or returns None if there w...
async def _reconsider_peak( self, block_record: BlockRecord, genesis: bool, fork_point_with_peak: Optional[uint32] ) -> Optional[uint32]: """ When a new block is added, this is called, to check if the new block is the new peak of the chain. This also handles reorgs by reverting block...
[ "async", "def", "_reconsider_peak", "(", "self", ",", "block_record", ":", "BlockRecord", ",", "genesis", ":", "bool", ",", "fork_point_with_peak", ":", "Optional", "[", "uint32", "]", ")", "->", "Optional", "[", "uint32", "]", ":", "peak", "=", "self", "....
[ 247, 4 ]
[ 326, 19 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.contains_block
(self, header_hash: bytes32)
True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory.
True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory.
def contains_block(self, header_hash: bytes32) -> bool: """ True if we have already added this block to the chain. This may return false for orphan blocks that we have added but no longer keep in memory. """ return header_hash in self.__block_records
[ "def", "contains_block", "(", "self", ",", "header_hash", ":", "bytes32", ")", "->", "bool", ":", "return", "header_hash", "in", "self", ".", "__block_records" ]
[ 349, 4 ]
[ 354, 50 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.warmup
(self, fork_point: uint32)
Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last block height to load in the cache
Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point.
async def warmup(self, fork_point: uint32): """ Loads blocks into the cache. The blocks loaded include all blocks from fork point - BLOCKS_CACHE_SIZE up to and including the fork_point. Args: fork_point: the last block height to load in the cache """ if sel...
[ "async", "def", "warmup", "(", "self", ",", "fork_point", ":", "uint32", ")", ":", "if", "self", ".", "_peak_height", "is", "None", ":", "return", "None", "blocks", "=", "await", "self", ".", "block_store", ".", "get_block_records_in_range", "(", "fork_point...
[ 378, 4 ]
[ 394, 47 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.clean_block_record
(self, height: int)
Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache
Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache
def clean_block_record(self, height: int): """ Clears all block records in the cache which have block_record < height. Args: height: Minimum height that we need to keep in the cache """ if height < 0: return None blocks_to_remove = self.__heights_...
[ "def", "clean_block_record", "(", "self", ",", "height", ":", "int", ")", ":", "if", "height", "<", "0", ":", "return", "None", "blocks_to_remove", "=", "self", ".", "__heights_in_cache", ".", "get", "(", "uint32", "(", "height", ")", ",", "None", ")", ...
[ 396, 4 ]
[ 412, 80 ]
python
en
['en', 'error', 'th']
False
WalletBlockchain.clean_block_records
(self)
Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments.
Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments.
def clean_block_records(self): """ Cleans the cache so that we only maintain relevant blocks. This removes block records that have height < peak - BLOCKS_CACHE_SIZE. These blocks are necessary for calculating future difficulty adjustments. """ if len(self.__block_records...
[ "def", "clean_block_records", "(", "self", ")", ":", "if", "len", "(", "self", ".", "__block_records", ")", "<", "self", ".", "constants", ".", "BLOCKS_CACHE_SIZE", ":", "return", "None", "peak", "=", "self", ".", "get_peak", "(", ")", "assert", "peak", ...
[ 414, 4 ]
[ 428, 79 ]
python
en
['en', 'error', 'th']
False
read_syms_from_list
(slist)
Read a list of symbols from a list of strings. Each string is one symbol.
Read a list of symbols from a list of strings. Each string is one symbol.
def read_syms_from_list(slist): """ Read a list of symbols from a list of strings. Each string is one symbol. """ return [ast.literal_eval(l) for l in slist]
[ "def", "read_syms_from_list", "(", "slist", ")", ":", "return", "[", "ast", ".", "literal_eval", "(", "l", ")", "for", "l", "in", "slist", "]" ]
[ 16, 0 ]
[ 21, 47 ]
python
en
['en', 'error', 'th']
False
read_syms_from_file
(filename)
Read a list of symbols in from a file.
Read a list of symbols in from a file.
def read_syms_from_file(filename): """ Read a list of symbols in from a file. """ with open(filename, 'r') as f: data = f.read() return read_syms_from_list(data.splitlines())
[ "def", "read_syms_from_file", "(", "filename", ")", ":", "with", "open", "(", "filename", ",", "'r'", ")", "as", "f", ":", "data", "=", "f", ".", "read", "(", ")", "return", "read_syms_from_list", "(", "data", ".", "splitlines", "(", ")", ")" ]
[ 24, 0 ]
[ 30, 49 ]
python
en
['en', 'error', 'th']
False
write_syms
(sym_list, out=None, names_only=False)
Write a list of symbols to the file named by out.
Write a list of symbols to the file named by out.
def write_syms(sym_list, out=None, names_only=False): """ Write a list of symbols to the file named by out. """ out_str = '' out_list = sym_list out_list.sort(key=lambda x: x['name']) if names_only: out_list = [sym['name'] for sym in sym_list] for sym in out_list: out_str...
[ "def", "write_syms", "(", "sym_list", ",", "out", "=", "None", ",", "names_only", "=", "False", ")", ":", "out_str", "=", "''", "out_list", "=", "sym_list", "out_list", ".", "sort", "(", "key", "=", "lambda", "x", ":", "x", "[", "'name'", "]", ")", ...
[ 41, 0 ]
[ 56, 28 ]
python
en
['en', 'error', 'th']
False
final_eos_is_already_included
( header_block: Union[UnfinishedHeaderBlock, UnfinishedBlock, HeaderBlock, FullBlock], blocks: BlockchainInterface, sub_slot_iters: uint64, )
Args: header_block: An overflow block, with potentially missing information about the new sub slot blocks: all blocks that have been included before header_block sub_slot_iters: sub_slot_iters at the header_block Returns: True iff the missing sub slot was already included in a previous...
Args: header_block: An overflow block, with potentially missing information about the new sub slot blocks: all blocks that have been included before header_block sub_slot_iters: sub_slot_iters at the header_block
def final_eos_is_already_included( header_block: Union[UnfinishedHeaderBlock, UnfinishedBlock, HeaderBlock, FullBlock], blocks: BlockchainInterface, sub_slot_iters: uint64, ) -> bool: """ Args: header_block: An overflow block, with potentially missing information about the new sub slot ...
[ "def", "final_eos_is_already_included", "(", "header_block", ":", "Union", "[", "UnfinishedHeaderBlock", ",", "UnfinishedBlock", ",", "HeaderBlock", ",", "FullBlock", "]", ",", "blocks", ":", "BlockchainInterface", ",", "sub_slot_iters", ":", "uint64", ",", ")", "->...
[ 16, 0 ]
[ 50, 16 ]
python
en
['en', 'error', 'th']
False
further_validated_draft_dict
( draft_dict: Dict[str, Any], user_profile: UserProfile )
Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a slightly different set of keys the values for which can be used to directly create a Draft object.
Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a slightly different set of keys the values for which can be used to directly create a Draft object.
def further_validated_draft_dict( draft_dict: Dict[str, Any], user_profile: UserProfile ) -> Dict[str, Any]: """Take a draft_dict that was already validated by draft_dict_validator then further sanitize, validate, and transform it. Ultimately return this "further validated" draft dict. It will have a sl...
[ "def", "further_validated_draft_dict", "(", "draft_dict", ":", "Dict", "[", "str", ",", "Any", "]", ",", "user_profile", ":", "UserProfile", ")", "->", "Dict", "[", "str", ",", "Any", "]", ":", "content", "=", "normalize_body", "(", "draft_dict", "[", "\"c...
[ 44, 0 ]
[ 85, 5 ]
python
en
['en', 'en', 'en']
True
TestIDCollisions.test_grouper_object_collisions
(self)
Certain functions such as itertools.groupby will cause new objects (namely, tuples and custom itertools._grouper iterables) to be created in the course of iterating over the object tree. If we're not careful, these will be released and the memory reallocated to new objects while we're s...
Certain functions such as itertools.groupby will cause new objects (namely, tuples and custom itertools._grouper iterables) to be created in the course of iterating over the object tree. If we're not careful, these will be released and the memory reallocated to new objects while we're s...
def test_grouper_object_collisions(self): """ Certain functions such as itertools.groupby will cause new objects (namely, tuples and custom itertools._grouper iterables) to be created in the course of iterating over the object tree. If we're not careful, these will be released and the me...
[ "def", "test_grouper_object_collisions", "(", "self", ")", ":", "# create 100 Ark objects all with distinct animals (no object references are re-used)", "arks", "=", "[", "Ark", "(", "[", "{", "'type'", ":", "'lion'", ",", "'name'", ":", "'Simba %i'", "%", "i", "}", "...
[ 267, 4 ]
[ 297, 14 ]
python
en
['en', 'error', 'th']
False
build_page_params_for_home_page_load
( request: HttpRequest, user_profile: Optional[UserProfile], realm: Realm, insecure_desktop_app: bool, narrow: List[List[str]], narrow_stream: Optional[Stream], narrow_topic: Optional[str], first_in_realm: bool, prompt_for_invites: bool, needs_tutorial: bool, )
This function computes page_params for when we load the home page. The page_params data structure gets sent to the client.
This function computes page_params for when we load the home page.
def build_page_params_for_home_page_load( request: HttpRequest, user_profile: Optional[UserProfile], realm: Realm, insecure_desktop_app: bool, narrow: List[List[str]], narrow_stream: Optional[Stream], narrow_topic: Optional[str], first_in_realm: bool, prompt_for_invites: bool, ne...
[ "def", "build_page_params_for_home_page_load", "(", "request", ":", "HttpRequest", ",", "user_profile", ":", "Optional", "[", "UserProfile", "]", ",", "realm", ":", "Realm", ",", "insecure_desktop_app", ":", "bool", ",", "narrow", ":", "List", "[", "List", "[", ...
[ 118, 0 ]
[ 246, 48 ]
python
en
['en', 'error', 'th']
False