INSTRUCTION
stringlengths
1
46.3k
RESPONSE
stringlengths
75
80.2k
Helper method that constructs the Event to be passed to Lambda :param request flask_request: Flask Request :return: String representing the event
def _construct_event(flask_request, port, binary_types): """ Helper method that constructs the Event to be passed to Lambda :param request flask_request: Flask Request :return: String representing the event """ identity = ContextIdentity(source_ip=flask_request.remote_a...
Constructs an APIGW equivalent query string dictionary Parameters ---------- flask_request request Request from Flask Returns dict (str: str) ------- Empty dict if no query params where in the request otherwise returns a dictionary of key to value
def _query_string_params(flask_request): """ Constructs an APIGW equivalent query string dictionary Parameters ---------- flask_request request Request from Flask Returns dict (str: str) ------- Empty dict if no query params where in the ...
Find the Lambda function with given name and invoke it. Pass the given event to the function and return response through the given streams. This function will block until either the function completes or times out. Parameters ---------- function_name str Name of the...
def invoke(self, function_name, event, stdout=None, stderr=None): """ Find the Lambda function with given name and invoke it. Pass the given event to the function and return response through the given streams. This function will block until either the function completes or times out. ...
Returns invoke configuration to pass to Lambda Runtime to invoke the given function :param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for :return samcli.local.lambdafn.config.FunctionConfig: Function configuration to pass to Lambda runtime
def _get_invoke_config(self, function): """ Returns invoke configuration to pass to Lambda Runtime to invoke the given function :param samcli.commands.local.lib.provider.Function function: Lambda function to generate the configuration for :return samcli.local.lambdafn.config.FunctionCon...
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.EnvironmentVariabl...
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 ------- sa...
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
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...
Constructs an dictionary representation of the Identity Object to be used in serializing to JSON :return: dict representing the object
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, "cognitoAuth...
Constructs an dictionary representation of the RequestContext Object to be used in serializing to JSON :return: dict representing the object
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_...
Constructs an dictionary representation of the ApiGatewayLambdaEvent Object to be used in serializing to JSON :return: dict representing the object
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.reque...
Implementation of the ``cli`` method
def do_cli(function_name, stack_name, filter_pattern, tailing, start_time, end_time): """ Implementation of the ``cli`` method """ LOG.debug("'logs' command is called") with LogsCommandContext(function_name, stack_name=stack_name, filter_patt...
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
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() ...
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...
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 cont...
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 ------ Docker...
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 t...
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
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) retu...
Publish the application based on command line inputs.
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 t...
Generate detailed success message for published applications. Parameters ---------- publish_output : dict Output from serverlessrepo publish_application Returns ------- str Detailed 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...
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
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 reg...
Helper function to create a Lambda Failure Response :return: A Flask 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)
Constructs a Flask Response for when a Lambda function is not found for an endpoint :return: a Flask 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, ServiceEr...
Constructs a Flask Response for when a API Route (path+method) is not found. This is usually HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840) :return: a Flask Response
def route_not_found(*args): """ Constructs a Flask Response for when a API Route (path+method) is not found. This is usually HTTP 404 but with API Gateway this is a HTTP 403 (https://forums.aws.amazon.com/thread.jspa?threadID=2166840) :return: a Flask Response """ respon...
Creates a progressbar Parameters ---------- length int Length of the ProgressBar label str Label to give to the progressbar Returns ------- click.progressbar 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,...
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 ---------- ...
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 Para...
This starts up the (threaded) Local Server. Note: This is a **blocking call** Raises ------ RuntimeError if the service was not created
def run(self): """ This starts up the (threaded) Local Server. Note: This is a **blocking call** Raises ------ RuntimeError if the service was not created """ if not self._app: raise RuntimeError("The application must be created be...
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
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: F...
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 ...
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 Syst...
Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke Parameters ---------- lambda_response str The response the container returned Returns ------- bool True if the output matches the Error/Exce...
def is_lambda_error_response(lambda_response): """ Check to see if the output from the container is in the form of an Error/Exception from the Lambda invoke Parameters ---------- lambda_response str The response the container returned Returns -------...
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
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: ...
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 ...
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...
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 ...
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 ---------- ...
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 ...
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 direc...
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 con...
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 ...
This method is unused and a Work In Progress
def __translate(self, parameter_values): """ This method is unused and a Work In Progress """ template_copy = self.template sam_parser = Parser() sam_translator = Translator(managed_policy_map=self.__managed_policy_map(), sam_parser=s...
This method is unused and a Work In Progress
def __managed_policy_map(self): """ This method is unused and a Work In Progress """ try: iam_client = boto3.client('iam') return ManagedPolicyLoader(iam_client).load() except Exception as ex: if self._offline_fallback: # If of...
Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template
def _validate(self, sam_template): """ Validates the template and parameter values and raises exceptions if there's an issue :param dict sam_template: SAM template """ if "Resources" not in sam_template or not isinstance(sam_template["Resources"], dict) \ or not sam_tem...
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, No...
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 ------- EventTypeSu...
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 C...
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 ...
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...
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 ...
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, res...
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 correspondin...
Iteratively adds features to the model
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 ...
Selects features for the model. see explain_instance_with_data to understand the parameters.
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': ...
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 ...
def explain_instance_with_data(self, neighborhood_data, neighborhood_labels, distances, label, num_features, f...
Helper function to generate random div ids. This is useful for embedding HTML into ipython notebooks.
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))
Returns the list of classification labels for which we have any explanations.
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.') ...
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 ...
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: ...
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 e...
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 exce...
Shows html explanation in ipython notebook. See as_html() for parameters. This will throw an error if you don't have IPython installed
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 e...
Saves html explanation to file. . Params: file_path: file to save explanations to See as_html() for additional parameters.
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...
Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you ask for a label for which an explanation wasn't computed, will throw an exception. If None, will show explanations for all available ...
def as_html(self, labels=None, predict_proba=True, show_predicted_value=True, **kwargs): """Returns the explanation as an html page. Args: labels: desired labels to show explanations for (as barcharts). If you a...
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...
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 ...
Filters `target_params` and return those in `fn`'s arguments. Args: fn : arbitrary function override: dict, values to override target_params Returns: result : dict, dictionary containing variables in both target_params and fn's arguments.
def filter_params(self, fn, override=None): """Filters `target_params` and return those in `fn`'s arguments. Args: fn : arbitrary function override: dict, values to override target_params Returns: result : dict, dictionary containing variables in b...
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',...
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, weigh...
Adds text with highlighted words to visualization. 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 text: i...
def visualize_instance_html(self, exp, label, div_name, exp_object_name, text=True, opacity=True): """Adds text with highlighted words to visualization. Args: exp: list of tuples [(id, weight), (id,weight)] label: label id (integer) ...
Returns a np array with indices to id_ (int) occurrences
def string_position(self, id_): """Returns a np array with indices to id_ (int) occurrences""" if self.bow: return self.string_start[self.positions[id_]] else: return self.string_start[[self.positions[id_]]]
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.
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 st...
Segment a string around the tokens created by a passed-in tokenizer
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_stri...
Returns indexes to appropriate words.
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]
Generates explanations for a prediction. First, we generate neighborhood data by randomly hiding features from the instance (see __data_labels_distance_mapping). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way...
def explain_instance(self, text_instance, classifier_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='cosine...
Generates a neighborhood around a prediction. Generates neighborhood data by randomly removing words from the instance, and predicting with the classifier. Uses cosine distance to compute distances between original and perturbed instances. Args: indexed_string: document (Ind...
def __data_labels_distances(self, indexed_string, classifier_fn, num_samples, distance_metric='cosine'): """Generates a neighborhood around a prediction. Generates neighborhoo...
Maps ids to feature names. Args: exp: list of tuples [(id, weight), (id,weight)] Returns: list of tuples (feature_name, weight)
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: ...
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: i...
def visualize_instance_html(self, exp, label, div_name, exp_object_name, show_table=True, show_all=False): """Shows the ...
Method to validate the structure of 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_key...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
def explain_instance(self, data_row, predict_fn, labels=(1,), top_labels=None, num_features=10, num_samples=5000, distance_metric='euclidean', ...
Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to the means and stds in the training data. For categorical features, perturb by sampling according ...
def __data_inverse(self, data_row, num_samples): """Generates a neighborhood around a prediction. For numerical features, perturb them by sampling from a Normal(0,1) and doing the inverse operation of mean-centering and scaling, according to ...
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 _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 expe...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
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): """Generates explanations for a prediction. First, we generate neighborhood data by ...
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...
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 ...
Generates explanations for a prediction. First, we generate neighborhood data by randomly perturbing features from the instance (see __data_inverse). We then learn locally weighted linear models on this neighborhood data to explain each of the classes in an interpretable way (see lime_b...
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, distance_metric='cosine', ...
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_f...
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: ...
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.
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 ...
Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized.
def discretize(self, data): """Discretizes the data. Args: data: numpy 2d or 1d array Returns: numpy array of same dimension, discretized. """ ret = data.copy() for feature in self.lambdas: if len(data.shape) == 1: ret[f...
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"'] ...
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 followin...
Build a DAG and draw it in ASCII. Args: vertexes (list): list of graph vertexes. edges (list): list of graph edges.
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 b...
Draws ASCII canvas on the screen.
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))
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 ...
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): ch...
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)...
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 ...
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.
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): ...
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.
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 ...
Refreshes progress bar.
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._w...
Updates progress bar for a specified target.
def update_target(self, name, current, total): """Updates progress bar for a specified target.""" self.refresh(self._bar(name, current, total))
Finishes progress bar for a specified 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) ...
Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip
def _bar(self, target_name, current, total): """ Make a progress bar out of info, which looks like: (1/2): [########################################] 100% master.zip """ bar_len = 30 if total is None: state = 0 percent = "?% " else: ...
Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to file in .dvc/cache values -...
def _extract_dir(self, dir_not_exists, output): """Extract the content of dvc tree file Args: self(object) - Repo class instance dir_not_exists(bool) - flag for directory existence output(object) - OutputLOCAL class instance Returns: dict - dictionary with keys - paths to fil...
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
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 """ res...
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 pip...
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 t...
Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file.
def istextfile(fname, blocksize=512): """ Uses heuristics to guess whether the given file is text or binary, by reading a single block of bytes from the file. If more than 30% of the chars in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. ...
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
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...
Source: https://github.com/ipython/ipython_genutils
def cast_bytes(s, encoding=None): """Source: https://github.com/ipython/ipython_genutils""" if not isinstance(s, bytes): return encode(s, encoding) return s
Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226
def _makedirs(name, mode=0o777, exist_ok=False): """Source: https://github.com/python/cpython/blob/ 3ce3dea60646d8a5a1c952469a2eb65f937875b3/Lib/os.py#L196-L226 """ head, tail = os.path.split(name) if not tail: head, tail = os.path.split(head) if head and tail and not os.path.exists(...
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
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 Res...
Whether the stage file was created with `dvc 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
Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.
def remove_outs(self, ignore_remove=False, force=False): """Used mainly for `dvc remove --outs` and :func:`Stage.reproduce`.""" for out in self.outs: if out.persist and not force: out.unprotect() else: logger.debug( "Removing ou...
Checks if this stage has been already ran and stored
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: ...
Launch a `dvc daemon` command in a detached process. Args: args (list): list of arguments to append to `dvc daemon` command.
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_...
We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc run echo "foo bar"
def _parsed_cmd(self): """ We need to take into account two cases: - ['python code.py foo bar']: Used mainly with dvc as a library - ['echo', 'foo bar']: List of arguments received from the CLI The second case would need quoting, as it was passed through: dvc ru...
Setup parser for `dvc init`.
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." ) in...
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\...
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_...
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.
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): ...
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|...
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 me...
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_...
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: ...
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: ...
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 ...