Code stringlengths 103 85.9k | Summary listlengths 0 94 |
|---|---|
Please provide a description of the function:def create(self):
self._app = Flask(__name__,
static_url_path="", # Mount static files at root '/'
static_folder=self.static_dir # Serve static files from this directory
)
... | [
"\n Creates a Flask Application that can be started.\n "
] |
Please provide a description of the function:def _generate_route_keys(self, methods, path):
for method in methods:
yield self._route_key(method, path) | [
"\n Generates the key to the _dict_of_routes based on the list of methods\n and path supplied\n\n :param list(str) methods: List of HTTP Methods\n :param str path: Path off the base url\n :return: str of Path:Method\n "
] |
Please provide a description of the function:def _construct_error_handling(self):
# Both path and method not present
self._app.register_error_handler(404, ServiceErrorResponses.route_not_found)
# Path is present, but method not allowed
self._app.register_error_handler(405, Servi... | [
"\n Updates the Flask app with Error Handlers for different Error Codes\n "
] |
Please provide a description of the function:def _request_handler(self, **kwargs):
route = self._get_current_route(request)
try:
event = self._construct_event(request, self.port, route.binary_types)
except UnicodeDecodeError:
return ServiceErrorResponses.lambda_... | [
"\n We handle all requests to the host:port. The general flow of handling a request is as follows\n\n * Fetch request from the Flask Global state. This is where Flask places the request and is per thread so\n multiple requests are still handled correctly\n * Find the Lambda function to... |
Please provide a description of the function:def _get_current_route(self, flask_request):
endpoint = flask_request.endpoint
method = flask_request.method
route_key = self._route_key(method, endpoint)
route = self._dict_of_routes.get(route_key, None)
if not route:
... | [
"\n Get the route (Route) based on the current request\n\n :param request flask_request: Flask Request\n :return: Route matching the endpoint and method of the request\n "
] |
Please provide a description of the function:def _parse_lambda_output(lambda_output, binary_types, flask_request):
json_output = json.loads(lambda_output)
if not isinstance(json_output, dict):
raise TypeError("Lambda returned %{s} instead of dict", type(json_output))
statu... | [
"\n Parses the output from the Lambda Container\n\n :param str lambda_output: Output from Lambda Invoke\n :return: Tuple(int, dict, str, bool)\n "
] |
Please provide a description of the function:def _should_base64_decode_body(binary_types, flask_request, lamba_response_headers, is_base_64_encoded):
best_match_mimetype = flask_request.accept_mimetypes.best_match([lamba_response_headers["Content-Type"]])
is_best_match_in_binary_types = best_ma... | [
"\n Whether or not the body should be decoded from Base64 to Binary\n\n Parameters\n ----------\n binary_types list(basestring)\n Corresponds to self.binary_types (aka. what is parsed from SAM Template\n flask_request flask.request\n Flask request\n la... |
Please provide a description of the function:def _construct_event(flask_request, port, binary_types):
identity = ContextIdentity(source_ip=flask_request.remote_addr)
endpoint = PathConverter.convert_path_to_api_gateway(flask_request.endpoint)
method = flask_request.method
req... | [
"\n Helper method that constructs the Event to be passed to Lambda\n\n :param request flask_request: Flask Request\n :return: String representing the event\n "
] |
Please provide a description of the function:def _query_string_params(flask_request):
query_string_dict = {}
# Flask returns an ImmutableMultiDict so convert to a dictionary that becomes
# a dict(str: list) then iterate over
for query_string_key, query_string_list in flask_requ... | [
"\n Constructs an APIGW equivalent query string dictionary\n\n Parameters\n ----------\n flask_request request\n Request from Flask\n\n Returns dict (str: str)\n -------\n Empty dict if no query params where in the request otherwise returns a dictionar... |
Please provide a description of the function:def invoke(self, function_name, event, stdout=None, stderr=None):
# Generate the correct configuration based on given inputs
function = self.provider.get(function_name)
if not function:
all_functions = [f.name for f in self.prov... | [
"\n Find the Lambda function with given name and invoke it. Pass the given event to the function and return\n response through the given streams.\n\n This function will block until either the function completes or times out.\n\n Parameters\n ----------\n function_name str\n... |
Please provide a description of the function:def _get_invoke_config(self, function):
env_vars = self._make_env_vars(function)
code_abs_path = resolve_code_path(self.cwd, function.codeuri)
LOG.debug("Resolved absolute path to code is %s", code_abs_path)
function_timeout = func... | [
"\n Returns invoke configuration to pass to Lambda Runtime to invoke the given function\n\n :param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for\n :return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lam... |
Please provide a description of the function:def _make_env_vars(self, function):
name = function.name
variables = None
if function.environment and isinstance(function.environment, dict) and "Variables" in function.environment:
variables = function.environment["Variables"]
... | [
"Returns the environment variables configuration for this function\n\n Parameters\n ----------\n function : samcli.commands.local.lib.provider.Function\n Lambda function to generate the configuration for\n\n Returns\n -------\n samcli.local.lambdafn.env_vars.Envi... |
Please provide a description of the function: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:
session = boto3.session... | [
"\n Returns AWS credentials obtained from the shell environment or given profile\n\n :return dict: A dictionary containing credentials. This dict has the structure\n {\"region\": \"\", \"key\": \"\", \"secret\": \"\", \"sessiontoken\": \"\"}. If credentials could not be resolved,\n ... |
Please provide a description of the function:def to_dict(self):
json_dict = {"apiKey": self.api_key,
"userArn": self.user_arn,
"cognitoAuthenticationType": self.cognito_authentication_type,
"caller": self.caller,
"userA... | [
"\n Constructs an dictionary representation of the Identity Object to be used in serializing to JSON\n\n :return: dict representing the object\n "
] |
Please provide a description of the function:def to_dict(self):
identity_dict = {}
if self.identity:
identity_dict = self.identity.to_dict()
json_dict = {"resourceId": self.resource_id,
"apiId": self.api_id,
"resourcePath": self.res... | [
"\n Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON\n\n :return: dict representing the object\n "
] |
Please provide a description of the function:def to_dict(self):
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 Non... | [
"\n Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON\n\n :return: dict representing the object\n "
] |
Please provide a description of the function:def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time):
LOG.debug("'logs' command is called")
with LogsCommandContext(function_name,
stack_name=stack_name,
filter_pattern=fil... | [
"\n Implementation of the ``cli`` method\n "
] |
Please provide a description of the function: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.APIError, requests.exceptions.Connection... | [
"\n Checks if Docker daemon is running. This is required for us to invoke the function locally\n\n Returns\n -------\n bool\n True, if Docker is available, False otherwise\n "
] |
Please provide a description of the function: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.image
is_image_local = self.has_image(image_name)
# Skip P... | [
"\n Create and run a Docker container based on the given configuration.\n\n :param samcli.local.docker.container.Container container: Container to create and run\n :param input_data: Optional. Input data sent to the container through container's stdin.\n :param bool warm: Indicates if an... |
Please provide a description of the function:def pull_image(self, image_name, stream=None):
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:
... | [
"\n Ask Docker to pull the container image with given name.\n\n Parameters\n ----------\n image_name str\n Name of the image\n stream samcli.lib.utils.stream_writer.StreamWriter\n Optional stream writer to output to. Defaults to stderr\n\n Raises\n ... |
Please provide a description of the function:def has_image(self, image_name):
try:
self.docker_client.images.get(image_name)
return True
except docker.errors.ImageNotFound:
return False | [
"\n Is the container image with given name available?\n\n :param string image_name: Name of the image\n :return bool: True, if image is available. False, otherwise\n "
] |
Please provide a description of the function:def do_cli(ctx, template, semantic_version):
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 metada... | [
"Publish the application based on command line inputs."
] |
Please provide a description of the function:def _gen_success_message(publish_output):
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 wit... | [
"\n Generate detailed success message for published applications.\n\n Parameters\n ----------\n publish_output : dict\n Output from serverlessrepo publish_application\n\n Returns\n -------\n str\n Detailed success message\n "
] |
Please provide a description of the function:def _print_console_link(region, application_id):
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 A... | [
"\n Print link for the application in AWS Serverless Application Repository console.\n\n Parameters\n ----------\n region : str\n AWS region name\n application_id : str\n The Amazon Resource Name (ARN) of the application\n\n "
] |
Please provide a description of the function:def lambda_failure_response(*args):
response_data = jsonify(ServiceErrorResponses._LAMBDA_FAILURE)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"\n Helper function to create a Lambda Failure Response\n\n :return: A Flask Response\n "
] |
Please provide a description of the function:def lambda_not_found_response(*args):
response_data = jsonify(ServiceErrorResponses._NO_LAMBDA_INTEGRATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_502) | [
"\n Constructs a Flask Response for when a Lambda function is not found for an endpoint\n\n :return: a Flask Response\n "
] |
Please provide a description of the function:def route_not_found(*args):
response_data = jsonify(ServiceErrorResponses._MISSING_AUTHENTICATION)
return make_response(response_data, ServiceErrorResponses.HTTP_STATUS_CODE_403) | [
"\n Constructs a Flask Response for when a API Route (path+method) is not found. This is usually\n HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840)\n\n :return: a Flask Response\n "
] |
Please provide a description of the function:def progressbar(length, label):
return click.progressbar(length=length, label=label, show_pos=True) | [
"\n Creates a progressbar\n\n Parameters\n ----------\n length int\n Length of the ProgressBar\n label str\n Label to give to the progressbar\n\n Returns\n -------\n click.progressbar\n Progressbar\n\n "
] |
Please provide a description of the function:def _unquote(value):
r
if value and (value[0] == value[-1] == '"'):
# Remove quotes only if the string is wrapped in quotes
value = value.strip('"')
return value.replace("\\ ", " ").replace('\\"', '"') | [
"\n Removes wrapping double quotes and any '\\ ' characters. They are usually added to preserve spaces when passing\n value thru shell.\n\n Examples\n --------\n >>> _unquote('val\\ ue')\n value\n\n >>> _unquote(\"hel\\ lo\")\n hello\n\n Parameters\n ... |
Please provide a description of the function:def run(self):
if not self._app:
raise RuntimeError("The application must be created before running")
# Flask can operate as a single threaded server (which is default) and a multi-threaded server which is
# more for development.... | [
"\n This starts up the (threaded) Local Server.\n Note: This is a **blocking call**\n\n Raises\n ------\n RuntimeError\n if the service was not created\n "
] |
Please provide a description of the function:def service_response(body, headers, status_code):
response = Response(body)
response.headers = headers
response.status_code = status_code
return response | [
"\n Constructs a Flask Response from the body, headers, and status_code.\n\n :param str body: Response body as a string\n :param dict headers: headers for the response\n :param int status_code: status_code for response\n :return: Flask Response\n "
] |
Please provide a description of the function: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
... | [
"\n This method will extract read the given stream and return the response from Lambda function separated out\n from any log statements it might have outputted. Logs end up in the stdout stream if the Lambda function\n wrote directly to stdout using System.out.println or equivalents.\n\n ... |
Please provide a description of the function:def is_lambda_error_response(lambda_response):
is_lambda_user_error_response = False
try:
lambda_response_dict = json.loads(lambda_response)
# This is a best effort attempt to determine if the output (lambda_response) from th... | [
"\n Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke\n\n Parameters\n ----------\n lambda_response str\n The response the container returned\n\n Returns\n -------\n bool\n True if the outp... |
Please provide a description of the function:def build(self):
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,
... | [
"\n Build the entire application\n\n Returns\n -------\n dict\n Returns the path to where each resource was built as a map of resource's LogicalId to the path string\n "
] |
Please provide a description of the function:def update_template(self, template_dict, original_template_path, built_artifacts):
original_dir = os.path.dirname(original_template_path)
for logical_id, resource in template_dict.get("Resources", {}).items():
if logical_id not in buil... | [
"\n Given the path to built artifacts, update the template to point appropriate resource CodeUris to the artifacts\n folder\n\n Parameters\n ----------\n template_dict\n original_template_path : str\n Path where the template file will be written to\n\n bui... |
Please provide a description of the function: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(self._base_dir, codeuri).resolve())
config ... | [
"\n Given the function information, this method will build the Lambda function. Depending on the configuration\n it will either build the function in process or by spinning up a Docker container.\n\n Parameters\n ----------\n function_name : str\n Name or LogicalId of t... |
Please provide a description of the function:def _get_container_dirs(source_dir, manifest_dir):
base = "/tmp/samcli"
result = {
"source_dir": "{}/source".format(base),
"artifacts_dir": "{}/artifacts".format(base),
"scratch_dir": "{}/scratch".format(base),
... | [
"\n Provides paths to directories within the container that is required by the builder\n\n Parameters\n ----------\n source_dir : str\n Path to the function source code\n\n manifest_dir : str\n Path to the directory containing manifest\n\n Returns\n ... |
Please provide a description of the function: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 ... | [
"\n Use this method to convert a list of host paths to a list of equivalent paths within the container\n where the given host path is mounted. This is necessary when SAM CLI needs to pass path information to\n the Lambda Builder running within the container.\n\n If a host path is not mou... |
Please provide a description of the function:def __translate(self, parameter_values):
template_copy = self.template
sam_parser = Parser()
sam_translator = Translator(managed_policy_map=self.__managed_policy_map(),
sam_parser=sam_parser,
... | [
"\n This method is unused and a Work In Progress\n "
] |
Please provide a description of the function:def __managed_policy_map(self):
try:
iam_client = boto3.client('iam')
return ManagedPolicyLoader(iam_client).load()
except Exception as ex:
if self._offline_fallback:
# If offline flag is set, then... | [
"\n This method is unused and a Work In Progress\n "
] |
Please provide a description of the function:def _validate(self, sam_template):
if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \
or not sam_template["Resources"]:
raise InvalidDocumentException(
[InvalidTemplateExceptio... | [
" Validates the template and parameter values and raises exceptions if there's an issue\n\n :param dict sam_template: SAM template\n "
] |
Please provide a description of the function: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.all_cmds[cmd_name]) | [
"\n gets the subcommands under the service name\n\n Parameters\n ----------\n ctx : Context\n the context object passed into the method\n cmd_name : str\n the service name\n Returns\n -------\n EventTypeSubCommand:\n returns su... |
Please provide a description of the function: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[cmd_name][self.TAGS].keys():
default = self.subcmd_definition[cmd_... | [
"\n gets the Click Commands underneath a service name\n\n Parameters\n ----------\n ctx: Context\n context object passed in\n cmd_name: string\n the service name\n Returns\n -------\n cmd: Click.Command\n the Click Commands tha... |
Please provide a description of the function: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, kwargs)
click.echo(event)
return event | [
"\n calls for value substitution in the event json and returns the\n customized json as a string\n\n Parameters\n ----------\n events_lib\n top_level_cmd_name: string\n the name of the service\n subcmd_name: string\n the name of the event under ... |
Please provide a description of the function:def generate_lars_path(weighted_data, weighted_labels):
x_vector = weighted_data
alphas, _, coefs = lars_path(x_vector,
weighted_labels,
method='lasso',
... | [
"Generates the lars path for weighted data.\n\n Args:\n weighted_data: data that has been weighted by kernel\n weighted_label: labels, weighted by kernel\n\n Returns:\n (alphas, coefs), both are arrays corresponding to the\n regularization parameter and coef... |
Please provide a description of the function:def forward_selection(self, data, labels, weights, num_features):
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
... | [
"Iteratively adds features to the model"
] |
Please provide a description of the function:def feature_selection(self, data, labels, weights, num_features, method):
if method == 'none':
return np.array(range(data.shape[1]))
elif method == 'forward_selection':
return self.forward_selection(data, labels, weights, num_... | [
"Selects features for the model. see explain_instance_with_data to\n understand the parameters."
] |
Please provide a description of the function:def explain_instance_with_data(self,
neighborhood_data,
neighborhood_labels,
distances,
label,
num_f... | [
"Takes perturbed data, labels and distances, returns explanation.\n\n Args:\n neighborhood_data: perturbed data, 2d array. first element is\n assumed to be the original data point.\n neighborhood_labels: corresponding perturbed labels. should have as\n ... |
Please provide a description of the function:def id_generator(size=15, random_state=None):
chars = list(string.ascii_uppercase + string.digits)
return ''.join(random_state.choice(chars, size, replace=True)) | [
"Helper function to generate random div ids. This is useful for embedding\n HTML into ipython notebooks."
] |
Please provide a description of the function:def available_labels(self):
try:
assert self.mode == "classification"
except AssertionError:
raise NotImplementedError('Not supported for regression explanations.')
else:
ans = self.top_labels if self.top_l... | [
"\n Returns the list of classification labels for which we have any explanations.\n "
] |
Please provide a description of the function:def as_list(self, label=1, **kwargs):
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]
re... | [
"Returns the explanation as a list.\n\n Args:\n label: desired label. If you ask for a label for which an\n explanation wasn't computed, will throw an exception.\n Will be ignored for regression explanations.\n kwargs: keyword arguments, passed to domain_ma... |
Please provide a description of the function:def as_pyplot_figure(self, label=1, **kwargs):
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()
... | [
"Returns the explanation as a pyplot figure.\n\n Will throw an error if you don't have matplotlib installed\n Args:\n label: desired label. If you ask for a label for which an\n explanation wasn't computed, will throw an exception.\n Will be ignored for r... |
Please provide a description of the function:def show_in_notebook(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
from IPython.core.display import display, HTML
disp... | [
"Shows html explanation in ipython notebook.\n\n See as_html() for parameters.\n This will throw an error if you don't have IPython installed"
] |
Please provide a description of the function:def save_to_file(self,
file_path,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
file_ = open(file_path, 'w', encoding='utf8')
... | [
"Saves html explanation to file. .\n\n Params:\n file_path: file to save explanations to\n\n See as_html() for additional parameters.\n\n "
] |
Please provide a description of the function:def as_html(self,
labels=None,
predict_proba=True,
show_predicted_value=True,
**kwargs):
def jsonize(x):
return json.dumps(x, ensure_ascii=False)
if labels is None and self... | [
"Returns the explanation as an html page.\n\n Args:\n labels: desired labels to show explanations for (as barcharts).\n If you ask for a label for which an explanation wasn't\n computed, will throw an exception. If None, will show\n explanations for all... |
Please provide a description of the function:def _check_params(self, parameters):
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 ... | [
"Checks for mistakes in 'parameters'\n\n Args :\n parameters: dict, parameters to be checked\n\n Raises :\n ValueError: if any parameter is not a valid argument for the target function\n or the target function is not defined\n TypeError: if argument para... |
Please provide a description of the function:def filter_params(self, fn, override=None):
override = override or {}
result = {}
for name, value in self.target_params.items():
if has_arg(fn, name):
result.update({name: value})
result.update(override)
... | [
"Filters `target_params` and return those in `fn`'s arguments.\n Args:\n fn : arbitrary function\n override: dict, values to override target_params\n Returns:\n result : dict, dictionary containing variables\n in both target_params and fn's arguments.\n ... |
Please provide a description of the function:def map_exp_ids(self, exp, positions=False):
if positions:
exp = [('%s_%s' % (
self.indexed_string.word(x[0]),
'-'.join(
map(str,
self.indexed_string.string_position(x[0]... | [
"Maps ids to words or word-position strings.\n\n Args:\n exp: list of tuples [(id, weight), (id,weight)]\n positions: if True, also return word positions\n\n Returns:\n list of tuples (word, weight), or (word_positions, weight) if\n examples: ('bad', 1) or (... |
Please provide a description of the function:def visualize_instance_html(self, exp, label, div_name, exp_object_name,
text=True, opacity=True):
if not text:
return u''
text = (self.indexed_string.raw_string()
.encode('utf-8', 'xmlcharr... | [
"Adds text with highlighted words to visualization.\n\n Args:\n exp: list of tuples [(id, weight), (id,weight)]\n label: label id (integer)\n div_name: name of div object to be used for rendering(in js)\n exp_object_name: name of js explanation object\n ... |
Please provide a description of the function:def string_position(self, id_):
if self.bow:
return self.string_start[self.positions[id_]]
else:
return self.string_start[[self.positions[id_]]] | [
"Returns a np array with indices to id_ (int) occurrences"
] |
Please provide a description of the function:def inverse_removing(self, words_to_remove):
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]
... | [
"Returns a string after removing the appropriate words.\n\n If self.bow is false, replaces word with UNKWORDZ instead of removing\n it.\n\n Args:\n words_to_remove: list of ids (ints) to remove\n\n Returns:\n original raw string with appropriate words removed.\n ... |
Please provide a description of the function:def _segment_with_tokens(text, tokens):
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])
... | [
"Segment a string around the tokens created by a passed-in tokenizer"
] |
Please provide a description of the function:def __get_idxs(self, words):
if self.bow:
return list(itertools.chain.from_iterable(
[self.positions[z] for z in words]))
else:
return self.positions[words] | [
"Returns indexes to appropriate words."
] |
Please provide a description of the function:def explain_instance(self,
text_instance,
classifier_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
... | [
"Generates explanations for a prediction.\n\n First, we generate neighborhood data by randomly hiding features from\n the instance (see __data_labels_distance_mapping). We then learn\n locally weighted linear models on this neighborhood data to explain\n each of the classes in an interpr... |
Please provide a description of the function:def __data_labels_distances(self,
indexed_string,
classifier_fn,
num_samples,
distance_metric='cosine'):
def distance_fn(x):
... | [
"Generates a neighborhood around a prediction.\n\n Generates neighborhood data by randomly removing words from\n the instance, and predicting with the classifier. Uses cosine distance\n to compute distances between original and perturbed instances.\n Args:\n indexed_string: do... |
Please provide a description of the function: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 [(names[x[0]], x[1]) for x in exp] | [
"Maps ids to feature names.\n\n Args:\n exp: list of tuples [(id, weight), (id,weight)]\n\n Returns:\n list of tuples (feature_name, weight)\n "
] |
Please provide a description of the function:def visualize_instance_html(self,
exp,
label,
div_name,
exp_object_name,
show_table=True,
... | [
"Shows the current example in a table format.\n\n Args:\n exp: list of tuples [(id, weight), (id,weight)]\n label: label id (integer)\n div_name: name of div object to be used for rendering(in js)\n exp_object_name: name of js explanation object\n s... |
Please provide a description of the function:def validate_training_data_stats(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(st... | [
"\n Method to validate the structure of training data stats\n "
] |
Please provide a description of the function:def explain_instance(self,
data_row,
predict_fn,
labels=(1,),
top_labels=None,
num_features=10,
num_samples=5000,
... | [
"Generates explanations for a prediction.\n\n First, we generate neighborhood data by randomly perturbing features\n from the instance (see __data_inverse). We then learn locally weighted\n linear models on this neighborhood data to explain each of the classes\n in an interpretable way (... |
Please provide a description of the function:def __data_inverse(self,
data_row,
num_samples):
data = np.zeros((num_samples, data_row.shape[0]))
categorical_features = range(data_row.shape[0])
if self.discretizer is None:
data = s... | [
"Generates a neighborhood around a prediction.\n\n For numerical features, perturb them by sampling from a Normal(0,1) and\n doing the inverse operation of mean-centering and scaling, according to\n the means and stds in the training data. For categorical features,\n perturb by sampling ... |
Please provide a description of the function:def _make_predict_proba(self, func):
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... | [
"\n The predict_proba method will expect 3d arrays, but we are reshaping\n them to 2D so that LIME works correctly. This wraps the function\n you give in explain_instance to first reshape the data to have\n the shape the the keras-style network expects.\n "
] |
Please provide a description of the function:def explain_instance(self, data_row, classifier_fn, labels=(1,),
top_labels=None, num_features=10, num_samples=5000,
distance_metric='euclidean', model_regressor=None):
# Flatten input so that the normal exp... | [
"Generates explanations for a prediction.\n\n First, we generate neighborhood data by randomly perturbing features\n from the instance (see __data_inverse). We then learn locally weighted\n linear models on this neighborhood data to explain each of the classes\n in an interpretable way (... |
Please provide a description of the function: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:
raise KeyError('Label not in explanation')
segments = self.segments
... | [
"Init function.\n\n Args:\n label: label to explain\n positive_only: if True, only take superpixels that contribute to\n the prediction of the label. Otherwise, use the top\n num_features superpixels, which can be positive or negative\n towar... |
Please provide a description of the function:def explain_instance(self, image, classifier_fn, labels=(1,),
hide_color=None,
top_labels=5, num_features=100000, num_samples=1000,
batch_size=10,
segmentation_fn=None,
... | [
"Generates explanations for a prediction.\n\n First, we generate neighborhood data by randomly perturbing features\n from the instance (see __data_inverse). We then learn locally weighted\n linear models on this neighborhood data to explain each of the classes\n in an interpretable way (... |
Please provide a description of the function: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.\n\n Args:\n image: 3d numpy array, the image\n fudged_image: 3d numpy array, image to replace original image when\n superpixel is turned off\n segments: segmentation of the image\n ... |
Please provide a description of the function:def has_arg(fn, arg_name):
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.__... | [
"Checks if a callable accepts a given keyword argument.\n\n Args:\n fn: callable to inspect\n arg_name: string, keyword argument name to check\n\n Returns:\n bool, whether `fn` accepts a `arg_name` keyword argument.\n "
] |
Please provide a description of the function:def discretize(self, data):
ret = data.copy()
for feature in self.lambdas:
if len(data.shape) == 1:
ret[feature] = int(self.lambdas[feature](ret[feature]))
else:
ret[:, feature] = self.lambdas[f... | [
"Discretizes the data.\n Args:\n data: numpy 2d or 1d array\n Returns:\n numpy array of same dimension, discretized.\n "
] |
Please provide a description of the function:def _get_remote(self, config, name):
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) | [
"\n The config file is stored in a way that allows you to have a\n cache for each remote.\n\n This is needed when specifying external outputs\n (as they require you to have an external cache location).\n\n Imagine a config file like the following:\n\n ['remote \"dvc... |
Please provide a description of the function: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 = [] # pylint: disable=... | [
"Build a DAG and draw it in ASCII.\n\n Args:\n vertexes (list): list of graph vertexes.\n edges (list): list of graph edges.\n "
] |
Please provide a description of the function:def draw(self):
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)) | [
"Draws ASCII canvas on the screen."
] |
Please provide a description of the function:def point(self, x, y, char):
assert len(char) == 1
assert x >= 0
assert x < self.cols
assert y >= 0
assert y < self.lines
self.canvas[y][x] = char | [
"Create a point on ASCII canvas.\n\n Args:\n x (int): x coordinate. Should be >= 0 and < number of columns in\n the canvas.\n y (int): y coordinate. Should be >= 0 an < number of lines in the\n canvas.\n char (str): character to place in the spec... |
Please provide a description of the function: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, y1
dx = x1 - x0
dy = y1 - y0
if dx == 0 and dy == 0:
... | [
"Create a line on ASCII canvas.\n\n Args:\n x0 (int): x coordinate where the line should start.\n y0 (int): y coordinate where the line should start.\n x1 (int): x coordinate where the line should end.\n y1 (int): y coordinate where the line should end.\n ... |
Please provide a description of the function:def text(self, x, y, text):
for i, char in enumerate(text):
self.point(x + i, y, char) | [
"Print a text on ASCII canvas.\n\n Args:\n x (int): x coordinate where the text should start.\n y (int): y coordinate where the text should start.\n text (str): string that should be printed.\n "
] |
Please provide a description of the function:def box(self, x0, y0, width, 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... | [
"Create a box on ASCII canvas.\n\n Args:\n x0 (int): x coordinate of the box corner.\n y0 (int): y coordinate of the box corner.\n width (int): box width.\n height (int): box height.\n "
] |
Please provide a description of the function: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 = self._line
if sys.stdout.isatty() and line is not None:
... | [
"Refreshes progress bar."
] |
Please provide a description of the function:def update_target(self, name, current, total):
self.refresh(self._bar(name, current, total)) | [
"Updates progress bar for a specified target."
] |
Please provide a description of the function: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.isatty():
self.clearln()
self._print(pbar)
... | [
"Finishes progress bar for a specified target."
] |
Please provide a description of the function:def _bar(self, target_name, current, total):
bar_len = 30
if total is None:
state = 0
percent = "?% "
else:
total = int(total)
state = int((100 * current) / total) if current < total else 100
... | [
"\n Make a progress bar out of info, which looks like:\n (1/2): [########################################] 100% master.zip\n "
] |
Please provide a description of the function:def _extract_dir(self, dir_not_exists, output):
if not dir_not_exists:
lst = output.dir_cache
return {i["relpath"]: i["md5"] for i in lst}
return {} | [
"Extract the content of dvc tree file\n Args:\n self(object) - Repo class instance\n dir_not_exists(bool) - flag for directory existence\n output(object) - OutputLOCAL class instance\n Returns:\n dict - dictionary with keys - paths to file in .dvc/cache\n ... |
Please provide a description of the function: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[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]... | [
"Gerenates diff message string output\n\n Args:\n target(str) - file/directory to check diff of\n a_ref(str) - first tag\n (optional) b_ref(str) - second git tag\n\n Returns:\n string: string of output message with diff info\n "
] |
Please provide a description of the function:def _reproduce_stages(
G,
stages,
node,
force,
dry,
interactive,
ignore_build_cache,
no_commit,
downstream,
):
r
import networkx as nx
if downstream:
# NOTE (py3 only):
# Python's `deepcopy` defaults to pickle... | [
"Derive the evaluation of the given node for the given graph.\n\n When you _reproduce a stage_, you want to _evaluate the descendants_\n to know if it make sense to _recompute_ it. A post-ordered search\n will give us an order list of the nodes we want.\n\n For example, let's say that we have the follow... |
Please provide a description of the function:def istextfile(fname, blocksize=512):
with open(fname, "rb") as fobj:
block = fobj.read(blocksize)
if not block:
# An empty file is considered a valid text file
return True
if b"\x00" in block:
# Files with null bytes are bi... | [
" Uses heuristics to guess whether the given file is text or binary,\n by reading a single block of bytes from the file.\n If more than 30% of the chars in the block are non-text, or there\n are NUL ('\\x00') bytes in the block, assume this is a binary file.\n "
] |
Please provide a description of the function: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 object
for row in csv.reader(unicode_csv_data, dialect=dialect, **kwar... | [
"csv.reader doesn't support Unicode input, so need to use some tricks\n to work around this.\n\n Source: https://docs.python.org/2/library/csv.html#csv-examples\n "
] |
Please provide a description of the function:def cast_bytes(s, encoding=None):
if not isinstance(s, bytes):
return encode(s, encoding)
return s | [
"Source: https://github.com/ipython/ipython_genutils"
] |
Please provide a description of the function:def _makedirs(name, mode=0o777, exist_ok=False):
head, tail = os.path.split(name)
if not tail:
head, tail = os.path.split(head)
if head and tail and not os.path.exists(head):
try:
_makedirs(head, exist_ok=exist_ok)
except ... | [
"Source: https://github.com/python/cpython/blob/\n 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226\n "
] |
Please provide a description of the function:def install(self, address, target_dir, select=[], fname=None):
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.pa... | [
"\n Install package.\n\n The command can be run only from DVC project root.\n\n E.g.\n Having: DVC package in https://github.com/dmpetrov/tag_classifier\n\n $ dvc pkg install https://github.com/dmpetrov/tag_classifier\n\n Result: tag_classifier package in dvc_mod/ directory\n ... |
Please provide a description of the function: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`."
] |
Please provide a description of the function:def remove_outs(self, ignore_remove=False, force=False):
for out in self.outs:
if out.persist and not force:
out.unprotect()
else:
logger.debug(
"Removing output '{out}' of '{stage}'... | [
"Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`."
] |
Please provide a description of the function:def is_cached(self):
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... | [
"\n Checks if this stage has been already ran and stored\n "
] |
Please provide a description of the function:def daemon(args):
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... | [
"Launch a `dvc daemon` command in a detached process.\n\n Args:\n args (list): list of arguments to append to `dvc daemon` command.\n "
] |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.