id int32 0 252k | repo stringlengths 7 55 | path stringlengths 4 127 | func_name stringlengths 1 88 | original_string stringlengths 75 19.8k | language stringclasses 1 value | code stringlengths 75 19.8k | code_tokens list | docstring stringlengths 3 17.3k | docstring_tokens list | sha stringlengths 40 40 | url stringlengths 87 242 |
|---|---|---|---|---|---|---|---|---|---|---|---|
30,000 | awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner._make_env_vars | def _make_env_vars(self, function):
"""Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars
"""
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
else:
LOG.debug("No environment variables found for function '%s'", name)
# This could either be in standard format, or a CloudFormation parameter file format.
#
# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}
# CloudFormation parameter file is {"Parameters": {key:value}}
for env_var_value in self.env_vars_values.values():
if not isinstance(env_var_value, dict):
reason = """
Environment variables must be in either CloudFormation parameter file
format or in {FunctionName: {key:value}} JSON pairs
"""
LOG.debug(reason)
raise OverridesNotWellDefinedError(reason)
if "Parameters" in self.env_vars_values:
LOG.debug("Environment variables overrides data is in CloudFormation parameter file format")
# CloudFormation parameter file format
overrides = self.env_vars_values["Parameters"]
else:
# Standard format
LOG.debug("Environment variables overrides data is standard format")
overrides = self.env_vars_values.get(name, None)
shell_env = os.environ
aws_creds = self.get_aws_creds()
return EnvironmentVariables(function.memory,
function.timeout,
function.handler,
variables=variables,
shell_env_values=shell_env,
override_values=overrides,
aws_creds=aws_creds) | python | def _make_env_vars(self, function):
"""Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars
"""
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
else:
LOG.debug("No environment variables found for function '%s'", name)
# This could either be in standard format, or a CloudFormation parameter file format.
#
# Standard format is {FunctionName: {key:value}, FunctionName: {key:value}}
# CloudFormation parameter file is {"Parameters": {key:value}}
for env_var_value in self.env_vars_values.values():
if not isinstance(env_var_value, dict):
reason = """
Environment variables must be in either CloudFormation parameter file
format or in {FunctionName: {key:value}} JSON pairs
"""
LOG.debug(reason)
raise OverridesNotWellDefinedError(reason)
if "Parameters" in self.env_vars_values:
LOG.debug("Environment variables overrides data is in CloudFormation parameter file format")
# CloudFormation parameter file format
overrides = self.env_vars_values["Parameters"]
else:
# Standard format
LOG.debug("Environment variables overrides data is standard format")
overrides = self.env_vars_values.get(name, None)
shell_env = os.environ
aws_creds = self.get_aws_creds()
return EnvironmentVariables(function.memory,
function.timeout,
function.handler,
variables=variables,
shell_env_values=shell_env,
override_values=overrides,
aws_creds=aws_creds) | [
"def",
"_make_env_vars",
"(",
"self",
",",
"function",
")",
":",
"name",
"=",
"function",
".",
"name",
"variables",
"=",
"None",
"if",
"function",
".",
"environment",
"and",
"isinstance",
"(",
"function",
".",
"environment",
",",
"dict",
")",
"and",
"\"Var... | Returns the environment variables configuration for this function
Parameters
----------
function : samcli.commands.local.lib.provider.Function
Lambda function to generate the configuration for
Returns
-------
samcli.local.lambdafn.env_vars.EnvironmentVariables
Environment variable configuration for this function
Raises
------
samcli.commands.local.lib.exceptions.OverridesNotWellDefinedError
If the environment dict is in the wrong format to process environment vars | [
"Returns",
"the",
"environment",
"variables",
"configuration",
"for",
"this",
"function"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L133-L193 |
30,001 | awslabs/aws-sam-cli | samcli/commands/local/lib/local_lambda.py | LocalLambdaRunner.get_aws_creds | def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None
"""
result = {}
# to pass command line arguments for region & profile to setup boto3 default session
if boto3.DEFAULT_SESSION:
session = boto3.DEFAULT_SESSION
else:
session = boto3.session.Session()
profile_name = session.profile_name if session else None
LOG.debug("Loading AWS credentials from session with profile '%s'", profile_name)
if not session:
return result
# Load the credentials from profile/environment
creds = session.get_credentials()
if not creds:
# If we were unable to load credentials, then just return empty. We will use the default
return result
# After loading credentials, region name might be available here.
if hasattr(session, 'region_name') and session.region_name:
result["region"] = session.region_name
# Only add the key, if its value is present
if hasattr(creds, 'access_key') and creds.access_key:
result["key"] = creds.access_key
if hasattr(creds, 'secret_key') and creds.secret_key:
result["secret"] = creds.secret_key
if hasattr(creds, 'token') and creds.token:
result["sessiontoken"] = creds.token
return result | python | def get_aws_creds(self):
"""
Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None
"""
result = {}
# to pass command line arguments for region & profile to setup boto3 default session
if boto3.DEFAULT_SESSION:
session = boto3.DEFAULT_SESSION
else:
session = boto3.session.Session()
profile_name = session.profile_name if session else None
LOG.debug("Loading AWS credentials from session with profile '%s'", profile_name)
if not session:
return result
# Load the credentials from profile/environment
creds = session.get_credentials()
if not creds:
# If we were unable to load credentials, then just return empty. We will use the default
return result
# After loading credentials, region name might be available here.
if hasattr(session, 'region_name') and session.region_name:
result["region"] = session.region_name
# Only add the key, if its value is present
if hasattr(creds, 'access_key') and creds.access_key:
result["key"] = creds.access_key
if hasattr(creds, 'secret_key') and creds.secret_key:
result["secret"] = creds.secret_key
if hasattr(creds, 'token') and creds.token:
result["sessiontoken"] = creds.token
return result | [
"def",
"get_aws_creds",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"# to pass command line arguments for region & profile to setup boto3 default session",
"if",
"boto3",
".",
"DEFAULT_SESSION",
":",
"session",
"=",
"boto3",
".",
"DEFAULT_SESSION",
"else",
":",
"ses... | Returns AWS credentials obtained from the shell environment or given profile
:return dict: A dictionary containing credentials. This dict has the structure
{"region": "", "key": "", "secret": "", "sessiontoken": ""}. If credentials could not be resolved,
this returns None | [
"Returns",
"AWS",
"credentials",
"obtained",
"from",
"the",
"shell",
"environment",
"or",
"given",
"profile"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/lib/local_lambda.py#L195-L238 |
30,002 | awslabs/aws-sam-cli | samcli/local/events/api_event.py | ContextIdentity.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuthenticationType": self.cognito_authentication_type,
"caller": self.caller,
"userAgent": self.user_agent,
"user": self.user,
"cognitoIdentityPoolId": self.cognito_identity_pool_id,
"cognitoAuthenticationProvider": self.cognito_authentication_provider,
"sourceIp": self.source_ip,
"accountId": self.account_id
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object
"""
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuthenticationType": self.cognito_authentication_type,
"caller": self.caller,
"userAgent": self.user_agent,
"user": self.user,
"cognitoIdentityPoolId": self.cognito_identity_pool_id,
"cognitoAuthenticationProvider": self.cognito_authentication_provider,
"sourceIp": self.source_ip,
"accountId": self.account_id
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"json_dict",
"=",
"{",
"\"apiKey\"",
":",
"self",
".",
"api_key",
",",
"\"userArn\"",
":",
"self",
".",
"user_arn",
",",
"\"cognitoAuthenticationType\"",
":",
"self",
".",
"cognito_authentication_type",
",",
"\"caller\"",... | Constructs an dictionary representation of the Identity Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"Identity",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L42-L60 |
30,003 | awslabs/aws-sam-cli | samcli/local/events/api_event.py | RequestContext.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object
"""
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_dict = {"resourceId": self.resource_id,
"apiId": self.api_id,
"resourcePath": self.resource_path,
"httpMethod": self.http_method,
"requestId": self.request_id,
"accountId": self.account_id,
"stage": self.stage,
"identity": identity_dict,
"extendedRequestId": self.extended_request_id,
"path": self.path
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object
"""
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_dict = {"resourceId": self.resource_id,
"apiId": self.api_id,
"resourcePath": self.resource_path,
"httpMethod": self.http_method,
"requestId": self.request_id,
"accountId": self.account_id,
"stage": self.stage,
"identity": identity_dict,
"extendedRequestId": self.extended_request_id,
"path": self.path
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"identity_dict",
"=",
"{",
"}",
"if",
"self",
".",
"identity",
":",
"identity_dict",
"=",
"self",
".",
"identity",
".",
"to_dict",
"(",
")",
"json_dict",
"=",
"{",
"\"resourceId\"",
":",
"self",
".",
"resource_id"... | Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"RequestContext",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L102-L124 |
30,004 | awslabs/aws-sam-cli | samcli/local/events/api_event.py | ApiGatewayLambdaEvent.to_dict | def to_dict(self):
"""
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object
"""
request_context_dict = {}
if self.request_context:
request_context_dict = self.request_context.to_dict()
json_dict = {"httpMethod": self.http_method,
"body": self.body if self.body else None,
"resource": self.resource,
"requestContext": request_context_dict,
"queryStringParameters": dict(self.query_string_params) if self.query_string_params else None,
"headers": dict(self.headers) if self.headers else None,
"pathParameters": dict(self.path_parameters) if self.path_parameters else None,
"stageVariables": dict(self.stage_variables) if self.stage_variables else None,
"path": self.path,
"isBase64Encoded": self.is_base_64_encoded
}
return json_dict | python | def to_dict(self):
"""
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object
"""
request_context_dict = {}
if self.request_context:
request_context_dict = self.request_context.to_dict()
json_dict = {"httpMethod": self.http_method,
"body": self.body if self.body else None,
"resource": self.resource,
"requestContext": request_context_dict,
"queryStringParameters": dict(self.query_string_params) if self.query_string_params else None,
"headers": dict(self.headers) if self.headers else None,
"pathParameters": dict(self.path_parameters) if self.path_parameters else None,
"stageVariables": dict(self.stage_variables) if self.stage_variables else None,
"path": self.path,
"isBase64Encoded": self.is_base_64_encoded
}
return json_dict | [
"def",
"to_dict",
"(",
"self",
")",
":",
"request_context_dict",
"=",
"{",
"}",
"if",
"self",
".",
"request_context",
":",
"request_context_dict",
"=",
"self",
".",
"request_context",
".",
"to_dict",
"(",
")",
"json_dict",
"=",
"{",
"\"httpMethod\"",
":",
"s... | Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON
:return: dict representing the object | [
"Constructs",
"an",
"dictionary",
"representation",
"of",
"the",
"ApiGatewayLambdaEvent",
"Object",
"to",
"be",
"used",
"in",
"serializing",
"to",
"JSON"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/events/api_event.py#L179-L201 |
30,005 | awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.is_docker_reachable | def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
return True
# When Docker is not installed, a request.exceptions.ConnectionError is thrown.
except (docker.errors.APIError, requests.exceptions.ConnectionError):
LOG.debug("Docker is not reachable", exc_info=True)
return False | python | def is_docker_reachable(self):
"""
Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise
"""
try:
self.docker_client.ping()
return True
# When Docker is not installed, a request.exceptions.ConnectionError is thrown.
except (docker.errors.APIError, requests.exceptions.ConnectionError):
LOG.debug("Docker is not reachable", exc_info=True)
return False | [
"def",
"is_docker_reachable",
"(",
"self",
")",
":",
"try",
":",
"self",
".",
"docker_client",
".",
"ping",
"(",
")",
"return",
"True",
"# When Docker is not installed, a request.exceptions.ConnectionError is thrown.",
"except",
"(",
"docker",
".",
"errors",
".",
"API... | Checks if Docker daemon is running. This is required for us to invoke the function locally
Returns
-------
bool
True, if Docker is available, False otherwise | [
"Checks",
"if",
"Docker",
"daemon",
"is",
"running",
".",
"This",
"is",
"required",
"for",
"us",
"to",
"invoke",
"the",
"function",
"locally"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L40-L57 |
30,006 | awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.run | def run(self, container, input_data=None, warm=False):
"""
Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server
"""
if warm:
raise ValueError("The facility to invoke warm container does not exist")
image_name = container.image
is_image_local = self.has_image(image_name)
# Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND
# c) We are asked to skip pulling the image
if (is_image_local and self.skip_pull_image) or image_name.startswith('samcli/lambda'):
LOG.info("Requested to skip pulling images ...\n")
else:
try:
self.pull_image(image_name)
except DockerImagePullFailedException:
if not is_image_local:
raise DockerImagePullFailedException(
"Could not find {} image locally and failed to pull it from docker.".format(image_name))
LOG.info(
"Failed to download a new %s image. Invoking with the already downloaded image.", image_name)
if not container.is_created():
# Create the container first before running.
# Create the container in appropriate Docker network
container.network_id = self.docker_network_id
container.create()
container.start(input_data=input_data) | python | def run(self, container, input_data=None, warm=False):
"""
Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server
"""
if warm:
raise ValueError("The facility to invoke warm container does not exist")
image_name = container.image
is_image_local = self.has_image(image_name)
# Skip Pulling a new image if: a) Image name is samcli/lambda OR b) Image is available AND
# c) We are asked to skip pulling the image
if (is_image_local and self.skip_pull_image) or image_name.startswith('samcli/lambda'):
LOG.info("Requested to skip pulling images ...\n")
else:
try:
self.pull_image(image_name)
except DockerImagePullFailedException:
if not is_image_local:
raise DockerImagePullFailedException(
"Could not find {} image locally and failed to pull it from docker.".format(image_name))
LOG.info(
"Failed to download a new %s image. Invoking with the already downloaded image.", image_name)
if not container.is_created():
# Create the container first before running.
# Create the container in appropriate Docker network
container.network_id = self.docker_network_id
container.create()
container.start(input_data=input_data) | [
"def",
"run",
"(",
"self",
",",
"container",
",",
"input_data",
"=",
"None",
",",
"warm",
"=",
"False",
")",
":",
"if",
"warm",
":",
"raise",
"ValueError",
"(",
"\"The facility to invoke warm container does not exist\"",
")",
"image_name",
"=",
"container",
".",... | Create and run a Docker container based on the given configuration.
:param samcli.local.docker.container.Container container: Container to create and run
:param input_data: Optional. Input data sent to the container through container's stdin.
:param bool warm: Indicates if an existing container can be reused. Defaults False ie. a new container will
be created for every request.
:raises DockerImagePullFailedException: If the Docker image was not available in the server | [
"Create",
"and",
"run",
"a",
"Docker",
"container",
"based",
"on",
"the",
"given",
"configuration",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L59-L98 |
30,007 | awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.pull_image | def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server
"""
stream_writer = stream or StreamWriter(sys.stderr)
try:
result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True)
except docker.errors.APIError as ex:
LOG.debug("Failed to download image with name %s", image_name)
raise DockerImagePullFailedException(str(ex))
# io streams, especially StringIO, work only with unicode strings
stream_writer.write(u"\nFetching {} Docker container image...".format(image_name))
# Each line contains information on progress of the pull. Each line is a JSON string
for _ in result_itr:
# For every line, print a dot to show progress
stream_writer.write(u'.')
stream_writer.flush()
# We are done. Go to the next line
stream_writer.write(u"\n") | python | def pull_image(self, image_name, stream=None):
"""
Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server
"""
stream_writer = stream or StreamWriter(sys.stderr)
try:
result_itr = self.docker_client.api.pull(image_name, stream=True, decode=True)
except docker.errors.APIError as ex:
LOG.debug("Failed to download image with name %s", image_name)
raise DockerImagePullFailedException(str(ex))
# io streams, especially StringIO, work only with unicode strings
stream_writer.write(u"\nFetching {} Docker container image...".format(image_name))
# Each line contains information on progress of the pull. Each line is a JSON string
for _ in result_itr:
# For every line, print a dot to show progress
stream_writer.write(u'.')
stream_writer.flush()
# We are done. Go to the next line
stream_writer.write(u"\n") | [
"def",
"pull_image",
"(",
"self",
",",
"image_name",
",",
"stream",
"=",
"None",
")",
":",
"stream_writer",
"=",
"stream",
"or",
"StreamWriter",
"(",
"sys",
".",
"stderr",
")",
"try",
":",
"result_itr",
"=",
"self",
".",
"docker_client",
".",
"api",
".",... | Ask Docker to pull the container image with given name.
Parameters
----------
image_name str
Name of the image
stream samcli.lib.utils.stream_writer.StreamWriter
Optional stream writer to output to. Defaults to stderr
Raises
------
DockerImagePullFailedException
If the Docker image was not available in the server | [
"Ask",
"Docker",
"to",
"pull",
"the",
"container",
"image",
"with",
"given",
"name",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L108-L142 |
30,008 | awslabs/aws-sam-cli | samcli/local/docker/manager.py | ContainerManager.has_image | def has_image(self, image_name):
"""
Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise
"""
try:
self.docker_client.images.get(image_name)
return True
except docker.errors.ImageNotFound:
return False | python | def has_image(self, image_name):
"""
Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise
"""
try:
self.docker_client.images.get(image_name)
return True
except docker.errors.ImageNotFound:
return False | [
"def",
"has_image",
"(",
"self",
",",
"image_name",
")",
":",
"try",
":",
"self",
".",
"docker_client",
".",
"images",
".",
"get",
"(",
"image_name",
")",
"return",
"True",
"except",
"docker",
".",
"errors",
".",
"ImageNotFound",
":",
"return",
"False"
] | Is the container image with given name available?
:param string image_name: Name of the image
:return bool: True, if image is available. False, otherwise | [
"Is",
"the",
"container",
"image",
"with",
"given",
"name",
"available?"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/manager.py#L144-L156 |
30,009 | awslabs/aws-sam-cli | samcli/commands/publish/command.py | do_cli | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in template metadata when provided in command input
if semantic_version and SERVERLESS_REPO_APPLICATION in template_data.get(METADATA, {}):
template_data.get(METADATA).get(SERVERLESS_REPO_APPLICATION)[SEMANTIC_VERSION] = semantic_version
try:
publish_output = publish_application(template_data)
click.secho("Publish Succeeded", fg="green")
click.secho(_gen_success_message(publish_output))
except InvalidS3UriError:
click.secho("Publish Failed", fg='red')
raise UserException(
"Your SAM template contains invalid S3 URIs. Please make sure that you have uploaded application "
"artifacts to S3 by packaging the template. See more details in {}".format(SAM_PACKAGE_DOC))
except ServerlessRepoError as ex:
click.secho("Publish Failed", fg='red')
LOG.debug("Failed to publish application to serverlessrepo", exc_info=True)
error_msg = '{}\nPlease follow the instructions in {}'.format(str(ex), SAM_PUBLISH_DOC)
raise UserException(error_msg)
application_id = publish_output.get('application_id')
_print_console_link(ctx.region, application_id) | python | def do_cli(ctx, template, semantic_version):
"""Publish the application based on command line inputs."""
try:
template_data = get_template_data(template)
except ValueError as ex:
click.secho("Publish Failed", fg='red')
raise UserException(str(ex))
# Override SemanticVersion in template metadata when provided in command input
if semantic_version and SERVERLESS_REPO_APPLICATION in template_data.get(METADATA, {}):
template_data.get(METADATA).get(SERVERLESS_REPO_APPLICATION)[SEMANTIC_VERSION] = semantic_version
try:
publish_output = publish_application(template_data)
click.secho("Publish Succeeded", fg="green")
click.secho(_gen_success_message(publish_output))
except InvalidS3UriError:
click.secho("Publish Failed", fg='red')
raise UserException(
"Your SAM template contains invalid S3 URIs. Please make sure that you have uploaded application "
"artifacts to S3 by packaging the template. See more details in {}".format(SAM_PACKAGE_DOC))
except ServerlessRepoError as ex:
click.secho("Publish Failed", fg='red')
LOG.debug("Failed to publish application to serverlessrepo", exc_info=True)
error_msg = '{}\nPlease follow the instructions in {}'.format(str(ex), SAM_PUBLISH_DOC)
raise UserException(error_msg)
application_id = publish_output.get('application_id')
_print_console_link(ctx.region, application_id) | [
"def",
"do_cli",
"(",
"ctx",
",",
"template",
",",
"semantic_version",
")",
":",
"try",
":",
"template_data",
"=",
"get_template_data",
"(",
"template",
")",
"except",
"ValueError",
"as",
"ex",
":",
"click",
".",
"secho",
"(",
"\"Publish Failed\"",
",",
"fg"... | Publish the application based on command line inputs. | [
"Publish",
"the",
"application",
"based",
"on",
"command",
"line",
"inputs",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L55-L83 |
30,010 | awslabs/aws-sam-cli | samcli/commands/publish/command.py | _gen_success_message | def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id = publish_output.get('application_id')
details = json.dumps(publish_output.get('details'), indent=2)
if CREATE_APPLICATION in publish_output.get('actions'):
return "Created new application with the following metadata:\n{}".format(details)
return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details) | python | def _gen_success_message(publish_output):
"""
Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message
"""
application_id = publish_output.get('application_id')
details = json.dumps(publish_output.get('details'), indent=2)
if CREATE_APPLICATION in publish_output.get('actions'):
return "Created new application with the following metadata:\n{}".format(details)
return 'The following metadata of application "{}" has been updated:\n{}'.format(application_id, details) | [
"def",
"_gen_success_message",
"(",
"publish_output",
")",
":",
"application_id",
"=",
"publish_output",
".",
"get",
"(",
"'application_id'",
")",
"details",
"=",
"json",
".",
"dumps",
"(",
"publish_output",
".",
"get",
"(",
"'details'",
")",
",",
"indent",
"=... | Generate detailed success message for published applications.
Parameters
----------
publish_output : dict
Output from serverlessrepo publish_application
Returns
-------
str
Detailed success message | [
"Generate",
"detailed",
"success",
"message",
"for",
"published",
"applications",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L86-L106 |
30,011 | awslabs/aws-sam-cli | samcli/commands/publish/command.py | _print_console_link | def _print_console_link(region, application_id):
"""
Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application
"""
if not region:
region = boto3.Session().region_name
console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace('/', '~'))
msg = "Click the link below to view your application in AWS console:\n{}".format(console_link)
click.secho(msg, fg="yellow") | python | def _print_console_link(region, application_id):
"""
Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application
"""
if not region:
region = boto3.Session().region_name
console_link = SERVERLESSREPO_CONSOLE_URL.format(region, application_id.replace('/', '~'))
msg = "Click the link below to view your application in AWS console:\n{}".format(console_link)
click.secho(msg, fg="yellow") | [
"def",
"_print_console_link",
"(",
"region",
",",
"application_id",
")",
":",
"if",
"not",
"region",
":",
"region",
"=",
"boto3",
".",
"Session",
"(",
")",
".",
"region_name",
"console_link",
"=",
"SERVERLESSREPO_CONSOLE_URL",
".",
"format",
"(",
"region",
","... | Print link for the application in AWS Serverless Application Repository console.
Parameters
----------
region : str
AWS region name
application_id : str
The Amazon Resource Name (ARN) of the application | [
"Print",
"link",
"for",
"the",
"application",
"in",
"AWS",
"Serverless",
"Application",
"Repository",
"console",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/publish/command.py#L109-L126 |
30,012 | awslabs/aws-sam-cli | samcli/local/apigw/service_error_responses.py | ServiceErrorResponses.lambda_failure_response | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | python | def lambda_failure_response(*args):
"""
Helper function to create a Lambda Failure Response
:return: A Flask Response
"""
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"def",
"lambda_failure_response",
"(",
"*",
"args",
")",
":",
"response_data",
"=",
"jsonify",
"(",
"ServiceErrorResponses",
".",
"_LAMBDA_FAILURE",
")",
"return",
"make_response",
"(",
"response_data",
",",
"ServiceErrorResponses",
".",
"HTTP_STATUS_CODE_502",
")"
] | Helper function to create a Lambda Failure Response
:return: A Flask Response | [
"Helper",
"function",
"to",
"create",
"a",
"Lambda",
"Failure",
"Response"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/service_error_responses.py#L16-L23 |
30,013 | awslabs/aws-sam-cli | samcli/local/apigw/service_error_responses.py | ServiceErrorResponses.lambda_not_found_response | def lambda_not_found_response(*args):
"""
Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | python | def lambda_not_found_response(*args):
"""
Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response
"""
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"def",
"lambda_not_found_response",
"(",
"*",
"args",
")",
":",
"response_data",
"=",
"jsonify",
"(",
"ServiceErrorResponses",
".",
"_NO_LAMBDA_INTEGRATION",
")",
"return",
"make_response",
"(",
"response_data",
",",
"ServiceErrorResponses",
".",
"HTTP_STATUS_CODE_502",
... | Constructs a Flask Response for when a Lambda function is not found for an endpoint
:return: a Flask Response | [
"Constructs",
"a",
"Flask",
"Response",
"for",
"when",
"a",
"Lambda",
"function",
"is",
"not",
"found",
"for",
"an",
"endpoint"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/apigw/service_error_responses.py#L26-L33 |
30,014 | awslabs/aws-sam-cli | samcli/lib/utils/progressbar.py | progressbar | def progressbar(length, label):
"""
Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar
"""
return click.progressbar(length=length, label=label, show_pos=True) | python | def progressbar(length, label):
"""
Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar
"""
return click.progressbar(length=length, label=label, show_pos=True) | [
"def",
"progressbar",
"(",
"length",
",",
"label",
")",
":",
"return",
"click",
".",
"progressbar",
"(",
"length",
"=",
"length",
",",
"label",
"=",
"label",
",",
"show_pos",
"=",
"True",
")"
] | Creates a progressbar
Parameters
----------
length int
Length of the ProgressBar
label str
Label to give to the progressbar
Returns
-------
click.progressbar
Progressbar | [
"Creates",
"a",
"progressbar"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/utils/progressbar.py#L8-L25 |
30,015 | awslabs/aws-sam-cli | samcli/cli/types.py | CfnParameterOverridesType._unquote | def _unquote(value):
r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
"""
if value and (value[0] == value[-1] == '"'):
# Remove quotes only if the string is wrapped in quotes
value = value.strip('"')
return value.replace("\\ ", " ").replace('\\"', '"') | python | def _unquote(value):
r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string
"""
if value and (value[0] == value[-1] == '"'):
# Remove quotes only if the string is wrapped in quotes
value = value.strip('"')
return value.replace("\\ ", " ").replace('\\"', '"') | [
"def",
"_unquote",
"(",
"value",
")",
":",
"if",
"value",
"and",
"(",
"value",
"[",
"0",
"]",
"==",
"value",
"[",
"-",
"1",
"]",
"==",
"'\"'",
")",
":",
"# Remove quotes only if the string is wrapped in quotes",
"value",
"=",
"value",
".",
"strip",
"(",
... | r"""
Removes wrapping double quotes and any '\ ' characters. They are usually added to preserve spaces when passing
value thru shell.
Examples
--------
>>> _unquote('val\ ue')
value
>>> _unquote("hel\ lo")
hello
Parameters
----------
value : str
Input to unquote
Returns
-------
Unquoted string | [
"r",
"Removes",
"wrapping",
"double",
"quotes",
"and",
"any",
"\\",
"characters",
".",
"They",
"are",
"usually",
"added",
"to",
"preserve",
"spaces",
"when",
"passing",
"value",
"thru",
"shell",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/cli/types.py#L42-L68 |
30,016 | awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | BaseLocalService.service_response | def service_response(body, headers, status_code):
"""
Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response
"""
response = Response(body)
response.headers = headers
response.status_code = status_code
return response | python | def service_response(body, headers, status_code):
"""
Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response
"""
response = Response(body)
response.headers = headers
response.status_code = status_code
return response | [
"def",
"service_response",
"(",
"body",
",",
"headers",
",",
"status_code",
")",
":",
"response",
"=",
"Response",
"(",
"body",
")",
"response",
".",
"headers",
"=",
"headers",
"response",
".",
"status_code",
"=",
"status_code",
"return",
"response"
] | Constructs a Flask Response from the body, headers, and status_code.
:param str body: Response body as a string
:param dict headers: headers for the response
:param int status_code: status_code for response
:return: Flask Response | [
"Constructs",
"a",
"Flask",
"Response",
"from",
"the",
"body",
"headers",
"and",
"status_code",
"."
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L84-L96 |
30,017 | awslabs/aws-sam-cli | samcli/local/services/base_local_service.py | LambdaOutputParser.get_lambda_output | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container
"""
# We only want the last line of stdout, because it's possible that
# the function may have written directly to stdout using
# System.out.println or similar, before docker-lambda output the result
stdout_data = stdout_stream.getvalue().rstrip(b'\n')
# Usually the output is just one line and contains response as JSON string, but if the Lambda function
# wrote anything directly to stdout, there will be additional lines. So just extract the last line as
# response and everything else as log output.
lambda_response = stdout_data
lambda_logs = None
last_line_position = stdout_data.rfind(b'\n')
if last_line_position >= 0:
# So there are multiple lines. Separate them out.
# Everything but the last line are logs
lambda_logs = stdout_data[:last_line_position]
# Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around
lambda_response = stdout_data[last_line_position:].strip()
lambda_response = lambda_response.decode('utf-8')
# When the Lambda Function returns an Error/Exception, the output is added to the stdout of the container. From
# our perspective, the container returned some value, which is not always true. Since the output is the only
# information we have, we need to inspect this to understand if the container returned a some data or raised an
# error
is_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)
return lambda_response, lambda_logs, is_lambda_user_error_response | python | def get_lambda_output(stdout_stream):
"""
This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container
"""
# We only want the last line of stdout, because it's possible that
# the function may have written directly to stdout using
# System.out.println or similar, before docker-lambda output the result
stdout_data = stdout_stream.getvalue().rstrip(b'\n')
# Usually the output is just one line and contains response as JSON string, but if the Lambda function
# wrote anything directly to stdout, there will be additional lines. So just extract the last line as
# response and everything else as log output.
lambda_response = stdout_data
lambda_logs = None
last_line_position = stdout_data.rfind(b'\n')
if last_line_position >= 0:
# So there are multiple lines. Separate them out.
# Everything but the last line are logs
lambda_logs = stdout_data[:last_line_position]
# Last line is Lambda response. Make sure to strip() so we get rid of extra whitespaces & newlines around
lambda_response = stdout_data[last_line_position:].strip()
lambda_response = lambda_response.decode('utf-8')
# When the Lambda Function returns an Error/Exception, the output is added to the stdout of the container. From
# our perspective, the container returned some value, which is not always true. Since the output is the only
# information we have, we need to inspect this to understand if the container returned a some data or raised an
# error
is_lambda_user_error_response = LambdaOutputParser.is_lambda_error_response(lambda_response)
return lambda_response, lambda_logs, is_lambda_user_error_response | [
"def",
"get_lambda_output",
"(",
"stdout_stream",
")",
":",
"# We only want the last line of stdout, because it's possible that",
"# the function may have written directly to stdout using",
"# System.out.println or similar, before docker-lambda output the result",
"stdout_data",
"=",
"stdout_s... | This method will extract read the given stream and return the response from Lambda function separated out
from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function
wrote directly to stdout using System.out.println or equivalents.
Parameters
----------
stdout_stream : io.BaseIO
Stream to fetch data from
Returns
-------
str
String data containing response from Lambda function
str
String data containng logs statements, if any.
bool
If the response is an error/exception from the container | [
"This",
"method",
"will",
"extract",
"read",
"the",
"given",
"stream",
"and",
"return",
"the",
"response",
"from",
"Lambda",
"function",
"separated",
"out",
"from",
"any",
"log",
"statements",
"it",
"might",
"have",
"outputted",
".",
"Logs",
"end",
"up",
"in... | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/services/base_local_service.py#L102-L149 |
30,018 | awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder.build | def build(self):
"""
Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string
"""
result = {}
for lambda_function in self._functions_to_build:
LOG.info("Building resource '%s'", lambda_function.name)
result[lambda_function.name] = self._build_function(lambda_function.name,
lambda_function.codeuri,
lambda_function.runtime)
return result | python | def build(self):
"""
Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string
"""
result = {}
for lambda_function in self._functions_to_build:
LOG.info("Building resource '%s'", lambda_function.name)
result[lambda_function.name] = self._build_function(lambda_function.name,
lambda_function.codeuri,
lambda_function.runtime)
return result | [
"def",
"build",
"(",
"self",
")",
":",
"result",
"=",
"{",
"}",
"for",
"lambda_function",
"in",
"self",
".",
"_functions_to_build",
":",
"LOG",
".",
"info",
"(",
"\"Building resource '%s'\"",
",",
"lambda_function",
".",
"name",
")",
"result",
"[",
"lambda_f... | Build the entire application
Returns
-------
dict
Returns the path to where each resource was built as a map of resource's LogicalId to the path string | [
"Build",
"the",
"entire",
"application"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L91-L110 |
30,019 | awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder.update_template | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template
"""
original_dir = os.path.dirname(original_template_path)
for logical_id, resource in template_dict.get("Resources", {}).items():
if logical_id not in built_artifacts:
# this resource was not built. So skip it
continue
# Artifacts are written relative to the template because it makes the template portable
# Ex: A CI/CD pipeline build stage could zip the output folder and pass to a
# package stage running on a different machine
artifact_relative_path = os.path.relpath(built_artifacts[logical_id], original_dir)
resource_type = resource.get("Type")
properties = resource.setdefault("Properties", {})
if resource_type == "AWS::Serverless::Function":
properties["CodeUri"] = artifact_relative_path
if resource_type == "AWS::Lambda::Function":
properties["Code"] = artifact_relative_path
return template_dict | python | def update_template(self, template_dict, original_template_path, built_artifacts):
"""
Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template
"""
original_dir = os.path.dirname(original_template_path)
for logical_id, resource in template_dict.get("Resources", {}).items():
if logical_id not in built_artifacts:
# this resource was not built. So skip it
continue
# Artifacts are written relative to the template because it makes the template portable
# Ex: A CI/CD pipeline build stage could zip the output folder and pass to a
# package stage running on a different machine
artifact_relative_path = os.path.relpath(built_artifacts[logical_id], original_dir)
resource_type = resource.get("Type")
properties = resource.setdefault("Properties", {})
if resource_type == "AWS::Serverless::Function":
properties["CodeUri"] = artifact_relative_path
if resource_type == "AWS::Lambda::Function":
properties["Code"] = artifact_relative_path
return template_dict | [
"def",
"update_template",
"(",
"self",
",",
"template_dict",
",",
"original_template_path",
",",
"built_artifacts",
")",
":",
"original_dir",
"=",
"os",
".",
"path",
".",
"dirname",
"(",
"original_template_path",
")",
"for",
"logical_id",
",",
"resource",
"in",
... | Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts
folder
Parameters
----------
template_dict
original_template_path : str
Path where the template file will be written to
built_artifacts : dict
Map of LogicalId of a resource to the path where the the built artifacts for this resource lives
Returns
-------
dict
Updated template | [
"Given",
"the",
"path",
"to",
"built",
"artifacts",
"update",
"the",
"template",
"to",
"point",
"appropriate",
"resource",
"CodeUris",
"to",
"the",
"artifacts",
"folder"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L112-L153 |
30,020 | awslabs/aws-sam-cli | samcli/lib/build/app_builder.py | ApplicationBuilder._build_function | def _build_function(self, function_name, codeuri, runtime):
"""
Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available
"""
# Create the arguments to pass to the builder
# Code is always relative to the given base directory.
code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve())
config = get_workflow_config(runtime, code_dir, self._base_dir)
# artifacts directory will be created by the builder
artifacts_dir = str(pathlib.Path(self._build_dir, function_name))
with osutils.mkdir_temp() as scratch_dir:
manifest_path = self._manifest_path_override or os.path.join(code_dir, config.manifest_name)
# By default prefer to build in-process for speed
build_method = self._build_function_in_process
if self._container_manager:
build_method = self._build_function_on_container
return build_method(config,
code_dir,
artifacts_dir,
scratch_dir,
manifest_path,
runtime) | python | def _build_function(self, function_name, codeuri, runtime):
"""
Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available
"""
# Create the arguments to pass to the builder
# Code is always relative to the given base directory.
code_dir = str(pathlib.Path(self._base_dir, codeuri).resolve())
config = get_workflow_config(runtime, code_dir, self._base_dir)
# artifacts directory will be created by the builder
artifacts_dir = str(pathlib.Path(self._build_dir, function_name))
with osutils.mkdir_temp() as scratch_dir:
manifest_path = self._manifest_path_override or os.path.join(code_dir, config.manifest_name)
# By default prefer to build in-process for speed
build_method = self._build_function_in_process
if self._container_manager:
build_method = self._build_function_on_container
return build_method(config,
code_dir,
artifacts_dir,
scratch_dir,
manifest_path,
runtime) | [
"def",
"_build_function",
"(",
"self",
",",
"function_name",
",",
"codeuri",
",",
"runtime",
")",
":",
"# Create the arguments to pass to the builder",
"# Code is always relative to the given base directory.",
"code_dir",
"=",
"str",
"(",
"pathlib",
".",
"Path",
"(",
"sel... | Given the function information, this method will build the Lambda function. Depending on the configuration
it will either build the function in process or by spinning up a Docker container.
Parameters
----------
function_name : str
Name or LogicalId of the function
codeuri : str
Path to where the code lives
runtime : str
AWS Lambda function runtime
Returns
-------
str
Path to the location where built artifacts are available | [
"Given",
"the",
"function",
"information",
"this",
"method",
"will",
"build",
"the",
"Lambda",
"function",
".",
"Depending",
"on",
"the",
"configuration",
"it",
"will",
"either",
"build",
"the",
"function",
"in",
"process",
"or",
"by",
"spinning",
"up",
"a",
... | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/lib/build/app_builder.py#L155-L199 |
30,021 | awslabs/aws-sam-cli | samcli/local/docker/lambda_build_container.py | LambdaBuildContainer._get_container_dirs | def _get_container_dirs(source_dir, manifest_dir):
"""
Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories
"""
base = "/tmp/samcli"
result = {
"source_dir": "{}/source".format(base),
"artifacts_dir": "{}/artifacts".format(base),
"scratch_dir": "{}/scratch".format(base),
"manifest_dir": "{}/manifest".format(base)
}
if pathlib.PurePath(source_dir) == pathlib.PurePath(manifest_dir):
# It is possible that the manifest resides within the source. In that case, we won't mount the manifest
# directory separately.
result["manifest_dir"] = result["source_dir"]
return result | python | def _get_container_dirs(source_dir, manifest_dir):
"""
Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories
"""
base = "/tmp/samcli"
result = {
"source_dir": "{}/source".format(base),
"artifacts_dir": "{}/artifacts".format(base),
"scratch_dir": "{}/scratch".format(base),
"manifest_dir": "{}/manifest".format(base)
}
if pathlib.PurePath(source_dir) == pathlib.PurePath(manifest_dir):
# It is possible that the manifest resides within the source. In that case, we won't mount the manifest
# directory separately.
result["manifest_dir"] = result["source_dir"]
return result | [
"def",
"_get_container_dirs",
"(",
"source_dir",
",",
"manifest_dir",
")",
":",
"base",
"=",
"\"/tmp/samcli\"",
"result",
"=",
"{",
"\"source_dir\"",
":",
"\"{}/source\"",
".",
"format",
"(",
"base",
")",
",",
"\"artifacts_dir\"",
":",
"\"{}/artifacts\"",
".",
"... | Provides paths to directories within the container that is required by the builder
Parameters
----------
source_dir : str
Path to the function source code
manifest_dir : str
Path to the directory containing manifest
Returns
-------
dict
Contains paths to source, artifacts, scratch & manifest directories | [
"Provides",
"paths",
"to",
"directories",
"within",
"the",
"container",
"that",
"is",
"required",
"by",
"the",
"builder"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_build_container.py#L150-L180 |
30,022 | awslabs/aws-sam-cli | samcli/local/docker/lambda_build_container.py | LambdaBuildContainer._convert_to_container_dirs | def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container
"""
if not host_paths_to_convert:
# Nothing to do
return host_paths_to_convert
# Make sure the key is absolute host path. Relative paths are tricky to work with because two different
# relative paths can point to the same directory ("../foo", "../../foo")
mapping = {str(pathlib.Path(p).resolve()): v for p, v in host_to_container_path_mapping.items()}
result = []
for original_path in host_paths_to_convert:
abspath = str(pathlib.Path(original_path).resolve())
if abspath in mapping:
result.append(mapping[abspath])
else:
result.append(original_path)
LOG.debug("Cannot convert host path '%s' to its equivalent path within the container. "
"Host path is not mounted within the container", abspath)
return result | python | def _convert_to_container_dirs(host_paths_to_convert, host_to_container_path_mapping):
"""
Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container
"""
if not host_paths_to_convert:
# Nothing to do
return host_paths_to_convert
# Make sure the key is absolute host path. Relative paths are tricky to work with because two different
# relative paths can point to the same directory ("../foo", "../../foo")
mapping = {str(pathlib.Path(p).resolve()): v for p, v in host_to_container_path_mapping.items()}
result = []
for original_path in host_paths_to_convert:
abspath = str(pathlib.Path(original_path).resolve())
if abspath in mapping:
result.append(mapping[abspath])
else:
result.append(original_path)
LOG.debug("Cannot convert host path '%s' to its equivalent path within the container. "
"Host path is not mounted within the container", abspath)
return result | [
"def",
"_convert_to_container_dirs",
"(",
"host_paths_to_convert",
",",
"host_to_container_path_mapping",
")",
":",
"if",
"not",
"host_paths_to_convert",
":",
"# Nothing to do",
"return",
"host_paths_to_convert",
"# Make sure the key is absolute host path. Relative paths are tricky to ... | Use this method to convert a list of host paths to a list of equivalent paths within the container
where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to
the Lambda Builder running within the container.
If a host path is not mounted within the container, then this method simply passes the path to the result
without any changes.
Ex:
[ "/home/foo", "/home/bar", "/home/not/mounted"] => ["/tmp/source", "/tmp/manifest", "/home/not/mounted"]
Parameters
----------
host_paths_to_convert : list
List of paths in host that needs to be converted
host_to_container_path_mapping : dict
Mapping of paths in host to the equivalent paths within the container
Returns
-------
list
Equivalent paths within the container | [
"Use",
"this",
"method",
"to",
"convert",
"a",
"list",
"of",
"host",
"paths",
"to",
"a",
"list",
"of",
"equivalent",
"paths",
"within",
"the",
"container",
"where",
"the",
"given",
"host",
"path",
"is",
"mounted",
".",
"This",
"is",
"necessary",
"when",
... | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/local/docker/lambda_build_container.py#L183-L228 |
30,023 | awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | ServiceCommand.get_command | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not.
"""
if cmd_name not in self.all_cmds:
return None
return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name]) | python | def get_command(self, ctx, cmd_name):
"""
gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not.
"""
if cmd_name not in self.all_cmds:
return None
return EventTypeSubCommand(self.events_lib, cmd_name, self.all_cmds[cmd_name]) | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"all_cmds",
":",
"return",
"None",
"return",
"EventTypeSubCommand",
"(",
"self",
".",
"events_lib",
",",
"cmd_name",
",",
"self",
".",
"... | gets the subcommands under the service name
Parameters
----------
ctx : Context
the context object passed into the method
cmd_name : str
the service name
Returns
-------
EventTypeSubCommand:
returns subcommand if successful, None if not. | [
"gets",
"the",
"subcommands",
"under",
"the",
"service",
"name"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L45-L63 |
30,024 | awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | EventTypeSubCommand.get_command | def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI
"""
if cmd_name not in self.subcmd_definition:
return None
parameters = []
for param_name in self.subcmd_definition[cmd_name][self.TAGS].keys():
default = self.subcmd_definition[cmd_name][self.TAGS][param_name]["default"]
parameters.append(click.Option(
["--{}".format(param_name)],
default=default,
help="Specify the {} name you'd like, otherwise the default = {}".format(param_name, default)
))
command_callback = functools.partial(self.cmd_implementation,
self.events_lib,
self.top_level_cmd_name,
cmd_name)
cmd = click.Command(name=cmd_name,
short_help=self.subcmd_definition[cmd_name]["help"],
params=parameters,
callback=command_callback)
cmd = debug_option(cmd)
return cmd | python | def get_command(self, ctx, cmd_name):
"""
gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI
"""
if cmd_name not in self.subcmd_definition:
return None
parameters = []
for param_name in self.subcmd_definition[cmd_name][self.TAGS].keys():
default = self.subcmd_definition[cmd_name][self.TAGS][param_name]["default"]
parameters.append(click.Option(
["--{}".format(param_name)],
default=default,
help="Specify the {} name you'd like, otherwise the default = {}".format(param_name, default)
))
command_callback = functools.partial(self.cmd_implementation,
self.events_lib,
self.top_level_cmd_name,
cmd_name)
cmd = click.Command(name=cmd_name,
short_help=self.subcmd_definition[cmd_name]["help"],
params=parameters,
callback=command_callback)
cmd = debug_option(cmd)
return cmd | [
"def",
"get_command",
"(",
"self",
",",
"ctx",
",",
"cmd_name",
")",
":",
"if",
"cmd_name",
"not",
"in",
"self",
".",
"subcmd_definition",
":",
"return",
"None",
"parameters",
"=",
"[",
"]",
"for",
"param_name",
"in",
"self",
".",
"subcmd_definition",
"[",... | gets the Click Commands underneath a service name
Parameters
----------
ctx: Context
context object passed in
cmd_name: string
the service name
Returns
-------
cmd: Click.Command
the Click Commands that can be called from the CLI | [
"gets",
"the",
"Click",
"Commands",
"underneath",
"a",
"service",
"name"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L119-L157 |
30,025 | awslabs/aws-sam-cli | samcli/commands/local/generate_event/event_generation.py | EventTypeSubCommand.cmd_implementation | def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs):
"""
calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string
"""
event = events_lib.generate_event(top_level_cmd_name, subcmd_name, kwargs)
click.echo(event)
return event | python | def cmd_implementation(self, events_lib, top_level_cmd_name, subcmd_name, *args, **kwargs):
"""
calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string
"""
event = events_lib.generate_event(top_level_cmd_name, subcmd_name, kwargs)
click.echo(event)
return event | [
"def",
"cmd_implementation",
"(",
"self",
",",
"events_lib",
",",
"top_level_cmd_name",
",",
"subcmd_name",
",",
"*",
"args",
",",
"*",
"*",
"kwargs",
")",
":",
"event",
"=",
"events_lib",
".",
"generate_event",
"(",
"top_level_cmd_name",
",",
"subcmd_name",
"... | calls for value substitution in the event json and returns the
customized json as a string
Parameters
----------
events_lib
top_level_cmd_name: string
the name of the service
subcmd_name: string
the name of the event under the service
args: tuple
any arguments passed in before kwargs
kwargs: dict
the keys and values for substitution in the json
Returns
-------
event: string
returns the customized event json as a string | [
"calls",
"for",
"value",
"substitution",
"in",
"the",
"event",
"json",
"and",
"returns",
"the",
"customized",
"json",
"as",
"a",
"string"
] | c05af5e7378c6f05f7d82ad3f0bca17204177db6 | https://github.com/awslabs/aws-sam-cli/blob/c05af5e7378c6f05f7d82ad3f0bca17204177db6/samcli/commands/local/generate_event/event_generation.py#L173-L196 |
30,026 | marcotcr/lime | lime/lime_base.py | LimeBase.generate_lars_path | def generate_lars_path(weighted_data, weighted_labels):
"""Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively
"""
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
verbose=False)
return alphas, coefs | python | def generate_lars_path(weighted_data, weighted_labels):
"""Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively
"""
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
verbose=False)
return alphas, coefs | [
"def",
"generate_lars_path",
"(",
"weighted_data",
",",
"weighted_labels",
")",
":",
"x_vector",
"=",
"weighted_data",
"alphas",
",",
"_",
",",
"coefs",
"=",
"lars_path",
"(",
"x_vector",
",",
"weighted_labels",
",",
"method",
"=",
"'lasso'",
",",
"verbose",
"... | Generates the lars path for weighted data.
Args:
weighted_data: data that has been weighted by kernel
weighted_label: labels, weighted by kernel
Returns:
(alphas, coefs), both are arrays corresponding to the
regularization parameter and coefficients, respectively | [
"Generates",
"the",
"lars",
"path",
"for",
"weighted",
"data",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L31-L47 |
30,027 | marcotcr/lime | lime/lime_base.py | LimeBase.forward_selection | def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
best = 0
for feature in range(data.shape[1]):
if feature in used_features:
continue
clf.fit(data[:, used_features + [feature]], labels,
sample_weight=weights)
score = clf.score(data[:, used_features + [feature]],
labels,
sample_weight=weights)
if score > max_:
best = feature
max_ = score
used_features.append(best)
return np.array(used_features) | python | def forward_selection(self, data, labels, weights, num_features):
"""Iteratively adds features to the model"""
clf = Ridge(alpha=0, fit_intercept=True, random_state=self.random_state)
used_features = []
for _ in range(min(num_features, data.shape[1])):
max_ = -100000000
best = 0
for feature in range(data.shape[1]):
if feature in used_features:
continue
clf.fit(data[:, used_features + [feature]], labels,
sample_weight=weights)
score = clf.score(data[:, used_features + [feature]],
labels,
sample_weight=weights)
if score > max_:
best = feature
max_ = score
used_features.append(best)
return np.array(used_features) | [
"def",
"forward_selection",
"(",
"self",
",",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
")",
":",
"clf",
"=",
"Ridge",
"(",
"alpha",
"=",
"0",
",",
"fit_intercept",
"=",
"True",
",",
"random_state",
"=",
"self",
".",
"random_state",
")"... | Iteratively adds features to the model | [
"Iteratively",
"adds",
"features",
"to",
"the",
"model"
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L49-L68 |
30,028 | marcotcr/lime | lime/lime_base.py | LimeBase.feature_selection | def feature_selection(self, data, labels, weights, num_features, method):
"""Selects features for the model. see explain_instance_with_data to
understand the parameters."""
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
return self.forward_selection(data, labels, weights, num_features)
elif method == 'highest_weights':
clf = Ridge(alpha=0, fit_intercept=True,
random_state=self.random_state)
clf.fit(data, labels, sample_weight=weights)
feature_weights = sorted(zip(range(data.shape[0]),
clf.coef_ * data[0]),
key=lambda x: np.abs(x[1]),
reverse=True)
return np.array([x[0] for x in feature_weights[:num_features]])
elif method == 'lasso_path':
weighted_data = ((data - np.average(data, axis=0, weights=weights))
* np.sqrt(weights[:, np.newaxis]))
weighted_labels = ((labels - np.average(labels, weights=weights))
* np.sqrt(weights))
nonzero = range(weighted_data.shape[1])
_, coefs = self.generate_lars_path(weighted_data,
weighted_labels)
for i in range(len(coefs.T) - 1, 0, -1):
nonzero = coefs.T[i].nonzero()[0]
if len(nonzero) <= num_features:
break
used_features = nonzero
return used_features
elif method == 'auto':
if num_features <= 6:
n_method = 'forward_selection'
else:
n_method = 'highest_weights'
return self.feature_selection(data, labels, weights,
num_features, n_method) | python | def feature_selection(self, data, labels, weights, num_features, method):
"""Selects features for the model. see explain_instance_with_data to
understand the parameters."""
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
return self.forward_selection(data, labels, weights, num_features)
elif method == 'highest_weights':
clf = Ridge(alpha=0, fit_intercept=True,
random_state=self.random_state)
clf.fit(data, labels, sample_weight=weights)
feature_weights = sorted(zip(range(data.shape[0]),
clf.coef_ * data[0]),
key=lambda x: np.abs(x[1]),
reverse=True)
return np.array([x[0] for x in feature_weights[:num_features]])
elif method == 'lasso_path':
weighted_data = ((data - np.average(data, axis=0, weights=weights))
* np.sqrt(weights[:, np.newaxis]))
weighted_labels = ((labels - np.average(labels, weights=weights))
* np.sqrt(weights))
nonzero = range(weighted_data.shape[1])
_, coefs = self.generate_lars_path(weighted_data,
weighted_labels)
for i in range(len(coefs.T) - 1, 0, -1):
nonzero = coefs.T[i].nonzero()[0]
if len(nonzero) <= num_features:
break
used_features = nonzero
return used_features
elif method == 'auto':
if num_features <= 6:
n_method = 'forward_selection'
else:
n_method = 'highest_weights'
return self.feature_selection(data, labels, weights,
num_features, n_method) | [
"def",
"feature_selection",
"(",
"self",
",",
"data",
",",
"labels",
",",
"weights",
",",
"num_features",
",",
"method",
")",
":",
"if",
"method",
"==",
"'none'",
":",
"return",
"np",
".",
"array",
"(",
"range",
"(",
"data",
".",
"shape",
"[",
"1",
"... | Selects features for the model. see explain_instance_with_data to
understand the parameters. | [
"Selects",
"features",
"for",
"the",
"model",
".",
"see",
"explain_instance_with_data",
"to",
"understand",
"the",
"parameters",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L70-L106 |
30,029 | marcotcr/lime | lime/lime_base.py | LimeBase.explain_instance_with_data | def explain_instance_with_data(self,
neighborhood_data,
neighborhood_labels,
distances,
label,
num_features,
feature_selection='auto',
model_regressor=None):
"""Takes perturbed data, labels and distances, returns explanation.
Args:
neighborhood_data: perturbed data, 2d array. first element is
assumed to be the original data point.
neighborhood_labels: corresponding perturbed labels. should have as
many columns as the number of possible labels.
distances: distances to original data point.
label: label for which we want an explanation
num_features: maximum number of features in explanation
feature_selection: how to select num_features. options are:
'forward_selection': iteratively add features to the model.
This is costly when num_features is high
'highest_weights': selects the features that have the highest
product of absolute weight * original data point when
learning with all the features
'lasso_path': chooses features based on the lasso
regularization path
'none': uses all features, ignores num_features
'auto': uses forward_selection if num_features <= 6, and
'highest_weights' otherwise.
model_regressor: sklearn regressor to use in explanation.
Defaults to Ridge regression if None. Must have
model_regressor.coef_ and 'sample_weight' as a parameter
to model_regressor.fit()
Returns:
(intercept, exp, score, local_pred):
intercept is a float.
exp is a sorted list of tuples, where each tuple (x,y) corresponds
to the feature id (x) and the local weight (y). The list is sorted
by decreasing absolute value of y.
score is the R^2 value of the returned explanation
local_pred is the prediction of the explanation model on the original instance
"""
weights = self.kernel_fn(distances)
labels_column = neighborhood_labels[:, label]
used_features = self.feature_selection(neighborhood_data,
labels_column,
weights,
num_features,
feature_selection)
if model_regressor is None:
model_regressor = Ridge(alpha=1, fit_intercept=True,
random_state=self.random_state)
easy_model = model_regressor
easy_model.fit(neighborhood_data[:, used_features],
labels_column, sample_weight=weights)
prediction_score = easy_model.score(
neighborhood_data[:, used_features],
labels_column, sample_weight=weights)
local_pred = easy_model.predict(neighborhood_data[0, used_features].reshape(1, -1))
if self.verbose:
print('Intercept', easy_model.intercept_)
print('Prediction_local', local_pred,)
print('Right:', neighborhood_labels[0, label])
return (easy_model.intercept_,
sorted(zip(used_features, easy_model.coef_),
key=lambda x: np.abs(x[1]), reverse=True),
prediction_score, local_pred) | python | def explain_instance_with_data(self,
neighborhood_data,
neighborhood_labels,
distances,
label,
num_features,
feature_selection='auto',
model_regressor=None):
"""Takes perturbed data, labels and distances, returns explanation.
Args:
neighborhood_data: perturbed data, 2d array. first element is
assumed to be the original data point.
neighborhood_labels: corresponding perturbed labels. should have as
many columns as the number of possible labels.
distances: distances to original data point.
label: label for which we want an explanation
num_features: maximum number of features in explanation
feature_selection: how to select num_features. options are:
'forward_selection': iteratively add features to the model.
This is costly when num_features is high
'highest_weights': selects the features that have the highest
product of absolute weight * original data point when
learning with all the features
'lasso_path': chooses features based on the lasso
regularization path
'none': uses all features, ignores num_features
'auto': uses forward_selection if num_features <= 6, and
'highest_weights' otherwise.
model_regressor: sklearn regressor to use in explanation.
Defaults to Ridge regression if None. Must have
model_regressor.coef_ and 'sample_weight' as a parameter
to model_regressor.fit()
Returns:
(intercept, exp, score, local_pred):
intercept is a float.
exp is a sorted list of tuples, where each tuple (x,y) corresponds
to the feature id (x) and the local weight (y). The list is sorted
by decreasing absolute value of y.
score is the R^2 value of the returned explanation
local_pred is the prediction of the explanation model on the original instance
"""
weights = self.kernel_fn(distances)
labels_column = neighborhood_labels[:, label]
used_features = self.feature_selection(neighborhood_data,
labels_column,
weights,
num_features,
feature_selection)
if model_regressor is None:
model_regressor = Ridge(alpha=1, fit_intercept=True,
random_state=self.random_state)
easy_model = model_regressor
easy_model.fit(neighborhood_data[:, used_features],
labels_column, sample_weight=weights)
prediction_score = easy_model.score(
neighborhood_data[:, used_features],
labels_column, sample_weight=weights)
local_pred = easy_model.predict(neighborhood_data[0, used_features].reshape(1, -1))
if self.verbose:
print('Intercept', easy_model.intercept_)
print('Prediction_local', local_pred,)
print('Right:', neighborhood_labels[0, label])
return (easy_model.intercept_,
sorted(zip(used_features, easy_model.coef_),
key=lambda x: np.abs(x[1]), reverse=True),
prediction_score, local_pred) | [
"def",
"explain_instance_with_data",
"(",
"self",
",",
"neighborhood_data",
",",
"neighborhood_labels",
",",
"distances",
",",
"label",
",",
"num_features",
",",
"feature_selection",
"=",
"'auto'",
",",
"model_regressor",
"=",
"None",
")",
":",
"weights",
"=",
"se... | Takes perturbed data, labels and distances, returns explanation.
Args:
neighborhood_data: perturbed data, 2d array. first element is
assumed to be the original data point.
neighborhood_labels: corresponding perturbed labels. should have as
many columns as the number of possible labels.
distances: distances to original data point.
label: label for which we want an explanation
num_features: maximum number of features in explanation
feature_selection: how to select num_features. options are:
'forward_selection': iteratively add features to the model.
This is costly when num_features is high
'highest_weights': selects the features that have the highest
product of absolute weight * original data point when
learning with all the features
'lasso_path': chooses features based on the lasso
regularization path
'none': uses all features, ignores num_features
'auto': uses forward_selection if num_features <= 6, and
'highest_weights' otherwise.
model_regressor: sklearn regressor to use in explanation.
Defaults to Ridge regression if None. Must have
model_regressor.coef_ and 'sample_weight' as a parameter
to model_regressor.fit()
Returns:
(intercept, exp, score, local_pred):
intercept is a float.
exp is a sorted list of tuples, where each tuple (x,y) corresponds
to the feature id (x) and the local weight (y). The list is sorted
by decreasing absolute value of y.
score is the R^2 value of the returned explanation
local_pred is the prediction of the explanation model on the original instance | [
"Takes",
"perturbed",
"data",
"labels",
"and",
"distances",
"returns",
"explanation",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_base.py#L108-L179 |
30,030 | marcotcr/lime | lime/explanation.py | id_generator | def id_generator(size=15, random_state=None):
"""Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) | python | def id_generator(size=15, random_state=None):
"""Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks."""
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) | [
"def",
"id_generator",
"(",
"size",
"=",
"15",
",",
"random_state",
"=",
"None",
")",
":",
"chars",
"=",
"list",
"(",
"string",
".",
"ascii_uppercase",
"+",
"string",
".",
"digits",
")",
"return",
"''",
".",
"join",
"(",
"random_state",
".",
"choice",
... | Helper function to generate random div ids. This is useful for embedding
HTML into ipython notebooks. | [
"Helper",
"function",
"to",
"generate",
"random",
"div",
"ids",
".",
"This",
"is",
"useful",
"for",
"embedding",
"HTML",
"into",
"ipython",
"notebooks",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L17-L21 |
30,031 | marcotcr/lime | lime/explanation.py | Explanation.available_labels | def available_labels(self):
"""
Returns the list of classification labels for which we have any explanations.
"""
try:
assert self.mode == "classification"
except AssertionError:
raise NotImplementedError('Not supported for regression explanations.')
else:
ans = self.top_labels if self.top_labels else self.local_exp.keys()
return list(ans) | python | def available_labels(self):
"""
Returns the list of classification labels for which we have any explanations.
"""
try:
assert self.mode == "classification"
except AssertionError:
raise NotImplementedError('Not supported for regression explanations.')
else:
ans = self.top_labels if self.top_labels else self.local_exp.keys()
return list(ans) | [
"def",
"available_labels",
"(",
"self",
")",
":",
"try",
":",
"assert",
"self",
".",
"mode",
"==",
"\"classification\"",
"except",
"AssertionError",
":",
"raise",
"NotImplementedError",
"(",
"'Not supported for regression explanations.'",
")",
"else",
":",
"ans",
"=... | Returns the list of classification labels for which we have any explanations. | [
"Returns",
"the",
"list",
"of",
"classification",
"labels",
"for",
"which",
"we",
"have",
"any",
"explanations",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L117-L127 |
30,032 | marcotcr/lime | lime/explanation.py | Explanation.as_list | def as_list(self, label=1, **kwargs):
"""Returns the explanation as a list.
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
list of tuples (representation, weight), where representation is
given by domain_mapper. Weight is a float.
"""
label_to_use = label if self.mode == "classification" else self.dummy_label
ans = self.domain_mapper.map_exp_ids(self.local_exp[label_to_use], **kwargs)
ans = [(x[0], float(x[1])) for x in ans]
return ans | python | def as_list(self, label=1, **kwargs):
"""Returns the explanation as a list.
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
list of tuples (representation, weight), where representation is
given by domain_mapper. Weight is a float.
"""
label_to_use = label if self.mode == "classification" else self.dummy_label
ans = self.domain_mapper.map_exp_ids(self.local_exp[label_to_use], **kwargs)
ans = [(x[0], float(x[1])) for x in ans]
return ans | [
"def",
"as_list",
"(",
"self",
",",
"label",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"label_to_use",
"=",
"label",
"if",
"self",
".",
"mode",
"==",
"\"classification\"",
"else",
"self",
".",
"dummy_label",
"ans",
"=",
"self",
".",
"domain_mapper",
... | Returns the explanation as a list.
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
list of tuples (representation, weight), where representation is
given by domain_mapper. Weight is a float. | [
"Returns",
"the",
"explanation",
"as",
"a",
"list",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L129-L145 |
30,033 | marcotcr/lime | lime/explanation.py | Explanation.as_pyplot_figure | def as_pyplot_figure(self, label=1, **kwargs):
"""Returns the explanation as a pyplot figure.
Will throw an error if you don't have matplotlib installed
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
pyplot figure (barchart).
"""
import matplotlib.pyplot as plt
exp = self.as_list(label=label, **kwargs)
fig = plt.figure()
vals = [x[1] for x in exp]
names = [x[0] for x in exp]
vals.reverse()
names.reverse()
colors = ['green' if x > 0 else 'red' for x in vals]
pos = np.arange(len(exp)) + .5
plt.barh(pos, vals, align='center', color=colors)
plt.yticks(pos, names)
if self.mode == "classification":
title = 'Local explanation for class %s' % self.class_names[label]
else:
title = 'Local explanation'
plt.title(title)
return fig | python | def as_pyplot_figure(self, label=1, **kwargs):
"""Returns the explanation as a pyplot figure.
Will throw an error if you don't have matplotlib installed
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
pyplot figure (barchart).
"""
import matplotlib.pyplot as plt
exp = self.as_list(label=label, **kwargs)
fig = plt.figure()
vals = [x[1] for x in exp]
names = [x[0] for x in exp]
vals.reverse()
names.reverse()
colors = ['green' if x > 0 else 'red' for x in vals]
pos = np.arange(len(exp)) + .5
plt.barh(pos, vals, align='center', color=colors)
plt.yticks(pos, names)
if self.mode == "classification":
title = 'Local explanation for class %s' % self.class_names[label]
else:
title = 'Local explanation'
plt.title(title)
return fig | [
"def",
"as_pyplot_figure",
"(",
"self",
",",
"label",
"=",
"1",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"matplotlib",
".",
"pyplot",
"as",
"plt",
"exp",
"=",
"self",
".",
"as_list",
"(",
"label",
"=",
"label",
",",
"*",
"*",
"kwargs",
")",
"fi... | Returns the explanation as a pyplot figure.
Will throw an error if you don't have matplotlib installed
Args:
label: desired label. If you ask for a label for which an
explanation wasn't computed, will throw an exception.
Will be ignored for regression explanations.
kwargs: keyword arguments, passed to domain_mapper
Returns:
pyplot figure (barchart). | [
"Returns",
"the",
"explanation",
"as",
"a",
"pyplot",
"figure",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L155-L184 |
30,034 | marcotcr/lime | lime/explanation.py | Explanation.show_in_notebook | def show_in_notebook(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Shows html explanation in ipython notebook.
See as_html() for parameters.
This will throw an error if you don't have IPython installed"""
from IPython.core.display import display, HTML
display(HTML(self.as_html(labels=labels,
predict_proba=predict_proba,
show_predicted_value=show_predicted_value,
**kwargs))) | python | def show_in_notebook(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Shows html explanation in ipython notebook.
See as_html() for parameters.
This will throw an error if you don't have IPython installed"""
from IPython.core.display import display, HTML
display(HTML(self.as_html(labels=labels,
predict_proba=predict_proba,
show_predicted_value=show_predicted_value,
**kwargs))) | [
"def",
"show_in_notebook",
"(",
"self",
",",
"labels",
"=",
"None",
",",
"predict_proba",
"=",
"True",
",",
"show_predicted_value",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"from",
"IPython",
".",
"core",
".",
"display",
"import",
"display",
",",
... | Shows html explanation in ipython notebook.
See as_html() for parameters.
This will throw an error if you don't have IPython installed | [
"Shows",
"html",
"explanation",
"in",
"ipython",
"notebook",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L186-L200 |
30,035 | marcotcr/lime | lime/explanation.py | Explanation.save_to_file | def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Saves html explanation to file. .
Params:
file_path: file to save explanations to
See as_html() for additional parameters.
"""
file_ = open(file_path, 'w', encoding='utf8')
file_.write(self.as_html(labels=labels,
predict_proba=predict_proba,
show_predicted_value=show_predicted_value,
**kwargs))
file_.close() | python | def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
"""Saves html explanation to file. .
Params:
file_path: file to save explanations to
See as_html() for additional parameters.
"""
file_ = open(file_path, 'w', encoding='utf8')
file_.write(self.as_html(labels=labels,
predict_proba=predict_proba,
show_predicted_value=show_predicted_value,
**kwargs))
file_.close() | [
"def",
"save_to_file",
"(",
"self",
",",
"file_path",
",",
"labels",
"=",
"None",
",",
"predict_proba",
"=",
"True",
",",
"show_predicted_value",
"=",
"True",
",",
"*",
"*",
"kwargs",
")",
":",
"file_",
"=",
"open",
"(",
"file_path",
",",
"'w'",
",",
"... | Saves html explanation to file. .
Params:
file_path: file to save explanations to
See as_html() for additional parameters. | [
"Saves",
"html",
"explanation",
"to",
"file",
".",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/explanation.py#L202-L221 |
30,036 | marcotcr/lime | lime/wrappers/scikit_image.py | BaseWrapper._check_params | def _check_params(self, parameters):
"""Checks for mistakes in 'parameters'
Args :
parameters: dict, parameters to be checked
Raises :
ValueError: if any parameter is not a valid argument for the target function
or the target function is not defined
TypeError: if argument parameters is not iterable
"""
a_valid_fn = []
if self.target_fn is None:
if callable(self):
a_valid_fn.append(self.__call__)
else:
raise TypeError('invalid argument: tested object is not callable,\
please provide a valid target_fn')
elif isinstance(self.target_fn, types.FunctionType) \
or isinstance(self.target_fn, types.MethodType):
a_valid_fn.append(self.target_fn)
else:
a_valid_fn.append(self.target_fn.__call__)
if not isinstance(parameters, str):
for p in parameters:
for fn in a_valid_fn:
if has_arg(fn, p):
pass
else:
raise ValueError('{} is not a valid parameter'.format(p))
else:
raise TypeError('invalid argument: list or dictionnary expected') | python | def _check_params(self, parameters):
"""Checks for mistakes in 'parameters'
Args :
parameters: dict, parameters to be checked
Raises :
ValueError: if any parameter is not a valid argument for the target function
or the target function is not defined
TypeError: if argument parameters is not iterable
"""
a_valid_fn = []
if self.target_fn is None:
if callable(self):
a_valid_fn.append(self.__call__)
else:
raise TypeError('invalid argument: tested object is not callable,\
please provide a valid target_fn')
elif isinstance(self.target_fn, types.FunctionType) \
or isinstance(self.target_fn, types.MethodType):
a_valid_fn.append(self.target_fn)
else:
a_valid_fn.append(self.target_fn.__call__)
if not isinstance(parameters, str):
for p in parameters:
for fn in a_valid_fn:
if has_arg(fn, p):
pass
else:
raise ValueError('{} is not a valid parameter'.format(p))
else:
raise TypeError('invalid argument: list or dictionnary expected') | [
"def",
"_check_params",
"(",
"self",
",",
"parameters",
")",
":",
"a_valid_fn",
"=",
"[",
"]",
"if",
"self",
".",
"target_fn",
"is",
"None",
":",
"if",
"callable",
"(",
"self",
")",
":",
"a_valid_fn",
".",
"append",
"(",
"self",
".",
"__call__",
")",
... | Checks for mistakes in 'parameters'
Args :
parameters: dict, parameters to be checked
Raises :
ValueError: if any parameter is not a valid argument for the target function
or the target function is not defined
TypeError: if argument parameters is not iterable | [
"Checks",
"for",
"mistakes",
"in",
"parameters"
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/wrappers/scikit_image.py#L26-L58 |
30,037 | marcotcr/lime | lime/lime_text.py | TextDomainMapper.map_exp_ids | def map_exp_ids(self, exp, positions=False):
"""Maps ids to words or word-position strings.
Args:
exp: list of tuples [(id, weight), (id,weight)]
positions: if True, also return word positions
Returns:
list of tuples (word, weight), or (word_positions, weight) if
examples: ('bad', 1) or ('bad_3-6-12', 1)
"""
if positions:
exp = [('%s_%s' % (
self.indexed_string.word(x[0]),
'-'.join(
map(str,
self.indexed_string.string_position(x[0])))), x[1])
for x in exp]
else:
exp = [(self.indexed_string.word(x[0]), x[1]) for x in exp]
return exp | python | def map_exp_ids(self, exp, positions=False):
"""Maps ids to words or word-position strings.
Args:
exp: list of tuples [(id, weight), (id,weight)]
positions: if True, also return word positions
Returns:
list of tuples (word, weight), or (word_positions, weight) if
examples: ('bad', 1) or ('bad_3-6-12', 1)
"""
if positions:
exp = [('%s_%s' % (
self.indexed_string.word(x[0]),
'-'.join(
map(str,
self.indexed_string.string_position(x[0])))), x[1])
for x in exp]
else:
exp = [(self.indexed_string.word(x[0]), x[1]) for x in exp]
return exp | [
"def",
"map_exp_ids",
"(",
"self",
",",
"exp",
",",
"positions",
"=",
"False",
")",
":",
"if",
"positions",
":",
"exp",
"=",
"[",
"(",
"'%s_%s'",
"%",
"(",
"self",
".",
"indexed_string",
".",
"word",
"(",
"x",
"[",
"0",
"]",
")",
",",
"'-'",
".",... | Maps ids to words or word-position strings.
Args:
exp: list of tuples [(id, weight), (id,weight)]
positions: if True, also return word positions
Returns:
list of tuples (word, weight), or (word_positions, weight) if
examples: ('bad', 1) or ('bad_3-6-12', 1) | [
"Maps",
"ids",
"to",
"words",
"or",
"word",
"-",
"position",
"strings",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L31-L51 |
30,038 | marcotcr/lime | lime/lime_text.py | IndexedString.inverse_removing | def inverse_removing(self, words_to_remove):
"""Returns a string after removing the appropriate words.
If self.bow is false, replaces word with UNKWORDZ instead of removing
it.
Args:
words_to_remove: list of ids (ints) to remove
Returns:
original raw string with appropriate words removed.
"""
mask = np.ones(self.as_np.shape[0], dtype='bool')
mask[self.__get_idxs(words_to_remove)] = False
if not self.bow:
return ''.join([self.as_list[i] if mask[i]
else 'UNKWORDZ' for i in range(mask.shape[0])])
return ''.join([self.as_list[v] for v in mask.nonzero()[0]]) | python | def inverse_removing(self, words_to_remove):
"""Returns a string after removing the appropriate words.
If self.bow is false, replaces word with UNKWORDZ instead of removing
it.
Args:
words_to_remove: list of ids (ints) to remove
Returns:
original raw string with appropriate words removed.
"""
mask = np.ones(self.as_np.shape[0], dtype='bool')
mask[self.__get_idxs(words_to_remove)] = False
if not self.bow:
return ''.join([self.as_list[i] if mask[i]
else 'UNKWORDZ' for i in range(mask.shape[0])])
return ''.join([self.as_list[v] for v in mask.nonzero()[0]]) | [
"def",
"inverse_removing",
"(",
"self",
",",
"words_to_remove",
")",
":",
"mask",
"=",
"np",
".",
"ones",
"(",
"self",
".",
"as_np",
".",
"shape",
"[",
"0",
"]",
",",
"dtype",
"=",
"'bool'",
")",
"mask",
"[",
"self",
".",
"__get_idxs",
"(",
"words_to... | Returns a string after removing the appropriate words.
If self.bow is false, replaces word with UNKWORDZ instead of removing
it.
Args:
words_to_remove: list of ids (ints) to remove
Returns:
original raw string with appropriate words removed. | [
"Returns",
"a",
"string",
"after",
"removing",
"the",
"appropriate",
"words",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L162-L179 |
30,039 | marcotcr/lime | lime/lime_text.py | IndexedString._segment_with_tokens | def _segment_with_tokens(text, tokens):
"""Segment a string around the tokens created by a passed-in tokenizer"""
list_form = []
text_ptr = 0
for token in tokens:
inter_token_string = []
while not text[text_ptr:].startswith(token):
inter_token_string.append(text[text_ptr])
text_ptr += 1
if text_ptr >= len(text):
raise ValueError("Tokenization produced tokens that do not belong in string!")
text_ptr += len(token)
if inter_token_string:
list_form.append(''.join(inter_token_string))
list_form.append(token)
if text_ptr < len(text):
list_form.append(text[text_ptr:])
return list_form | python | def _segment_with_tokens(text, tokens):
"""Segment a string around the tokens created by a passed-in tokenizer"""
list_form = []
text_ptr = 0
for token in tokens:
inter_token_string = []
while not text[text_ptr:].startswith(token):
inter_token_string.append(text[text_ptr])
text_ptr += 1
if text_ptr >= len(text):
raise ValueError("Tokenization produced tokens that do not belong in string!")
text_ptr += len(token)
if inter_token_string:
list_form.append(''.join(inter_token_string))
list_form.append(token)
if text_ptr < len(text):
list_form.append(text[text_ptr:])
return list_form | [
"def",
"_segment_with_tokens",
"(",
"text",
",",
"tokens",
")",
":",
"list_form",
"=",
"[",
"]",
"text_ptr",
"=",
"0",
"for",
"token",
"in",
"tokens",
":",
"inter_token_string",
"=",
"[",
"]",
"while",
"not",
"text",
"[",
"text_ptr",
":",
"]",
".",
"st... | Segment a string around the tokens created by a passed-in tokenizer | [
"Segment",
"a",
"string",
"around",
"the",
"tokens",
"created",
"by",
"a",
"passed",
"-",
"in",
"tokenizer"
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L182-L199 |
30,040 | marcotcr/lime | lime/lime_text.py | IndexedString.__get_idxs | def __get_idxs(self, words):
"""Returns indexes to appropriate words."""
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] | python | def __get_idxs(self, words):
"""Returns indexes to appropriate words."""
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] | [
"def",
"__get_idxs",
"(",
"self",
",",
"words",
")",
":",
"if",
"self",
".",
"bow",
":",
"return",
"list",
"(",
"itertools",
".",
"chain",
".",
"from_iterable",
"(",
"[",
"self",
".",
"positions",
"[",
"z",
"]",
"for",
"z",
"in",
"words",
"]",
")",... | Returns indexes to appropriate words. | [
"Returns",
"indexes",
"to",
"appropriate",
"words",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_text.py#L201-L207 |
30,041 | marcotcr/lime | lime/lime_tabular.py | TableDomainMapper.map_exp_ids | def map_exp_ids(self, exp):
"""Maps ids to feature names.
Args:
exp: list of tuples [(id, weight), (id,weight)]
Returns:
list of tuples (feature_name, weight)
"""
names = self.exp_feature_names
if self.discretized_feature_names is not None:
names = self.discretized_feature_names
return [(names[x[0]], x[1]) for x in exp] | python | def map_exp_ids(self, exp):
"""Maps ids to feature names.
Args:
exp: list of tuples [(id, weight), (id,weight)]
Returns:
list of tuples (feature_name, weight)
"""
names = self.exp_feature_names
if self.discretized_feature_names is not None:
names = self.discretized_feature_names
return [(names[x[0]], x[1]) for x in exp] | [
"def",
"map_exp_ids",
"(",
"self",
",",
"exp",
")",
":",
"names",
"=",
"self",
".",
"exp_feature_names",
"if",
"self",
".",
"discretized_feature_names",
"is",
"not",
"None",
":",
"names",
"=",
"self",
".",
"discretized_feature_names",
"return",
"[",
"(",
"na... | Maps ids to feature names.
Args:
exp: list of tuples [(id, weight), (id,weight)]
Returns:
list of tuples (feature_name, weight) | [
"Maps",
"ids",
"to",
"feature",
"names",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L45-L57 |
30,042 | marcotcr/lime | lime/lime_tabular.py | TableDomainMapper.visualize_instance_html | def visualize_instance_html(self,
exp,
label,
div_name,
exp_object_name,
show_table=True,
show_all=False):
"""Shows the current example in a table format.
Args:
exp: list of tuples [(id, weight), (id,weight)]
label: label id (integer)
div_name: name of div object to be used for rendering(in js)
exp_object_name: name of js explanation object
show_table: if False, don't show table visualization.
show_all: if True, show zero-weighted features in the table.
"""
if not show_table:
return ''
weights = [0] * len(self.feature_names)
for x in exp:
weights[x[0]] = x[1]
out_list = list(zip(self.exp_feature_names,
self.feature_values,
weights))
if not show_all:
out_list = [out_list[x[0]] for x in exp]
ret = u'''
%s.show_raw_tabular(%s, %d, %s);
''' % (exp_object_name, json.dumps(out_list, ensure_ascii=False), label, div_name)
return ret | python | def visualize_instance_html(self,
exp,
label,
div_name,
exp_object_name,
show_table=True,
show_all=False):
"""Shows the current example in a table format.
Args:
exp: list of tuples [(id, weight), (id,weight)]
label: label id (integer)
div_name: name of div object to be used for rendering(in js)
exp_object_name: name of js explanation object
show_table: if False, don't show table visualization.
show_all: if True, show zero-weighted features in the table.
"""
if not show_table:
return ''
weights = [0] * len(self.feature_names)
for x in exp:
weights[x[0]] = x[1]
out_list = list(zip(self.exp_feature_names,
self.feature_values,
weights))
if not show_all:
out_list = [out_list[x[0]] for x in exp]
ret = u'''
%s.show_raw_tabular(%s, %d, %s);
''' % (exp_object_name, json.dumps(out_list, ensure_ascii=False), label, div_name)
return ret | [
"def",
"visualize_instance_html",
"(",
"self",
",",
"exp",
",",
"label",
",",
"div_name",
",",
"exp_object_name",
",",
"show_table",
"=",
"True",
",",
"show_all",
"=",
"False",
")",
":",
"if",
"not",
"show_table",
":",
"return",
"''",
"weights",
"=",
"[",
... | Shows the current example in a table format.
Args:
exp: list of tuples [(id, weight), (id,weight)]
label: label id (integer)
div_name: name of div object to be used for rendering(in js)
exp_object_name: name of js explanation object
show_table: if False, don't show table visualization.
show_all: if True, show zero-weighted features in the table. | [
"Shows",
"the",
"current",
"example",
"in",
"a",
"table",
"format",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L59-L89 |
30,043 | marcotcr/lime | lime/lime_tabular.py | LimeTabularExplainer.validate_training_data_stats | def validate_training_data_stats(training_data_stats):
"""
Method to validate the structure of training data stats
"""
stat_keys = list(training_data_stats.keys())
valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"]
missing_keys = list(set(valid_stat_keys) - set(stat_keys))
if len(missing_keys) > 0:
raise Exception("Missing keys in training_data_stats. Details:" % (missing_keys)) | python | def validate_training_data_stats(training_data_stats):
"""
Method to validate the structure of training data stats
"""
stat_keys = list(training_data_stats.keys())
valid_stat_keys = ["means", "mins", "maxs", "stds", "feature_values", "feature_frequencies"]
missing_keys = list(set(valid_stat_keys) - set(stat_keys))
if len(missing_keys) > 0:
raise Exception("Missing keys in training_data_stats. Details:" % (missing_keys)) | [
"def",
"validate_training_data_stats",
"(",
"training_data_stats",
")",
":",
"stat_keys",
"=",
"list",
"(",
"training_data_stats",
".",
"keys",
"(",
")",
")",
"valid_stat_keys",
"=",
"[",
"\"means\"",
",",
"\"mins\"",
",",
"\"maxs\"",
",",
"\"stds\"",
",",
"\"fe... | Method to validate the structure of training data stats | [
"Method",
"to",
"validate",
"the",
"structure",
"of",
"training",
"data",
"stats"
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L260-L268 |
30,044 | marcotcr/lime | lime/lime_tabular.py | RecurrentTabularExplainer._make_predict_proba | def _make_predict_proba(self, func):
"""
The predict_proba method will expect 3d arrays, but we are reshaping
them to 2D so that LIME works correctly. This wraps the function
you give in explain_instance to first reshape the data to have
the shape the the keras-style network expects.
"""
def predict_proba(X):
n_samples = X.shape[0]
new_shape = (n_samples, self.n_features, self.n_timesteps)
X = np.transpose(X.reshape(new_shape), axes=(0, 2, 1))
return func(X)
return predict_proba | python | def _make_predict_proba(self, func):
"""
The predict_proba method will expect 3d arrays, but we are reshaping
them to 2D so that LIME works correctly. This wraps the function
you give in explain_instance to first reshape the data to have
the shape the the keras-style network expects.
"""
def predict_proba(X):
n_samples = X.shape[0]
new_shape = (n_samples, self.n_features, self.n_timesteps)
X = np.transpose(X.reshape(new_shape), axes=(0, 2, 1))
return func(X)
return predict_proba | [
"def",
"_make_predict_proba",
"(",
"self",
",",
"func",
")",
":",
"def",
"predict_proba",
"(",
"X",
")",
":",
"n_samples",
"=",
"X",
".",
"shape",
"[",
"0",
"]",
"new_shape",
"=",
"(",
"n_samples",
",",
"self",
".",
"n_features",
",",
"self",
".",
"n... | The predict_proba method will expect 3d arrays, but we are reshaping
them to 2D so that LIME works correctly. This wraps the function
you give in explain_instance to first reshape the data to have
the shape the the keras-style network expects. | [
"The",
"predict_proba",
"method",
"will",
"expect",
"3d",
"arrays",
"but",
"we",
"are",
"reshaping",
"them",
"to",
"2D",
"so",
"that",
"LIME",
"works",
"correctly",
".",
"This",
"wraps",
"the",
"function",
"you",
"give",
"in",
"explain_instance",
"to",
"firs... | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_tabular.py#L571-L585 |
30,045 | marcotcr/lime | lime/lime_image.py | ImageExplanation.get_image_and_mask | def get_image_and_mask(self, label, positive_only=True, hide_rest=False,
num_features=5, min_weight=0.):
"""Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of the label. Otherwise, use the top
num_features superpixels, which can be positive or negative
towards the label
hide_rest: if True, make the non-explanation part of the return
image gray
num_features: number of superpixels to include in explanation
min_weight: TODO
Returns:
(image, mask), where image is a 3d numpy array and mask is a 2d
numpy array that can be used with
skimage.segmentation.mark_boundaries
"""
if label not in self.local_exp:
raise KeyError('Label not in explanation')
segments = self.segments
image = self.image
exp = self.local_exp[label]
mask = np.zeros(segments.shape, segments.dtype)
if hide_rest:
temp = np.zeros(self.image.shape)
else:
temp = self.image.copy()
if positive_only:
fs = [x[0] for x in exp
if x[1] > 0 and x[1] > min_weight][:num_features]
for f in fs:
temp[segments == f] = image[segments == f].copy()
mask[segments == f] = 1
return temp, mask
else:
for f, w in exp[:num_features]:
if np.abs(w) < min_weight:
continue
c = 0 if w < 0 else 1
mask[segments == f] = 1 if w < 0 else 2
temp[segments == f] = image[segments == f].copy()
temp[segments == f, c] = np.max(image)
for cp in [0, 1, 2]:
if c == cp:
continue
# temp[segments == f, cp] *= 0.5
return temp, mask | python | def get_image_and_mask(self, label, positive_only=True, hide_rest=False,
num_features=5, min_weight=0.):
"""Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of the label. Otherwise, use the top
num_features superpixels, which can be positive or negative
towards the label
hide_rest: if True, make the non-explanation part of the return
image gray
num_features: number of superpixels to include in explanation
min_weight: TODO
Returns:
(image, mask), where image is a 3d numpy array and mask is a 2d
numpy array that can be used with
skimage.segmentation.mark_boundaries
"""
if label not in self.local_exp:
raise KeyError('Label not in explanation')
segments = self.segments
image = self.image
exp = self.local_exp[label]
mask = np.zeros(segments.shape, segments.dtype)
if hide_rest:
temp = np.zeros(self.image.shape)
else:
temp = self.image.copy()
if positive_only:
fs = [x[0] for x in exp
if x[1] > 0 and x[1] > min_weight][:num_features]
for f in fs:
temp[segments == f] = image[segments == f].copy()
mask[segments == f] = 1
return temp, mask
else:
for f, w in exp[:num_features]:
if np.abs(w) < min_weight:
continue
c = 0 if w < 0 else 1
mask[segments == f] = 1 if w < 0 else 2
temp[segments == f] = image[segments == f].copy()
temp[segments == f, c] = np.max(image)
for cp in [0, 1, 2]:
if c == cp:
continue
# temp[segments == f, cp] *= 0.5
return temp, mask | [
"def",
"get_image_and_mask",
"(",
"self",
",",
"label",
",",
"positive_only",
"=",
"True",
",",
"hide_rest",
"=",
"False",
",",
"num_features",
"=",
"5",
",",
"min_weight",
"=",
"0.",
")",
":",
"if",
"label",
"not",
"in",
"self",
".",
"local_exp",
":",
... | Init function.
Args:
label: label to explain
positive_only: if True, only take superpixels that contribute to
the prediction of the label. Otherwise, use the top
num_features superpixels, which can be positive or negative
towards the label
hide_rest: if True, make the non-explanation part of the return
image gray
num_features: number of superpixels to include in explanation
min_weight: TODO
Returns:
(image, mask), where image is a 3d numpy array and mask is a 2d
numpy array that can be used with
skimage.segmentation.mark_boundaries | [
"Init",
"function",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_image.py#L31-L80 |
30,046 | marcotcr/lime | lime/lime_image.py | LimeImageExplainer.data_labels | def data_labels(self,
image,
fudged_image,
segments,
classifier_fn,
num_samples,
batch_size=10):
"""Generates images and predictions in the neighborhood of this image.
Args:
image: 3d numpy array, the image
fudged_image: 3d numpy array, image to replace original image when
superpixel is turned off
segments: segmentation of the image
classifier_fn: function that takes a list of images and returns a
matrix of prediction probabilities
num_samples: size of the neighborhood to learn the linear model
batch_size: classifier_fn will be called on batches of this size.
Returns:
A tuple (data, labels), where:
data: dense num_samples * num_superpixels
labels: prediction probabilities matrix
"""
n_features = np.unique(segments).shape[0]
data = self.random_state.randint(0, 2, num_samples * n_features)\
.reshape((num_samples, n_features))
labels = []
data[0, :] = 1
imgs = []
for row in data:
temp = copy.deepcopy(image)
zeros = np.where(row == 0)[0]
mask = np.zeros(segments.shape).astype(bool)
for z in zeros:
mask[segments == z] = True
temp[mask] = fudged_image[mask]
imgs.append(temp)
if len(imgs) == batch_size:
preds = classifier_fn(np.array(imgs))
labels.extend(preds)
imgs = []
if len(imgs) > 0:
preds = classifier_fn(np.array(imgs))
labels.extend(preds)
return data, np.array(labels) | python | def data_labels(self,
image,
fudged_image,
segments,
classifier_fn,
num_samples,
batch_size=10):
"""Generates images and predictions in the neighborhood of this image.
Args:
image: 3d numpy array, the image
fudged_image: 3d numpy array, image to replace original image when
superpixel is turned off
segments: segmentation of the image
classifier_fn: function that takes a list of images and returns a
matrix of prediction probabilities
num_samples: size of the neighborhood to learn the linear model
batch_size: classifier_fn will be called on batches of this size.
Returns:
A tuple (data, labels), where:
data: dense num_samples * num_superpixels
labels: prediction probabilities matrix
"""
n_features = np.unique(segments).shape[0]
data = self.random_state.randint(0, 2, num_samples * n_features)\
.reshape((num_samples, n_features))
labels = []
data[0, :] = 1
imgs = []
for row in data:
temp = copy.deepcopy(image)
zeros = np.where(row == 0)[0]
mask = np.zeros(segments.shape).astype(bool)
for z in zeros:
mask[segments == z] = True
temp[mask] = fudged_image[mask]
imgs.append(temp)
if len(imgs) == batch_size:
preds = classifier_fn(np.array(imgs))
labels.extend(preds)
imgs = []
if len(imgs) > 0:
preds = classifier_fn(np.array(imgs))
labels.extend(preds)
return data, np.array(labels) | [
"def",
"data_labels",
"(",
"self",
",",
"image",
",",
"fudged_image",
",",
"segments",
",",
"classifier_fn",
",",
"num_samples",
",",
"batch_size",
"=",
"10",
")",
":",
"n_features",
"=",
"np",
".",
"unique",
"(",
"segments",
")",
".",
"shape",
"[",
"0",... | Generates images and predictions in the neighborhood of this image.
Args:
image: 3d numpy array, the image
fudged_image: 3d numpy array, image to replace original image when
superpixel is turned off
segments: segmentation of the image
classifier_fn: function that takes a list of images and returns a
matrix of prediction probabilities
num_samples: size of the neighborhood to learn the linear model
batch_size: classifier_fn will be called on batches of this size.
Returns:
A tuple (data, labels), where:
data: dense num_samples * num_superpixels
labels: prediction probabilities matrix | [
"Generates",
"images",
"and",
"predictions",
"in",
"the",
"neighborhood",
"of",
"this",
"image",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/lime_image.py#L216-L261 |
30,047 | marcotcr/lime | lime/utils/generic_utils.py | has_arg | def has_arg(fn, arg_name):
"""Checks if a callable accepts a given keyword argument.
Args:
fn: callable to inspect
arg_name: string, keyword argument name to check
Returns:
bool, whether `fn` accepts a `arg_name` keyword argument.
"""
if sys.version_info < (3,):
if isinstance(fn, types.FunctionType) or isinstance(fn, types.MethodType):
arg_spec = inspect.getargspec(fn)
else:
try:
arg_spec = inspect.getargspec(fn.__call__)
except AttributeError:
return False
return (arg_name in arg_spec.args)
elif sys.version_info < (3, 6):
arg_spec = inspect.getfullargspec(fn)
return (arg_name in arg_spec.args or
arg_name in arg_spec.kwonlyargs)
else:
try:
signature = inspect.signature(fn)
except ValueError:
# handling Cython
signature = inspect.signature(fn.__call__)
parameter = signature.parameters.get(arg_name)
if parameter is None:
return False
return (parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY)) | python | def has_arg(fn, arg_name):
"""Checks if a callable accepts a given keyword argument.
Args:
fn: callable to inspect
arg_name: string, keyword argument name to check
Returns:
bool, whether `fn` accepts a `arg_name` keyword argument.
"""
if sys.version_info < (3,):
if isinstance(fn, types.FunctionType) or isinstance(fn, types.MethodType):
arg_spec = inspect.getargspec(fn)
else:
try:
arg_spec = inspect.getargspec(fn.__call__)
except AttributeError:
return False
return (arg_name in arg_spec.args)
elif sys.version_info < (3, 6):
arg_spec = inspect.getfullargspec(fn)
return (arg_name in arg_spec.args or
arg_name in arg_spec.kwonlyargs)
else:
try:
signature = inspect.signature(fn)
except ValueError:
# handling Cython
signature = inspect.signature(fn.__call__)
parameter = signature.parameters.get(arg_name)
if parameter is None:
return False
return (parameter.kind in (inspect.Parameter.POSITIONAL_OR_KEYWORD,
inspect.Parameter.KEYWORD_ONLY)) | [
"def",
"has_arg",
"(",
"fn",
",",
"arg_name",
")",
":",
"if",
"sys",
".",
"version_info",
"<",
"(",
"3",
",",
")",
":",
"if",
"isinstance",
"(",
"fn",
",",
"types",
".",
"FunctionType",
")",
"or",
"isinstance",
"(",
"fn",
",",
"types",
".",
"Method... | Checks if a callable accepts a given keyword argument.
Args:
fn: callable to inspect
arg_name: string, keyword argument name to check
Returns:
bool, whether `fn` accepts a `arg_name` keyword argument. | [
"Checks",
"if",
"a",
"callable",
"accepts",
"a",
"given",
"keyword",
"argument",
"."
] | 08133d47df00ed918e22005e0c98f6eefd5a1d71 | https://github.com/marcotcr/lime/blob/08133d47df00ed918e22005e0c98f6eefd5a1d71/lime/utils/generic_utils.py#L6-L39 |
30,048 | iterative/dvc | dvc/cache.py | Cache._get_remote | def _get_remote(self, config, name):
"""
The config file is stored in a way that allows you to have a
cache for each remote.
This is needed when specifying external outputs
(as they require you to have an external cache location).
Imagine a config file like the following:
['remote "dvc-storage"']
url = ssh://localhost/tmp
ask_password = true
[cache]
ssh = dvc-storage
This method resolves the name under the cache section into the
correct Remote instance.
Args:
config (dict): The cache section on the config file
name (str): Name of the section we are interested in to retrieve
Returns:
remote (dvc.Remote): Remote instance that the section is referring.
None when there's no remote with that name.
Example:
>>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh')
"""
from dvc.remote import Remote
remote = config.get(name)
if not remote:
return None
settings = self.repo.config.get_remote_settings(remote)
return Remote(self.repo, settings) | python | def _get_remote(self, config, name):
"""
The config file is stored in a way that allows you to have a
cache for each remote.
This is needed when specifying external outputs
(as they require you to have an external cache location).
Imagine a config file like the following:
['remote "dvc-storage"']
url = ssh://localhost/tmp
ask_password = true
[cache]
ssh = dvc-storage
This method resolves the name under the cache section into the
correct Remote instance.
Args:
config (dict): The cache section on the config file
name (str): Name of the section we are interested in to retrieve
Returns:
remote (dvc.Remote): Remote instance that the section is referring.
None when there's no remote with that name.
Example:
>>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh')
"""
from dvc.remote import Remote
remote = config.get(name)
if not remote:
return None
settings = self.repo.config.get_remote_settings(remote)
return Remote(self.repo, settings) | [
"def",
"_get_remote",
"(",
"self",
",",
"config",
",",
"name",
")",
":",
"from",
"dvc",
".",
"remote",
"import",
"Remote",
"remote",
"=",
"config",
".",
"get",
"(",
"name",
")",
"if",
"not",
"remote",
":",
"return",
"None",
"settings",
"=",
"self",
"... | The config file is stored in a way that allows you to have a
cache for each remote.
This is needed when specifying external outputs
(as they require you to have an external cache location).
Imagine a config file like the following:
['remote "dvc-storage"']
url = ssh://localhost/tmp
ask_password = true
[cache]
ssh = dvc-storage
This method resolves the name under the cache section into the
correct Remote instance.
Args:
config (dict): The cache section on the config file
name (str): Name of the section we are interested in to retrieve
Returns:
remote (dvc.Remote): Remote instance that the section is referring.
None when there's no remote with that name.
Example:
>>> _get_remote(config={'ssh': 'dvc-storage'}, name='ssh') | [
"The",
"config",
"file",
"is",
"stored",
"in",
"a",
"way",
"that",
"allows",
"you",
"to",
"have",
"a",
"cache",
"for",
"each",
"remote",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cache.py#L52-L91 |
30,049 | iterative/dvc | dvc/dagascii.py | draw | def draw(vertexes, edges):
"""Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges.
"""
# pylint: disable=too-many-locals
# NOTE: coordinates might me negative, so we need to shift
# everything to the positive plane before we actually draw it.
Xs = [] # pylint: disable=invalid-name
Ys = [] # pylint: disable=invalid-name
sug = _build_sugiyama_layout(vertexes, edges)
for vertex in sug.g.sV:
# NOTE: moving boxes w/2 to the left
Xs.append(vertex.view.xy[0] - vertex.view.w / 2.0)
Xs.append(vertex.view.xy[0] + vertex.view.w / 2.0)
Ys.append(vertex.view.xy[1])
Ys.append(vertex.view.xy[1] + vertex.view.h)
for edge in sug.g.sE:
for x, y in edge.view._pts: # pylint: disable=protected-access
Xs.append(x)
Ys.append(y)
minx = min(Xs)
miny = min(Ys)
maxx = max(Xs)
maxy = max(Ys)
canvas_cols = int(math.ceil(math.ceil(maxx) - math.floor(minx))) + 1
canvas_lines = int(round(maxy - miny))
canvas = AsciiCanvas(canvas_cols, canvas_lines)
# NOTE: first draw edges so that node boxes could overwrite them
for edge in sug.g.sE:
# pylint: disable=protected-access
assert len(edge.view._pts) > 1
for index in range(1, len(edge.view._pts)):
start = edge.view._pts[index - 1]
end = edge.view._pts[index]
start_x = int(round(start[0] - minx))
start_y = int(round(start[1] - miny))
end_x = int(round(end[0] - minx))
end_y = int(round(end[1] - miny))
assert start_x >= 0
assert start_y >= 0
assert end_x >= 0
assert end_y >= 0
canvas.line(start_x, start_y, end_x, end_y, "*")
for vertex in sug.g.sV:
# NOTE: moving boxes w/2 to the left
x = vertex.view.xy[0] - vertex.view.w / 2.0
y = vertex.view.xy[1]
canvas.box(
int(round(x - minx)),
int(round(y - miny)),
vertex.view.w,
vertex.view.h,
)
canvas.text(
int(round(x - minx)) + 1, int(round(y - miny)) + 1, vertex.data
)
canvas.draw() | python | def draw(vertexes, edges):
"""Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges.
"""
# pylint: disable=too-many-locals
# NOTE: coordinates might me negative, so we need to shift
# everything to the positive plane before we actually draw it.
Xs = [] # pylint: disable=invalid-name
Ys = [] # pylint: disable=invalid-name
sug = _build_sugiyama_layout(vertexes, edges)
for vertex in sug.g.sV:
# NOTE: moving boxes w/2 to the left
Xs.append(vertex.view.xy[0] - vertex.view.w / 2.0)
Xs.append(vertex.view.xy[0] + vertex.view.w / 2.0)
Ys.append(vertex.view.xy[1])
Ys.append(vertex.view.xy[1] + vertex.view.h)
for edge in sug.g.sE:
for x, y in edge.view._pts: # pylint: disable=protected-access
Xs.append(x)
Ys.append(y)
minx = min(Xs)
miny = min(Ys)
maxx = max(Xs)
maxy = max(Ys)
canvas_cols = int(math.ceil(math.ceil(maxx) - math.floor(minx))) + 1
canvas_lines = int(round(maxy - miny))
canvas = AsciiCanvas(canvas_cols, canvas_lines)
# NOTE: first draw edges so that node boxes could overwrite them
for edge in sug.g.sE:
# pylint: disable=protected-access
assert len(edge.view._pts) > 1
for index in range(1, len(edge.view._pts)):
start = edge.view._pts[index - 1]
end = edge.view._pts[index]
start_x = int(round(start[0] - minx))
start_y = int(round(start[1] - miny))
end_x = int(round(end[0] - minx))
end_y = int(round(end[1] - miny))
assert start_x >= 0
assert start_y >= 0
assert end_x >= 0
assert end_y >= 0
canvas.line(start_x, start_y, end_x, end_y, "*")
for vertex in sug.g.sV:
# NOTE: moving boxes w/2 to the left
x = vertex.view.xy[0] - vertex.view.w / 2.0
y = vertex.view.xy[1]
canvas.box(
int(round(x - minx)),
int(round(y - miny)),
vertex.view.w,
vertex.view.h,
)
canvas.text(
int(round(x - minx)) + 1, int(round(y - miny)) + 1, vertex.data
)
canvas.draw() | [
"def",
"draw",
"(",
"vertexes",
",",
"edges",
")",
":",
"# pylint: disable=too-many-locals",
"# NOTE: coordinates might me negative, so we need to shift",
"# everything to the positive plane before we actually draw it.",
"Xs",
"=",
"[",
"]",
"# pylint: disable=invalid-name",
"Ys",
... | Build a DAG and draw it in ASCII.
Args:
vertexes (list): list of graph vertexes.
edges (list): list of graph edges. | [
"Build",
"a",
"DAG",
"and",
"draw",
"it",
"in",
"ASCII",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L297-L370 |
30,050 | iterative/dvc | dvc/dagascii.py | AsciiCanvas.draw | def draw(self):
"""Draws ASCII canvas on the screen."""
if sys.stdout.isatty(): # pragma: no cover
from asciimatics.screen import Screen
Screen.wrapper(self._do_draw)
else:
for line in self.canvas:
print("".join(line)) | python | def draw(self):
"""Draws ASCII canvas on the screen."""
if sys.stdout.isatty(): # pragma: no cover
from asciimatics.screen import Screen
Screen.wrapper(self._do_draw)
else:
for line in self.canvas:
print("".join(line)) | [
"def",
"draw",
"(",
"self",
")",
":",
"if",
"sys",
".",
"stdout",
".",
"isatty",
"(",
")",
":",
"# pragma: no cover",
"from",
"asciimatics",
".",
"screen",
"import",
"Screen",
"Screen",
".",
"wrapper",
"(",
"self",
".",
"_do_draw",
")",
"else",
":",
"f... | Draws ASCII canvas on the screen. | [
"Draws",
"ASCII",
"canvas",
"on",
"the",
"screen",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L59-L67 |
30,051 | iterative/dvc | dvc/dagascii.py | AsciiCanvas.point | def point(self, x, y, char):
"""Create a point on ASCII canvas.
Args:
x (int): x coordinate. Should be >= 0 and < number of columns in
the canvas.
y (int): y coordinate. Should be >= 0 an < number of lines in the
canvas.
char (str): character to place in the specified point on the
canvas.
"""
assert len(char) == 1
assert x >= 0
assert x < self.cols
assert y >= 0
assert y < self.lines
self.canvas[y][x] = char | python | def point(self, x, y, char):
"""Create a point on ASCII canvas.
Args:
x (int): x coordinate. Should be >= 0 and < number of columns in
the canvas.
y (int): y coordinate. Should be >= 0 an < number of lines in the
canvas.
char (str): character to place in the specified point on the
canvas.
"""
assert len(char) == 1
assert x >= 0
assert x < self.cols
assert y >= 0
assert y < self.lines
self.canvas[y][x] = char | [
"def",
"point",
"(",
"self",
",",
"x",
",",
"y",
",",
"char",
")",
":",
"assert",
"len",
"(",
"char",
")",
"==",
"1",
"assert",
"x",
">=",
"0",
"assert",
"x",
"<",
"self",
".",
"cols",
"assert",
"y",
">=",
"0",
"assert",
"y",
"<",
"self",
"."... | Create a point on ASCII canvas.
Args:
x (int): x coordinate. Should be >= 0 and < number of columns in
the canvas.
y (int): y coordinate. Should be >= 0 an < number of lines in the
canvas.
char (str): character to place in the specified point on the
canvas. | [
"Create",
"a",
"point",
"on",
"ASCII",
"canvas",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L155-L172 |
30,052 | iterative/dvc | dvc/dagascii.py | AsciiCanvas.line | def line(self, x0, y0, x1, y1, char):
"""Create a line on ASCII canvas.
Args:
x0 (int): x coordinate where the line should start.
y0 (int): y coordinate where the line should start.
x1 (int): x coordinate where the line should end.
y1 (int): y coordinate where the line should end.
char (str): character to draw the line with.
"""
# pylint: disable=too-many-arguments, too-many-branches
if x0 > x1:
x1, x0 = x0, x1
y1, y0 = y0, y1
dx = x1 - x0
dy = y1 - y0
if dx == 0 and dy == 0:
self.point(x0, y0, char)
elif abs(dx) >= abs(dy):
for x in range(x0, x1 + 1):
if dx == 0:
y = y0
else:
y = y0 + int(round((x - x0) * dy / float((dx))))
self.point(x, y, char)
elif y0 < y1:
for y in range(y0, y1 + 1):
if dy == 0:
x = x0
else:
x = x0 + int(round((y - y0) * dx / float((dy))))
self.point(x, y, char)
else:
for y in range(y1, y0 + 1):
if dy == 0:
x = x0
else:
x = x1 + int(round((y - y1) * dx / float((dy))))
self.point(x, y, char) | python | def line(self, x0, y0, x1, y1, char):
"""Create a line on ASCII canvas.
Args:
x0 (int): x coordinate where the line should start.
y0 (int): y coordinate where the line should start.
x1 (int): x coordinate where the line should end.
y1 (int): y coordinate where the line should end.
char (str): character to draw the line with.
"""
# pylint: disable=too-many-arguments, too-many-branches
if x0 > x1:
x1, x0 = x0, x1
y1, y0 = y0, y1
dx = x1 - x0
dy = y1 - y0
if dx == 0 and dy == 0:
self.point(x0, y0, char)
elif abs(dx) >= abs(dy):
for x in range(x0, x1 + 1):
if dx == 0:
y = y0
else:
y = y0 + int(round((x - x0) * dy / float((dx))))
self.point(x, y, char)
elif y0 < y1:
for y in range(y0, y1 + 1):
if dy == 0:
x = x0
else:
x = x0 + int(round((y - y0) * dx / float((dy))))
self.point(x, y, char)
else:
for y in range(y1, y0 + 1):
if dy == 0:
x = x0
else:
x = x1 + int(round((y - y1) * dx / float((dy))))
self.point(x, y, char) | [
"def",
"line",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"x1",
",",
"y1",
",",
"char",
")",
":",
"# pylint: disable=too-many-arguments, too-many-branches",
"if",
"x0",
">",
"x1",
":",
"x1",
",",
"x0",
"=",
"x0",
",",
"x1",
"y1",
",",
"y0",
"=",
"y0",
... | Create a line on ASCII canvas.
Args:
x0 (int): x coordinate where the line should start.
y0 (int): y coordinate where the line should start.
x1 (int): x coordinate where the line should end.
y1 (int): y coordinate where the line should end.
char (str): character to draw the line with. | [
"Create",
"a",
"line",
"on",
"ASCII",
"canvas",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L174-L214 |
30,053 | iterative/dvc | dvc/dagascii.py | AsciiCanvas.text | def text(self, x, y, text):
"""Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
"""
for i, char in enumerate(text):
self.point(x + i, y, char) | python | def text(self, x, y, text):
"""Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed.
"""
for i, char in enumerate(text):
self.point(x + i, y, char) | [
"def",
"text",
"(",
"self",
",",
"x",
",",
"y",
",",
"text",
")",
":",
"for",
"i",
",",
"char",
"in",
"enumerate",
"(",
"text",
")",
":",
"self",
".",
"point",
"(",
"x",
"+",
"i",
",",
"y",
",",
"char",
")"
] | Print a text on ASCII canvas.
Args:
x (int): x coordinate where the text should start.
y (int): y coordinate where the text should start.
text (str): string that should be printed. | [
"Print",
"a",
"text",
"on",
"ASCII",
"canvas",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L216-L225 |
30,054 | iterative/dvc | dvc/dagascii.py | AsciiCanvas.box | def box(self, x0, y0, width, height):
"""Create a box on ASCII canvas.
Args:
x0 (int): x coordinate of the box corner.
y0 (int): y coordinate of the box corner.
width (int): box width.
height (int): box height.
"""
assert width > 1
assert height > 1
width -= 1
height -= 1
for x in range(x0, x0 + width):
self.point(x, y0, "-")
self.point(x, y0 + height, "-")
for y in range(y0, y0 + height):
self.point(x0, y, "|")
self.point(x0 + width, y, "|")
self.point(x0, y0, "+")
self.point(x0 + width, y0, "+")
self.point(x0, y0 + height, "+")
self.point(x0 + width, y0 + height, "+") | python | def box(self, x0, y0, width, height):
"""Create a box on ASCII canvas.
Args:
x0 (int): x coordinate of the box corner.
y0 (int): y coordinate of the box corner.
width (int): box width.
height (int): box height.
"""
assert width > 1
assert height > 1
width -= 1
height -= 1
for x in range(x0, x0 + width):
self.point(x, y0, "-")
self.point(x, y0 + height, "-")
for y in range(y0, y0 + height):
self.point(x0, y, "|")
self.point(x0 + width, y, "|")
self.point(x0, y0, "+")
self.point(x0 + width, y0, "+")
self.point(x0, y0 + height, "+")
self.point(x0 + width, y0 + height, "+") | [
"def",
"box",
"(",
"self",
",",
"x0",
",",
"y0",
",",
"width",
",",
"height",
")",
":",
"assert",
"width",
">",
"1",
"assert",
"height",
">",
"1",
"width",
"-=",
"1",
"height",
"-=",
"1",
"for",
"x",
"in",
"range",
"(",
"x0",
",",
"x0",
"+",
... | Create a box on ASCII canvas.
Args:
x0 (int): x coordinate of the box corner.
y0 (int): y coordinate of the box corner.
width (int): box width.
height (int): box height. | [
"Create",
"a",
"box",
"on",
"ASCII",
"canvas",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/dagascii.py#L227-L253 |
30,055 | iterative/dvc | dvc/progress.py | Progress.refresh | def refresh(self, line=None):
"""Refreshes progress bar."""
# Just go away if it is locked. Will update next time
if not self._lock.acquire(False):
return
if line is None:
line = self._line
if sys.stdout.isatty() and line is not None:
self._writeln(line)
self._line = line
self._lock.release() | python | def refresh(self, line=None):
"""Refreshes progress bar."""
# Just go away if it is locked. Will update next time
if not self._lock.acquire(False):
return
if line is None:
line = self._line
if sys.stdout.isatty() and line is not None:
self._writeln(line)
self._line = line
self._lock.release() | [
"def",
"refresh",
"(",
"self",
",",
"line",
"=",
"None",
")",
":",
"# Just go away if it is locked. Will update next time",
"if",
"not",
"self",
".",
"_lock",
".",
"acquire",
"(",
"False",
")",
":",
"return",
"if",
"line",
"is",
"None",
":",
"line",
"=",
"... | Refreshes progress bar. | [
"Refreshes",
"progress",
"bar",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L49-L62 |
30,056 | iterative/dvc | dvc/progress.py | Progress.update_target | def update_target(self, name, current, total):
"""Updates progress bar for a specified target."""
self.refresh(self._bar(name, current, total)) | python | def update_target(self, name, current, total):
"""Updates progress bar for a specified target."""
self.refresh(self._bar(name, current, total)) | [
"def",
"update_target",
"(",
"self",
",",
"name",
",",
"current",
",",
"total",
")",
":",
"self",
".",
"refresh",
"(",
"self",
".",
"_bar",
"(",
"name",
",",
"current",
",",
"total",
")",
")"
] | Updates progress bar for a specified target. | [
"Updates",
"progress",
"bar",
"for",
"a",
"specified",
"target",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L64-L66 |
30,057 | iterative/dvc | dvc/progress.py | Progress.finish_target | def finish_target(self, name):
"""Finishes progress bar for a specified target."""
# We have to write a msg about finished target
with self._lock:
pbar = self._bar(name, 100, 100)
if sys.stdout.isatty():
self.clearln()
self._print(pbar)
self._n_finished += 1
self._line = None | python | def finish_target(self, name):
"""Finishes progress bar for a specified target."""
# We have to write a msg about finished target
with self._lock:
pbar = self._bar(name, 100, 100)
if sys.stdout.isatty():
self.clearln()
self._print(pbar)
self._n_finished += 1
self._line = None | [
"def",
"finish_target",
"(",
"self",
",",
"name",
")",
":",
"# We have to write a msg about finished target",
"with",
"self",
".",
"_lock",
":",
"pbar",
"=",
"self",
".",
"_bar",
"(",
"name",
",",
"100",
",",
"100",
")",
"if",
"sys",
".",
"stdout",
".",
... | Finishes progress bar for a specified target. | [
"Finishes",
"progress",
"bar",
"for",
"a",
"specified",
"target",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/progress.py#L68-L80 |
30,058 | iterative/dvc | dvc/repo/diff.py | diff | def diff(self, a_ref, target=None, b_ref=None):
"""Gerenates diff message string output
Args:
target(str) - file/directory to check diff of
a_ref(str) - first tag
(optional) b_ref(str) - second git tag
Returns:
string: string of output message with diff info
"""
result = {}
diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref)
result[DIFF_A_REF] = diff_dct[DIFF_A_REF]
result[DIFF_B_REF] = diff_dct[DIFF_B_REF]
if diff_dct[DIFF_EQUAL]:
result[DIFF_EQUAL] = True
return result
result[DIFF_LIST] = []
diff_outs = _get_diff_outs(self, diff_dct)
if target is None:
result[DIFF_LIST] = [
_diff_royal(self, path, diff_outs[path]) for path in diff_outs
]
elif target in diff_outs:
result[DIFF_LIST] = [_diff_royal(self, target, diff_outs[target])]
else:
msg = "Have not found file/directory '{}' in the commits"
raise FileNotInCommitError(msg.format(target))
return result | python | def diff(self, a_ref, target=None, b_ref=None):
"""Gerenates diff message string output
Args:
target(str) - file/directory to check diff of
a_ref(str) - first tag
(optional) b_ref(str) - second git tag
Returns:
string: string of output message with diff info
"""
result = {}
diff_dct = self.scm.get_diff_trees(a_ref, b_ref=b_ref)
result[DIFF_A_REF] = diff_dct[DIFF_A_REF]
result[DIFF_B_REF] = diff_dct[DIFF_B_REF]
if diff_dct[DIFF_EQUAL]:
result[DIFF_EQUAL] = True
return result
result[DIFF_LIST] = []
diff_outs = _get_diff_outs(self, diff_dct)
if target is None:
result[DIFF_LIST] = [
_diff_royal(self, path, diff_outs[path]) for path in diff_outs
]
elif target in diff_outs:
result[DIFF_LIST] = [_diff_royal(self, target, diff_outs[target])]
else:
msg = "Have not found file/directory '{}' in the commits"
raise FileNotInCommitError(msg.format(target))
return result | [
"def",
"diff",
"(",
"self",
",",
"a_ref",
",",
"target",
"=",
"None",
",",
"b_ref",
"=",
"None",
")",
":",
"result",
"=",
"{",
"}",
"diff_dct",
"=",
"self",
".",
"scm",
".",
"get_diff_trees",
"(",
"a_ref",
",",
"b_ref",
"=",
"b_ref",
")",
"result",... | Gerenates diff message string output
Args:
target(str) - file/directory to check diff of
a_ref(str) - first tag
(optional) b_ref(str) - second git tag
Returns:
string: string of output message with diff info | [
"Gerenates",
"diff",
"message",
"string",
"output"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/diff.py#L223-L252 |
30,059 | iterative/dvc | dvc/repo/reproduce.py | _reproduce_stages | def _reproduce_stages(
G,
stages,
node,
force,
dry,
interactive,
ignore_build_cache,
no_commit,
downstream,
):
r"""Derive the evaluation of the given node for the given graph.
When you _reproduce a stage_, you want to _evaluate the descendants_
to know if it make sense to _recompute_ it. A post-ordered search
will give us an order list of the nodes we want.
For example, let's say that we have the following pipeline:
E
/ \
D F
/ \ \
B C G
\ /
A
The derived evaluation of D would be: [A, B, C, D]
In case that `downstream` option is specifed, the desired effect
is to derive the evaluation starting from the given stage up to the
ancestors. However, the `networkx.ancestors` returns a set, without
any guarantee of any order, so we are going to reverse the graph and
use a pre-ordered search using the given stage as a starting point.
E A
/ \ / \
D F B C G
/ \ \ --- reverse --> \ / /
B C G D F
\ / \ /
A E
The derived evaluation of _downstream_ B would be: [B, D, E]
"""
import networkx as nx
if downstream:
# NOTE (py3 only):
# Python's `deepcopy` defaults to pickle/unpickle the object.
# Stages are complex objects (with references to `repo`, `outs`,
# and `deps`) that cause struggles when you try to serialize them.
# We need to create a copy of the graph itself, and then reverse it,
# instead of using graph.reverse() directly because it calls
# `deepcopy` underneath -- unless copy=False is specified.
pipeline = nx.dfs_preorder_nodes(G.copy().reverse(copy=False), node)
else:
pipeline = nx.dfs_postorder_nodes(G, node)
result = []
for n in pipeline:
try:
ret = _reproduce_stage(
stages, n, force, dry, interactive, no_commit
)
if len(ret) != 0 and ignore_build_cache:
# NOTE: we are walking our pipeline from the top to the
# bottom. If one stage is changed, it will be reproduced,
# which tells us that we should force reproducing all of
# the other stages down below, even if their direct
# dependencies didn't change.
force = True
result += ret
except Exception as ex:
raise ReproductionError(stages[n].relpath, ex)
return result | python | def _reproduce_stages(
G,
stages,
node,
force,
dry,
interactive,
ignore_build_cache,
no_commit,
downstream,
):
r"""Derive the evaluation of the given node for the given graph.
When you _reproduce a stage_, you want to _evaluate the descendants_
to know if it make sense to _recompute_ it. A post-ordered search
will give us an order list of the nodes we want.
For example, let's say that we have the following pipeline:
E
/ \
D F
/ \ \
B C G
\ /
A
The derived evaluation of D would be: [A, B, C, D]
In case that `downstream` option is specifed, the desired effect
is to derive the evaluation starting from the given stage up to the
ancestors. However, the `networkx.ancestors` returns a set, without
any guarantee of any order, so we are going to reverse the graph and
use a pre-ordered search using the given stage as a starting point.
E A
/ \ / \
D F B C G
/ \ \ --- reverse --> \ / /
B C G D F
\ / \ /
A E
The derived evaluation of _downstream_ B would be: [B, D, E]
"""
import networkx as nx
if downstream:
# NOTE (py3 only):
# Python's `deepcopy` defaults to pickle/unpickle the object.
# Stages are complex objects (with references to `repo`, `outs`,
# and `deps`) that cause struggles when you try to serialize them.
# We need to create a copy of the graph itself, and then reverse it,
# instead of using graph.reverse() directly because it calls
# `deepcopy` underneath -- unless copy=False is specified.
pipeline = nx.dfs_preorder_nodes(G.copy().reverse(copy=False), node)
else:
pipeline = nx.dfs_postorder_nodes(G, node)
result = []
for n in pipeline:
try:
ret = _reproduce_stage(
stages, n, force, dry, interactive, no_commit
)
if len(ret) != 0 and ignore_build_cache:
# NOTE: we are walking our pipeline from the top to the
# bottom. If one stage is changed, it will be reproduced,
# which tells us that we should force reproducing all of
# the other stages down below, even if their direct
# dependencies didn't change.
force = True
result += ret
except Exception as ex:
raise ReproductionError(stages[n].relpath, ex)
return result | [
"def",
"_reproduce_stages",
"(",
"G",
",",
"stages",
",",
"node",
",",
"force",
",",
"dry",
",",
"interactive",
",",
"ignore_build_cache",
",",
"no_commit",
",",
"downstream",
",",
")",
":",
"import",
"networkx",
"as",
"nx",
"if",
"downstream",
":",
"# NOT... | r"""Derive the evaluation of the given node for the given graph.
When you _reproduce a stage_, you want to _evaluate the descendants_
to know if it make sense to _recompute_ it. A post-ordered search
will give us an order list of the nodes we want.
For example, let's say that we have the following pipeline:
E
/ \
D F
/ \ \
B C G
\ /
A
The derived evaluation of D would be: [A, B, C, D]
In case that `downstream` option is specifed, the desired effect
is to derive the evaluation starting from the given stage up to the
ancestors. However, the `networkx.ancestors` returns a set, without
any guarantee of any order, so we are going to reverse the graph and
use a pre-ordered search using the given stage as a starting point.
E A
/ \ / \
D F B C G
/ \ \ --- reverse --> \ / /
B C G D F
\ / \ /
A E
The derived evaluation of _downstream_ B would be: [B, D, E] | [
"r",
"Derive",
"the",
"evaluation",
"of",
"the",
"given",
"node",
"for",
"the",
"given",
"graph",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/reproduce.py#L132-L210 |
30,060 | iterative/dvc | dvc/utils/compat.py | csv_reader | def csv_reader(unicode_csv_data, dialect=None, **kwargs):
"""csv.reader doesn't support Unicode input, so need to use some tricks
to work around this.
Source: https://docs.python.org/2/library/csv.html#csv-examples
"""
import csv
dialect = dialect or csv.excel
if is_py3:
# Python3 supports encoding by default, so just return the object
for row in csv.reader(unicode_csv_data, dialect=dialect, **kwargs):
yield [cell for cell in row]
else:
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
reader = csv.reader(
utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs
)
for row in reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, "utf-8") for cell in row] | python | def csv_reader(unicode_csv_data, dialect=None, **kwargs):
"""csv.reader doesn't support Unicode input, so need to use some tricks
to work around this.
Source: https://docs.python.org/2/library/csv.html#csv-examples
"""
import csv
dialect = dialect or csv.excel
if is_py3:
# Python3 supports encoding by default, so just return the object
for row in csv.reader(unicode_csv_data, dialect=dialect, **kwargs):
yield [cell for cell in row]
else:
# csv.py doesn't do Unicode; encode temporarily as UTF-8:
reader = csv.reader(
utf_8_encoder(unicode_csv_data), dialect=dialect, **kwargs
)
for row in reader:
# decode UTF-8 back to Unicode, cell by cell:
yield [unicode(cell, "utf-8") for cell in row] | [
"def",
"csv_reader",
"(",
"unicode_csv_data",
",",
"dialect",
"=",
"None",
",",
"*",
"*",
"kwargs",
")",
":",
"import",
"csv",
"dialect",
"=",
"dialect",
"or",
"csv",
".",
"excel",
"if",
"is_py3",
":",
"# Python3 supports encoding by default, so just return the ob... | csv.reader doesn't support Unicode input, so need to use some tricks
to work around this.
Source: https://docs.python.org/2/library/csv.html#csv-examples | [
"csv",
".",
"reader",
"doesn",
"t",
"support",
"Unicode",
"input",
"so",
"need",
"to",
"use",
"some",
"tricks",
"to",
"work",
"around",
"this",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/compat.py#L30-L52 |
30,061 | iterative/dvc | dvc/repo/pkg/install.py | install | def install(self, address, target_dir, select=[], fname=None):
"""
Install package.
The command can be run only from DVC project root.
E.g.
Having: DVC package in https://github.com/dmpetrov/tag_classifier
$ dvc pkg install https://github.com/dmpetrov/tag_classifier
Result: tag_classifier package in dvc_mod/ directory
"""
if not os.path.isdir(target_dir):
raise DvcException(
"target directory '{}' does not exist".format(target_dir)
)
curr_dir = os.path.realpath(os.curdir)
if not os.path.realpath(target_dir).startswith(curr_dir):
raise DvcException(
"the current directory should be a subdirectory of the target "
"dir '{}'".format(target_dir)
)
addresses = [address] if address else PackageManager.read_packages()
for addr in addresses:
mgr = PackageManager.get_package(addr)
mgr.install_or_update(self, address, target_dir, select, fname) | python | def install(self, address, target_dir, select=[], fname=None):
"""
Install package.
The command can be run only from DVC project root.
E.g.
Having: DVC package in https://github.com/dmpetrov/tag_classifier
$ dvc pkg install https://github.com/dmpetrov/tag_classifier
Result: tag_classifier package in dvc_mod/ directory
"""
if not os.path.isdir(target_dir):
raise DvcException(
"target directory '{}' does not exist".format(target_dir)
)
curr_dir = os.path.realpath(os.curdir)
if not os.path.realpath(target_dir).startswith(curr_dir):
raise DvcException(
"the current directory should be a subdirectory of the target "
"dir '{}'".format(target_dir)
)
addresses = [address] if address else PackageManager.read_packages()
for addr in addresses:
mgr = PackageManager.get_package(addr)
mgr.install_or_update(self, address, target_dir, select, fname) | [
"def",
"install",
"(",
"self",
",",
"address",
",",
"target_dir",
",",
"select",
"=",
"[",
"]",
",",
"fname",
"=",
"None",
")",
":",
"if",
"not",
"os",
".",
"path",
".",
"isdir",
"(",
"target_dir",
")",
":",
"raise",
"DvcException",
"(",
"\"target di... | Install package.
The command can be run only from DVC project root.
E.g.
Having: DVC package in https://github.com/dmpetrov/tag_classifier
$ dvc pkg install https://github.com/dmpetrov/tag_classifier
Result: tag_classifier package in dvc_mod/ directory | [
"Install",
"package",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/pkg/install.py#L144-L173 |
30,062 | iterative/dvc | dvc/stage.py | Stage.is_import | def is_import(self):
"""Whether the stage file was created with `dvc import`."""
return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1 | python | def is_import(self):
"""Whether the stage file was created with `dvc import`."""
return not self.cmd and len(self.deps) == 1 and len(self.outs) == 1 | [
"def",
"is_import",
"(",
"self",
")",
":",
"return",
"not",
"self",
".",
"cmd",
"and",
"len",
"(",
"self",
".",
"deps",
")",
"==",
"1",
"and",
"len",
"(",
"self",
".",
"outs",
")",
"==",
"1"
] | Whether the stage file was created with `dvc import`. | [
"Whether",
"the",
"stage",
"file",
"was",
"created",
"with",
"dvc",
"import",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/stage.py#L211-L213 |
30,063 | iterative/dvc | dvc/stage.py | Stage.is_cached | def is_cached(self):
"""
Checks if this stage has been already ran and stored
"""
from dvc.remote.local import RemoteLOCAL
from dvc.remote.s3 import RemoteS3
old = Stage.load(self.repo, self.path)
if old._changed_outs():
return False
# NOTE: need to save checksums for deps in order to compare them
# with what is written in the old stage.
for dep in self.deps:
dep.save()
old_d = old.dumpd()
new_d = self.dumpd()
# NOTE: need to remove checksums from old dict in order to compare
# it to the new one, since the new one doesn't have checksums yet.
old_d.pop(self.PARAM_MD5, None)
new_d.pop(self.PARAM_MD5, None)
outs = old_d.get(self.PARAM_OUTS, [])
for out in outs:
out.pop(RemoteLOCAL.PARAM_CHECKSUM, None)
out.pop(RemoteS3.PARAM_CHECKSUM, None)
if old_d != new_d:
return False
# NOTE: committing to prevent potential data duplication. For example
#
# $ dvc config cache.type hardlink
# $ echo foo > foo
# $ dvc add foo
# $ rm -f foo
# $ echo foo > foo
# $ dvc add foo # should replace foo with a link to cache
#
old.commit()
return True | python | def is_cached(self):
"""
Checks if this stage has been already ran and stored
"""
from dvc.remote.local import RemoteLOCAL
from dvc.remote.s3 import RemoteS3
old = Stage.load(self.repo, self.path)
if old._changed_outs():
return False
# NOTE: need to save checksums for deps in order to compare them
# with what is written in the old stage.
for dep in self.deps:
dep.save()
old_d = old.dumpd()
new_d = self.dumpd()
# NOTE: need to remove checksums from old dict in order to compare
# it to the new one, since the new one doesn't have checksums yet.
old_d.pop(self.PARAM_MD5, None)
new_d.pop(self.PARAM_MD5, None)
outs = old_d.get(self.PARAM_OUTS, [])
for out in outs:
out.pop(RemoteLOCAL.PARAM_CHECKSUM, None)
out.pop(RemoteS3.PARAM_CHECKSUM, None)
if old_d != new_d:
return False
# NOTE: committing to prevent potential data duplication. For example
#
# $ dvc config cache.type hardlink
# $ echo foo > foo
# $ dvc add foo
# $ rm -f foo
# $ echo foo > foo
# $ dvc add foo # should replace foo with a link to cache
#
old.commit()
return True | [
"def",
"is_cached",
"(",
"self",
")",
":",
"from",
"dvc",
".",
"remote",
".",
"local",
"import",
"RemoteLOCAL",
"from",
"dvc",
".",
"remote",
".",
"s3",
"import",
"RemoteS3",
"old",
"=",
"Stage",
".",
"load",
"(",
"self",
".",
"repo",
",",
"self",
".... | Checks if this stage has been already ran and stored | [
"Checks",
"if",
"this",
"stage",
"has",
"been",
"already",
"ran",
"and",
"stored"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/stage.py#L369-L411 |
30,064 | iterative/dvc | dvc/daemon.py | daemon | def daemon(args):
"""Launch a `dvc daemon` command in a detached process.
Args:
args (list): list of arguments to append to `dvc daemon` command.
"""
if os.environ.get(DVC_DAEMON):
logger.debug("skipping launching a new daemon.")
return
cmd = [sys.executable]
if not is_binary():
cmd += ["-m", "dvc"]
cmd += ["daemon", "-q"] + args
env = fix_env()
file_path = os.path.abspath(inspect.stack()[0][1])
env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2(
os.path.dirname(os.path.dirname(file_path))
)
env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1")
_spawn(cmd, env) | python | def daemon(args):
"""Launch a `dvc daemon` command in a detached process.
Args:
args (list): list of arguments to append to `dvc daemon` command.
"""
if os.environ.get(DVC_DAEMON):
logger.debug("skipping launching a new daemon.")
return
cmd = [sys.executable]
if not is_binary():
cmd += ["-m", "dvc"]
cmd += ["daemon", "-q"] + args
env = fix_env()
file_path = os.path.abspath(inspect.stack()[0][1])
env[cast_bytes_py2("PYTHONPATH")] = cast_bytes_py2(
os.path.dirname(os.path.dirname(file_path))
)
env[cast_bytes_py2(DVC_DAEMON)] = cast_bytes_py2("1")
_spawn(cmd, env) | [
"def",
"daemon",
"(",
"args",
")",
":",
"if",
"os",
".",
"environ",
".",
"get",
"(",
"DVC_DAEMON",
")",
":",
"logger",
".",
"debug",
"(",
"\"skipping launching a new daemon.\"",
")",
"return",
"cmd",
"=",
"[",
"sys",
".",
"executable",
"]",
"if",
"not",
... | Launch a `dvc daemon` command in a detached process.
Args:
args (list): list of arguments to append to `dvc daemon` command. | [
"Launch",
"a",
"dvc",
"daemon",
"command",
"in",
"a",
"detached",
"process",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/daemon.py#L85-L107 |
30,065 | iterative/dvc | dvc/command/init.py | add_parser | def add_parser(subparsers, parent_parser):
"""Setup parser for `dvc init`."""
INIT_HELP = "Initialize DVC in the current directory."
INIT_DESCRIPTION = (
"Initialize DVC in the current directory. Expects directory\n"
"to be a Git repository unless --no-scm option is specified."
)
init_parser = subparsers.add_parser(
"init",
parents=[parent_parser],
description=append_doc_link(INIT_DESCRIPTION, "init"),
help=INIT_HELP,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
init_parser.add_argument(
"--no-scm",
action="store_true",
default=False,
help="Initiate dvc in directory that is "
"not tracked by any scm tool (e.g. git).",
)
init_parser.add_argument(
"-f",
"--force",
action="store_true",
default=False,
help=(
"Overwrite existing '.dvc' directory. "
"This operation removes local cache."
),
)
init_parser.set_defaults(func=CmdInit) | python | def add_parser(subparsers, parent_parser):
"""Setup parser for `dvc init`."""
INIT_HELP = "Initialize DVC in the current directory."
INIT_DESCRIPTION = (
"Initialize DVC in the current directory. Expects directory\n"
"to be a Git repository unless --no-scm option is specified."
)
init_parser = subparsers.add_parser(
"init",
parents=[parent_parser],
description=append_doc_link(INIT_DESCRIPTION, "init"),
help=INIT_HELP,
formatter_class=argparse.RawDescriptionHelpFormatter,
)
init_parser.add_argument(
"--no-scm",
action="store_true",
default=False,
help="Initiate dvc in directory that is "
"not tracked by any scm tool (e.g. git).",
)
init_parser.add_argument(
"-f",
"--force",
action="store_true",
default=False,
help=(
"Overwrite existing '.dvc' directory. "
"This operation removes local cache."
),
)
init_parser.set_defaults(func=CmdInit) | [
"def",
"add_parser",
"(",
"subparsers",
",",
"parent_parser",
")",
":",
"INIT_HELP",
"=",
"\"Initialize DVC in the current directory.\"",
"INIT_DESCRIPTION",
"=",
"(",
"\"Initialize DVC in the current directory. Expects directory\\n\"",
"\"to be a Git repository unless --no-scm option ... | Setup parser for `dvc init`. | [
"Setup",
"parser",
"for",
"dvc",
"init",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/init.py#L31-L63 |
30,066 | iterative/dvc | dvc/repo/metrics/show.py | _format_csv | def _format_csv(content, delimiter):
"""Format delimited text to have same column width.
Args:
content (str): The content of a metric.
delimiter (str): Value separator
Returns:
str: Formatted content.
Example:
>>> content = (
"value_mse,deviation_mse,data_set\n"
"0.421601,0.173461,train\n"
"0.67528,0.289545,testing\n"
"0.671502,0.297848,validation\n"
)
>>> _format_csv(content, ",")
"value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n"
"""
reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter))
rows = [row for row in reader]
max_widths = [max(map(len, column)) for column in zip(*rows)]
lines = [
" ".join(
"{entry:{width}}".format(entry=entry, width=width + 2)
for entry, width in zip(row, max_widths)
)
for row in rows
]
return "\n".join(lines) | python | def _format_csv(content, delimiter):
"""Format delimited text to have same column width.
Args:
content (str): The content of a metric.
delimiter (str): Value separator
Returns:
str: Formatted content.
Example:
>>> content = (
"value_mse,deviation_mse,data_set\n"
"0.421601,0.173461,train\n"
"0.67528,0.289545,testing\n"
"0.671502,0.297848,validation\n"
)
>>> _format_csv(content, ",")
"value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n"
"""
reader = csv_reader(StringIO(content), delimiter=builtin_str(delimiter))
rows = [row for row in reader]
max_widths = [max(map(len, column)) for column in zip(*rows)]
lines = [
" ".join(
"{entry:{width}}".format(entry=entry, width=width + 2)
for entry, width in zip(row, max_widths)
)
for row in rows
]
return "\n".join(lines) | [
"def",
"_format_csv",
"(",
"content",
",",
"delimiter",
")",
":",
"reader",
"=",
"csv_reader",
"(",
"StringIO",
"(",
"content",
")",
",",
"delimiter",
"=",
"builtin_str",
"(",
"delimiter",
")",
")",
"rows",
"=",
"[",
"row",
"for",
"row",
"in",
"reader",
... | Format delimited text to have same column width.
Args:
content (str): The content of a metric.
delimiter (str): Value separator
Returns:
str: Formatted content.
Example:
>>> content = (
"value_mse,deviation_mse,data_set\n"
"0.421601,0.173461,train\n"
"0.67528,0.289545,testing\n"
"0.671502,0.297848,validation\n"
)
>>> _format_csv(content, ",")
"value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n" | [
"Format",
"delimited",
"text",
"to",
"have",
"same",
"column",
"width",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L77-L114 |
30,067 | iterative/dvc | dvc/repo/metrics/show.py | _format_output | def _format_output(content, typ):
"""Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format.
"""
if "csv" in str(typ):
return _format_csv(content, delimiter=",")
if "tsv" in str(typ):
return _format_csv(content, delimiter="\t")
return content | python | def _format_output(content, typ):
"""Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format.
"""
if "csv" in str(typ):
return _format_csv(content, delimiter=",")
if "tsv" in str(typ):
return _format_csv(content, delimiter="\t")
return content | [
"def",
"_format_output",
"(",
"content",
",",
"typ",
")",
":",
"if",
"\"csv\"",
"in",
"str",
"(",
"typ",
")",
":",
"return",
"_format_csv",
"(",
"content",
",",
"delimiter",
"=",
"\",\"",
")",
"if",
"\"tsv\"",
"in",
"str",
"(",
"typ",
")",
":",
"retu... | Tabularize the content according to its type.
Args:
content (str): The content of a metric.
typ (str): The type of metric -- (raw|json|tsv|htsv|csv|hcsv).
Returns:
str: Content in a raw or tabular format. | [
"Tabularize",
"the",
"content",
"according",
"to",
"its",
"type",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L117-L134 |
30,068 | iterative/dvc | dvc/repo/metrics/show.py | _collect_metrics | def _collect_metrics(repo, path, recursive, typ, xpath, branch):
"""Gather all the metric outputs.
Args:
path (str): Path to a metric file or a directory.
recursive (bool): If path is a directory, do a recursive search for
metrics on the given path.
typ (str): The type of metric to search for, could be one of the
following (raw|json|tsv|htsv|csv|hcsv).
xpath (str): Path to search for.
branch (str): Branch to look up for metrics.
Returns:
list(tuple): (output, typ, xpath)
- output:
- typ:
- xpath:
"""
outs = [out for stage in repo.stages() for out in stage.outs]
if path:
try:
outs = repo.find_outs_by_path(path, outs=outs, recursive=recursive)
except OutputNotFoundError:
logger.debug(
"stage file not for found for '{}' in branch '{}'".format(
path, branch
)
)
return []
res = []
for o in outs:
if not o.metric:
continue
if not typ and isinstance(o.metric, dict):
t = o.metric.get(o.PARAM_METRIC_TYPE, typ)
x = o.metric.get(o.PARAM_METRIC_XPATH, xpath)
else:
t = typ
x = xpath
res.append((o, t, x))
return res | python | def _collect_metrics(repo, path, recursive, typ, xpath, branch):
"""Gather all the metric outputs.
Args:
path (str): Path to a metric file or a directory.
recursive (bool): If path is a directory, do a recursive search for
metrics on the given path.
typ (str): The type of metric to search for, could be one of the
following (raw|json|tsv|htsv|csv|hcsv).
xpath (str): Path to search for.
branch (str): Branch to look up for metrics.
Returns:
list(tuple): (output, typ, xpath)
- output:
- typ:
- xpath:
"""
outs = [out for stage in repo.stages() for out in stage.outs]
if path:
try:
outs = repo.find_outs_by_path(path, outs=outs, recursive=recursive)
except OutputNotFoundError:
logger.debug(
"stage file not for found for '{}' in branch '{}'".format(
path, branch
)
)
return []
res = []
for o in outs:
if not o.metric:
continue
if not typ and isinstance(o.metric, dict):
t = o.metric.get(o.PARAM_METRIC_TYPE, typ)
x = o.metric.get(o.PARAM_METRIC_XPATH, xpath)
else:
t = typ
x = xpath
res.append((o, t, x))
return res | [
"def",
"_collect_metrics",
"(",
"repo",
",",
"path",
",",
"recursive",
",",
"typ",
",",
"xpath",
",",
"branch",
")",
":",
"outs",
"=",
"[",
"out",
"for",
"stage",
"in",
"repo",
".",
"stages",
"(",
")",
"for",
"out",
"in",
"stage",
".",
"outs",
"]",... | Gather all the metric outputs.
Args:
path (str): Path to a metric file or a directory.
recursive (bool): If path is a directory, do a recursive search for
metrics on the given path.
typ (str): The type of metric to search for, could be one of the
following (raw|json|tsv|htsv|csv|hcsv).
xpath (str): Path to search for.
branch (str): Branch to look up for metrics.
Returns:
list(tuple): (output, typ, xpath)
- output:
- typ:
- xpath: | [
"Gather",
"all",
"the",
"metric",
"outputs",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L155-L200 |
30,069 | iterative/dvc | dvc/repo/metrics/show.py | _read_metrics | def _read_metrics(repo, metrics, branch):
"""Read the content of each metric file and format it.
Args:
metrics (list): List of metric touples
branch (str): Branch to look up for metrics.
Returns:
A dict mapping keys with metrics path name and content.
For example:
{'metric.csv': ("value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n")}
"""
res = {}
for out, typ, xpath in metrics:
assert out.scheme == "local"
if not typ:
typ = os.path.splitext(out.path.lower())[1].replace(".", "")
if out.use_cache:
open_fun = open
path = repo.cache.local.get(out.checksum)
else:
open_fun = repo.tree.open
path = out.path
try:
with open_fun(path) as fd:
metric = _read_metric(
fd,
typ=typ,
xpath=xpath,
rel_path=out.rel_path,
branch=branch,
)
except IOError as e:
if e.errno == errno.ENOENT:
logger.warning(
NO_METRICS_FILE_AT_REFERENCE_WARNING.format(
out.rel_path, branch
)
)
metric = None
else:
raise
if not metric:
continue
res[out.rel_path] = metric
return res | python | def _read_metrics(repo, metrics, branch):
"""Read the content of each metric file and format it.
Args:
metrics (list): List of metric touples
branch (str): Branch to look up for metrics.
Returns:
A dict mapping keys with metrics path name and content.
For example:
{'metric.csv': ("value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n")}
"""
res = {}
for out, typ, xpath in metrics:
assert out.scheme == "local"
if not typ:
typ = os.path.splitext(out.path.lower())[1].replace(".", "")
if out.use_cache:
open_fun = open
path = repo.cache.local.get(out.checksum)
else:
open_fun = repo.tree.open
path = out.path
try:
with open_fun(path) as fd:
metric = _read_metric(
fd,
typ=typ,
xpath=xpath,
rel_path=out.rel_path,
branch=branch,
)
except IOError as e:
if e.errno == errno.ENOENT:
logger.warning(
NO_METRICS_FILE_AT_REFERENCE_WARNING.format(
out.rel_path, branch
)
)
metric = None
else:
raise
if not metric:
continue
res[out.rel_path] = metric
return res | [
"def",
"_read_metrics",
"(",
"repo",
",",
"metrics",
",",
"branch",
")",
":",
"res",
"=",
"{",
"}",
"for",
"out",
",",
"typ",
",",
"xpath",
"in",
"metrics",
":",
"assert",
"out",
".",
"scheme",
"==",
"\"local\"",
"if",
"not",
"typ",
":",
"typ",
"="... | Read the content of each metric file and format it.
Args:
metrics (list): List of metric touples
branch (str): Branch to look up for metrics.
Returns:
A dict mapping keys with metrics path name and content.
For example:
{'metric.csv': ("value_mse deviation_mse data_set\n"
"0.421601 0.173461 train\n"
"0.67528 0.289545 testing\n"
"0.671502 0.297848 validation\n")} | [
"Read",
"the",
"content",
"of",
"each",
"metric",
"file",
"and",
"format",
"it",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/metrics/show.py#L203-L256 |
30,070 | iterative/dvc | dvc/repo/__init__.py | Repo.graph | def graph(self, stages=None, from_directory=None):
"""Generate a graph by using the given stages on the given directory
The nodes of the graph are the stage's path relative to the root.
Edges are created when the output of one stage is used as a
dependency in other stage.
The direction of the edges goes from the stage to its dependency:
For example, running the following:
$ dvc run -o A "echo A > A"
$ dvc run -d A -o B "echo B > B"
$ dvc run -d B -o C "echo C > C"
Will create the following graph:
ancestors <--
|
C.dvc -> B.dvc -> A.dvc
| |
| --> descendants
|
------- pipeline ------>
|
v
(weakly connected components)
Args:
stages (list): used to build a graph, if None given, use the ones
on the `from_directory`.
from_directory (str): directory where to look at for stages, if
None is given, use the current working directory
Raises:
OutputDuplicationError: two outputs with the same path
StagePathAsOutputError: stage inside an output directory
OverlappingOutputPathsError: output inside output directory
CyclicGraphError: resulting graph has cycles
"""
import networkx as nx
from dvc.exceptions import (
OutputDuplicationError,
StagePathAsOutputError,
OverlappingOutputPathsError,
)
G = nx.DiGraph()
G_active = nx.DiGraph()
stages = stages or self.stages(from_directory, check_dag=False)
stages = [stage for stage in stages if stage]
outs = []
for stage in stages:
for out in stage.outs:
existing = []
for o in outs:
if o.path == out.path:
existing.append(o.stage)
in_o_dir = out.path.startswith(o.path + o.sep)
in_out_dir = o.path.startswith(out.path + out.sep)
if in_o_dir or in_out_dir:
raise OverlappingOutputPathsError(o, out)
if existing:
stages = [stage.relpath, existing[0].relpath]
raise OutputDuplicationError(out.path, stages)
outs.append(out)
for stage in stages:
path_dir = os.path.dirname(stage.path) + os.sep
for out in outs:
if path_dir.startswith(out.path + os.sep):
raise StagePathAsOutputError(stage.wdir, stage.relpath)
for stage in stages:
node = os.path.relpath(stage.path, self.root_dir)
G.add_node(node, stage=stage)
G_active.add_node(node, stage=stage)
for dep in stage.deps:
for out in outs:
if (
out.path != dep.path
and not dep.path.startswith(out.path + out.sep)
and not out.path.startswith(dep.path + dep.sep)
):
continue
dep_stage = out.stage
dep_node = os.path.relpath(dep_stage.path, self.root_dir)
G.add_node(dep_node, stage=dep_stage)
G.add_edge(node, dep_node)
if not stage.locked:
G_active.add_node(dep_node, stage=dep_stage)
G_active.add_edge(node, dep_node)
self._check_cyclic_graph(G)
return G, G_active | python | def graph(self, stages=None, from_directory=None):
"""Generate a graph by using the given stages on the given directory
The nodes of the graph are the stage's path relative to the root.
Edges are created when the output of one stage is used as a
dependency in other stage.
The direction of the edges goes from the stage to its dependency:
For example, running the following:
$ dvc run -o A "echo A > A"
$ dvc run -d A -o B "echo B > B"
$ dvc run -d B -o C "echo C > C"
Will create the following graph:
ancestors <--
|
C.dvc -> B.dvc -> A.dvc
| |
| --> descendants
|
------- pipeline ------>
|
v
(weakly connected components)
Args:
stages (list): used to build a graph, if None given, use the ones
on the `from_directory`.
from_directory (str): directory where to look at for stages, if
None is given, use the current working directory
Raises:
OutputDuplicationError: two outputs with the same path
StagePathAsOutputError: stage inside an output directory
OverlappingOutputPathsError: output inside output directory
CyclicGraphError: resulting graph has cycles
"""
import networkx as nx
from dvc.exceptions import (
OutputDuplicationError,
StagePathAsOutputError,
OverlappingOutputPathsError,
)
G = nx.DiGraph()
G_active = nx.DiGraph()
stages = stages or self.stages(from_directory, check_dag=False)
stages = [stage for stage in stages if stage]
outs = []
for stage in stages:
for out in stage.outs:
existing = []
for o in outs:
if o.path == out.path:
existing.append(o.stage)
in_o_dir = out.path.startswith(o.path + o.sep)
in_out_dir = o.path.startswith(out.path + out.sep)
if in_o_dir or in_out_dir:
raise OverlappingOutputPathsError(o, out)
if existing:
stages = [stage.relpath, existing[0].relpath]
raise OutputDuplicationError(out.path, stages)
outs.append(out)
for stage in stages:
path_dir = os.path.dirname(stage.path) + os.sep
for out in outs:
if path_dir.startswith(out.path + os.sep):
raise StagePathAsOutputError(stage.wdir, stage.relpath)
for stage in stages:
node = os.path.relpath(stage.path, self.root_dir)
G.add_node(node, stage=stage)
G_active.add_node(node, stage=stage)
for dep in stage.deps:
for out in outs:
if (
out.path != dep.path
and not dep.path.startswith(out.path + out.sep)
and not out.path.startswith(dep.path + dep.sep)
):
continue
dep_stage = out.stage
dep_node = os.path.relpath(dep_stage.path, self.root_dir)
G.add_node(dep_node, stage=dep_stage)
G.add_edge(node, dep_node)
if not stage.locked:
G_active.add_node(dep_node, stage=dep_stage)
G_active.add_edge(node, dep_node)
self._check_cyclic_graph(G)
return G, G_active | [
"def",
"graph",
"(",
"self",
",",
"stages",
"=",
"None",
",",
"from_directory",
"=",
"None",
")",
":",
"import",
"networkx",
"as",
"nx",
"from",
"dvc",
".",
"exceptions",
"import",
"(",
"OutputDuplicationError",
",",
"StagePathAsOutputError",
",",
"Overlapping... | Generate a graph by using the given stages on the given directory
The nodes of the graph are the stage's path relative to the root.
Edges are created when the output of one stage is used as a
dependency in other stage.
The direction of the edges goes from the stage to its dependency:
For example, running the following:
$ dvc run -o A "echo A > A"
$ dvc run -d A -o B "echo B > B"
$ dvc run -d B -o C "echo C > C"
Will create the following graph:
ancestors <--
|
C.dvc -> B.dvc -> A.dvc
| |
| --> descendants
|
------- pipeline ------>
|
v
(weakly connected components)
Args:
stages (list): used to build a graph, if None given, use the ones
on the `from_directory`.
from_directory (str): directory where to look at for stages, if
None is given, use the current working directory
Raises:
OutputDuplicationError: two outputs with the same path
StagePathAsOutputError: stage inside an output directory
OverlappingOutputPathsError: output inside output directory
CyclicGraphError: resulting graph has cycles | [
"Generate",
"a",
"graph",
"by",
"using",
"the",
"given",
"stages",
"on",
"the",
"given",
"directory"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/__init__.py#L300-L404 |
30,071 | iterative/dvc | dvc/logger.py | ColorFormatter._progress_aware | def _progress_aware(self):
"""Add a new line if progress bar hasn't finished"""
from dvc.progress import progress
if not progress.is_finished:
progress._print()
progress.clearln() | python | def _progress_aware(self):
"""Add a new line if progress bar hasn't finished"""
from dvc.progress import progress
if not progress.is_finished:
progress._print()
progress.clearln() | [
"def",
"_progress_aware",
"(",
"self",
")",
":",
"from",
"dvc",
".",
"progress",
"import",
"progress",
"if",
"not",
"progress",
".",
"is_finished",
":",
"progress",
".",
"_print",
"(",
")",
"progress",
".",
"clearln",
"(",
")"
] | Add a new line if progress bar hasn't finished | [
"Add",
"a",
"new",
"line",
"if",
"progress",
"bar",
"hasn",
"t",
"finished"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/logger.py#L134-L140 |
30,072 | iterative/dvc | dvc/scm/tree.py | WorkingTree.open | def open(self, path, binary=False):
"""Open file and return a stream."""
if binary:
return open(path, "rb")
return open(path, encoding="utf-8") | python | def open(self, path, binary=False):
"""Open file and return a stream."""
if binary:
return open(path, "rb")
return open(path, encoding="utf-8") | [
"def",
"open",
"(",
"self",
",",
"path",
",",
"binary",
"=",
"False",
")",
":",
"if",
"binary",
":",
"return",
"open",
"(",
"path",
",",
"\"rb\"",
")",
"return",
"open",
"(",
"path",
",",
"encoding",
"=",
"\"utf-8\"",
")"
] | Open file and return a stream. | [
"Open",
"file",
"and",
"return",
"a",
"stream",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/tree.py#L45-L49 |
30,073 | iterative/dvc | dvc/remote/s3.py | RemoteS3._list_paths | def _list_paths(self, bucket, prefix):
""" Read config for list object api, paginate through list objects."""
s3 = self.s3
kwargs = {"Bucket": bucket, "Prefix": prefix}
if self.list_objects:
list_objects_api = "list_objects"
else:
list_objects_api = "list_objects_v2"
paginator = s3.get_paginator(list_objects_api)
for page in paginator.paginate(**kwargs):
contents = page.get("Contents", None)
if not contents:
continue
for item in contents:
yield item["Key"] | python | def _list_paths(self, bucket, prefix):
""" Read config for list object api, paginate through list objects."""
s3 = self.s3
kwargs = {"Bucket": bucket, "Prefix": prefix}
if self.list_objects:
list_objects_api = "list_objects"
else:
list_objects_api = "list_objects_v2"
paginator = s3.get_paginator(list_objects_api)
for page in paginator.paginate(**kwargs):
contents = page.get("Contents", None)
if not contents:
continue
for item in contents:
yield item["Key"] | [
"def",
"_list_paths",
"(",
"self",
",",
"bucket",
",",
"prefix",
")",
":",
"s3",
"=",
"self",
".",
"s3",
"kwargs",
"=",
"{",
"\"Bucket\"",
":",
"bucket",
",",
"\"Prefix\"",
":",
"prefix",
"}",
"if",
"self",
".",
"list_objects",
":",
"list_objects_api",
... | Read config for list object api, paginate through list objects. | [
"Read",
"config",
"for",
"list",
"object",
"api",
"paginate",
"through",
"list",
"objects",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/s3.py#L212-L226 |
30,074 | iterative/dvc | dvc/command/remote.py | CmdRemoteAdd.resolve_path | def resolve_path(path, config_file):
"""Resolve path relative to config file location.
Args:
path: Path to be resolved.
config_file: Path to config file, which `path` is specified
relative to.
Returns:
Path relative to the `config_file` location. If `path` is an
absolute path then it will be returned without change.
"""
if os.path.isabs(path):
return path
return os.path.relpath(path, os.path.dirname(config_file)) | python | def resolve_path(path, config_file):
"""Resolve path relative to config file location.
Args:
path: Path to be resolved.
config_file: Path to config file, which `path` is specified
relative to.
Returns:
Path relative to the `config_file` location. If `path` is an
absolute path then it will be returned without change.
"""
if os.path.isabs(path):
return path
return os.path.relpath(path, os.path.dirname(config_file)) | [
"def",
"resolve_path",
"(",
"path",
",",
"config_file",
")",
":",
"if",
"os",
".",
"path",
".",
"isabs",
"(",
"path",
")",
":",
"return",
"path",
"return",
"os",
".",
"path",
".",
"relpath",
"(",
"path",
",",
"os",
".",
"path",
".",
"dirname",
"(",... | Resolve path relative to config file location.
Args:
path: Path to be resolved.
config_file: Path to config file, which `path` is specified
relative to.
Returns:
Path relative to the `config_file` location. If `path` is an
absolute path then it will be returned without change. | [
"Resolve",
"path",
"relative",
"to",
"config",
"file",
"location",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/remote.py#L18-L33 |
30,075 | iterative/dvc | dvc/remote/base.py | RemoteBase.changed | def changed(self, path_info, checksum_info):
"""Checks if data has changed.
A file is considered changed if:
- It doesn't exist on the working directory (was unlinked)
- Checksum is not computed (saving a new file)
- The checkusm stored in the State is different from the given one
- There's no file in the cache
Args:
path_info: dict with path information.
checksum: expected checksum for this data.
Returns:
bool: True if data has changed, False otherwise.
"""
logger.debug(
"checking if '{}'('{}') has changed.".format(
path_info, checksum_info
)
)
if not self.exists(path_info):
logger.debug("'{}' doesn't exist.".format(path_info))
return True
checksum = checksum_info.get(self.PARAM_CHECKSUM)
if checksum is None:
logger.debug("checksum for '{}' is missing.".format(path_info))
return True
if self.changed_cache(checksum):
logger.debug(
"cache for '{}'('{}') has changed.".format(path_info, checksum)
)
return True
actual = self.save_info(path_info)[self.PARAM_CHECKSUM]
if checksum != actual:
logger.debug(
"checksum '{}'(actual '{}') for '{}' has changed.".format(
checksum, actual, path_info
)
)
return True
logger.debug("'{}' hasn't changed.".format(path_info))
return False | python | def changed(self, path_info, checksum_info):
"""Checks if data has changed.
A file is considered changed if:
- It doesn't exist on the working directory (was unlinked)
- Checksum is not computed (saving a new file)
- The checkusm stored in the State is different from the given one
- There's no file in the cache
Args:
path_info: dict with path information.
checksum: expected checksum for this data.
Returns:
bool: True if data has changed, False otherwise.
"""
logger.debug(
"checking if '{}'('{}') has changed.".format(
path_info, checksum_info
)
)
if not self.exists(path_info):
logger.debug("'{}' doesn't exist.".format(path_info))
return True
checksum = checksum_info.get(self.PARAM_CHECKSUM)
if checksum is None:
logger.debug("checksum for '{}' is missing.".format(path_info))
return True
if self.changed_cache(checksum):
logger.debug(
"cache for '{}'('{}') has changed.".format(path_info, checksum)
)
return True
actual = self.save_info(path_info)[self.PARAM_CHECKSUM]
if checksum != actual:
logger.debug(
"checksum '{}'(actual '{}') for '{}' has changed.".format(
checksum, actual, path_info
)
)
return True
logger.debug("'{}' hasn't changed.".format(path_info))
return False | [
"def",
"changed",
"(",
"self",
",",
"path_info",
",",
"checksum_info",
")",
":",
"logger",
".",
"debug",
"(",
"\"checking if '{}'('{}') has changed.\"",
".",
"format",
"(",
"path_info",
",",
"checksum_info",
")",
")",
"if",
"not",
"self",
".",
"exists",
"(",
... | Checks if data has changed.
A file is considered changed if:
- It doesn't exist on the working directory (was unlinked)
- Checksum is not computed (saving a new file)
- The checkusm stored in the State is different from the given one
- There's no file in the cache
Args:
path_info: dict with path information.
checksum: expected checksum for this data.
Returns:
bool: True if data has changed, False otherwise. | [
"Checks",
"if",
"data",
"has",
"changed",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/base.py#L270-L318 |
30,076 | iterative/dvc | dvc/prompt.py | confirm | def confirm(statement):
"""Ask the user for confirmation about the specified statement.
Args:
statement (unicode): statement to ask the user confirmation about.
Returns:
bool: whether or not specified statement was confirmed.
"""
prompt = "{statement} [y/n]".format(statement=statement)
answer = _ask(prompt, limited_to=["yes", "no", "y", "n"])
return answer and answer.startswith("y") | python | def confirm(statement):
"""Ask the user for confirmation about the specified statement.
Args:
statement (unicode): statement to ask the user confirmation about.
Returns:
bool: whether or not specified statement was confirmed.
"""
prompt = "{statement} [y/n]".format(statement=statement)
answer = _ask(prompt, limited_to=["yes", "no", "y", "n"])
return answer and answer.startswith("y") | [
"def",
"confirm",
"(",
"statement",
")",
":",
"prompt",
"=",
"\"{statement} [y/n]\"",
".",
"format",
"(",
"statement",
"=",
"statement",
")",
"answer",
"=",
"_ask",
"(",
"prompt",
",",
"limited_to",
"=",
"[",
"\"yes\"",
",",
"\"no\"",
",",
"\"y\"",
",",
... | Ask the user for confirmation about the specified statement.
Args:
statement (unicode): statement to ask the user confirmation about.
Returns:
bool: whether or not specified statement was confirmed. | [
"Ask",
"the",
"user",
"for",
"confirmation",
"about",
"the",
"specified",
"statement",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/prompt.py#L38-L49 |
30,077 | iterative/dvc | dvc/main.py | main | def main(argv=None):
"""Run dvc CLI command.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Returns:
int: command's return code.
"""
args = None
cmd = None
try:
args = parse_args(argv)
if args.quiet:
logger.setLevel(logging.CRITICAL)
elif args.verbose:
logger.setLevel(logging.DEBUG)
cmd = args.func(args)
ret = cmd.run_cmd()
except KeyboardInterrupt:
logger.exception("interrupted by the user")
ret = 252
except NotDvcRepoError:
logger.exception("")
ret = 253
except DvcParserError:
ret = 254
except Exception: # pylint: disable=broad-except
logger.exception("unexpected error")
ret = 255
Analytics().send_cmd(cmd, args, ret)
return ret | python | def main(argv=None):
"""Run dvc CLI command.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Returns:
int: command's return code.
"""
args = None
cmd = None
try:
args = parse_args(argv)
if args.quiet:
logger.setLevel(logging.CRITICAL)
elif args.verbose:
logger.setLevel(logging.DEBUG)
cmd = args.func(args)
ret = cmd.run_cmd()
except KeyboardInterrupt:
logger.exception("interrupted by the user")
ret = 252
except NotDvcRepoError:
logger.exception("")
ret = 253
except DvcParserError:
ret = 254
except Exception: # pylint: disable=broad-except
logger.exception("unexpected error")
ret = 255
Analytics().send_cmd(cmd, args, ret)
return ret | [
"def",
"main",
"(",
"argv",
"=",
"None",
")",
":",
"args",
"=",
"None",
"cmd",
"=",
"None",
"try",
":",
"args",
"=",
"parse_args",
"(",
"argv",
")",
"if",
"args",
".",
"quiet",
":",
"logger",
".",
"setLevel",
"(",
"logging",
".",
"CRITICAL",
")",
... | Run dvc CLI command.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Returns:
int: command's return code. | [
"Run",
"dvc",
"CLI",
"command",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/main.py#L15-L52 |
30,078 | iterative/dvc | dvc/config.py | supported_cache_type | def supported_cache_type(types):
"""Checks if link type config option has a valid value.
Args:
types (list/string): type(s) of links that dvc should try out.
"""
if isinstance(types, str):
types = [typ.strip() for typ in types.split(",")]
for typ in types:
if typ not in ["reflink", "hardlink", "symlink", "copy"]:
return False
return True | python | def supported_cache_type(types):
"""Checks if link type config option has a valid value.
Args:
types (list/string): type(s) of links that dvc should try out.
"""
if isinstance(types, str):
types = [typ.strip() for typ in types.split(",")]
for typ in types:
if typ not in ["reflink", "hardlink", "symlink", "copy"]:
return False
return True | [
"def",
"supported_cache_type",
"(",
"types",
")",
":",
"if",
"isinstance",
"(",
"types",
",",
"str",
")",
":",
"types",
"=",
"[",
"typ",
".",
"strip",
"(",
")",
"for",
"typ",
"in",
"types",
".",
"split",
"(",
"\",\"",
")",
"]",
"for",
"typ",
"in",
... | Checks if link type config option has a valid value.
Args:
types (list/string): type(s) of links that dvc should try out. | [
"Checks",
"if",
"link",
"type",
"config",
"option",
"has",
"a",
"valid",
"value",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L32-L43 |
30,079 | iterative/dvc | dvc/config.py | Config.init | def init(dvc_dir):
"""Initializes dvc config.
Args:
dvc_dir (str): path to .dvc directory.
Returns:
dvc.config.Config: config object.
"""
config_file = os.path.join(dvc_dir, Config.CONFIG)
open(config_file, "w+").close()
return Config(dvc_dir) | python | def init(dvc_dir):
"""Initializes dvc config.
Args:
dvc_dir (str): path to .dvc directory.
Returns:
dvc.config.Config: config object.
"""
config_file = os.path.join(dvc_dir, Config.CONFIG)
open(config_file, "w+").close()
return Config(dvc_dir) | [
"def",
"init",
"(",
"dvc_dir",
")",
":",
"config_file",
"=",
"os",
".",
"path",
".",
"join",
"(",
"dvc_dir",
",",
"Config",
".",
"CONFIG",
")",
"open",
"(",
"config_file",
",",
"\"w+\"",
")",
".",
"close",
"(",
")",
"return",
"Config",
"(",
"dvc_dir"... | Initializes dvc config.
Args:
dvc_dir (str): path to .dvc directory.
Returns:
dvc.config.Config: config object. | [
"Initializes",
"dvc",
"config",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L345-L356 |
30,080 | iterative/dvc | dvc/config.py | Config.load | def load(self, validate=True):
"""Loads config from all the config files.
Args:
validate (bool): optional flag to tell dvc if it should validate
the config or just load it as is. 'True' by default.
Raises:
dvc.config.ConfigError: thrown if config has invalid format.
"""
self._load()
try:
self.config = self._load_config(self.system_config_file)
user = self._load_config(self.global_config_file)
config = self._load_config(self.config_file)
local = self._load_config(self.config_local_file)
# NOTE: schema doesn't support ConfigObj.Section validation, so we
# need to convert our config to dict before passing it to
for conf in [user, config, local]:
self.config = self._merge(self.config, conf)
if validate:
self.config = Schema(self.SCHEMA).validate(self.config)
# NOTE: now converting back to ConfigObj
self.config = configobj.ConfigObj(
self.config, write_empty_values=True
)
self.config.filename = self.config_file
self._resolve_paths(self.config, self.config_file)
except Exception as ex:
raise ConfigError(ex) | python | def load(self, validate=True):
"""Loads config from all the config files.
Args:
validate (bool): optional flag to tell dvc if it should validate
the config or just load it as is. 'True' by default.
Raises:
dvc.config.ConfigError: thrown if config has invalid format.
"""
self._load()
try:
self.config = self._load_config(self.system_config_file)
user = self._load_config(self.global_config_file)
config = self._load_config(self.config_file)
local = self._load_config(self.config_local_file)
# NOTE: schema doesn't support ConfigObj.Section validation, so we
# need to convert our config to dict before passing it to
for conf in [user, config, local]:
self.config = self._merge(self.config, conf)
if validate:
self.config = Schema(self.SCHEMA).validate(self.config)
# NOTE: now converting back to ConfigObj
self.config = configobj.ConfigObj(
self.config, write_empty_values=True
)
self.config.filename = self.config_file
self._resolve_paths(self.config, self.config_file)
except Exception as ex:
raise ConfigError(ex) | [
"def",
"load",
"(",
"self",
",",
"validate",
"=",
"True",
")",
":",
"self",
".",
"_load",
"(",
")",
"try",
":",
"self",
".",
"config",
"=",
"self",
".",
"_load_config",
"(",
"self",
".",
"system_config_file",
")",
"user",
"=",
"self",
".",
"_load_con... | Loads config from all the config files.
Args:
validate (bool): optional flag to tell dvc if it should validate
the config or just load it as is. 'True' by default.
Raises:
dvc.config.ConfigError: thrown if config has invalid format. | [
"Loads",
"config",
"from",
"all",
"the",
"config",
"files",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L408-L441 |
30,081 | iterative/dvc | dvc/config.py | Config.save | def save(self, config=None):
"""Saves config to config files.
Args:
config (configobj.ConfigObj): optional config object to save.
Raises:
dvc.config.ConfigError: thrown if failed to write config file.
"""
if config is not None:
clist = [config]
else:
clist = [
self._system_config,
self._global_config,
self._repo_config,
self._local_config,
]
for conf in clist:
if conf.filename is None:
continue
try:
logger.debug("Writing '{}'.".format(conf.filename))
dname = os.path.dirname(os.path.abspath(conf.filename))
try:
os.makedirs(dname)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
conf.write()
except Exception as exc:
msg = "failed to write config '{}'".format(conf.filename)
raise ConfigError(msg, exc) | python | def save(self, config=None):
"""Saves config to config files.
Args:
config (configobj.ConfigObj): optional config object to save.
Raises:
dvc.config.ConfigError: thrown if failed to write config file.
"""
if config is not None:
clist = [config]
else:
clist = [
self._system_config,
self._global_config,
self._repo_config,
self._local_config,
]
for conf in clist:
if conf.filename is None:
continue
try:
logger.debug("Writing '{}'.".format(conf.filename))
dname = os.path.dirname(os.path.abspath(conf.filename))
try:
os.makedirs(dname)
except OSError as exc:
if exc.errno != errno.EEXIST:
raise
conf.write()
except Exception as exc:
msg = "failed to write config '{}'".format(conf.filename)
raise ConfigError(msg, exc) | [
"def",
"save",
"(",
"self",
",",
"config",
"=",
"None",
")",
":",
"if",
"config",
"is",
"not",
"None",
":",
"clist",
"=",
"[",
"config",
"]",
"else",
":",
"clist",
"=",
"[",
"self",
".",
"_system_config",
",",
"self",
".",
"_global_config",
",",
"s... | Saves config to config files.
Args:
config (configobj.ConfigObj): optional config object to save.
Raises:
dvc.config.ConfigError: thrown if failed to write config file. | [
"Saves",
"config",
"to",
"config",
"files",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L455-L489 |
30,082 | iterative/dvc | dvc/config.py | Config.set | def set(config, section, opt, value):
"""Sets specified option in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
value: value to set option to.
"""
if section not in config.keys():
config[section] = {}
config[section][opt] = value | python | def set(config, section, opt, value):
"""Sets specified option in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
value: value to set option to.
"""
if section not in config.keys():
config[section] = {}
config[section][opt] = value | [
"def",
"set",
"(",
"config",
",",
"section",
",",
"opt",
",",
"value",
")",
":",
"if",
"section",
"not",
"in",
"config",
".",
"keys",
"(",
")",
":",
"config",
"[",
"section",
"]",
"=",
"{",
"}",
"config",
"[",
"section",
"]",
"[",
"opt",
"]",
"... | Sets specified option in the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
value: value to set option to. | [
"Sets",
"specified",
"option",
"in",
"the",
"config",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L567-L579 |
30,083 | iterative/dvc | dvc/config.py | Config.show | def show(config, section, opt):
"""Prints option value from the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
"""
if section not in config.keys():
raise ConfigError("section '{}' doesn't exist".format(section))
if opt not in config[section].keys():
raise ConfigError(
"option '{}.{}' doesn't exist".format(section, opt)
)
logger.info(config[section][opt]) | python | def show(config, section, opt):
"""Prints option value from the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name.
"""
if section not in config.keys():
raise ConfigError("section '{}' doesn't exist".format(section))
if opt not in config[section].keys():
raise ConfigError(
"option '{}.{}' doesn't exist".format(section, opt)
)
logger.info(config[section][opt]) | [
"def",
"show",
"(",
"config",
",",
"section",
",",
"opt",
")",
":",
"if",
"section",
"not",
"in",
"config",
".",
"keys",
"(",
")",
":",
"raise",
"ConfigError",
"(",
"\"section '{}' doesn't exist\"",
".",
"format",
"(",
"section",
")",
")",
"if",
"opt",
... | Prints option value from the config.
Args:
config (configobj.ConfigObj): config to work on.
section (str): section name.
opt (str): option name. | [
"Prints",
"option",
"value",
"from",
"the",
"config",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/config.py#L582-L598 |
30,084 | iterative/dvc | dvc/repo/move.py | move | def move(self, from_path, to_path):
"""
Renames an output file and modifies the stage associated
to reflect the change on the pipeline.
If the output has the same name as its stage, it would
also rename the corresponding stage file.
E.g.
Having: (hello, hello.dvc)
$ dvc move hello greetings
Result: (greeting, greeting.dvc)
It only works with outputs generated by `add` or `import`,
also known as data sources.
"""
import dvc.output as Output
from dvc.stage import Stage
from_out = Output.loads_from(Stage(self), [from_path])[0]
to_path = _expand_target_path(from_path, to_path)
outs = self.find_outs_by_path(from_out.path)
assert len(outs) == 1
out = outs[0]
stage = out.stage
if not stage.is_data_source:
raise MoveNotDataSourceError(stage.relpath)
stage_name = os.path.splitext(os.path.basename(stage.path))[0]
from_name = os.path.basename(from_out.path)
if stage_name == from_name:
os.unlink(stage.path)
stage.path = os.path.join(
os.path.dirname(to_path),
os.path.basename(to_path) + Stage.STAGE_FILE_SUFFIX,
)
stage.wdir = os.path.abspath(
os.path.join(os.curdir, os.path.dirname(to_path))
)
to_out = Output.loads_from(
stage, [os.path.basename(to_path)], out.use_cache, out.metric
)[0]
with self.state:
out.move(to_out)
stage.dump() | python | def move(self, from_path, to_path):
"""
Renames an output file and modifies the stage associated
to reflect the change on the pipeline.
If the output has the same name as its stage, it would
also rename the corresponding stage file.
E.g.
Having: (hello, hello.dvc)
$ dvc move hello greetings
Result: (greeting, greeting.dvc)
It only works with outputs generated by `add` or `import`,
also known as data sources.
"""
import dvc.output as Output
from dvc.stage import Stage
from_out = Output.loads_from(Stage(self), [from_path])[0]
to_path = _expand_target_path(from_path, to_path)
outs = self.find_outs_by_path(from_out.path)
assert len(outs) == 1
out = outs[0]
stage = out.stage
if not stage.is_data_source:
raise MoveNotDataSourceError(stage.relpath)
stage_name = os.path.splitext(os.path.basename(stage.path))[0]
from_name = os.path.basename(from_out.path)
if stage_name == from_name:
os.unlink(stage.path)
stage.path = os.path.join(
os.path.dirname(to_path),
os.path.basename(to_path) + Stage.STAGE_FILE_SUFFIX,
)
stage.wdir = os.path.abspath(
os.path.join(os.curdir, os.path.dirname(to_path))
)
to_out = Output.loads_from(
stage, [os.path.basename(to_path)], out.use_cache, out.metric
)[0]
with self.state:
out.move(to_out)
stage.dump() | [
"def",
"move",
"(",
"self",
",",
"from_path",
",",
"to_path",
")",
":",
"import",
"dvc",
".",
"output",
"as",
"Output",
"from",
"dvc",
".",
"stage",
"import",
"Stage",
"from_out",
"=",
"Output",
".",
"loads_from",
"(",
"Stage",
"(",
"self",
")",
",",
... | Renames an output file and modifies the stage associated
to reflect the change on the pipeline.
If the output has the same name as its stage, it would
also rename the corresponding stage file.
E.g.
Having: (hello, hello.dvc)
$ dvc move hello greetings
Result: (greeting, greeting.dvc)
It only works with outputs generated by `add` or `import`,
also known as data sources. | [
"Renames",
"an",
"output",
"file",
"and",
"modifies",
"the",
"stage",
"associated",
"to",
"reflect",
"the",
"change",
"on",
"the",
"pipeline",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/repo/move.py#L14-L68 |
30,085 | iterative/dvc | dvc/version.py | _generate_version | def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version
if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir):
return base_version
return "{base_version}+{short_sha}{dirty}".format(
base_version=base_version,
short_sha=_git_revision(pkg_dir).decode("utf-8")[0:6],
dirty=".mod" if _is_dirty(pkg_dir) else "",
) | python | def _generate_version(base_version):
"""Generate a version with information about the git repository"""
pkg_dir = os.path.abspath(os.path.dirname(os.path.dirname(__file__)))
if not _is_git_repo(pkg_dir) or not _have_git():
return base_version
if _is_release(pkg_dir, base_version) and not _is_dirty(pkg_dir):
return base_version
return "{base_version}+{short_sha}{dirty}".format(
base_version=base_version,
short_sha=_git_revision(pkg_dir).decode("utf-8")[0:6],
dirty=".mod" if _is_dirty(pkg_dir) else "",
) | [
"def",
"_generate_version",
"(",
"base_version",
")",
":",
"pkg_dir",
"=",
"os",
".",
"path",
".",
"abspath",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"os",
".",
"path",
".",
"dirname",
"(",
"__file__",
")",
")",
")",
"if",
"not",
"_is_git_repo",
... | Generate a version with information about the git repository | [
"Generate",
"a",
"version",
"with",
"information",
"about",
"the",
"git",
"repository"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/version.py#L13-L27 |
30,086 | iterative/dvc | dvc/version.py | _is_dirty | def _is_dirty(dir_path):
"""Check whether a git repository has uncommitted changes."""
try:
subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path)
return False
except subprocess.CalledProcessError:
return True | python | def _is_dirty(dir_path):
"""Check whether a git repository has uncommitted changes."""
try:
subprocess.check_call(["git", "diff", "--quiet"], cwd=dir_path)
return False
except subprocess.CalledProcessError:
return True | [
"def",
"_is_dirty",
"(",
"dir_path",
")",
":",
"try",
":",
"subprocess",
".",
"check_call",
"(",
"[",
"\"git\"",
",",
"\"diff\"",
",",
"\"--quiet\"",
"]",
",",
"cwd",
"=",
"dir_path",
")",
"return",
"False",
"except",
"subprocess",
".",
"CalledProcessError",... | Check whether a git repository has uncommitted changes. | [
"Check",
"whether",
"a",
"git",
"repository",
"has",
"uncommitted",
"changes",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/version.py#L66-L72 |
30,087 | iterative/dvc | dvc/utils/__init__.py | dict_filter | def dict_filter(d, exclude=[]):
"""
Exclude specified keys from a nested dict
"""
if isinstance(d, list):
ret = []
for e in d:
ret.append(dict_filter(e, exclude))
return ret
elif isinstance(d, dict):
ret = {}
for k, v in d.items():
if isinstance(k, builtin_str):
k = str(k)
assert isinstance(k, str)
if k in exclude:
continue
ret[k] = dict_filter(v, exclude)
return ret
return d | python | def dict_filter(d, exclude=[]):
"""
Exclude specified keys from a nested dict
"""
if isinstance(d, list):
ret = []
for e in d:
ret.append(dict_filter(e, exclude))
return ret
elif isinstance(d, dict):
ret = {}
for k, v in d.items():
if isinstance(k, builtin_str):
k = str(k)
assert isinstance(k, str)
if k in exclude:
continue
ret[k] = dict_filter(v, exclude)
return ret
return d | [
"def",
"dict_filter",
"(",
"d",
",",
"exclude",
"=",
"[",
"]",
")",
":",
"if",
"isinstance",
"(",
"d",
",",
"list",
")",
":",
"ret",
"=",
"[",
"]",
"for",
"e",
"in",
"d",
":",
"ret",
".",
"append",
"(",
"dict_filter",
"(",
"e",
",",
"exclude",
... | Exclude specified keys from a nested dict | [
"Exclude",
"specified",
"keys",
"from",
"a",
"nested",
"dict"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L83-L105 |
30,088 | iterative/dvc | dvc/utils/__init__.py | copyfile | def copyfile(src, dest, no_progress_bar=False, name=None):
"""Copy file with progress bar"""
from dvc.progress import progress
copied = 0
name = name if name else os.path.basename(dest)
total = os.stat(src).st_size
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
with open(src, "rb") as fsrc, open(dest, "wb+") as fdest:
while True:
buf = fsrc.read(LOCAL_CHUNK_SIZE)
if not buf:
break
fdest.write(buf)
copied += len(buf)
if not no_progress_bar:
progress.update_target(name, copied, total)
if not no_progress_bar:
progress.finish_target(name) | python | def copyfile(src, dest, no_progress_bar=False, name=None):
"""Copy file with progress bar"""
from dvc.progress import progress
copied = 0
name = name if name else os.path.basename(dest)
total = os.stat(src).st_size
if os.path.isdir(dest):
dest = os.path.join(dest, os.path.basename(src))
with open(src, "rb") as fsrc, open(dest, "wb+") as fdest:
while True:
buf = fsrc.read(LOCAL_CHUNK_SIZE)
if not buf:
break
fdest.write(buf)
copied += len(buf)
if not no_progress_bar:
progress.update_target(name, copied, total)
if not no_progress_bar:
progress.finish_target(name) | [
"def",
"copyfile",
"(",
"src",
",",
"dest",
",",
"no_progress_bar",
"=",
"False",
",",
"name",
"=",
"None",
")",
":",
"from",
"dvc",
".",
"progress",
"import",
"progress",
"copied",
"=",
"0",
"name",
"=",
"name",
"if",
"name",
"else",
"os",
".",
"pat... | Copy file with progress bar | [
"Copy",
"file",
"with",
"progress",
"bar"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L114-L136 |
30,089 | iterative/dvc | dvc/utils/__init__.py | dvc_walk | def dvc_walk(
top,
topdown=True,
onerror=None,
followlinks=False,
ignore_file_handler=None,
):
"""
Proxy for `os.walk` directory tree generator.
Utilizes DvcIgnoreFilter functionality.
"""
ignore_filter = None
if topdown:
from dvc.ignore import DvcIgnoreFilter
ignore_filter = DvcIgnoreFilter(
top, ignore_file_handler=ignore_file_handler
)
for root, dirs, files in os.walk(
top, topdown=topdown, onerror=onerror, followlinks=followlinks
):
if ignore_filter:
dirs[:], files[:] = ignore_filter(root, dirs, files)
yield root, dirs, files | python | def dvc_walk(
top,
topdown=True,
onerror=None,
followlinks=False,
ignore_file_handler=None,
):
"""
Proxy for `os.walk` directory tree generator.
Utilizes DvcIgnoreFilter functionality.
"""
ignore_filter = None
if topdown:
from dvc.ignore import DvcIgnoreFilter
ignore_filter = DvcIgnoreFilter(
top, ignore_file_handler=ignore_file_handler
)
for root, dirs, files in os.walk(
top, topdown=topdown, onerror=onerror, followlinks=followlinks
):
if ignore_filter:
dirs[:], files[:] = ignore_filter(root, dirs, files)
yield root, dirs, files | [
"def",
"dvc_walk",
"(",
"top",
",",
"topdown",
"=",
"True",
",",
"onerror",
"=",
"None",
",",
"followlinks",
"=",
"False",
",",
"ignore_file_handler",
"=",
"None",
",",
")",
":",
"ignore_filter",
"=",
"None",
"if",
"topdown",
":",
"from",
"dvc",
".",
"... | Proxy for `os.walk` directory tree generator.
Utilizes DvcIgnoreFilter functionality. | [
"Proxy",
"for",
"os",
".",
"walk",
"directory",
"tree",
"generator",
".",
"Utilizes",
"DvcIgnoreFilter",
"functionality",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L251-L277 |
30,090 | iterative/dvc | dvc/utils/__init__.py | colorize | def colorize(message, color=None):
"""Returns a message in a specified color."""
if not color:
return message
colors = {
"green": colorama.Fore.GREEN,
"yellow": colorama.Fore.YELLOW,
"blue": colorama.Fore.BLUE,
"red": colorama.Fore.RED,
}
return "{color}{message}{nc}".format(
color=colors.get(color, ""), message=message, nc=colorama.Fore.RESET
) | python | def colorize(message, color=None):
"""Returns a message in a specified color."""
if not color:
return message
colors = {
"green": colorama.Fore.GREEN,
"yellow": colorama.Fore.YELLOW,
"blue": colorama.Fore.BLUE,
"red": colorama.Fore.RED,
}
return "{color}{message}{nc}".format(
color=colors.get(color, ""), message=message, nc=colorama.Fore.RESET
) | [
"def",
"colorize",
"(",
"message",
",",
"color",
"=",
"None",
")",
":",
"if",
"not",
"color",
":",
"return",
"message",
"colors",
"=",
"{",
"\"green\"",
":",
"colorama",
".",
"Fore",
".",
"GREEN",
",",
"\"yellow\"",
":",
"colorama",
".",
"Fore",
".",
... | Returns a message in a specified color. | [
"Returns",
"a",
"message",
"in",
"a",
"specified",
"color",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L288-L302 |
30,091 | iterative/dvc | dvc/utils/__init__.py | boxify | def boxify(message, border_color=None):
"""Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with.
"""
lines = message.split("\n")
max_width = max(_visual_width(line) for line in lines)
padding_horizontal = 5
padding_vertical = 1
box_size_horizontal = max_width + (padding_horizontal * 2)
chars = {"corner": "+", "horizontal": "-", "vertical": "|", "empty": " "}
margin = "{corner}{line}{corner}\n".format(
corner=chars["corner"], line=chars["horizontal"] * box_size_horizontal
)
padding_lines = [
"{border}{space}{border}\n".format(
border=colorize(chars["vertical"], color=border_color),
space=chars["empty"] * box_size_horizontal,
)
* padding_vertical
]
content_lines = [
"{border}{space}{content}{space}{border}\n".format(
border=colorize(chars["vertical"], color=border_color),
space=chars["empty"] * padding_horizontal,
content=_visual_center(line, max_width),
)
for line in lines
]
box_str = "{margin}{padding}{content}{padding}{margin}".format(
margin=colorize(margin, color=border_color),
padding="".join(padding_lines),
content="".join(content_lines),
)
return box_str | python | def boxify(message, border_color=None):
"""Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with.
"""
lines = message.split("\n")
max_width = max(_visual_width(line) for line in lines)
padding_horizontal = 5
padding_vertical = 1
box_size_horizontal = max_width + (padding_horizontal * 2)
chars = {"corner": "+", "horizontal": "-", "vertical": "|", "empty": " "}
margin = "{corner}{line}{corner}\n".format(
corner=chars["corner"], line=chars["horizontal"] * box_size_horizontal
)
padding_lines = [
"{border}{space}{border}\n".format(
border=colorize(chars["vertical"], color=border_color),
space=chars["empty"] * box_size_horizontal,
)
* padding_vertical
]
content_lines = [
"{border}{space}{content}{space}{border}\n".format(
border=colorize(chars["vertical"], color=border_color),
space=chars["empty"] * padding_horizontal,
content=_visual_center(line, max_width),
)
for line in lines
]
box_str = "{margin}{padding}{content}{padding}{margin}".format(
margin=colorize(margin, color=border_color),
padding="".join(padding_lines),
content="".join(content_lines),
)
return box_str | [
"def",
"boxify",
"(",
"message",
",",
"border_color",
"=",
"None",
")",
":",
"lines",
"=",
"message",
".",
"split",
"(",
"\"\\n\"",
")",
"max_width",
"=",
"max",
"(",
"_visual_width",
"(",
"line",
")",
"for",
"line",
"in",
"lines",
")",
"padding_horizont... | Put a message inside a box.
Args:
message (unicode): message to decorate.
border_color (unicode): name of the color to outline the box with. | [
"Put",
"a",
"message",
"inside",
"a",
"box",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L305-L349 |
30,092 | iterative/dvc | dvc/utils/__init__.py | _visual_width | def _visual_width(line):
"""Get the the number of columns required to display a string"""
return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line)) | python | def _visual_width(line):
"""Get the the number of columns required to display a string"""
return len(re.sub(colorama.ansitowin32.AnsiToWin32.ANSI_CSI_RE, "", line)) | [
"def",
"_visual_width",
"(",
"line",
")",
":",
"return",
"len",
"(",
"re",
".",
"sub",
"(",
"colorama",
".",
"ansitowin32",
".",
"AnsiToWin32",
".",
"ANSI_CSI_RE",
",",
"\"\"",
",",
"line",
")",
")"
] | Get the the number of columns required to display a string | [
"Get",
"the",
"the",
"number",
"of",
"columns",
"required",
"to",
"display",
"a",
"string"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L352-L355 |
30,093 | iterative/dvc | dvc/utils/__init__.py | _visual_center | def _visual_center(line, width):
"""Center align string according to it's visual width"""
spaces = max(width - _visual_width(line), 0)
left_padding = int(spaces / 2)
right_padding = spaces - left_padding
return (left_padding * " ") + line + (right_padding * " ") | python | def _visual_center(line, width):
"""Center align string according to it's visual width"""
spaces = max(width - _visual_width(line), 0)
left_padding = int(spaces / 2)
right_padding = spaces - left_padding
return (left_padding * " ") + line + (right_padding * " ") | [
"def",
"_visual_center",
"(",
"line",
",",
"width",
")",
":",
"spaces",
"=",
"max",
"(",
"width",
"-",
"_visual_width",
"(",
"line",
")",
",",
"0",
")",
"left_padding",
"=",
"int",
"(",
"spaces",
"/",
"2",
")",
"right_padding",
"=",
"spaces",
"-",
"l... | Center align string according to it's visual width | [
"Center",
"align",
"string",
"according",
"to",
"it",
"s",
"visual",
"width"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/__init__.py#L358-L365 |
30,094 | iterative/dvc | dvc/command/base.py | CmdBase.default_targets | def default_targets(self):
"""Default targets for `dvc repro` and `dvc pipeline`."""
from dvc.stage import Stage
msg = "assuming default target '{}'.".format(Stage.STAGE_FILE)
logger.warning(msg)
return [Stage.STAGE_FILE] | python | def default_targets(self):
"""Default targets for `dvc repro` and `dvc pipeline`."""
from dvc.stage import Stage
msg = "assuming default target '{}'.".format(Stage.STAGE_FILE)
logger.warning(msg)
return [Stage.STAGE_FILE] | [
"def",
"default_targets",
"(",
"self",
")",
":",
"from",
"dvc",
".",
"stage",
"import",
"Stage",
"msg",
"=",
"\"assuming default target '{}'.\"",
".",
"format",
"(",
"Stage",
".",
"STAGE_FILE",
")",
"logger",
".",
"warning",
"(",
"msg",
")",
"return",
"[",
... | Default targets for `dvc repro` and `dvc pipeline`. | [
"Default",
"targets",
"for",
"dvc",
"repro",
"and",
"dvc",
"pipeline",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/command/base.py#L47-L53 |
30,095 | iterative/dvc | dvc/scm/__init__.py | SCM | def SCM(root_dir, repo=None): # pylint: disable=invalid-name
"""Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm.base.Base: SCM instance.
"""
if Git.is_repo(root_dir) or Git.is_submodule(root_dir):
return Git(root_dir, repo=repo)
return NoSCM(root_dir, repo=repo) | python | def SCM(root_dir, repo=None): # pylint: disable=invalid-name
"""Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm.base.Base: SCM instance.
"""
if Git.is_repo(root_dir) or Git.is_submodule(root_dir):
return Git(root_dir, repo=repo)
return NoSCM(root_dir, repo=repo) | [
"def",
"SCM",
"(",
"root_dir",
",",
"repo",
"=",
"None",
")",
":",
"# pylint: disable=invalid-name",
"if",
"Git",
".",
"is_repo",
"(",
"root_dir",
")",
"or",
"Git",
".",
"is_submodule",
"(",
"root_dir",
")",
":",
"return",
"Git",
"(",
"root_dir",
",",
"r... | Returns SCM instance that corresponds to a repo at the specified
path.
Args:
root_dir (str): path to a root directory of the repo.
repo (dvc.repo.Repo): dvc repo instance that root_dir belongs to.
Returns:
dvc.scm.base.Base: SCM instance. | [
"Returns",
"SCM",
"instance",
"that",
"corresponds",
"to",
"a",
"repo",
"at",
"the",
"specified",
"path",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/scm/__init__.py#L15-L29 |
30,096 | iterative/dvc | dvc/cli.py | get_parent_parser | def get_parent_parser():
"""Create instances of a parser containing common arguments shared among
all the commands.
When overwritting `-q` or `-v`, you need to instantiate a new object
in order to prevent some weird behavior.
"""
parent_parser = argparse.ArgumentParser(add_help=False)
log_level_group = parent_parser.add_mutually_exclusive_group()
log_level_group.add_argument(
"-q", "--quiet", action="store_true", default=False, help="Be quiet."
)
log_level_group.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="Be verbose.",
)
return parent_parser | python | def get_parent_parser():
"""Create instances of a parser containing common arguments shared among
all the commands.
When overwritting `-q` or `-v`, you need to instantiate a new object
in order to prevent some weird behavior.
"""
parent_parser = argparse.ArgumentParser(add_help=False)
log_level_group = parent_parser.add_mutually_exclusive_group()
log_level_group.add_argument(
"-q", "--quiet", action="store_true", default=False, help="Be quiet."
)
log_level_group.add_argument(
"-v",
"--verbose",
action="store_true",
default=False,
help="Be verbose.",
)
return parent_parser | [
"def",
"get_parent_parser",
"(",
")",
":",
"parent_parser",
"=",
"argparse",
".",
"ArgumentParser",
"(",
"add_help",
"=",
"False",
")",
"log_level_group",
"=",
"parent_parser",
".",
"add_mutually_exclusive_group",
"(",
")",
"log_level_group",
".",
"add_argument",
"(... | Create instances of a parser containing common arguments shared among
all the commands.
When overwritting `-q` or `-v`, you need to instantiate a new object
in order to prevent some weird behavior. | [
"Create",
"instances",
"of",
"a",
"parser",
"containing",
"common",
"arguments",
"shared",
"among",
"all",
"the",
"commands",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cli.py#L98-L119 |
30,097 | iterative/dvc | dvc/cli.py | parse_args | def parse_args(argv=None):
"""Parses CLI arguments.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Raises:
dvc.exceptions.DvcParserError: raised for argument parsing errors.
"""
parent_parser = get_parent_parser()
# Main parser
desc = "Data Version Control"
parser = DvcParser(
prog="dvc",
description=desc,
parents=[parent_parser],
formatter_class=argparse.RawTextHelpFormatter,
)
# NOTE: On some python versions action='version' prints to stderr
# instead of stdout https://bugs.python.org/issue18920
parser.add_argument(
"-V",
"--version",
action=VersionAction,
nargs=0,
help="Show program's version.",
)
# Sub commands
subparsers = parser.add_subparsers(
title="Available Commands",
metavar="COMMAND",
dest="cmd",
help="Use dvc COMMAND --help for command-specific help.",
)
fix_subparsers(subparsers)
for cmd in COMMANDS:
cmd.add_parser(subparsers, parent_parser)
args = parser.parse_args(argv)
return args | python | def parse_args(argv=None):
"""Parses CLI arguments.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Raises:
dvc.exceptions.DvcParserError: raised for argument parsing errors.
"""
parent_parser = get_parent_parser()
# Main parser
desc = "Data Version Control"
parser = DvcParser(
prog="dvc",
description=desc,
parents=[parent_parser],
formatter_class=argparse.RawTextHelpFormatter,
)
# NOTE: On some python versions action='version' prints to stderr
# instead of stdout https://bugs.python.org/issue18920
parser.add_argument(
"-V",
"--version",
action=VersionAction,
nargs=0,
help="Show program's version.",
)
# Sub commands
subparsers = parser.add_subparsers(
title="Available Commands",
metavar="COMMAND",
dest="cmd",
help="Use dvc COMMAND --help for command-specific help.",
)
fix_subparsers(subparsers)
for cmd in COMMANDS:
cmd.add_parser(subparsers, parent_parser)
args = parser.parse_args(argv)
return args | [
"def",
"parse_args",
"(",
"argv",
"=",
"None",
")",
":",
"parent_parser",
"=",
"get_parent_parser",
"(",
")",
"# Main parser",
"desc",
"=",
"\"Data Version Control\"",
"parser",
"=",
"DvcParser",
"(",
"prog",
"=",
"\"dvc\"",
",",
"description",
"=",
"desc",
",... | Parses CLI arguments.
Args:
argv: optional list of arguments to parse. sys.argv is used by default.
Raises:
dvc.exceptions.DvcParserError: raised for argument parsing errors. | [
"Parses",
"CLI",
"arguments",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/cli.py#L122-L167 |
30,098 | iterative/dvc | dvc/utils/collections.py | apply_diff | def apply_diff(src, dest):
"""Recursively apply changes from src to dest.
Preserves dest type and hidden info in dest structure,
like ruamel.yaml leaves when parses files. This includes comments,
ordering and line foldings.
Used in Stage load/dump cycle to preserve comments and custom formatting.
"""
Seq = (list, tuple)
Container = (Mapping, list, tuple)
def is_same_type(a, b):
return any(
isinstance(a, t) and isinstance(b, t)
for t in [str, Mapping, Seq, bool]
)
if isinstance(src, Mapping) and isinstance(dest, Mapping):
for key, value in src.items():
if isinstance(value, Container) and is_same_type(
value, dest.get(key)
):
apply_diff(value, dest[key])
elif key not in dest or value != dest[key]:
dest[key] = value
for key in set(dest) - set(src):
del dest[key]
elif isinstance(src, Seq) and isinstance(dest, Seq):
if len(src) != len(dest):
dest[:] = src
else:
for i, value in enumerate(src):
if isinstance(value, Container) and is_same_type(
value, dest[i]
):
apply_diff(value, dest[i])
elif value != dest[i]:
dest[i] = value
else:
raise AssertionError(
"Can't apply diff from {} to {}".format(
src.__class__.__name__, dest.__class__.__name__
)
) | python | def apply_diff(src, dest):
"""Recursively apply changes from src to dest.
Preserves dest type and hidden info in dest structure,
like ruamel.yaml leaves when parses files. This includes comments,
ordering and line foldings.
Used in Stage load/dump cycle to preserve comments and custom formatting.
"""
Seq = (list, tuple)
Container = (Mapping, list, tuple)
def is_same_type(a, b):
return any(
isinstance(a, t) and isinstance(b, t)
for t in [str, Mapping, Seq, bool]
)
if isinstance(src, Mapping) and isinstance(dest, Mapping):
for key, value in src.items():
if isinstance(value, Container) and is_same_type(
value, dest.get(key)
):
apply_diff(value, dest[key])
elif key not in dest or value != dest[key]:
dest[key] = value
for key in set(dest) - set(src):
del dest[key]
elif isinstance(src, Seq) and isinstance(dest, Seq):
if len(src) != len(dest):
dest[:] = src
else:
for i, value in enumerate(src):
if isinstance(value, Container) and is_same_type(
value, dest[i]
):
apply_diff(value, dest[i])
elif value != dest[i]:
dest[i] = value
else:
raise AssertionError(
"Can't apply diff from {} to {}".format(
src.__class__.__name__, dest.__class__.__name__
)
) | [
"def",
"apply_diff",
"(",
"src",
",",
"dest",
")",
":",
"Seq",
"=",
"(",
"list",
",",
"tuple",
")",
"Container",
"=",
"(",
"Mapping",
",",
"list",
",",
"tuple",
")",
"def",
"is_same_type",
"(",
"a",
",",
"b",
")",
":",
"return",
"any",
"(",
"isin... | Recursively apply changes from src to dest.
Preserves dest type and hidden info in dest structure,
like ruamel.yaml leaves when parses files. This includes comments,
ordering and line foldings.
Used in Stage load/dump cycle to preserve comments and custom formatting. | [
"Recursively",
"apply",
"changes",
"from",
"src",
"to",
"dest",
"."
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/utils/collections.py#L10-L54 |
30,099 | iterative/dvc | dvc/remote/ssh/connection.py | percent_cb | def percent_cb(name, complete, total):
""" Callback for updating target progress """
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) | python | def percent_cb(name, complete, total):
""" Callback for updating target progress """
logger.debug(
"{}: {} transferred out of {}".format(
name, sizeof_fmt(complete), sizeof_fmt(total)
)
)
progress.update_target(name, complete, total) | [
"def",
"percent_cb",
"(",
"name",
",",
"complete",
",",
"total",
")",
":",
"logger",
".",
"debug",
"(",
"\"{}: {} transferred out of {}\"",
".",
"format",
"(",
"name",
",",
"sizeof_fmt",
"(",
"complete",
")",
",",
"sizeof_fmt",
"(",
"total",
")",
")",
")",... | Callback for updating target progress | [
"Callback",
"for",
"updating",
"target",
"progress"
] | 8bb21261e34c9632453e09090de7ebe50e38d341 | https://github.com/iterative/dvc/blob/8bb21261e34c9632453e09090de7ebe50e38d341/dvc/remote/ssh/connection.py#L31-L38 |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.