project_name stringlengths 6 104 | file_name stringlengths 4 89 | full_name stringlengths 1 102 | func_name stringlengths 1 85 | docstring stringlengths 13 836 | docstring_tokens listlengths 4 122 | code stringlengths 23 39.7k | code_tokens stringlengths 29 44.6k | url int64 3 986k |
|---|---|---|---|---|---|---|---|---|
wandb/wandb | auto_logging.py | PatchAPI.patch | patch | Patches the API to log media or metrics to W&B. | [
"Patches",
"the",
"API",
"to",
"log",
"media",
"or",
"metrics",
"to",
"W&B."
] | def patch(self, run: 'wandb.sdk.wandb_run.Run') -> None:
for symbol in self.symbols:
symbol_parts = symbol.split('.')
original = functools.reduce(getattr, symbol_parts, self.set_api)
def method_factory(original_method: Any):
async def async_method(*args, **kwargs):
... | ['def', 'patch(self,', 'run:', "'wandb.sdk.wandb_run.Run')", '->', 'None:', 'for', 'symbol', 'in', 'self.symbols:', 'symbol_parts', '=', "symbol.split('.')", 'original', '=', 'functools.reduce(getattr,', 'symbol_parts,', 'self.set_api)', 'def', 'method_factory(original_method:', 'Any):', 'async', 'def', 'async_method(*... | 941,706 |
wandb/wandb | datastore.py | DataStore.in_last_block | in_last_block | Determine if we're in the last block to handle in-progress writes. | [
"Determine",
"if",
"we're",
"in",
"the",
"last",
"block",
"to",
"handle",
"in-progress",
"writes."
] | def in_last_block(self):
return self._index > self._size_bytes - LEVELDBLOG_DATA_LEN | ['def', 'in_last_block(self):', 'return', 'self._index', '>', 'self._size_bytes', '-', 'LEVELDBLOG_DATA_LEN'] | 941,709 |
wandb/wandb | progress.py | Progress.read | read | Read bytes and call the callback. | [
"Read",
"bytes",
"and",
"call",
"the",
"callback."
] | def read(self, size=-1):
bites = self.file.read(size)
self.bytes_read += len(bites)
if not bites and self.bytes_read < self.len:
raise CommError('File {} size shrank from {} to {} while it was being uploaded.'.format(self.file.name, self.len, self.bytes_read))
self.callback(len(bites), self.byte... | ['def', 'read(self,', 'size=-1):', 'bites', '=', 'self.file.read(size)', 'self.bytes_read', '+=', 'len(bites)', 'if', 'not', 'bites', 'and', 'self.bytes_read', '<', 'self.len:', 'raise', "CommError('File", '{}', 'size', 'shrank', 'from', '{}', 'to', '{}', 'while', 'it', 'was', 'being', "uploaded.'.format(self.file.name... | 941,719 |
wandb/wandb | env_probe_helpers.py | is_aws_lambda | is_aws_lambda | Check if we are running in a lambda environment. | [
"Check",
"if",
"we",
"are",
"running",
"in",
"a",
"lambda",
"environment."
] | def is_aws_lambda() -> bool:
lambda_bootstrap = get_lambda_bootstrap()
if not lambda_bootstrap or not hasattr(lambda_bootstrap, 'handle_event_request'):
return False
return True | ['def', 'is_aws_lambda()', '->', 'bool:', 'lambda_bootstrap', '=', 'get_lambda_bootstrap()', 'if', 'not', 'lambda_bootstrap', 'or', 'not', 'hasattr(lambda_bootstrap,', "'handle_event_request'):", 'return', 'False', 'return', 'True'] | 941,724 |
wandb/wandb | system_info.py | SystemInfo.probe | probe | Probe the system for information about the current environment. | [
"Probe",
"the",
"system",
"for",
"information",
"about",
"the",
"current",
"environment."
] | def probe(self) -> Dict[str, Any]:
logger.debug('Probing system')
data: Dict[str, Any] = dict()
data['os'] = self.settings._os
data['python'] = self.settings._python
data['heartbeatAt'] = datetime.datetime.utcnow().isoformat()
data['startedAt'] = datetime.datetime.utcfromtimestamp(self.settings.... | ['def', 'probe(self)', '->', 'Dict[str,', 'Any]:', "logger.debug('Probing", "system')", 'data:', 'Dict[str,', 'Any]', '=', 'dict()', "data['os']", '=', 'self.settings._os', "data['python']", '=', 'self.settings._python', "data['heartbeatAt']", '=', 'datetime.datetime.utcnow().isoformat()', "data['startedAt']", '=', 'da... | 941,725 |
wandb/wandb | gpu_amd.py | GPUAMDStats.parse_stats | parse_stats | Parse stats from rocm-smi output. | [
"Parse",
"stats",
"from",
"rocm-smi",
"output."
] | def parse_stats(stats: Dict[str, str]) -> _Stats:
parsed_stats: _Stats = {}
try:
parsed_stats['gpu'] = float(stats.get('GPU use (%)'))
except (TypeError, ValueError):
logger.warning('Could not parse GPU usage as float')
try:
parsed_stats['memoryAllocated'] = float(stats.get('GPU ... | ['def', 'parse_stats(stats:', 'Dict[str,', 'str])', '->', '_Stats:', 'parsed_stats:', '_Stats', '=', '{}', 'try:', "parsed_stats['gpu']", '=', "float(stats.get('GPU", 'use', "(%)'))", 'except', '(TypeError,', 'ValueError):', "logger.warning('Could", 'not', 'parse', 'GPU', 'usage', 'as', "float')", 'try:', "parsed_stats... | 941,727 |
wandb/wandb | interfaces.py | SetupTeardown.setup | setup | Extra setup required for the metric beyond __init__. | [
"Extra",
"setup",
"required",
"for",
"the",
"metric",
"beyond",
"__init__."
] | def setup(self) -> None:
... | ['def', 'setup(self)', '->', 'None:', '...'] | 941,728 |
wandb/wandb | interfaces.py | SetupTeardown.teardown | teardown | Extra teardown required for the metric. | [
"Extra",
"teardown",
"required",
"for",
"the",
"metric."
] | def teardown(self) -> None:
... | ['def', 'teardown(self)', '->', 'None:', '...'] | 941,729 |
wandb/wandb | interfaces.py | Asset.start | start | Start monitoring the resource. | [
"Start",
"monitoring",
"the",
"resource."
] | def start(self) -> None:
... | ['def', 'start(self)', '->', 'None:', '...'] | 941,731 |
wandb/wandb | interfaces.py | Asset.finish | finish | Finish monitoring the resource. | [
"Finish",
"monitoring",
"the",
"resource."
] | def finish(self) -> None:
... | ['def', 'finish(self)', '->', 'None:', '...'] | 941,732 |
wandb/wandb | interfaces.py | MetricsMonitor.aggregate | aggregate | Return a dict of metrics. | [
"Return",
"a",
"dict",
"of",
"metrics."
] | def aggregate(self) -> dict:
aggregated_metrics = {}
for metric in self.metrics:
try:
serialized_metric = metric.aggregate()
aggregated_metrics.update(serialized_metric)
except Exception as e:
logger.error(f'Failed to serialize metric: {e}')
return aggrega... | ['def', 'aggregate(self)', '->', 'dict:', 'aggregated_metrics', '=', '{}', 'for', 'metric', 'in', 'self.metrics:', 'try:', 'serialized_metric', '=', 'metric.aggregate()', 'aggregated_metrics.update(serialized_metric)', 'except', 'Exception', 'as', 'e:', "logger.error(f'Failed", 'to', 'serialize', 'metric:', "{e}')", 'r... | 941,735 |
wandb/wandb | memory.py | Memory.is_available | is_available | Return a new instance of the CPU metrics. | [
"Return",
"a",
"new",
"instance",
"of",
"the",
"CPU",
"metrics."
] | def is_available(cls) -> bool:
return psutil is not None | ['def', 'is_available(cls)', '->', 'bool:', 'return', 'psutil', 'is', 'not', 'None'] | 941,737 |
wandb/wandb | network.py | Network.probe | probe | Return a dict of the hardware information. | [
"Return",
"a",
"dict",
"of",
"the",
"hardware",
"information."
] | def probe(self) -> dict:
return {} | ['def', 'probe(self)', '->', 'dict:', 'return', '{}'] | 941,740 |
wandb/wandb | trainium.py | NeuronCoreStats.write_neuron_monitor_config | write_neuron_monitor_config | Write neuron monitor config file. | [
"Write",
"neuron",
"monitor",
"config",
"file."
] | def write_neuron_monitor_config(self) -> None:
pathlib.Path(self.neuron_monitor_config_path).parent.mkdir(parents=True, exist_ok=True)
with open(self.neuron_monitor_config_path, 'w') as f:
json.dump(NEURON_MONITOR_DEFAULT_CONFIG, f, indent=4) | ['def', 'write_neuron_monitor_config(self)', '->', 'None:', 'pathlib.Path(self.neuron_monitor_config_path).parent.mkdir(parents=True,', 'exist_ok=True)', 'with', 'open(self.neuron_monitor_config_path,', "'w')", 'as', 'f:', 'json.dump(NEURON_MONITOR_DEFAULT_CONFIG,', 'f,', 'indent=4)'] | 941,741 |
wandb/wandb | trainium.py | NeuronCoreStats.setup | setup | Start the neuron-monitor thread for collecting raw data. | [
"Start",
"the",
"neuron-monitor",
"thread",
"for",
"collecting",
"raw",
"data."
] | def setup(self) -> None:
if self.neuron_monitor_thread is not None:
return
logger.debug('Starting neuron-monitor thread')
self.shutdown_event.clear()
self.neuron_monitor_thread = threading.Thread(name='NeuronCoreMntr', target=self.neuron_monitor, daemon=True)
self.neuron_monitor_thread.start... | ['def', 'setup(self)', '->', 'None:', 'if', 'self.neuron_monitor_thread', 'is', 'not', 'None:', 'return', "logger.debug('Starting", 'neuron-monitor', "thread')", 'self.shutdown_event.clear()', 'self.neuron_monitor_thread', '=', "threading.Thread(name='NeuronCoreMntr',", 'target=self.neuron_monitor,', 'daemon=True)', 's... | 941,743 |
wandb/wandb | trainium.py | NeuronCoreStats.teardown | teardown | Stop the neuron-monitor thread. | [
"Stop",
"the",
"neuron-monitor",
"thread."
] | def teardown(self) -> None:
logger.debug('Stopping neuron-monitor thread')
try:
self.shutdown_event.set()
assert self.neuron_monitor_thread is not None
self.neuron_monitor_thread.join()
except Exception as e:
logger.error('neuron-monitor thread failed to stop: %s' % e)
fi... | ['def', 'teardown(self)', '->', 'None:', "logger.debug('Stopping", 'neuron-monitor', "thread')", 'try:', 'self.shutdown_event.set()', 'assert', 'self.neuron_monitor_thread', 'is', 'not', 'None', 'self.neuron_monitor_thread.join()', 'except', 'Exception', 'as', 'e:', "logger.error('neuron-monitor", 'thread', 'failed', '... | 941,744 |
wandb/wandb | trainium.py | NeuronCoreStats.flatten_stats | flatten_stats | Flatten _Stats object into a flat dict of numbers. | [
"Flatten",
"_Stats",
"object",
"into",
"a",
"flat",
"dict",
"of",
"numbers."
] | def flatten_stats(sample: _Stats) -> dict:
flattened = {}
def helper(key: str, value: Any) -> None:
if isinstance(value, (int, float)):
ret = {f'{key}': value}
flattened.update(ret)
return
elif isinstance(value, dict):
for (kk, vv) in value.items(... | ['def', 'flatten_stats(sample:', '_Stats)', '->', 'dict:', 'flattened', '=', '{}', 'def', 'helper(key:', 'str,', 'value:', 'Any)', '->', 'None:', 'if', 'isinstance(value,', '(int,', 'float)):', 'ret', '=', "{f'{key}':", 'value}', 'flattened.update(ret)', 'return', 'elif', 'isinstance(value,', 'dict):', 'for', '(kk,', '... | 941,745 |
wandb/wandb | github_reference.py | GitHubReference.parse | parse | Attempt to parse a string as a GitHub URL. | [
"Attempt",
"to",
"parse",
"a",
"string",
"as",
"a",
"GitHub",
"URL."
] | def parse(uri: str) -> Optional['GitHubReference']:
ref = GitHubReference()
if uri.startswith(PREFIX_SSH):
index = uri.find(':', len(PREFIX_SSH))
if index > 0:
ref.host = uri[len(PREFIX_SSH):index]
parts = uri[index + 1:].split('/', 1)
if len(parts) < 2 or not... | ['def', 'parse(uri:', 'str)', '->', "Optional['GitHubReference']:", 'ref', '=', 'GitHubReference()', 'if', 'uri.startswith(PREFIX_SSH):', 'index', '=', "uri.find(':',", 'len(PREFIX_SSH))', 'if', 'index', '>', '0:', 'ref.host', '=', 'uri[len(PREFIX_SSH):index]', 'parts', '=', 'uri[index', '+', "1:].split('/',", '1)', 'i... | 941,746 |
wandb/wandb | utils.py | diff_pip_requirements | diff_pip_requirements | Return a list of pip requirements that are not in req_1 but are in req_2. | [
"Return",
"a",
"list",
"of",
"pip",
"requirements",
"that",
"are",
"not",
"in",
"req_1",
"but",
"are",
"in",
"req_2."
] | def diff_pip_requirements(req_1: List[str], req_2: List[str]) -> Dict[str, str]:
def _parse_req(req: List[str]) -> Dict[str, str]:
d: Dict[str, str] = dict()
for line in req:
_name: str = None
_version: str = None
if line.startswith('#'):
continue... | ['def', 'diff_pip_requirements(req_1:', 'List[str],', 'req_2:', 'List[str])', '->', 'Dict[str,', 'str]:', 'def', '_parse_req(req:', 'List[str])', '->', 'Dict[str,', 'str]:', 'd:', 'Dict[str,', 'str]', '=', 'dict()', 'for', 'line', 'in', 'req:', '_name:', 'str', '=', 'None', '_version:', 'str', '=', 'None', 'if', "line.... | 941,755 |
wandb/wandb | utils.py | apply_patch | apply_patch | Applies a patch file to a directory. | [
"Applies",
"a",
"patch",
"file",
"to",
"a",
"directory."
] | def apply_patch(patch_string: str, dst_dir: str) -> None:
_logger.info('Applying diff.patch')
with open(os.path.join(dst_dir, 'diff.patch'), 'w') as fp:
fp.write(patch_string)
try:
subprocess.check_call(['patch', '-s', f'--directory={dst_dir}', '-p1', '-i', 'diff.patch'])
except subproce... | ['def', 'apply_patch(patch_string:', 'str,', 'dst_dir:', 'str)', '->', 'None:', "_logger.info('Applying", "diff.patch')", 'with', 'open(os.path.join(dst_dir,', "'diff.patch'),", "'w')", 'as', 'fp:', 'fp.write(patch_string)', 'try:', "subprocess.check_call(['patch',", "'-s',", "f'--directory={dst_dir}',", "'-p1',", "'-i... | 941,758 |
wandb/wandb | utils.py | merge_parameters | merge_parameters | Merge the contents of two dicts, keeping values from higher_priority_params if there are conflicts. | [
"Merge",
"the",
"contents",
"of",
"two",
"dicts,",
"keeping",
"values",
"from",
"higher_priority_params",
"if",
"there",
"are",
"conflicts."
] | def merge_parameters(higher_priority_params: Dict[str, Any], lower_priority_params: Dict[str, Any]) -> Dict[str, Any]:
return {**lower_priority_params, **higher_priority_params} | ['def', 'merge_parameters(higher_priority_params:', 'Dict[str,', 'Any],', 'lower_priority_params:', 'Dict[str,', 'Any])', '->', 'Dict[str,', 'Any]:', 'return', '{**lower_priority_params,', '**higher_priority_params}'] | 941,759 |
wandb/wandb | _project_spec.py | LaunchProject.get_single_entry_point | get_single_entry_point | Returns the first entrypoint for the project, or None if no entry point was provided because a docker image was provided. | [
"Returns",
"the",
"first",
"entrypoint",
"for",
"the",
"project,",
"or",
"None",
"if",
"no",
"entry",
"point",
"was",
"provided",
"because",
"a",
"docker",
"image",
"was",
"provided."
] | def get_single_entry_point(self) -> Optional['EntryPoint']:
if not self._entry_point:
if not self.docker_image:
raise LaunchError('Project must have at least one entry point unless docker image is specified.')
return None
return self._entry_point | ['def', 'get_single_entry_point(self)', '->', "Optional['EntryPoint']:", 'if', 'not', 'self._entry_point:', 'if', 'not', 'self.docker_image:', 'raise', "LaunchError('Project", 'must', 'have', 'at', 'least', 'one', 'entry', 'point', 'unless', 'docker', 'image', 'is', "specified.')", 'return', 'None', 'return', 'self._en... | 941,770 |
wandb/wandb | _project_spec.py | LaunchProject.set_entry_point | set_entry_point | Add an entry point to the project. | [
"Add",
"an",
"entry",
"point",
"to",
"the",
"project."
] | def set_entry_point(self, command: List[str]) -> 'EntryPoint':
assert self._entry_point is None, 'Cannot set entry point twice. Use LaunchProject.override_entrypoint'
new_entrypoint = EntryPoint(name=command[-1], command=command)
self._entry_point = new_entrypoint
return new_entrypoint | ['def', 'set_entry_point(self,', 'command:', 'List[str])', '->', "'EntryPoint':", 'assert', 'self._entry_point', 'is', 'None,', "'Cannot", 'set', 'entry', 'point', 'twice.', 'Use', "LaunchProject.override_entrypoint'", 'new_entrypoint', '=', 'EntryPoint(name=command[-1],', 'command=command)', 'self._entry_point', '=', ... | 941,771 |
wandb/wandb | _project_spec.py | EntryPoint.compute_command | compute_command | Converts user parameter dictionary to a string. | [
"Converts",
"user",
"parameter",
"dictionary",
"to",
"a",
"string."
] | def compute_command(self, user_parameters: Optional[List[str]]) -> List[str]:
ret = self.command
if user_parameters:
return ret + user_parameters
return ret | ['def', 'compute_command(self,', 'user_parameters:', 'Optional[List[str]])', '->', 'List[str]:', 'ret', '=', 'self.command', 'if', 'user_parameters:', 'return', 'ret', '+', 'user_parameters', 'return', 'ret'] | 941,773 |
wandb/wandb | build.py | image_tag_from_dockerfile_and_source | image_tag_from_dockerfile_and_source | Hashes the source and dockerfile contents into a unique tag. | [
"Hashes",
"the",
"source",
"and",
"dockerfile",
"contents",
"into",
"a",
"unique",
"tag."
] | def image_tag_from_dockerfile_and_source(launch_project: LaunchProject, dockerfile_contents: str) -> str:
image_source_string = launch_project.get_image_source_string()
unique_id_string = image_source_string + dockerfile_contents
image_tag = hashlib.sha256(unique_id_string.encode('utf-8')).hexdigest()[:8]
... | ['def', 'image_tag_from_dockerfile_and_source(launch_project:', 'LaunchProject,', 'dockerfile_contents:', 'str)', '->', 'str:', 'image_source_string', '=', 'launch_project.get_image_source_string()', 'unique_id_string', '=', 'image_source_string', '+', 'dockerfile_contents', 'image_tag', '=', "hashlib.sha256(unique_id_... | 941,783 |
wandb/wandb | docker_builder.py | DockerBuilder.login | login | Login to the registry. | [
"Login",
"to",
"the",
"registry."
] | def login(self) -> None:
if isinstance(self.registry, LocalRegistry):
_logger.info(f'{LOG_PREFIX}No registry configured, skipping login.')
else:
(username, password) = self.registry.get_username_password()
docker.login(username, password, self.registry.uri) | ['def', 'login(self)', '->', 'None:', 'if', 'isinstance(self.registry,', 'LocalRegistry):', "_logger.info(f'{LOG_PREFIX}No", 'registry', 'configured,', 'skipping', "login.')", 'else:', '(username,', 'password)', '=', 'self.registry.get_username_password()', 'docker.login(username,', 'password,', 'self.registry.uri)'] | 941,785 |
wandb/wandb | noop.py | NoOpBuilder.from_config | from_config | Create a noop builder from a config. | [
"Create",
"a",
"noop",
"builder",
"from",
"a",
"config."
] | def from_config(cls, config: dict, environment: AbstractEnvironment, registry: AbstractRegistry, verify: bool=True) -> 'AbstractBuilder':
return cls(config, environment, registry) | ['def', 'from_config(cls,', 'config:', 'dict,', 'environment:', 'AbstractEnvironment,', 'registry:', 'AbstractRegistry,', 'verify:', 'bool=True)', '->', "'AbstractBuilder':", 'return', 'cls(config,', 'environment,', 'registry)'] | 941,790 |
wandb/wandb | abstract.py | AbstractEnvironment.verify | verify | Verify that the environment is configured correctly. | [
"Verify",
"that",
"the",
"environment",
"is",
"configured",
"correctly."
] | def verify(self) -> None:
raise NotImplementedError | ['def', 'verify(self)', '->', 'None:', 'raise', 'NotImplementedError'] | 941,795 |
wandb/wandb | abstract.py | AbstractEnvironment.upload_file | upload_file | Upload a file from the local filesystem to storage in the environment. | [
"Upload",
"a",
"file",
"from",
"the",
"local",
"filesystem",
"to",
"storage",
"in",
"the",
"environment."
] | def upload_file(self, source: str, destination: str) -> None:
raise NotImplementedError | ['def', 'upload_file(self,', 'source:', 'str,', 'destination:', 'str)', '->', 'None:', 'raise', 'NotImplementedError'] | 941,796 |
wandb/wandb | abstract.py | AbstractEnvironment.verify_storage_uri | verify_storage_uri | Verify that the storage URI is configured correctly. | [
"Verify",
"that",
"the",
"storage",
"URI",
"is",
"configured",
"correctly."
] | def verify_storage_uri(self, uri: str) -> None:
raise NotImplementedError | ['def', 'verify_storage_uri(self,', 'uri:', 'str)', '->', 'None:', 'raise', 'NotImplementedError'] | 941,798 |
wandb/wandb | azure_environment.py | AzureEnvironment.from_config | from_config | Create an AzureEnvironment from a config dict. | [
"Create",
"an",
"AzureEnvironment",
"from",
"a",
"config",
"dict."
] | def from_config(cls, config: dict, verify: bool=True) -> 'AzureEnvironment':
return cls(verify=verify) | ['def', 'from_config(cls,', 'config:', 'dict,', 'verify:', 'bool=True)', '->', "'AzureEnvironment':", 'return', 'cls(verify=verify)'] | 941,806 |
wandb/wandb | azure_environment.py | AzureEnvironment.verify_storage_uri | verify_storage_uri | Verify that the given blob storage prefix exists. | [
"Verify",
"that",
"the",
"given",
"blob",
"storage",
"prefix",
"exists."
] | def verify_storage_uri(self, uri: str) -> None:
creds = self.get_credentials()
(storage_account, storage_container, _) = self.parse_uri(uri)
try:
client = BlobServiceClient(f'https://{storage_account}.blob.core.windows.net', credential=creds)
client.get_container_client(storage_container)
... | ['def', 'verify_storage_uri(self,', 'uri:', 'str)', '->', 'None:', 'creds', '=', 'self.get_credentials()', '(storage_account,', 'storage_container,', '_)', '=', 'self.parse_uri(uri)', 'try:', 'client', '=', "BlobServiceClient(f'https://{storage_account}.blob.core.windows.net',", 'credential=creds)', 'client.get_contain... | 941,809 |
wandb/wandb | azure_environment.py | AzureEnvironment.verify | verify | Verify that the AzureEnvironment is valid. | [
"Verify",
"that",
"the",
"AzureEnvironment",
"is",
"valid."
] | def verify(self) -> None:
self.get_credentials() | ['def', 'verify(self)', '->', 'None:', 'self.get_credentials()'] | 941,810 |
wandb/wandb | abstract.py | AbstractRegistry.from_config | from_config | Create a registry from a config. | [
"Create",
"a",
"registry",
"from",
"a",
"config."
] | def from_config(cls, config: dict, environment: 'AbstractEnvironment', verify: bool=True) -> 'AbstractRegistry':
raise NotImplementedError | ['def', 'from_config(cls,', 'config:', 'dict,', 'environment:', "'AbstractEnvironment',", 'verify:', 'bool=True)', '->', "'AbstractRegistry':", 'raise', 'NotImplementedError'] | 941,832 |
wandb/wandb | azure_container_registry.py | AzureContainerRegistry.from_config | from_config | Create an AzureContainerRegistry from a config dict. | [
"Create",
"an",
"AzureContainerRegistry",
"from",
"a",
"config",
"dict."
] | def from_config(cls, config: dict, environment: AbstractEnvironment, verify: bool=True) -> 'AzureContainerRegistry':
if not isinstance(environment, AzureEnvironment):
raise LaunchError('AzureContainerRegistry requires an AzureEnvironment to be passed in.')
uri = config.get('uri')
if uri is None:
... | ['def', 'from_config(cls,', 'config:', 'dict,', 'environment:', 'AbstractEnvironment,', 'verify:', 'bool=True)', '->', "'AzureContainerRegistry':", 'if', 'not', 'isinstance(environment,', 'AzureEnvironment):', 'raise', "LaunchError('AzureContainerRegistry", 'requires', 'an', 'AzureEnvironment', 'to', 'be', 'passed', "i... | 941,833 |
wandb/wandb | azure_container_registry.py | AzureContainerRegistry.get_username_password | get_username_password | Get username and password for container registry. | [
"Get",
"username",
"and",
"password",
"for",
"container",
"registry."
] | def get_username_password(self) -> Tuple[str, str]:
raise NotImplementedError | ['def', 'get_username_password(self)', '->', 'Tuple[str,', 'str]:', 'raise', 'NotImplementedError'] | 941,834 |
wandb/wandb | google_artifact_registry.py | GoogleArtifactRegistry.uri | uri | The uri of the registry. | [
"The",
"uri",
"of",
"the",
"registry."
] | def uri(self) -> str:
return f'{self.environment.region}-docker.pkg.dev/{self.environment.project}/{self.repository}/{self.image_name}' | ['def', 'uri(self)', '->', 'str:', 'return', "f'{self.environment.region}-docker.pkg.dev/{self.environment.project}/{self.repository}/{self.image_name}'"] | 941,842 |
wandb/wandb | abstract.py | AbstractRunner.find_executable | find_executable | Cross platform utility for checking if a program is available. | [
"Cross",
"platform",
"utility",
"for",
"checking",
"if",
"a",
"program",
"is",
"available."
] | def find_executable(self, cmd: str) -> Any:
return find_executable(cmd) | ['def', 'find_executable(self,', 'cmd:', 'str)', '->', 'Any:', 'return', 'find_executable(cmd)'] | 941,858 |
wandb/wandb | kubernetes_monitor.py | KubernetesRunMonitor.start | start | Start the run monitor. | [
"Start",
"the",
"run",
"monitor."
] | def start(self) -> None:
if self.custom_api is None:
self._watch_job_thread.start()
else:
self._watch_crd_thread.start()
self._watch_pods_thread.start() | ['def', 'start(self)', '->', 'None:', 'if', 'self.custom_api', 'is', 'None:', 'self._watch_job_thread.start()', 'else:', 'self._watch_crd_thread.start()', 'self._watch_pods_thread.start()'] | 941,861 |
wandb/wandb | kubernetes_monitor.py | KubernetesRunMonitor.get_status | get_status | Get the run status. | [
"Get",
"the",
"run",
"status."
] | def get_status(self) -> Status:
with self._status_lock:
if self._status.state in ['running', 'starting']:
if self.custom_api is None:
if not self._watch_job_thread.is_alive():
wandb.termwarn(f'Job watcher thread is dead for {self.job_field_selector}')
... | ['def', 'get_status(self)', '->', 'Status:', 'with', 'self._status_lock:', 'if', 'self._status.state', 'in', "['running',", "'starting']:", 'if', 'self.custom_api', 'is', 'None:', 'if', 'not', 'self._watch_job_thread.is_alive():', "wandb.termwarn(f'Job", 'watcher', 'thread', 'is', 'dead', 'for', "{self.job_field_select... | 941,863 |
wandb/wandb | kubernetes_runner.py | KubernetesSubmittedRun.id | id | Return the run id. | [
"Return",
"the",
"run",
"id."
] | def id(self) -> str:
return self.name | ['def', 'id(self)', '->', 'str:', 'return', 'self.name'] | 941,869 |
wandb/wandb | kubernetes_runner.py | KubernetesSubmittedRun.get_job | get_job | Return the job object. | [
"Return",
"the",
"job",
"object."
] | def get_job(self) -> 'V1Job':
return self.batch_api.read_namespaced_job(name=self.name, namespace=self.namespace) | ['def', 'get_job(self)', '->', "'V1Job':", 'return', 'self.batch_api.read_namespaced_job(name=self.name,', 'namespace=self.namespace)'] | 941,870 |
wandb/wandb | kubernetes_runner.py | CrdSubmittedRun.id | id | Get the name of the custom object. | [
"Get",
"the",
"name",
"of",
"the",
"custom",
"object."
] | def id(self) -> str:
return self.name | ['def', 'id(self)', '->', 'str:', 'return', 'self.name'] | 941,872 |
wandb/wandb | kubernetes_runner.py | CrdSubmittedRun.get_logs | get_logs | Get logs for custom object. | [
"Get",
"logs",
"for",
"custom",
"object."
] | def get_logs(self) -> Optional[str]:
logs: Dict[str, Optional[str]] = {}
try:
pods = self.core_api.list_namespaced_pod(label_selector=f'wandb/run-id={self.name}', namespace=self.namespace)
pod_names = [pi.metadata.name for pi in pods.items]
for pod_name in pod_names:
logs[pod... | ['def', 'get_logs(self)', '->', 'Optional[str]:', 'logs:', 'Dict[str,', 'Optional[str]]', '=', '{}', 'try:', 'pods', '=', "self.core_api.list_namespaced_pod(label_selector=f'wandb/run-id={self.name}',", 'namespace=self.namespace)', 'pod_names', '=', '[pi.metadata.name', 'for', 'pi', 'in', 'pods.items]', 'for', 'pod_nam... | 941,873 |
wandb/wandb | kubernetes_runner.py | CrdSubmittedRun.cancel | cancel | Cancel the custom object. | [
"Cancel",
"the",
"custom",
"object."
] | def cancel(self) -> None:
try:
self.custom_api.delete_namespaced_custom_object(group=self.group, version=self.version, namespace=self.namespace, plural=self.plural, name=self.name)
except ApiException as e:
raise LaunchError(f'Failed to delete CRD {self.name} in namespace {self.namespace}: {str(... | ['def', 'cancel(self)', '->', 'None:', 'try:', 'self.custom_api.delete_namespaced_custom_object(group=self.group,', 'version=self.version,', 'namespace=self.namespace,', 'plural=self.plural,', 'name=self.name)', 'except', 'ApiException', 'as', 'e:', 'raise', "LaunchError(f'Failed", 'to', 'delete', 'CRD', '{self.name}',... | 941,875 |
wandb/wandb | kubernetes_runner.py | CrdSubmittedRun.wait | wait | Wait for this custom object to finish running. | [
"Wait",
"for",
"this",
"custom",
"object",
"to",
"finish",
"running."
] | def wait(self) -> bool:
while True:
status = self.get_status()
wandb.termlog(f'{LOG_PREFIX}Job {self.name} status: {status}')
time.sleep(5)
if status.state in ['finished', 'failed', 'preempted']:
return status.state == 'finished' | ['def', 'wait(self)', '->', 'bool:', 'while', 'True:', 'status', '=', 'self.get_status()', "wandb.termlog(f'{LOG_PREFIX}Job", '{self.name}', 'status:', "{status}')", 'time.sleep(5)', 'if', 'status.state', 'in', "['finished',", "'failed',", "'preempted']:", 'return', 'status.state', '==', "'finished'"] | 941,876 |
wandb/wandb | sagemaker_runner.py | get_role_arn | get_role_arn | Get the role arn from the sagemaker args or the backend config. | [
"Get",
"the",
"role",
"arn",
"from",
"the",
"sagemaker",
"args",
"or",
"the",
"backend",
"config."
] | def get_role_arn(sagemaker_args: Dict[str, Any], backend_config: Dict[str, Any], account_id: str) -> str:
role_arn = sagemaker_args.get('RoleArn') or sagemaker_args.get('role_arn')
if role_arn is None:
role_arn = backend_config.get('runner', {}).get('role_arn')
if role_arn is None or not isinstance(... | ['def', 'get_role_arn(sagemaker_args:', 'Dict[str,', 'Any],', 'backend_config:', 'Dict[str,', 'Any],', 'account_id:', 'str)', '->', 'str:', 'role_arn', '=', "sagemaker_args.get('RoleArn')", 'or', "sagemaker_args.get('role_arn')", 'if', 'role_arn', 'is', 'None:', 'role_arn', '=', "backend_config.get('runner',", "{}).get... | 941,882 |
wandb/wandb | scheduler.py | Scheduler.available_workers | available_workers | Returns dict of id:worker ready to launch another run. | [
"Returns",
"dict",
"of",
"id:worker",
"ready",
"to",
"launch",
"another",
"run."
] | def available_workers(self) -> Dict[int, _Worker]:
if len(self._workers) == 0:
return {}
return {_id: w for (_id, w) in self._workers.items() if _id not in self.busy_workers} | ['def', 'available_workers(self)', '->', 'Dict[int,', '_Worker]:', 'if', 'len(self._workers)', '==', '0:', 'return', '{}', 'return', '{_id:', 'w', 'for', '(_id,', 'w)', 'in', 'self._workers.items()', 'if', '_id', 'not', 'in', 'self.busy_workers}'] | 941,887 |
wandb/wandb | scheduler.py | Scheduler.start | start | Start a scheduler, confirms prerequisites, begins execution loop. | [
"Start",
"a",
"scheduler,",
"confirms",
"prerequisites,",
"begins",
"execution",
"loop."
] | def start(self) -> None:
wandb.termlog(f'{LOG_PREFIX}Scheduler starting.')
if not self.is_alive:
wandb.termerror(f'{LOG_PREFIX}Sweep already in end state ({self.state.name.lower()}). Exiting...')
self.exit()
return
self._state = SchedulerState.STARTING
if not self._try_load_execu... | ['def', 'start(self)', '->', 'None:', "wandb.termlog(f'{LOG_PREFIX}Scheduler", "starting.')", 'if', 'not', 'self.is_alive:', "wandb.termerror(f'{LOG_PREFIX}Sweep", 'already', 'in', 'end', 'state', '({self.state.name.lower()}).', "Exiting...')", 'self.exit()', 'return', 'self._state', '=', 'SchedulerState.STARTING', 'if... | 941,889 |
wandb/wandb | utils.py | load_sweep_config | load_sweep_config | Load a sweep yaml from path. | [
"Load",
"a",
"sweep",
"yaml",
"from",
"path."
] | def load_sweep_config(sweep_config_path: str) -> Optional[Dict[str, Any]]:
try:
yaml_file = open(sweep_config_path)
except OSError:
wandb.termerror(f"Couldn't open sweep file: {sweep_config_path}")
return None
try:
config: Optional[Dict[str, Any]] = yaml.safe_load(yaml_file)
... | ['def', 'load_sweep_config(sweep_config_path:', 'str)', '->', 'Optional[Dict[str,', 'Any]]:', 'try:', 'yaml_file', '=', 'open(sweep_config_path)', 'except', 'OSError:', 'wandb.termerror(f"Couldn\'t', 'open', 'sweep', 'file:', '{sweep_config_path}")', 'return', 'None', 'try:', 'config:', 'Optional[Dict[str,', 'Any]]', '... | 941,893 |
wandb/wandb | ipython.py | display_html | display_html | Display HTML in notebooks, is a noop outside a jupyter context. | [
"Display",
"HTML",
"in",
"notebooks,",
"is",
"a",
"noop",
"outside",
"a",
"jupyter",
"context."
] | def display_html(html: str):
if wandb.run and wandb.run._settings.silent:
return
try:
from IPython.core.display import HTML, display
except ImportError:
wandb.termwarn("Unable to render HTML, can't import display from ipython.core")
return False
return display(HTML(html)) | ['def', 'display_html(html:', 'str):', 'if', 'wandb.run', 'and', 'wandb.run._settings.silent:', 'return', 'try:', 'from', 'IPython.core.display', 'import', 'HTML,', 'display', 'except', 'ImportError:', 'wandb.termwarn("Unable', 'to', 'render', 'HTML,', "can't", 'import', 'display', 'from', 'ipython.core")', 'return', '... | 941,915 |
wandb/wandb | ipython.py | display_widget | display_widget | Display ipywidgets in notebooks, is a noop outside of a jupyter context. | [
"Display",
"ipywidgets",
"in",
"notebooks,",
"is",
"a",
"noop",
"outside",
"of",
"a",
"jupyter",
"context."
] | def display_widget(widget):
if wandb.run and wandb.run._settings.silent:
return
try:
from IPython.core.display import display
except ImportError:
wandb.termwarn("Unable to render Widget, can't import display from ipython.core")
return False
return display(widget) | ['def', 'display_widget(widget):', 'if', 'wandb.run', 'and', 'wandb.run._settings.silent:', 'return', 'try:', 'from', 'IPython.core.display', 'import', 'display', 'except', 'ImportError:', 'wandb.termwarn("Unable', 'to', 'render', 'Widget,', "can't", 'import', 'display', 'from', 'ipython.core")', 'return', 'False', 're... | 941,916 |
wandb/wandb | ipython.py | jupyter_progress_bar | jupyter_progress_bar | Return an ipywidget progress bar or None if we can't import it. | [
"Return",
"an",
"ipywidget",
"progress",
"bar",
"or",
"None",
"if",
"we",
"can't",
"import",
"it."
] | def jupyter_progress_bar(min: float=0, max: float=1.0) -> Optional[ProgressWidget]:
widgets = wandb.util.get_module('ipywidgets')
try:
if widgets is None:
with warnings.catch_warnings():
warnings.simplefilter('ignore')
from IPython.html import widgets
... | ['def', 'jupyter_progress_bar(min:', 'float=0,', 'max:', 'float=1.0)', '->', 'Optional[ProgressWidget]:', 'widgets', '=', "wandb.util.get_module('ipywidgets')", 'try:', 'if', 'widgets', 'is', 'None:', 'with', 'warnings.catch_warnings():', "warnings.simplefilter('ignore')", 'from', 'IPython.html', 'import', 'widgets', '... | 941,917 |
wandb/wandb | paths.py | LogicalPath.to_path | to_path | Convert this path to a PurePosixPath. | [
"Convert",
"this",
"path",
"to",
"a",
"PurePosixPath."
] | def to_path(self) -> PurePosixPath:
return PurePosixPath(self) | ['def', 'to_path(self)', '->', 'PurePosixPath:', 'return', 'PurePosixPath(self)'] | 941,918 |
wandb/wandb | proto_util.py | message_to_dict | message_to_dict | Convert a protobuf message into a dictionary. | [
"Convert",
"a",
"protobuf",
"message",
"into",
"a",
"dictionary."
] | def message_to_dict(message: 'Message') -> Dict[str, Any]:
from google.protobuf.json_format import MessageToDict
return MessageToDict(message, preserving_proto_field_name=True) | ['def', 'message_to_dict(message:', "'Message')", '->', 'Dict[str,', 'Any]:', 'from', 'google.protobuf.json_format', 'import', 'MessageToDict', 'return', 'MessageToDict(message,', 'preserving_proto_field_name=True)'] | 941,919 |
wandb/wandb | retry.py | Retry.num_iters | num_iters | The number of iterations the previous __call__ retried. | [
"The",
"number",
"of",
"iterations",
"the",
"previous",
"__call__",
"retried."
] | def num_iters(self) -> int:
return self._num_iter | ['def', 'num_iters(self)', '->', 'int:', 'return', 'self._num_iter'] | 941,920 |
wandb/wandb | runid.py | generate_id | generate_id | Generate a random base-36 string of `length` digits. | [
"Generate",
"a",
"random",
"base-36",
"string",
"of",
"`length`",
"digits."
] | def generate_id(length: int=8) -> str:
alphabet = string.ascii_lowercase + string.digits
return ''.join((secrets.choice(alphabet) for _ in range(length))) | ['def', 'generate_id(length:', 'int=8)', '->', 'str:', 'alphabet', '=', 'string.ascii_lowercase', '+', 'string.digits', 'return', "''.join((secrets.choice(alphabet)", 'for', '_', 'in', 'range(length)))'] | 941,921 |
wandb/wandb | base.py | default_resolve_fn | default_resolve_fn | If a resolve function is not given, then a default resolve behavior is used which takes the property of the source object of the same name as the field and returns it as the result, or if it's a function, returns the result of calling that function. | [
"If",
"a",
"resolve",
"function",
"is",
"not",
"given,",
"then",
"a",
"default",
"resolve",
"behavior",
"is",
"used",
"which",
"takes",
"the",
"property",
"of",
"the",
"source",
"object",
"of",
"the",
"same",
"name",
"as",
"the",
"field",
"and",
"returns",... | def default_resolve_fn(source, args, context, info):
name = info.field_name
property = getattr(source, name, None)
if callable(property):
return property()
return property | ['def', 'default_resolve_fn(source,', 'args,', 'context,', 'info):', 'name', '=', 'info.field_name', 'property', '=', 'getattr(source,', 'name,', 'None)', 'if', 'callable(property):', 'return', 'property()', 'return', 'property'] | 941,933 |
wandb/wandb | executor.py | complete_abstract_value | complete_abstract_value | Complete an value of an abstract type by determining the runtime type of that value, then completing based on that type. | [
"Complete",
"an",
"value",
"of",
"an",
"abstract",
"type",
"by",
"determining",
"the",
"runtime",
"type",
"of",
"that",
"value,",
"then",
"completing",
"based",
"on",
"that",
"type."
] | def complete_abstract_value(exe_context, return_type, field_asts, info, result):
runtime_type = None
if isinstance(return_type, (GraphQLInterfaceType, GraphQLUnionType)):
if return_type.resolve_type:
runtime_type = return_type.resolve_type(result, exe_context.context_value, info)
els... | ['def', 'complete_abstract_value(exe_context,', 'return_type,', 'field_asts,', 'info,', 'result):', 'runtime_type', '=', 'None', 'if', 'isinstance(return_type,', '(GraphQLInterfaceType,', 'GraphQLUnionType)):', 'if', 'return_type.resolve_type:', 'runtime_type', '=', 'return_type.resolve_type(result,', 'exe_context.cont... | 941,937 |
wandb/wandb | values.py | get_variable_value | get_variable_value | Given a variable definition, and any value of input, return a value which adheres to the variable definition, or throw an error. | [
"Given",
"a",
"variable",
"definition,",
"and",
"any",
"value",
"of",
"input,",
"return",
"a",
"value",
"which",
"adheres",
"to",
"the",
"variable",
"definition,",
"or",
"throw",
"an",
"error."
] | def get_variable_value(schema, definition_ast, input):
type = type_from_ast(schema, definition_ast.type)
variable = definition_ast.variable
if not type or not is_input_type(type):
raise GraphQLError('Variable "${}" expected value of type "{}" which cannot be used as an input type.'.format(variable.n... | ['def', 'get_variable_value(schema,', 'definition_ast,', 'input):', 'type', '=', 'type_from_ast(schema,', 'definition_ast.type)', 'variable', '=', 'definition_ast.variable', 'if', 'not', 'type', 'or', 'not', 'is_input_type(type):', 'raise', "GraphQLError('Variable", '"${}"', 'expected', 'value', 'of', 'type', '"{}"', '... | 941,942 |
wandb/wandb | values.py | coerce_value | coerce_value | Given a type and any value, return a runtime value coerced to match the type. | [
"Given",
"a",
"type",
"and",
"any",
"value,",
"return",
"a",
"runtime",
"value",
"coerced",
"to",
"match",
"the",
"type."
] | def coerce_value(type, value):
if isinstance(type, GraphQLNonNull):
return coerce_value(type.of_type, value)
if value is None:
return None
if isinstance(type, GraphQLList):
item_type = type.of_type
if not isinstance(value, str) and isinstance(value, Iterable):
ret... | ['def', 'coerce_value(type,', 'value):', 'if', 'isinstance(type,', 'GraphQLNonNull):', 'return', 'coerce_value(type.of_type,', 'value)', 'if', 'value', 'is', 'None:', 'return', 'None', 'if', 'isinstance(type,', 'GraphQLList):', 'item_type', '=', 'type.of_type', 'if', 'not', 'isinstance(value,', 'str)', 'and', 'isinstan... | 941,943 |
wandb/wandb | assert_valid_name.py | assert_valid_name | assert_valid_name | Helper to assert that provided names are valid. | [
"Helper",
"to",
"assert",
"that",
"provided",
"names",
"are",
"valid."
] | def assert_valid_name(name):
assert COMPILED_NAME_PATTERN.match(name), 'Names must match /{}/ but "{}" does not.'.format(NAME_PATTERN, name) | ['def', 'assert_valid_name(name):', 'assert', 'COMPILED_NAME_PATTERN.match(name),', "'Names", 'must', 'match', '/{}/', 'but', '"{}"', 'does', "not.'.format(NAME_PATTERN,", 'name)'] | 941,957 |
wandb/wandb | ast_to_code.py | ast_to_code | ast_to_code | Converts an ast into a python code representation of the AST. | [
"Converts",
"an",
"ast",
"into",
"a",
"python",
"code",
"representation",
"of",
"the",
"AST."
] | def ast_to_code(ast, indent=0):
code = []
def append(line):
code.append(' ' * indent + line)
if isinstance(ast, Node):
append('ast.{}('.format(ast.__class__.__name__))
indent += 1
for (i, k) in enumerate(ast._fields, 1):
v = getattr(ast, k)
append(... | ['def', 'ast_to_code(ast,', 'indent=0):', 'code', '=', '[]', 'def', 'append(line):', "code.append('", "'", '*', 'indent', '+', 'line)', 'if', 'isinstance(ast,', 'Node):', "append('ast.{}('.format(ast.__class__.__name__))", 'indent', '+=', '1', 'for', '(i,', 'k)', 'in', 'enumerate(ast._fields,', '1):', 'v', '=', 'getatt... | 941,958 |
wandb/wandb | get_field_def.py | get_field_def | get_field_def | Not exactly the same as the executor's definition of get_field_def, in this statically evaluated environment we do not always have an Object type, and need to handle Interface and Union types. | [
"Not",
"exactly",
"the",
"same",
"as",
"the",
"executor's",
"definition",
"of",
"get_field_def,",
"in",
"this",
"statically",
"evaluated",
"environment",
"we",
"do",
"not",
"always",
"have",
"an",
"Object",
"type,",
"and",
"need",
"to",
"handle",
"Interface",
... | def get_field_def(schema, parent_type, field_ast):
name = field_ast.name.value
if name == '__schema' and schema.get_query_type() == parent_type:
return SchemaMetaFieldDef
elif name == '__type' and schema.get_query_type() == parent_type:
return TypeMetaFieldDef
elif name == '__typename' a... | ['def', 'get_field_def(schema,', 'parent_type,', 'field_ast):', 'name', '=', 'field_ast.name.value', 'if', 'name', '==', "'__schema'", 'and', 'schema.get_query_type()', '==', 'parent_type:', 'return', 'SchemaMetaFieldDef', 'elif', 'name', '==', "'__type'", 'and', 'schema.get_query_type()', '==', 'parent_type:', 'return... | 941,960 |
wandb/wandb | quoted_or_list.py | quoted_or_list | quoted_or_list | Given [ A, B, C ] return '"A", "B" or "C"'. | [
"Given",
"[",
"A,",
"B,",
"C",
"]",
"return",
"'\"A\",",
"\"B\"",
"or",
"\"C\"'."
] | def quoted_or_list(items):
selected = items[:MAX_LENGTH]
quoted_items = ('"{}"'.format(t) for t in selected)
def quoted_or_text(text, quoted_and_index):
index = quoted_and_index[0]
quoted_item = quoted_and_index[1]
text += (', ' if len(selected) > 2 and (not index == len(selected) -... | ['def', 'quoted_or_list(items):', 'selected', '=', 'items[:MAX_LENGTH]', 'quoted_items', '=', '(\'"{}"\'.format(t)', 'for', 't', 'in', 'selected)', 'def', 'quoted_or_text(text,', 'quoted_and_index):', 'index', '=', 'quoted_and_index[0]', 'quoted_item', '=', 'quoted_and_index[1]', 'text', '+=', "(',", "'", 'if', 'len(se... | 941,962 |
wandb/wandb | suggestion_list.py | suggestion_list | suggestion_list | Given an invalid input string and a list of valid options, returns a filtered list of valid options sorted based on their similarity with the input. | [
"Given",
"an",
"invalid",
"input",
"string",
"and",
"a",
"list",
"of",
"valid",
"options,",
"returns",
"a",
"filtered",
"list",
"of",
"valid",
"options",
"sorted",
"based",
"on",
"their",
"similarity",
"with",
"the",
"input."
] | def suggestion_list(inp, options):
options_by_distance = OrderedDict()
input_threshold = len(inp) / 2
for option in options:
distance = lexical_distance(inp, option)
threshold = max(input_threshold, len(option) / 2, 1)
if distance <= threshold:
options_by_distance[option]... | ['def', 'suggestion_list(inp,', 'options):', 'options_by_distance', '=', 'OrderedDict()', 'input_threshold', '=', 'len(inp)', '/', '2', 'for', 'option', 'in', 'options:', 'distance', '=', 'lexical_distance(inp,', 'option)', 'threshold', '=', 'max(input_threshold,', 'len(option)', '/', '2,', '1)', 'if', 'distance', '<='... | 941,963 |
wandb/wandb | value_from_ast.py | value_from_ast | value_from_ast | Given a type and a value AST node known to match this type, build a runtime value. | [
"Given",
"a",
"type",
"and",
"a",
"value",
"AST",
"node",
"known",
"to",
"match",
"this",
"type,",
"build",
"a",
"runtime",
"value."
] | def value_from_ast(value_ast, type, variables=None):
if isinstance(type, GraphQLNonNull):
return value_from_ast(value_ast, type.of_type, variables)
if not value_ast:
return None
if isinstance(value_ast, ast.Variable):
variable_name = value_ast.name.value
if not variables or v... | ['def', 'value_from_ast(value_ast,', 'type,', 'variables=None):', 'if', 'isinstance(type,', 'GraphQLNonNull):', 'return', 'value_from_ast(value_ast,', 'type.of_type,', 'variables)', 'if', 'not', 'value_ast:', 'return', 'None', 'if', 'isinstance(value_ast,', 'ast.Variable):', 'variable_name', '=', 'value_ast.name.value'... | 941,965 |
wandb/wandb | fields_on_correct_type.py | get_suggested_field_names | get_suggested_field_names | For the field name provided, determine if there are any similar field names that may be the result of a typo. | [
"For",
"the",
"field",
"name",
"provided,",
"determine",
"if",
"there",
"are",
"any",
"similar",
"field",
"names",
"that",
"may",
"be",
"the",
"result",
"of",
"a",
"typo."
] | def get_suggested_field_names(schema, graphql_type, field_name):
if isinstance(graphql_type, (GraphQLInterfaceType, GraphQLObjectType)):
possible_field_names = list(graphql_type.fields.keys())
return suggestion_list(field_name, possible_field_names)
return [] | ['def', 'get_suggested_field_names(schema,', 'graphql_type,', 'field_name):', 'if', 'isinstance(graphql_type,', '(GraphQLInterfaceType,', 'GraphQLObjectType)):', 'possible_field_names', '=', 'list(graphql_type.fields.keys())', 'return', 'suggestion_list(field_name,', 'possible_field_names)', 'return', '[]'] | 941,967 |
wandb/wandb | test_spec.py | test_3_2_1 | test_3_2_1 | Test that the arguments to 'then' are optional. | [
"Test",
"that",
"the",
"arguments",
"to",
"'then'",
"are",
"optional."
] | def test_3_2_1():
p1 = Promise()
p2 = p1.then()
p3 = Promise()
p4 = p3.then()
p1.do_resolve(5)
p3.do_reject(Exception('How dare you!')) | ['def', 'test_3_2_1():', 'p1', '=', 'Promise()', 'p2', '=', 'p1.then()', 'p3', '=', 'Promise()', 'p4', '=', 'p3.then()', 'p1.do_resolve(5)', "p3.do_reject(Exception('How", 'dare', "you!'))"] | 941,969 |
wandb/wandb | test_spec.py | test_3_2_1_1 | test_3_2_1_1 | That that the first argument to 'then' is ignored if it is not a function. | [
"That",
"that",
"the",
"first",
"argument",
"to",
"'then'",
"is",
"ignored",
"if",
"it",
"is",
"not",
"a",
"function."
] | def test_3_2_1_1():
results = {}
nonFunctions = [None, False, 5, {}, []]
def testNonFunction(nonFunction):
def foo(k, r):
results[k] = r
p1 = Promise.reject(Exception('Error: ' + str(nonFunction)))
p2 = p1.then(nonFunction, lambda r: foo(str(nonFunction), r))
p2... | ['def', 'test_3_2_1_1():', 'results', '=', '{}', 'nonFunctions', '=', '[None,', 'False,', '5,', '{},', '[]]', 'def', 'testNonFunction(nonFunction):', 'def', 'foo(k,', 'r):', 'results[k]', '=', 'r', 'p1', '=', "Promise.reject(Exception('Error:", "'", '+', 'str(nonFunction)))', 'p2', '=', 'p1.then(nonFunction,', 'lambda'... | 941,970 |
wandb/wandb | test_spec.py | test_3_2_1_2 | test_3_2_1_2 | That that the second argument to 'then' is ignored if it is not a function. | [
"That",
"that",
"the",
"second",
"argument",
"to",
"'then'",
"is",
"ignored",
"if",
"it",
"is",
"not",
"a",
"function."
] | def test_3_2_1_2():
results = {}
nonFunctions = [None, False, 5, {}, []]
def testNonFunction(nonFunction):
def foo(k, r):
results[k] = r
p1 = Promise.resolve('Error: ' + str(nonFunction))
p2 = p1.then(lambda r: foo(str(nonFunction), r), nonFunction)
p2._wait()
... | ['def', 'test_3_2_1_2():', 'results', '=', '{}', 'nonFunctions', '=', '[None,', 'False,', '5,', '{},', '[]]', 'def', 'testNonFunction(nonFunction):', 'def', 'foo(k,', 'r):', 'results[k]', '=', 'r', 'p1', '=', "Promise.resolve('Error:", "'", '+', 'str(nonFunction))', 'p2', '=', 'p1.then(lambda', 'r:', 'foo(str(nonFuncti... | 941,971 |
wandb/wandb | test_spec.py | test_3_2_2_1 | test_3_2_2_1 | The first argument to 'then' must be called when a promise is fulfilled. | [
"The",
"first",
"argument",
"to",
"'then'",
"must",
"be",
"called",
"when",
"a",
"promise",
"is",
"fulfilled."
] | def test_3_2_2_1():
c = Counter()
def check(v, c):
assert v == 5
c.tick()
p1 = Promise.resolve(5)
p2 = p1.then(lambda v: check(v, c))
p2._wait()
assert 1 == c.value() | ['def', 'test_3_2_2_1():', 'c', '=', 'Counter()', 'def', 'check(v,', 'c):', 'assert', 'v', '==', '5', 'c.tick()', 'p1', '=', 'Promise.resolve(5)', 'p2', '=', 'p1.then(lambda', 'v:', 'check(v,', 'c))', 'p2._wait()', 'assert', '1', '==', 'c.value()'] | 941,972 |
wandb/wandb | test_spec.py | test_3_2_3_2 | test_3_2_3_2 | Make sure callbacks are never called more than once. | [
"Make",
"sure",
"callbacks",
"are",
"never",
"called",
"more",
"than",
"once."
] | def test_3_2_3_2():
c = Counter()
p1 = Promise.reject(Exception('Error'))
p2 = p1.then(None, lambda v: c.tick())
p2._wait()
try:
p1.do_reject(Exception('Error'))
assert False
except AssertionError:
pass
assert 1 == c.value() | ['def', 'test_3_2_3_2():', 'c', '=', 'Counter()', 'p1', '=', "Promise.reject(Exception('Error'))", 'p2', '=', 'p1.then(None,', 'lambda', 'v:', 'c.tick())', 'p2._wait()', 'try:', "p1.do_reject(Exception('Error'))", 'assert', 'False', 'except', 'AssertionError:', 'pass', 'assert', '1', '==', 'c.value()'] | 941,976 |
wandb/wandb | test_spec.py | test_3_2_5_1_when | test_3_2_5_1_when | Then can be called multiple times on the same promise and callbacks must be called in the order of the then calls. | [
"Then",
"can",
"be",
"called",
"multiple",
"times",
"on",
"the",
"same",
"promise",
"and",
"callbacks",
"must",
"be",
"called",
"in",
"the",
"order",
"of",
"the",
"then",
"calls."
] | def test_3_2_5_1_when():
def add(l, v):
l.append(v)
p1 = Promise.resolve(2)
order = []
p2 = p1.then(lambda v: add(order, 'p2'))
p3 = p1.then(lambda v: add(order, 'p3'))
p2._wait()
p3._wait()
assert 2 == len(order)
assert 'p2' == order[0]
assert 'p3' == order[1] | ['def', 'test_3_2_5_1_when():', 'def', 'add(l,', 'v):', 'l.append(v)', 'p1', '=', 'Promise.resolve(2)', 'order', '=', '[]', 'p2', '=', 'p1.then(lambda', 'v:', 'add(order,', "'p2'))", 'p3', '=', 'p1.then(lambda', 'v:', 'add(order,', "'p3'))", 'p2._wait()', 'p3._wait()', 'assert', '2', '==', 'len(order)', 'assert', "'p2'... | 941,978 |
wandb/wandb | test_spec.py | test_3_2_6_1 | test_3_2_6_1 | Promises returned by then must be fulfilled when the promise they are chained from is fulfilled IF the fulfillment value is not a promise. | [
"Promises",
"returned",
"by",
"then",
"must",
"be",
"fulfilled",
"when",
"the",
"promise",
"they",
"are",
"chained",
"from",
"is",
"fulfilled",
"IF",
"the",
"fulfillment",
"value",
"is",
"not",
"a",
"promise."
] | def test_3_2_6_1():
p1 = Promise.resolve(5)
pf = p1.then(lambda v: v * v)
assert pf.get() == 25
p2 = Promise.reject(Exception('Error'))
pr = p2.then(None, lambda r: 5)
assert 5 == pr.get() | ['def', 'test_3_2_6_1():', 'p1', '=', 'Promise.resolve(5)', 'pf', '=', 'p1.then(lambda', 'v:', 'v', '*', 'v)', 'assert', 'pf.get()', '==', '25', 'p2', '=', "Promise.reject(Exception('Error'))", 'pr', '=', 'p2.then(None,', 'lambda', 'r:', '5)', 'assert', '5', '==', 'pr.get()'] | 941,982 |
wandb/wandb | test_spec.py | test_3_2_6_2_when | test_3_2_6_2_when | Promises returned by then must be rejected when any of their callbacks throw an exception. | [
"Promises",
"returned",
"by",
"then",
"must",
"be",
"rejected",
"when",
"any",
"of",
"their",
"callbacks",
"throw",
"an",
"exception."
] | def test_3_2_6_2_when():
def fail(v):
raise AssertionError('Exception Message')
p1 = Promise.resolve(5)
pf = p1.then(fail)
pf._wait()
assert pf.is_rejected
assert_exception(pf.reason, AssertionError, 'Exception Message')
p2 = Promise.reject(Exception('Error'))
pr = p2.then(None,... | ['def', 'test_3_2_6_2_when():', 'def', 'fail(v):', 'raise', "AssertionError('Exception", "Message')", 'p1', '=', 'Promise.resolve(5)', 'pf', '=', 'p1.then(fail)', 'pf._wait()', 'assert', 'pf.is_rejected', 'assert_exception(pf.reason,', 'AssertionError,', "'Exception", "Message')", 'p2', '=', "Promise.reject(Exception('... | 941,983 |
wandb/wandb | test_spec.py | test_3_2_6_4_fulfilled | test_3_2_6_4_fulfilled | Handles the case where the arguments to then are values, not functions or promises. | [
"Handles",
"the",
"case",
"where",
"the",
"arguments",
"to",
"then",
"are",
"values,",
"not",
"functions",
"or",
"promises."
] | def test_3_2_6_4_fulfilled():
p1 = Promise()
p1.do_resolve(10)
p2 = p1.then(5)
assert 10 == p1.get()
p2._wait()
assert p2.is_fulfilled
assert 10 == p2.get() | ['def', 'test_3_2_6_4_fulfilled():', 'p1', '=', 'Promise()', 'p1.do_resolve(10)', 'p2', '=', 'p1.then(5)', 'assert', '10', '==', 'p1.get()', 'p2._wait()', 'assert', 'p2.is_fulfilled', 'assert', '10', '==', 'p2.get()'] | 941,990 |
wandb/wandb | dataloader.py | dispatch_queue | dispatch_queue | Given the current state of a Loader instance, perform a batch load from its current queue. | [
"Given",
"the",
"current",
"state",
"of",
"a",
"Loader",
"instance,",
"perform",
"a",
"batch",
"load",
"from",
"its",
"current",
"queue."
] | def dispatch_queue(loader):
queue = loader._queue
loader._queue = []
max_batch_size = loader.max_batch_size
if max_batch_size and max_batch_size < len(queue):
chunks = get_chunks(queue, max_batch_size)
for chunk in chunks:
dispatch_queue_batch(loader, chunk)
else:
... | ['def', 'dispatch_queue(loader):', 'queue', '=', 'loader._queue', 'loader._queue', '=', '[]', 'max_batch_size', '=', 'loader.max_batch_size', 'if', 'max_batch_size', 'and', 'max_batch_size', '<', 'len(queue):', 'chunks', '=', 'get_chunks(queue,', 'max_batch_size)', 'for', 'chunk', 'in', 'chunks:', 'dispatch_queue_batch... | 941,997 |
wandb/wandb | dataloader.py | failed_dispatch | failed_dispatch | Do not cache individual loads if the entire batch dispatch fails, but still reject each request so they do not hang. | [
"Do",
"not",
"cache",
"individual",
"loads",
"if",
"the",
"entire",
"batch",
"dispatch",
"fails,",
"but",
"still",
"reject",
"each",
"request",
"so",
"they",
"do",
"not",
"hang."
] | def failed_dispatch(loader, queue, error):
for l in queue:
loader.clear(l.key)
l.reject(error) | ['def', 'failed_dispatch(loader,', 'queue,', 'error):', 'for', 'l', 'in', 'queue:', 'loader.clear(l.key)', 'l.reject(error)'] | 941,998 |
wandb/wandb | dataloader.py | DataLoader.load | load | Loads a key, returning a `Promise` for the value represented by that key. | [
"Loads",
"a",
"key,",
"returning",
"a",
"`Promise`",
"for",
"the",
"value",
"represented",
"by",
"that",
"key."
] | def load(self, key=None):
if key is None:
raise TypeError(('The loader.load() function must be called with a value,' + 'but got: {}.').format(key))
cache_key = self.get_cache_key(key)
if self.cache:
cached_promise = self._promise_cache.get(cache_key)
if cached_promise:
re... | ['def', 'load(self,', 'key=None):', 'if', 'key', 'is', 'None:', 'raise', "TypeError(('The", 'loader.load()', 'function', 'must', 'be', 'called', 'with', 'a', "value,'", '+', "'but", 'got:', "{}.').format(key))", 'cache_key', '=', 'self.get_cache_key(key)', 'if', 'self.cache:', 'cached_promise', '=', 'self._promise_cach... | 941,999 |
wandb/wandb | promise.py | Promise.is_thenable | is_thenable | A utility function to determine if the specified object is a promise using "duck typing". | [
"A",
"utility",
"function",
"to",
"determine",
"if",
"the",
"specified",
"object",
"is",
"a",
"promise",
"using",
"\"duck",
"typing\"."
] | def is_thenable(cls, obj):
_type = obj.__class__
if obj is None or _type in BASE_TYPES:
return False
return issubclass(_type, Promise) or iscoroutine(obj) or is_future_like(_type) | ['def', 'is_thenable(cls,', 'obj):', '_type', '=', 'obj.__class__', 'if', 'obj', 'is', 'None', 'or', '_type', 'in', 'BASE_TYPES:', 'return', 'False', 'return', 'issubclass(_type,', 'Promise)', 'or', 'iscoroutine(obj)', 'or', 'is_future_like(_type)'] | 942,011 |
wandb/wandb | version.py | get_version | get_version | Returns a PEP 440-compliant version number from VERSION. | [
"Returns",
"a",
"PEP",
"440-compliant",
"version",
"number",
"from",
"VERSION."
] | def get_version(version=None):
version = get_complete_version(version)
main = get_main_version(version)
sub = ''
if version[3] == 'alpha' and version[4] == 0:
git_changeset = get_git_changeset()
if git_changeset:
sub = '.dev%s' % git_changeset
else:
sub = ... | ['def', 'get_version(version=None):', 'version', '=', 'get_complete_version(version)', 'main', '=', 'get_main_version(version)', 'sub', '=', "''", 'if', 'version[3]', '==', "'alpha'", 'and', 'version[4]', '==', '0:', 'git_changeset', '=', 'get_git_changeset()', 'if', 'git_changeset:', 'sub', '=', "'.dev%s'", '%', 'git_... | 942,012 |
wandb/wandb | kqueue.py | is_deleted | is_deleted | Determines whether the given kevent represents deletion. | [
"Determines",
"whether",
"the",
"given",
"kevent",
"represents",
"deletion."
] | def is_deleted(kev):
return kev.fflags & select.KQ_NOTE_DELETE | ['def', 'is_deleted(kev):', 'return', 'kev.fflags', '&', 'select.KQ_NOTE_DELETE'] | 942,165 |
wandb/wandb | __init__.py | BaseThread.stop | stop | Signals the thread to stop. | [
"Signals",
"the",
"thread",
"to",
"stop."
] | def stop(self):
self._stopped_event.set()
self.on_thread_stop() | ['def', 'stop(self):', 'self._stopped_event.set()', 'self.on_thread_stop()'] | 942,223 |
salesforce/warp-drive | tag_continuous.py | TagContinuous.generate_observation | generate_observation | Generate and return the observations for every agent. | [
"Generate",
"and",
"return",
"the",
"observations",
"for",
"every",
"agent."
] | def generate_observation(self):
obs = {}
normalized_global_obs = None
for feature in [(_LOC_X, self.grid_diagonal), (_LOC_Y, self.grid_diagonal), (_SP, self.max_speed + self.eps), (_ACC, self.max_speed + self.eps), (_DIR, 2 * np.pi)]:
if normalized_global_obs is None:
normalized_global_o... | ['def', 'generate_observation(self):', 'obs', '=', '{}', 'normalized_global_obs', '=', 'None', 'for', 'feature', 'in', '[(_LOC_X,', 'self.grid_diagonal),', '(_LOC_Y,', 'self.grid_diagonal),', '(_SP,', 'self.max_speed', '+', 'self.eps),', '(_ACC,', 'self.max_speed', '+', 'self.eps),', '(_DIR,', '2', '*', 'np.pi)]:', 'if... | 942,230 |
salesforce/warp-drive | tag_continuous.py | TagContinuous.compute_reward | compute_reward | Compute and return the rewards for each agent. | [
"Compute",
"and",
"return",
"the",
"rewards",
"for",
"each",
"agent."
] | def compute_reward(self):
rew = {agent_id: 0.0 for agent_id in range(self.num_agents)}
taggers_list = sorted(self.taggers)
if self.num_runners > 0:
runners_list = sorted(self.runners)
runner_locations_x = self.global_state[_LOC_X][self.timestep][runners_list]
tagger_locations_x = sel... | ['def', 'compute_reward(self):', 'rew', '=', '{agent_id:', '0.0', 'for', 'agent_id', 'in', 'range(self.num_agents)}', 'taggers_list', '=', 'sorted(self.taggers)', 'if', 'self.num_runners', '>', '0:', 'runners_list', '=', 'sorted(self.runners)', 'runner_locations_x', '=', 'self.global_state[_LOC_X][self.timestep][runner... | 942,231 |
salesforce/warp-drive | test_env_training.py | launch_process | launch_process | Run a Python function on a separate process. | [
"Run",
"a",
"Python",
"function",
"on",
"a",
"separate",
"process."
] | def launch_process(func, kwargs):
p = ProcessWrapper(target=func, kwargs=kwargs)
p.start()
p.join()
if p.exception:
raise p.exception | ['def', 'launch_process(func,', 'kwargs):', 'p', '=', 'ProcessWrapper(target=func,', 'kwargs=kwargs)', 'p.start()', 'p.join()', 'if', 'p.exception:', 'raise', 'p.exception'] | 942,234 |
salesforce/warp-drive | env_cpu_gpu_consistency_checker.py | generate_random_actions | generate_random_actions | Generate random actions for each agent and each env. | [
"Generate",
"random",
"actions",
"for",
"each",
"agent",
"and",
"each",
"env."
] | def generate_random_actions(env, num_envs, seed=None):
agent_ids = list(env.action_space.keys())
np_random = np.random
if seed is not None:
np_random.seed(seed)
return [{agent_id: _generate_random_actions_helper(env.action_space[agent_id], np_random) for agent_id in agent_ids} for _ in range(num... | ['def', 'generate_random_actions(env,', 'num_envs,', 'seed=None):', 'agent_ids', '=', 'list(env.action_space.keys())', 'np_random', '=', 'np.random', 'if', 'seed', 'is', 'not', 'None:', 'np_random.seed(seed)', 'return', '[{agent_id:', '_generate_random_actions_helper(env.action_space[agent_id],', 'np_random)', 'for', '... | 942,235 |
salesforce/warp-drive | env_cpu_gpu_consistency_checker.py | EnvironmentCPUvsGPU.test_env_reset_and_step | test_env_reset_and_step | Perform consistency checks for the reset() and step() functions consistency_threshold_pct: consistency threshold as a percentage (defaults to 1%). | [
"Perform",
"consistency",
"checks",
"for",
"the",
"reset()",
"and",
"step()",
"functions",
"consistency_threshold_pct:",
"consistency",
"threshold",
"as",
"a",
"percentage",
"(defaults",
"to",
"1%)."
] | def test_env_reset_and_step(self, consistency_threshold_pct=1, seed=None):
for scenario in self.env_configs:
env_config = self.env_configs[scenario]
print(f'Performing the consistency checks for scenario: {scenario}...')
env_cpu = {}
obs_cpu = []
for env_id in range(self.num_... | ['def', 'test_env_reset_and_step(self,', 'consistency_threshold_pct=1,', 'seed=None):', 'for', 'scenario', 'in', 'self.env_configs:', 'env_config', '=', 'self.env_configs[scenario]', "print(f'Performing", 'the', 'consistency', 'checks', 'for', 'scenario:', "{scenario}...')", 'env_cpu', '=', '{}', 'obs_cpu', '=', '[]', ... | 942,236 |
salesforce/warp-drive | pytorch_lightning.py | WarpDriveModule.load_model_checkpoint | load_model_checkpoint | Load the model parameters if a checkpoint path is specified. | [
"Load",
"the",
"model",
"parameters",
"if",
"a",
"checkpoint",
"path",
"is",
"specified."
] | def load_model_checkpoint(self, ckpts_dict=None):
if ckpts_dict is None:
logging.info('Loading trainer model checkpoints from the run configuration.')
for policy in self.policies:
ckpt_filepath = self.config['policy'][policy]['model']['model_ckpt_filepath']
self._load_model_c... | ['def', 'load_model_checkpoint(self,', 'ckpts_dict=None):', 'if', 'ckpts_dict', 'is', 'None:', "logging.info('Loading", 'trainer', 'model', 'checkpoints', 'from', 'the', 'run', "configuration.')", 'for', 'policy', 'in', 'self.policies:', 'ckpt_filepath', '=', "self.config['policy'][policy]['model']['model_ckpt_filepath... | 942,277 |
salesforce/warp-drive | pytorch_lightning.py | WarpDriveModule.training_step | training_step | Carries out a single training step based on a batch of rollout data. | [
"Carries",
"out",
"a",
"single",
"training",
"step",
"based",
"on",
"a",
"batch",
"of",
"rollout",
"data."
] | def training_step(self, batch: Tuple[Tensor, Tensor, Tensor, Tensor], batch_idx=0, optimizer_idx=0):
assert batch_idx >= 0
assert optimizer_idx >= 0
if optimizer_idx == 0:
self.iters += 1
logging_flag = self.iters % self.config['saving']['metrics_log_freq'] == 0 or self.iters == self.num_iters -... | ['def', 'training_step(self,', 'batch:', 'Tuple[Tensor,', 'Tensor,', 'Tensor,', 'Tensor],', 'batch_idx=0,', 'optimizer_idx=0):', 'assert', 'batch_idx', '>=', '0', 'assert', 'optimizer_idx', '>=', '0', 'if', 'optimizer_idx', '==', '0:', 'self.iters', '+=', '1', 'logging_flag', '=', 'self.iters', '%', "self.config['savin... | 942,282 |
salesforce/warp-drive | param_scheduler.py | ParamScheduler.get_param_value | get_param_value | Obtain the parameter value at a desired timestep. | [
"Obtain",
"the",
"parameter",
"value",
"at",
"a",
"desired",
"timestep."
] | def get_param_value(self, timestep):
assert timestep >= 0
if self.type == 'constant':
param_value = self.schedule
elif self.type == 'piecewise_linear':
if timestep <= self.schedule[0][0]:
param_value = self.schedule[0][1]
elif timestep >= self.schedule[-1][0]:
... | ['def', 'get_param_value(self,', 'timestep):', 'assert', 'timestep', '>=', '0', 'if', 'self.type', '==', "'constant':", 'param_value', '=', 'self.schedule', 'elif', 'self.type', '==', "'piecewise_linear':", 'if', 'timestep', '<=', 'self.schedule[0][0]:', 'param_value', '=', 'self.schedule[0][1]', 'elif', 'timestep', '>... | 942,297 |
bmartacho/WASP | visualization.py | SegmentationVisualizer.id2color | id2color | Input: Int Array of shape [height, width] Containing Integers 0 <= i <= num_classes. | [
"Input:",
"Int",
"Array",
"of",
"shape",
"[height,",
"width]",
"Containing",
"Integers",
"0",
"<=",
"i",
"<=",
"num_classes."
] | def id2color(self, id_image, mask=None, ignore_idx=-100):
if mask is None:
if np.any(id_image != ignore_idx):
mask = id_image != ignore_idx
shape = id_image.shape
gt_out = np.zeros([shape[0], shape[1], self.chan], dtype=np.int32)
id_image
for (train_id, color) in enumerate(self.c... | ['def', 'id2color(self,', 'id_image,', 'mask=None,', 'ignore_idx=-100):', 'if', 'mask', 'is', 'None:', 'if', 'np.any(id_image', '!=', 'ignore_idx):', 'mask', '=', 'id_image', '!=', 'ignore_idx', 'shape', '=', 'id_image.shape', 'gt_out', '=', 'np.zeros([shape[0],', 'shape[1],', 'self.chan],', 'dtype=np.int32)', 'id_imag... | 942,320 |
huawei-noah/xingtian | broker_stats.py | BrokerStats.add_stats_recorder | add_stats_recorder | Add one stats recorder. | [
"Add",
"one",
"stats",
"recorder."
] | def add_stats_recorder(self, task_name, recorder):
self.tasks.update({task_name: recorder})
self.msg_delivers.update({task_name: recorder.msg_deliver}) | ['def', 'add_stats_recorder(self,', 'task_name,', 'recorder):', 'self.tasks.update({task_name:', 'recorder})', 'self.msg_delivers.update({task_name:', 'recorder.msg_deliver})'] | 962,197 |
huawei-noah/xingtian | broker_stats.py | BrokerStats.add_relation_task | add_relation_task | Record task in broker. | [
"Record",
"task",
"in",
"broker."
] | def add_relation_task(self, task):
self.relation_task.append(task) | ['def', 'add_relation_task(self,', 'task):', 'self.relation_task.append(task)'] | 962,198 |
huawei-noah/xingtian | evaluate_adapter.py | TesterManager.append_eval_queue | append_eval_queue | Append current train info into eval queue. | [
"Append",
"current",
"train",
"info",
"into",
"eval",
"queue."
] | def append_eval_queue(self, train_id, train_info):
self.record_station_buf.update({train_id: train_info}) | ['def', 'append_eval_queue(self,', 'train_id,', 'train_info):', 'self.record_station_buf.update({train_id:', 'train_info})'] | 962,200 |
huawei-noah/xingtian | evaluate_adapter.py | TesterManager.get_avail_node | get_avail_node | Get available test node. | [
"Get",
"available",
"test",
"node."
] | def get_avail_node(self):
if self.used_node:
min_key = min(self.used_node, key=self.used_node.get)
if self.used_node.get(min_key) < 1 or not self.avail_node:
return min_key
new_key = self.avail_node.pop(0)
self.send_create_evaluator_msg(*new_key)
self.used_node.update({new_ke... | ['def', 'get_avail_node(self):', 'if', 'self.used_node:', 'min_key', '=', 'min(self.used_node,', 'key=self.used_node.get)', 'if', 'self.used_node.get(min_key)', '<', '1', 'or', 'not', 'self.avail_node:', 'return', 'min_key', 'new_key', '=', 'self.avail_node.pop(0)', 'self.send_create_evaluator_msg(*new_key)', 'self.use... | 962,202 |
huawei-noah/xingtian | evaluate_adapter.py | EvalResultSummary.check_and_archive | check_and_archive | Check and archive api. | [
"Check",
"and",
"archive",
"api."
] | def check_and_archive(self):
deal_id = list()
single_record = dict()
for k in self._info:
if not self._train_id_end(k):
continue
single_record = self._analysis(k)
self._record_writer.writerow(single_record)
deal_id.append(k)
self._csv_open.flush()
for k in... | ['def', 'check_and_archive(self):', 'deal_id', '=', 'list()', 'single_record', '=', 'dict()', 'for', 'k', 'in', 'self._info:', 'if', 'not', 'self._train_id_end(k):', 'continue', 'single_record', '=', 'self._analysis(k)', 'self._record_writer.writerow(single_record)', 'deal_id.append(k)', 'self._csv_open.flush()', 'for'... | 962,204 |
huawei-noah/xingtian | evaluate_adapter.py | EvalResultSummary.processed_ids | processed_ids | Check have processed train ids. | [
"Check",
"have",
"processed",
"train",
"ids."
] | def processed_ids(self):
return self.processed_train_ids | ['def', 'processed_ids(self):', 'return', 'self.processed_train_ids'] | 962,205 |
huawei-noah/xingtian | learner.py | Learner.add_to_pbt | add_to_pbt | Add this lerner to population. | [
"Add",
"this",
"lerner",
"to",
"population."
] | def add_to_pbt(self, pbt_config, metric, weights):
self._pbt_aid = PbtAid(self.name, self.alg_para, pbt_config, metric, weights) | ['def', 'add_to_pbt(self,', 'pbt_config,', 'metric,', 'weights):', 'self._pbt_aid', '=', 'PbtAid(self.name,', 'self.alg_para,', 'pbt_config,', 'metric,', 'weights)'] | 962,211 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.