def Func(arg_0, arg_1=None, arg_2=None):
        """
        Retrieve an H2OGridSearch instance.

        Optionally specify a metric by which to sort models and a sort order.
        Note that if neither cross-validation nor a validation frame is used in the grid search, then the
        training metrics will display in the "get grid" output. If a validation frame is passed to the grid, and
        ``nfolds = 0``, then the validation metrics will display. However, if ``nfolds`` > 1, then cross-validation
        metrics will display even if a validation frame is provided.

        :param str sort_by: A metric by which to sort the models in the grid space. Choices are: ``"logloss"``,
            ``"residual_deviance"``, ``"mse"``, ``"auc"``, ``"r2"``, ``"accuracy"``, ``"precision"``, ``"recall"``,
            ``"f1"``, etc.
        :param bool decreasing: Sort the models in decreasing order of metric if true, otherwise sort in increasing
            order (default).

        :returns: A new H2OGridSearch instance optionally sorted on the specified metric.
        """
        if arg_1 is None and arg_2 is None: return arg_0

        arg_3 = h2o.api("GET /99/Grids/%s" % arg_0._id, data={"sort_by": arg_1, "decreasing": arg_2})
        arg_4 = H2OGridSearch(arg_0.model, arg_0.hyper_params, arg_0._id)
        arg_4.models = [h2o.get_model(key['name']) for key in arg_3['model_ids']]  # reordered
        arg_6 = h2o.api("GET /99/Models/%s" % arg_3['model_ids'][0]['name'])['models'][0]
        arg_7 = H2OGridSearch._metrics_class(arg_6)
        arg_8 = arg_7()
        arg_8._id = arg_0._id
        arg_8._grid_json = arg_3
        # m._metrics_class = metrics_class
        arg_8._parms = arg_4._parms
        H2OEstimator.mixin(arg_4, arg_7)
        arg_4.__dict__.update(arg_8.__dict__.copy())
        return arg_4


def Func(arg_0, arg_1=False):
        """
        Return the Importance of components associcated with a pca model.

        use_pandas: ``bool``  (default: ``False``).
        """
        arg_2 = arg_0._model_json["output"]
        if "importance" in list(arg_2.keys()) and arg_2["importance"]:
            arg_3 = arg_2["importance"].cell_values
            arg_4 = arg_2["importance"].col_header
            if arg_1 and can_use_pandas():
                import pandas
                return pandas.DataFrame(arg_3, columns=arg_4)
            else:
                return arg_3
        else:
            print("Warning: This model doesn't have importances of components.")


def Func(arg_0, arg_1, arg_2=False):
        """
        Convert archetypes of the model into original feature space.

        :param H2OFrame test_data: The dataset upon which the model was trained.
        :param bool reverse_transform: Whether the transformation of the training data during model-building
            should be reversed on the projected archetypes.

        :returns: model archetypes projected back into the original training data's feature space.
        """
        if arg_1 is None or arg_1.nrow == 0: raise ValueError("Must specify test data")
        arg_3 = h2o.api("POST /3/Predictions/models/%s/frames/%s" % (arg_0.model_id, arg_1.frame_id),
                    data={"project_archetypes": True, "reverse_transform": arg_2})
        return h2o.get_frame(arg_3["model_metrics"][0]["predictions"]["frame_id"]["name"])


def Func(arg_0):
    """
    Convert names with underscores into camelcase.

    For example:
        "num_rows" => "numRows"
        "very_long_json_name" => "veryLongJsonName"
        "build_GBM_model" => "buildGbmModel"
        "KEY" => "key"
        "middle___underscores" => "middleUnderscores"
        "_exclude_fields" => "_excludeFields" (retain initial/trailing underscores)
        "__http_status__" => "__httpStatus__"

    :param name: name to be converted
    """
    arg_1 = arg_0.split("_")
    arg_2 = 0
    while arg_1[arg_2] == "":
        arg_1[arg_2] = "_"
        arg_2 += 1
    arg_1[arg_2] = arg_1[arg_2].lower()
    for arg_3 in range(arg_2 + 1, len(arg_1)):
        arg_1[arg_3] = arg_1[arg_3].capitalize()
    arg_2 = len(arg_1) - 1
    while arg_1[arg_2] == "":
        arg_1[arg_2] = "_"
        arg_2 -= 1
    return "".join(arg_1)


def Func(arg_0, arg_1):
    """
    Dedent text to the specific indentation level.

    :param ind: common indentation level for the resulting text (number of spaces to append to every line)
    :param text: text that should be transformed.
    :return: ``text`` with all common indentation removed, and then the specified amount of indentation added.
    """
    arg_2 = textwrap.Func(arg_1)
    if arg_0 == 0:
        return arg_2
    arg_3 = " " * arg_0
    return "\n".join(arg_3 + arg_4 for arg_4 in arg_2.split("\n"))


def Func(arg_0):
    """
    This function will extract the various operation time for GLRM model building iterations.

    :param javaLogText:
    :return:
    """
    global g_initialXY
    global g_reguarlize_Y
    global g_regularize_X_objective
    global g_updateX
    global g_updateY
    global g_objective
    global g_stepsize
    global g_history

    if os.path.isfile(arg_0):

        arg_1 = dict()
        arg_1["total time (ms)"] = []
        arg_1["initialXY (ms)"] = []
        arg_1["regularize Y (ms)"] = []
        arg_1["regularize X and objective (ms)"] = []
        arg_1["update X (ms)"] = []
        arg_1["update Y (ms)"] = []
        arg_1["objective (ms)"] = []
        arg_1["step size (ms)"] = []
        arg_1["update history (ms)"] = []

        arg_2 = -1
        arg_3 = 0.0
        with open(arg_0, 'r') as thefile:   # go into tempfile and grab test run info
            for arg_4 in thefile:
                arg_5 = arg_4.split()

                if len(arg_5) > 0:
                    arg_3 = arg_5[-1].replace('\\','')

                if g_initialXY in arg_4:    # start of a new file
                    if arg_2 > 0:  # update total run time
                        arg_1["total time (ms)"].append(arg_2)
                        arg_2 = 0.0
                    else:
                        arg_2 = 0.0

                    arg_1["initialXY (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_reguarlize_Y in arg_4:
                    arg_1["regularize Y (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_regularize_X_objective in arg_4:
                    arg_1["regularize X and objective (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_updateX in arg_4:
                    arg_1["update X (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_updateY in arg_4:
                    arg_1["update Y (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_objective in arg_4:
                    arg_1["objective (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_stepsize in arg_4:
                    arg_1["step size (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

                if g_history in arg_4:
                    arg_1["update history (ms)"].append(float(arg_3))
                    arg_2 = arg_2+float(arg_3)

        arg_1["total time (ms)"].append(arg_2)    # save the last one
        print("Run result summary: \n {0}".format(arg_1))

    else:
        print("Cannot find your java log file.  Nothing is done.\n")


def Func(arg_0):
    """
    Main program.  Take user input, parse it and call other functions to execute the commands
    and extract run summary and store run result in json file

    @return: none
    """
    global g_test_root_dir
    global g_temp_filename

    if len(arg_0) < 2:
        print("invoke this script as python extractGLRMRuntimeJavaLog.py javatextlog.\n")
        sys.exit(1)
    else:   # we may be in business
        arg_1 = arg_0[1]         # filename while java log is stored

        print("your java text is {0}".format(arg_1))
        extractRunInto(arg_1)


def Func(arg_0):
        """
        Close an existing connection; once Funcd it cannot be used again.

        Strictly speaking it is not necessary to Func all connection that you opened -- we have several mechanisms
        in place that will do so automatically (__del__(), __exit__() and atexit() handlers), however there is also
        no good reason to make this method private.
        """
        if arg_0._session_id:
            try:
                # If the server gone bad, we don't want to wait forever...
                if arg_0._timeout is None: arg_0._timeout = 1
                arg_0.request("DELETE /4/sessions/%s" % arg_0._session_id)
                arg_0._print("H2O session %s Funcd." % arg_0._session_id)
            except Exception:
                pass
            arg_0._session_id = None
        arg_0._stage = -1


def Func(arg_0):
        """
        Return the session id of the current connection.

        The session id is issued (through an API request) the first time it is requested, but no sooner. This is
        because generating a session id puts it into the DKV on the server, which effectively locks the cluster. Once
        issued, the session id will stay the same until the connection is closed.
        """
        if arg_0._Func is None:
            arg_1 = arg_0.request("POST /4/sessions")
            arg_0._Func = arg_1.get("session_key") or arg_1.get("Func")
        return CallableString(arg_0._Func)


def Func(arg_0):
        """
        Prepare `filename` to be sent to the server.

        The "preparation" consists of creating a data structure suitable
        for passing to requests.request().
        """
        if not arg_0: return None
        arg_1 = os.path.abspath(arg_0)
        if not os.path.exists(arg_1):
            raise H2OValueError("File %s does not exist" % arg_0, skip_frames=1)
        return {os.path.basename(arg_1): open(arg_1, "rb")}


def Func(arg_0, arg_1, arg_2):
        """Log response from an API request."""
        if not arg_0._is_logging: return
        arg_3 = int((time.time() - arg_1) * 1000)
        arg_4 = "<<< HTTP %d %s   (%d ms)\n" % (arg_2.status_code, arg_2.reason, arg_3)
        if "Content-Type" in arg_2.headers:
            arg_4 += "    Content-Type: %s\n" % arg_2.headers["Content-Type"]
        arg_4 += arg_2.text
        arg_0._log_message(arg_4 + "\n\n")


def Func(arg_0, arg_1):
        """
        Given a response object, prepare it to be handed over to the external caller.

        Preparation steps include:
           * detect if the response has error status, and convert it to an appropriate exception;
           * detect Content-Type, and based on that either parse the response as JSON or return as plain text.
        """
        arg_2 = arg_0.status_code
        if arg_2 == 200 and arg_1:
            if arg_1.startswith("~"): arg_1 = os.path.expanduser(arg_1)
            if os.path.isdir(arg_1) or arg_1.endswith(os.path.sep):
                arg_3 = os.path.abspath(arg_1)
                arg_4 = H2OConnection._find_file_name(arg_0)
            else:
                arg_3, arg_4 = os.path.split(os.path.abspath(arg_1))
            arg_5 = os.path.join(arg_3, arg_4)
            try:
                if not os.path.exists(arg_3):
                    os.makedirs(arg_3)
                with open(arg_5, "wb") as f:
                    for arg_6 in arg_0.iter_content(chunk_size=65536):
                        if arg_6:  # Empty chunks may occasionally happen
                            f.write(arg_6)
            except OSError as e:
                raise H2OValueError("Cannot write to file %s: %s" % (arg_5, e))
            return arg_5

        arg_7 = arg_0.headers.get("Content-Type", "")
        if ";" in arg_7:  # Remove a ";charset=..." part
            arg_7 = arg_7[:arg_7.index(";")]

        # Auto-detect response type by its content-type. Decode JSON, all other responses pass as-is.
        if arg_7 == "application/json":
            try:
                arg_8 = arg_0.json(object_pairs_hook=H2OResponse)
            except (JSONDecodeError, requests.exceptions.ContentDecodingError) as e:
                raise H2OServerError("Malformed JSON from server (%s):\n%s" % (str(e), arg_0.text))
        else:
            arg_8 = arg_0.text

        # Success (200 = "Ok", 201 = "Created", 202 = "Accepted", 204 = "No Content")
        if arg_2 in {200, 201, 202, 204}:
            return arg_8

        # Client errors (400 = "Bad Request", 404 = "Not Found", 412 = "Precondition Failed")
        if arg_2 in {400, 404, 412} and isinstance(arg_8, (H2OErrorV3, H2OModelBuilderErrorV3)):
            raise H2OResponseError(arg_8)

        # Server errors (notably 500 = "Server Error")
        # Note that it is possible to receive valid H2OErrorV3 object in this case, however it merely means the server
        # did not provide the correct status code.
        raise H2OServerError("HTTP %d %s:\n%r" % (arg_2, arg_0.reason, arg_8))


def Func(arg_0, arg_1, arg_2=False, arg_3="\n"):
        """Helper function to print connection status messages when in verbose mode."""
        if arg_0._verbose:
            print2(arg_1, arg_3=arg_3, arg_2=arg_2)


def Func(arg_0, arg_1=".", arg_2=False, arg_3=""):
        """
        Download the leader model in AutoML in MOJO format.

        :param path: the path where MOJO file should be saved.
        :param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path``.
        :param genmodel_name Custom name of genmodel jar
        :returns: name of the MOJO file written.
        """

        return ModelBase.Func(arg_0.leader, arg_1, arg_2, arg_3)


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        """
        Fit this object by computing the means and standard deviations used by the transform method.

        :param X: An H2OFrame; may contain NAs and/or categoricals.
        :param y: None (Ignored)
        :param params: Ignored
        :returns: This H2OScaler instance
        """
        if isinstance(arg_0.parms["center"], (tuple, list)): arg_0._means = arg_0.parms["center"]
        if isinstance(arg_0.parms["scale"], (tuple, list)): arg_0._stds = arg_0.parms["scale"]
        if arg_0.means is None and arg_0.parms["center"]:
            arg_0._means = arg_1.mean(return_frame=True).getrow()
        else:
            arg_0._means = False
        if arg_0.stds is None and arg_0.parms["scale"]:
            arg_0._stds = arg_1.sd()
        else:
            arg_0._stds = False
        return arg_0


def Func(arg_0, arg_1, arg_2=None, **arg_3):
        """
        Scale an H2OFrame with the fitted means and standard deviations.

        :param X: An H2OFrame; may contain NAs and/or categoricals.
        :param y: None (Ignored)
        :param params: (Ignored)
        :returns: A scaled H2OFrame.
        """
        return arg_1.scale(arg_0.means, arg_0.stds)


def Func(arg_0):
    """
    remove extra characters before the actual string we are
    looking for.  The Jenkins console output is encoded using utf-8.  However, the stupid
    redirect function can only encode using ASCII.  I have googled for half a day with no
    results to how to resolve the issue.  Hence, we are going to the heat and just manually
    get rid of the junk.

    Parameters
    ----------

    string_content :  str
        contains a line read in from jenkins console

    :return: str: contains the content of the line after the string '[0m'

    """

    arg_1,arg_2,arg_3 = arg_0.partition('[0m')

    if arg_2:
        return arg_3
    else:
        return arg_0


def Func(arg_0,arg_1):
    """
    Find the slave machine where a Jenkins job was executed on.  It will save this
    information in g_failed_test_info_dict.  In addition, it will
    delete this particular function handle off the temp_func_list as we do not need
    to perform this action again.

    Parameters
    ----------

    each_line :  str
        contains a line read in from jenkins console
    temp_func_list :  list of Python function handles
        contains a list of functions that we want to invoke to extract information from
        the Jenkins console text.

    :return: bool to determine if text mining should continue on the jenkins console text
    """
    global g_node_name
    global arg_6

    if g_node_name in arg_0:
        arg_2 = arg_0.split()
        [arg_3,arg_4,arg_5] = arg_0.partition(g_node_name)

        if arg_4:
            arg_2 = arg_5.split()
            arg_6["6.node_name"] = extract_true_string(arg_2[1])
            arg_1.remove(Func)

    return True


def Func(arg_0,arg_1):
    """
    Find if a Jenkins job has taken too long to finish and was killed.  It will save this
    information in g_failed_test_info_dict.

    Parameters
    ----------

    each_line :  str
        contains a line read in from jenkins console
    temp_func_list :  list of Python function handles
        contains a list of functions that we want to invoke to extract information from
        the Jenkins console text.

    :return: bool to determine if text mining should continue on the jenkins console text
"""
    global g_build_timeout
    global arg_2
    global arg_3

    if g_build_timeout in arg_0:
        arg_2["8.build_timeout"] = 'Yes'
        arg_3 = True
        return False    # build timeout was found, no need to continue mining the console text
    else:
        return True


def Func(arg_0,arg_1):
    """
    Find if a Jenkins job has failed to build.  It will save this
    information in g_failed_test_info_dict.  In addition, it will delete this particular
    function handle off the temp_func_list as we do not need to perform this action again.

    Parameters
    ----------

    each_line :  str
        contains a line read in from jenkins console
    temp_func_list :  list of Python function handles
        contains a list of functions that we want to invoke to extract information from
        the Jenkins console text.

    :return: bool to determine if text mining should continue on the jenkins console text
    """
    global g_build_success
    global g_build_success_tests
    global arg_4
    global arg_3
    global g_build_failed_message

    for arg_2 in range(0,len(g_build_failed_message)):
        if g_build_failed_message[arg_2] in arg_0.lower():
            if ((arg_2 == 0) and (len(g_failed_jobs) > 0)):
                continue
            else:
                arg_3 = True
                arg_4["7.build_failure"] = 'Yes'
                arg_1.remove(Func)
                return False

    return True


def Func(arg_0,arg_1):
    """
    Find the build id of a jenkins job.  It will save this
    information in g_failed_test_info_dict.  In addition, it will delete this particular
    function handle off the temp_func_list as we do not need to perform this action again.

    Parameters
    ----------

    each_line :  str
        contains a line read in from jenkins console
    temp_func_list :  list of Python function handles
        contains a list of functions that we want to invoke to extract information from
        the Jenkins console text.

    :return: bool to determine if text mining should continue on the jenkins console text
    """
    global g_before_java_file
    global g_java_filenames
    global g_build_id_text
    global arg_6
    global g_output_filename
    global g_output_pickle_filename

    if g_build_id_text in arg_0:
        [arg_2,arg_3,arg_4] = arg_0.partition(g_build_id_text)
        arg_5["2.build_id"] = arg_4.strip()

        arg_1.remove(Func)
        arg_6 = os.path.join('http://',arg_6,'view',g_view_name,'job',arg_5["1.jobName"],arg_5["2.build_id"],'artifact')

    return True


def Func():
    """
    Save the log scraping results into logs denoted by g_output_filename_failed_tests and
    g_output_filename_passed_tests.

    :return: none
    """

    global g_test_root_dir
    global arg_2
    global arg_3
    global arg_4
    global arg_0

    # some build can fail really early that no buid id info is stored in the console text.
    if "2.build_id" not in arg_0.keys():
        arg_0["2.build_id"] = "unknown"

    arg_1 = arg_0["2.build_id"]

    arg_2 = arg_2+'_build_'+arg_1+'_failed_tests.log'
    arg_3 = arg_3+'_build_'+arg_1+'_passed_tests.log'
    arg_4 = arg_4+'_build_'+arg_1+'.pickle'

    arg_5 = sorted(arg_0.keys())

    # write out the jenkins job info into log files.
    with open(arg_4,'wb') as test_file:
        pickle.dump(arg_0,test_file)

    # write out the failure report as text into a text file
    arg_6 = open(arg_2,'w')
    arg_7 = None
    arg_5 = sorted(arg_0.keys())
    arg_8 = False

    if ("passed_tests_info *********" in arg_5):
        arg_7 = open(arg_3,'w')
        arg_8 = True

    for arg_9 in arg_5:
        arg_10 = arg_0[arg_9]
        if isinstance(arg_10,list):    # writing one of the job lists
            if (len(arg_10) == 3):     # it is a message for a test
                if arg_9 == "failed_tests_info *********":
                    write_test_java_message(arg_9,arg_10,arg_6)

                if arg_9 == "passed_tests_info *********":
                    write_test_java_message(arg_9,arg_10,arg_7)
            elif (len(arg_10) == 2):                   # it is a general bad java message
                write_java_message(arg_9,arg_10,arg_6)
                if arg_8:
                    write_java_message(arg_9,arg_10,arg_7)
        else:
            write_general_build_message(arg_9,arg_10,arg_6)
            if arg_8:
                write_general_build_message(arg_9,arg_10,arg_7)

    arg_6.close()
    if arg_8:
        arg_7.close()


def Func():
    """
    Concatecate all log file into a summary text file to be sent to users
    at the end of a daily log scraping.

    :return: none
    """
    global g_summary_text_filename
    global g_output_filename_failed_tests
    global g_output_filename_passed_tests

    with open(g_summary_text_filename,'a') as tempfile:
        write_file_content(tempfile,g_output_filename_failed_tests)
        write_file_content(tempfile,g_output_filename_passed_tests)


def Func(arg_0,arg_1):
    """
    Write one log file into the summary text file.

    Parameters
    ----------
    fhandle :  Python file handle
        file handle to the summary text file
    file2read : Python file handle
        file handle to log file where we want to add its content to the summary text file.

    :return: none
    """
    if os.path.isfile(arg_1):

        # write summary of failed tests logs
        with open(arg_1,'r') as tfile:
            arg_0.write('============ Content of '+ arg_1)
            arg_0.write('\n')
            arg_0.write(tfile.read())
            arg_0.write('\n\n')


def Func(arg_0,arg_1,arg_2):
    """
    Loop through all java messages that are not associated with a unit test and
    write them into a log file.

    Parameters
    ----------
    key :  str
        9.general_bad_java_messages
    val : list of list of str
        contains the bad java messages and the message types.

    :return: none
    """

    arg_2.write(arg_0)
    arg_2.write('\n')

    if (len(arg_1[0]) > 0) and (len(arg_1) >= 3):
        for arg_3 in range(len(arg_1[0])):
            arg_2.write("Java Message Type: ")
            arg_2.write(arg_1[1][arg_3])
            arg_2.write('\n')

            arg_2.write("Java Message: ")

            for arg_4 in arg_1[2][arg_3]:
                arg_2.write(arg_4)
                arg_2.write('\n')

        arg_2.write('\n \n')


def Func():
    """
    Load in pickle file that contains dict structure with bad java messages to ignore per unit test
    or for all cases.  The ignored bad java info is stored in g_ok_java_messages dict.

    :return:
    """
    global arg_0
    global g_java_message_pickle_filename

    if os.path.isfile(g_java_message_pickle_filename):
        with open(g_java_message_pickle_filename,'rb') as tfile:
            arg_0 = pickle.load(tfile)
    else:
        arg_0["general"] = []


def Func(arg_0):
    """Return enum constant `s` converted to a canonical snake-case."""
    if arg_0.islower(): return arg_0
    if arg_0.isupper(): return arg_0.lower()
    return "".join(arg_1 if arg_1.islower() else "_" + arg_1.lower() for arg_1 in arg_0).strip("_")


def Func(arg_0, arg_1, arg_2=lambda arg_3:arg_3, arg_4='mean'):
    # 5 ways of resolving fractional
    # floor, ceil, funky, linear, mean
    arg_5 = ['floor', 'ceil', 'funky', 'linear', 'mean']
    if arg_4 not in arg_5:
        print "Bad choice for interpolate:", arg_4
        print "Supported choices:", arg_5
    """
    Find the percentile of a list of values.

    @parameter N - is a list of values. Note N MUST BE already sorted.
    @parameter percent - a float value from 0.0 to 1.0.
    @parameter key - optional key function to compute value from each element of N.

    @return - the percentile of the values
    """
    if arg_0 is None:
        return None
    arg_6 = (len(arg_0)-1) * arg_1
    arg_7 = int(math.floor(arg_6))
    arg_8 = int(math.ceil(arg_6))

    if arg_7 == arg_8:
        arg_9 = arg_2(arg_0[arg_7])
        arg_10 = "aligned:"

    elif arg_4=='floor':
        arg_9 = arg_2(arg_0[arg_7])
        arg_10 = "fractional with floor:"

    elif arg_4=='ceil':
        arg_9 = arg_2(arg_0[arg_8])
        arg_10 = "fractional with ceil:"

    elif arg_4=='funky':
        arg_11 = arg_2(arg_0[arg_7]) * (arg_8-arg_6)
        arg_12 = arg_2(arg_0[arg_8]) * (arg_6-arg_7)
        arg_9 = arg_11+arg_12
        arg_10 = "fractional with Tung(floor and ceil) :"

    elif arg_4=='linear':
        assert (arg_8-arg_7)==1
        assert (arg_6>=arg_7) and (arg_6<=arg_8)
        arg_13 = arg_6-arg_7
        arg_14 = arg_13 * (arg_2(arg_0[arg_8]) - arg_2(arg_0[arg_7]))
        arg_9 = arg_2(arg_0[arg_7] + arg_14)
        arg_10 = "fractional %s with linear(floor and ceil):" % arg_13

    elif arg_4=='mean':
        arg_9 = (arg_2(arg_0[arg_8]) + arg_2(arg_0[arg_7])) / 2.0
        arg_10 = "fractional with mean(floor and ceil):"

    # print 3 around the floored k, for eyeballing when we're close
    arg_15 = int(arg_7)
    # print the 3 around the median
    if arg_15 > 0:
        print "prior->", arg_2(arg_0[arg_15-1]), " "
    else:
        print "prior->", "<bof>"
    print "floor->", arg_2(arg_0[arg_15]), " ", arg_10, 'result:', arg_9, "f:", arg_7, "len(N):", len(arg_0)
    if arg_15+1 < len(arg_0):
        print " ceil->", arg_2(arg_0[arg_15+1]), "c:", arg_8
    else:
        print " ceil-> <eof>", "c:", arg_8

    return arg_9


def Func(arg_0):
        """Dictionary of the default parameters of the model."""
        arg_1 = {}
        for arg_2 in arg_0.parms:
            arg_1[arg_2] = arg_0.parms[arg_2]["default_value"]
        return arg_1


def Func(arg_0):
        """
        Retrieve Model Score History.

        :returns: The score history as an H2OTwoDimTable or a Pandas DataFrame.
        """
        arg_1 = arg_0._model_json["output"]
        if "Func" in arg_1 and arg_1["Func"] is not None:
            return arg_1["Func"].as_data_frame()
        print("No score history for this model")


def Func(arg_0):
        """Print innards of model, without regards to type."""
        if arg_0._future:
            arg_0._job.poll_once()
            return
        if arg_0._model_json is None:
            print("No model trained yet")
            return
        if arg_0.model_id is None:
            print("This H2OEstimator has been removed.")
            return
        arg_1 = arg_0._model_json["output"]
        print("Model Details")
        print("=============")

        print(arg_0.__class__.__name__, ": ", arg_0._model_json["algo_full_name"])
        print("Model Key: ", arg_0._id)

        arg_0.summary()

        print()
        # training metrics
        arg_2 = arg_1["training_metrics"]
        if arg_2: arg_2.Func()
        arg_3 = arg_1["validation_metrics"]
        if arg_3: arg_3.Func()
        arg_4 = arg_1["cross_validation_metrics"]
        if arg_4: arg_4.Func()
        arg_5 = arg_1["cross_validation_metrics_summary"]
        if arg_5: arg_5.Func()

        if "scoring_history" in arg_1 and arg_1["scoring_history"]:
            arg_1["scoring_history"].Func()
        if "variable_importances" in arg_1 and arg_1["variable_importances"]:
            arg_1["variable_importances"].Func()


def Func(arg_0, arg_1=False, arg_2=False, arg_3=False):
        """
        Retreive the residual degress of freedom if this model has the attribute, or None otherwise.

        :param bool train: Get the residual dof for the training set. If both train and valid are False, then train
            is selected by default.
        :param bool valid: Get the residual dof for the validation set. If both train and valid are True, then train
            is selected by default.

        :returns: Return the residual dof, or None if it is not present.
        """
        if arg_3: raise H2OValueError("Cross-validation metrics are not available.")
        if not arg_1 and not arg_2: arg_1 = True
        if arg_1 and arg_2:         arg_1 = True
        if arg_1:
            return arg_0._model_json["output"]["training_metrics"].Func()
        else:
            return arg_0._model_json["output"]["validation_metrics"].Func()


def Func(arg_0):
        """
        Return the coefficients which can be applied to the non-standardized data.

        Note: standardize = True by default, if set to False then coef() return the coefficients which are fit directly.
        """
        arg_1 = arg_0._model_json["output"]["coefficients_table"]
        if arg_1 is None:
            return None
        return {arg_2: Func for arg_2, Func in zip(arg_1["names"], arg_1["coefficients"])}


def Func(arg_0, arg_1="", arg_2=False, arg_3=""):
        """
        Download the POJO for this model to the directory specified by path.

        If path is an empty string, then dump the output to screen.

        :param path:  An absolute path to the directory where POJO should be saved.
        :param get_genmodel_jar: if True, then also download h2o-genmodel.jar and store it in folder ``path``.
        :param genmodel_name Custom name of genmodel jar
        :returns: name of the POJO file written.
        """
        assert_is_type(arg_1, str)
        assert_is_type(arg_2, bool)
        arg_1 = arg_1.rstrip("/")
        return h2o.Func(arg_0, arg_1, get_jar=arg_2, jar_name=arg_3)


def Func(arg_0, arg_1):
        """Check that y_actual and y_predicted have the same length.

        :param H2OFrame y_actual:
        :param H2OFrame y_predicted:

        :returns: None
        """
        if len(arg_0) != len(arg_1):
            raise ValueError("Row mismatch: [{},{}]".format(len(arg_0), len(arg_1)))


def Func(arg_0=True, arg_1=True, arg_2=False):
    """Deep Learning model demo."""

    def demo_body(arg_3):
        """
        Demo of H2O's Deep Learning model.

        This demo uploads a dataset to h2o, parses it, and shows a description.
        Then it divides the dataset into training and test sets, builds a GLM
        from the training set, and makes predictions for the test set.
        Finally, default performance metrics are displayed.
        """
        arg_3()
        # Connect to H2O
        h2o.init()

        arg_3()
        # Upload the prostate dataset that comes included in the h2o python package
        arg_4 = h2o.load_dataset("prostate")

        arg_3()
        # Print a description of the prostate data
        arg_4.describe()

        arg_3()
        # Randomly split the dataset into ~70/30, training/test sets
        arg_5, arg_6 = arg_4.split_frame(ratios=[0.70])

        arg_3()
        # Convert the response columns to factors (for binary classification problems)
        arg_5["CAPSULE"] = arg_5["CAPSULE"].asfactor()
        arg_6["CAPSULE"] = arg_6["CAPSULE"].asfactor()

        arg_3()
        # Build a (classification) GLM
        from h2o.estimators import H2ODeepLearningEstimator
        arg_7 = H2ODeepLearningEstimator(activation="Tanh", hidden=[10, 10, 10], epochs=10000)
        arg_7.train(x=list(set(arg_4.col_names) - {"ID", "CAPSULE"}),
                          y="CAPSULE", training_frame=arg_5)

        arg_3()
        # Show the model
        arg_7.show()

        arg_3()
        # Predict on the test set and show the first ten predictions
        arg_8 = arg_7.predict(arg_6)
        arg_8.show()

        arg_3()
        # Show default performance metrics
        arg_9 = arg_7.model_performance(arg_6)
        arg_9.show()

    # Execute:
    _run_demo(demo_body, arg_0, arg_1, arg_2)


def Func(arg_0=True, arg_1=True, arg_2=False):
    """GLM model demo."""

    def demo_body(arg_3):
        """
        Demo of H2O's Generalized Linear Estimator.

        This demo uploads a dataset to h2o, parses it, and shows a description.
        Then it divides the dataset into training and test sets, builds a GLM
        from the training set, and makes predictions for the test set.
        Finally, default performance metrics are displayed.
        """
        arg_3()
        # Connect to H2O
        h2o.init()

        arg_3()
        # Upload the prostate dataset that comes included in the h2o python package
        arg_4 = h2o.load_dataset("prostate")

        arg_3()
        # Print a description of the prostate data
        arg_4.describe()

        arg_3()
        # Randomly split the dataset into ~70/30, training/test sets
        arg_5, arg_6 = arg_4.split_frame(ratios=[0.70])

        arg_3()
        # Convert the response columns to factors (for binary classification problems)
        arg_5["CAPSULE"] = arg_5["CAPSULE"].asfactor()
        arg_6["CAPSULE"] = arg_6["CAPSULE"].asfactor()

        arg_3()
        # Build a (classification) GLM
        from h2o.estimators import H2OGeneralizedLinearEstimator
        arg_7 = H2OGeneralizedLinearEstimator(family="binomial", alpha=[0.5])
        arg_7.train(x=["AGE", "RACE", "PSA", "VOL", "GLEASON"],
                           y="CAPSULE", training_frame=arg_5)

        arg_3()
        # Show the model
        arg_7.show()

        arg_3()
        # Predict on the test set and show the first ten predictions
        arg_8 = arg_7.predict(arg_6)
        arg_8.show()

        arg_3()
        # Show default performance metrics
        arg_9 = arg_7.model_performance(arg_6)
        arg_9.show()

    # Execute:
    _run_demo(demo_body, arg_0, arg_1, arg_2)


def Func():
    """
    Wait for a key press on the console and return it.

    Borrowed from http://stackoverflow.com/questions/983354/how-do-i-make-python-to-wait-for-a-pressed-key
    """
    arg_0 = None
    if os.name == "nt":
        # noinspection PyUnresolvedReferences
        import msvcrt
        arg_0 = msvcrt.getch()
    else:
        import termios
        arg_1 = sys.stdin.fileno()

        arg_2 = termios.tcgetattr(arg_1)
        arg_3 = termios.tcgetattr(arg_1)
        arg_3[3] = arg_3[3] & ~termios.ICANON & ~termios.ECHO
        termios.tcsetattr(arg_1, termios.TCSANOW, arg_3)

        try:
            arg_0 = sys.stdin.read(1)
        except IOError:
            pass
        finally:
            termios.tcsetattr(arg_1, termios.TCSAFLUSH, arg_2)

    return arg_0


def Func(arg_0):
        """Convert to a python 'data frame'."""
        if can_use_pandas():
            import arg_1
            arg_1.options.display.max_colwidth = 70
            return arg_1.DataFrame(arg_0._cell_values, columns=arg_0._col_header)
        return arg_0


def Func(arg_0, arg_1=True):
        """Print the contents of this table."""
        # if h2o.can_use_pandas():
        #  import pandas
        #  pandas.options.display.max_rows = 20
        #  print pandas.DataFrame(self._cell_values,columns=self._col_header)
        #  return
        if arg_1 and arg_0._table_header:
            print(arg_0._table_header + ":", end=' ')
            if arg_0._table_description: print(arg_0._table_description)
        print()
        arg_2 = copy.deepcopy(arg_0._cell_values)
        arg_3 = 0
        if _is_list_of_lists(arg_2): arg_3 = len(
            arg_2)  # only set if we truly have multiple rows... not just one long row :)
        if arg_3 > 20:  # create a truncated view of the table, first/last 5 rows
            arg_4 = []
            arg_4 += [arg_5 for arg_5 in arg_2[:5]]
            arg_4.append(["---"] * len(arg_2[0]))
            arg_4 += [arg_5 for arg_5 in arg_2[(arg_3 - 5):]]
            arg_2 = arg_4

        H2ODisplay(arg_2, arg_0._col_header, numalign="left", stralign="left")
        if arg_3 > 20 and can_use_pandas(): print('\nSee the whole table with table.as_data_frame()')


def Func(arg_0, arg_1=None):
        """
        Return the location of an h2o.jar executable.

        :param path0: Explicitly given h2o.jar path. If provided, then we will simply check whether the file is there,
            otherwise we will search for an executable in locations returned by ._jar_paths().

        :raises H2OStartupError: if no h2o.jar executable can be found.
        """
        arg_2 = [arg_1] if arg_1 else arg_0._jar_paths()
        arg_3 = []
        for arg_4 in arg_2:
            arg_3.append(arg_4)
            if os.path.exists(arg_4):
                return arg_4
        raise H2OStartupError("Cannot start local server: h2o.jar not found. Paths searched:\n" +
                              "".join("    %s\n" % arg_5 for arg_5 in arg_3))


def Func():
        """Produce potential paths for an h2o.jar executable."""

        # PUBDEV-3534 hook to use arbitrary h2o.jar
        arg_0 = os.getenv("H2O_JAR_PATH", "")
        if arg_0 != "":
            if not os.path.isfile(arg_0):
                raise H2OStartupError("Environment variable H2O_JAR_PATH is set to '%d' but file does not exists, unset environment variable or provide valid path to h2o.jar file." % arg_0)
            yield arg_0

        # Check if running from an h2o-3 src folder (or any subfolder), in which case use the freshly-built h2o.jar
        arg_1 = os.path.abspath(".").split(os.path.sep)
        for arg_2 in range(len(arg_1), 0, -1):
            if arg_1[arg_2 - 1] == "h2o-3":
                yield os.path.sep.join(arg_1[:arg_2] + ["build", "h2o.jar"])
        # Then check the backend/bin folder:
        # (the following works assuming this code is located in h2o/backend/server.py file)
        arg_3 = os.path.split(os.path.realpath(__file__))[0]
        yield os.path.join(arg_3, "bin", "h2o.jar")

        # Then try several old locations where h2o.jar might have been installed
        arg_4 = arg_5 = sys.prefix
        # On Unix-like systems Python typically gets installed into /Library/... or /System/Library/... If one of
        # those paths is sys.prefix, then we also build its counterpart.
        if arg_4.startswith(os.path.sep + "Library"):
            arg_5 = os.path.join("", "System", arg_4)
        elif arg_4.startswith(os.path.sep + "System"):
            arg_5 = arg_4[len(os.path.join("", "System")):]
        yield os.path.join(arg_4, "h2o_jar", "h2o.jar")
        yield os.path.join(os.path.abspath(os.sep), "usr", "local", "h2o_jar", "h2o.jar")
        yield os.path.join(arg_4, "local", "h2o_jar", "h2o.jar")
        yield os.path.join(get_config_var("userbase"), "h2o_jar", "h2o.jar")
        yield os.path.join(arg_5, "h2o_jar", "h2o.jar")


def Func(arg_0, arg_1):
        ''' Convert uri to absolute filepath

        Parameters
        ----------
        uri : string
            URI of python module to return path for

        Returns
        -------
        path : None or string
            Returns None if there is no valid path for this URI
            Otherwise returns absolute file system path for URI

        Examples
        --------
        >>> docwriter = ApiDocWriter('sphinx')
        >>> import sphinx
        >>> modpath = sphinx.__path__[0]
        >>> res = docwriter.Func('sphinx.builder')
        >>> res == os.path.join(modpath, 'builder.py')
        True
        >>> res = docwriter.Func('sphinx')
        >>> res == os.path.join(modpath, '__init__.py')
        True
        >>> docwriter.Func('sphinx.does_not_exist')

        '''
        if arg_1 == arg_0.package_name:
            return os.path.join(arg_0.root_path, '__init__.py')
        arg_2 = arg_1.replace('.', os.path.sep)
        arg_2 = arg_2.replace(arg_0.package_name + os.path.sep, '')
        arg_2 = os.path.join(arg_0.root_path, arg_2)
        # XXX maybe check for extensions as well?
        if os.path.exists(arg_2 + '.py'): # file
            arg_2 += '.py'
        elif os.path.exists(os.path.join(arg_2, '__init__.py')):
            arg_2 = os.path.join(arg_2, '__init__.py')
        else:
            return None
        return arg_2


def Func(arg_0, arg_1):
        ''' Parse lines of text for functions and classes '''
        arg_2 = []
        arg_3 = []
        for arg_4 in arg_1:
            if arg_4.startswith('def ') and arg_4.count('('):
                # exclude private stuff
                arg_5 = arg_0._get_object_name(arg_4)
                if not arg_5.startswith('_'):
                    arg_2.append(arg_5)
            elif arg_4.startswith('class '):
                # exclude private stuff
                arg_5 = arg_0._get_object_name(arg_4)
                if not arg_5.startswith('_'):
                    arg_3.append(arg_5)
            else:
                pass
        arg_2.sort()
        arg_3.sort()
        return arg_2, arg_3


def Func(arg_0, arg_1):
        """Generate API reST files.

        Parameters
        ----------
        outdir : string
            Directory name in which to store files
            We create automatic filenames for each module

        Returns
        -------
        None

        Notes
        -----
        Sets self.written_modules to list of written modules
        """
        if not os.path.exists(arg_1):
            os.mkdir(arg_1)
        # compose list of modules
        arg_2 = arg_0.discover_modules()
        arg_0.write_modules_api(arg_2,arg_1)


def Func(arg_0,arg_1):
    """
    Update the g_ok_java_messages dict structure by
    1. add the new java ignored messages stored in message_dict if action == 1
    2. remove the java ignored messages stired in message_dict if action == 2.

    Parameters
    ----------

    message_dict :  Python dict
      key: unit test name or "general"
      value: list of java messages that are to be ignored if they are found when running the test stored as the key.  If
        the key is "general", the list of java messages are to be ignored when running all tests.
    action : int
      if 1: add java ignored messages stored in message_dict to g_ok_java_messages dict;
      if 2: remove java ignored messages stored in message_dict from g_ok_java_messages dict.

    :return: none
    """
    global arg_5

    arg_2 = arg_5.keys()

    for arg_3 in arg_0.keys():
        if arg_3 in arg_2:  # key already exists, just add to it
            for arg_4 in arg_0[arg_3]:

                if arg_1 == 1:
                    if arg_4 not in arg_5[arg_3]:
                        arg_5[arg_3].append(arg_4)

                if arg_1 == 2:
                    if arg_4 in arg_5[arg_3]:
                        arg_5[arg_3].remove(arg_4)
        else:   # new key here.  Can only add and cannot remove
            if arg_1 == 1:
                arg_5[arg_3] = arg_0[arg_3]


def Func():
    """
    Save the ignored java message dict stored in g_ok_java_messages into a pickle file for future use.

    :return: none
    """
    global g_ok_java_messages
    global g_save_java_message_filename
    global g_dict_changed

    if g_dict_changed:
        with open(g_save_java_message_filename,'wb') as ofile:
            pickle.dump(g_ok_java_messages,ofile)


def Func():
    """
    Write the java ignored messages in g_ok_java_messages into a text file for humans to read.

    :return: none
    """
    global g_ok_java_messages
    global g_java_messages_to_ignore_text_filename

    arg_0 = sorted(g_ok_java_messages.keys())

    with open(g_java_messages_to_ignore_text_filename,'w') as ofile:
        for arg_1 in arg_0:

            for arg_2 in g_ok_java_messages[arg_1]:
                ofile.write('KeyName: '+arg_1+'\n')
                ofile.write('IgnoredMessage: '+arg_2+'\n')

            print('KeyName: ',arg_1)
            print('IgnoredMessage: ',g_ok_java_messages[arg_1])
            print('\n')


def Func(arg_0):
    """
    Parse user inputs and set the corresponing global variables to perform the
    necessary tasks.

    Parameters
    ----------

    argv : string array
        contains flags and input options from users

    :return:
    """
    global arg_3
    global arg_4
    global arg_5
    global arg_6
    global arg_7

    if len(arg_0) < 2:   # print out help menu if user did not enter any arguments.
        usage()

    arg_1 = 1
    while (arg_1 < len(arg_0)):
        arg_2 = arg_0[arg_1]

        if (arg_2 == "--inputfileadd"):         # input text file where new java messages are stored
            arg_1 += 1
            if (arg_1 > len(arg_0)):
                usage()
            arg_3 = arg_0[arg_1]
        elif (arg_2 == "--inputfilerm"):        # input text file containing java messages to be removed from the ignored list
            arg_1 += 1
            if (arg_1 > len(arg_0)):
                usage()
            arg_4 = arg_0[arg_1]
        elif (arg_2 == "--loadjavamessage"):    # load previously saved java message pickle file from file other than
            arg_1 += 1                          # the default one before performing update
            if arg_1 > len(arg_0):
                usage()
            arg_5 = arg_0[arg_1]
        elif (arg_2 == "--savejavamessage"):    # save updated java message in this file instead of default file
            arg_1 += 1
            if (arg_1 > len(arg_0)):
                usage()
            arg_6 = arg_0[arg_1]
        elif (arg_2 == '--printjavamessage'):   # will print java message out to console and save in a text file
            arg_1 += 1
            arg_7 = True
            arg_5 = arg_0[arg_1]
        elif (arg_2 == '--help'):               # print help menu and exit
            usage()
        else:
            unknown_arg(arg_2)

        arg_1 += 1


def Func(arg_0):
    """Find all python files in the given directory and all subfolders."""
    arg_1 = []
    arg_0 = os.path.abspath(arg_0)
    for arg_2, arg_3, arg_4 in os.walk(arg_0):
        for arg_5 in arg_4:
            if arg_5.endswith(".py"):
                arg_1.append(os.path.join(arg_2, arg_5))
    return arg_1


def Func(arg_0):
    """
    Search the file for any magic incantations.

    :param filename: file to search
    :returns: a tuple containing the spell and then maybe some extra words (or None if no magic present)
    """
    with open(arg_0, "rt", encoding="utf-8") as f:
        for arg_1 in f:
            if arg_1.startswith("#"):
                arg_2 = arg_1[1:].strip()
                if arg_2.startswith("~~~~* ") or arg_2.startswith("----* ") or arg_2.startswith("====* "):
                    arg_3 = arg_2[5:].strip()
                    return tuple(arg_3.split())
            else:
                break
    return None


def Func(arg_0, arg_1, arg_2=False):
        """
        Transform H2OFrame using a MOJO Pipeline.

        :param data: Frame to be Funced.
        :param allow_timestamps: Allows datetime columns to be used directly with MOJO pipelines. It is recommended
        to parse your datetime columns as Strings when using pipelines because pipelines can interpret certain datetime
        formats in a different way. If your H2OFrame is parsed from a binary file format (eg. Parquet) instead of CSV
        it is safe to turn this option on and use datetime columns directly.

        :returns: A new H2OFrame.
        """
        assert_is_type(arg_1, H2OFrame)
        assert_is_type(arg_2, bool)
        return H2OFrame._expr(ExprNode("mojo.pipeline.Func", arg_0.pipeline_id[0], arg_1, arg_2))


def Func():
    """
    This function will print out the intermittents onto the screen for casual viewing.  It will also print out
    where the giant summary dictionary is going to be stored.

    :return: None
    """
    # extract intermittents from collected failed tests
    global g_summary_dict_intermittents

    arg_0 = time.tzname[0]

    for arg_1 in range(len(g_summary_dict_all["TestName"])):
        if g_summary_dict_all["TestInfo"][arg_1]["FailureCount"] >= g_threshold_failure:
            addFailedTests(g_summary_dict_intermittents, g_summary_dict_all, arg_1)

    # save dict in file
    if len(g_summary_dict_intermittents["TestName"]) > 0:
        json.dump(g_summary_dict_intermittents, open(g_summary_dict_name, 'w'))

        with open(g_summary_csv_filename, 'w') as summaryFile:
            for arg_1 in range(len(g_summary_dict_intermittents["TestName"])):
                arg_2 = g_summary_dict_intermittents["TestName"][arg_1]
                arg_3 = g_summary_dict_intermittents["TestInfo"][arg_1]["FailureCount"]
                arg_4  = parser.parse(time.ctime(min(g_summary_dict_intermittents["TestInfo"][arg_1]["Timestamp"]))+
                                              ' '+arg_0)
                arg_5 = arg_4.strftime("%a %b %d %H:%M:%S %Y %Z")
                arg_6 = parser.parse(time.ctime(max(g_summary_dict_intermittents["TestInfo"][arg_1]["Timestamp"]))+
                                          ' '+arg_0)
                arg_7 = arg_6.strftime("%a %b %d %H:%M:%S %Y %Z")
                arg_8 = "{0}, {1}, {2}, {3}\n".format(arg_2, arg_7, arg_3,
                                                       g_summary_dict_intermittents["TestInfo"][arg_1]["TestCategory"][0])
                summaryFile.write(arg_8)
                print("Intermittent: {0}, Last failed: {1}, Failed {2} times since "
                      "{3}".format(arg_2, arg_7, arg_3, arg_5))


def Func(arg_0, arg_1="roc", arg_2=False):
        """
        Produce the desired metric Func.

        :param type: the type of metric Func (currently, only ROC supported).
        :param server: if True, generate Func inline using matFunclib's "Agg" backend.
        :returns: None
        """
        # TODO: add more types (i.e. cutoffs)
        assert_is_type(arg_1, "roc")
        # check for matFunclib. exit if absent.
        try:
            imp.find_module('matFunclib')
            import matFunclib
            if arg_2: matFunclib.use('Agg', warn=False)
            import matFunclib.pyFunc as plt
        except ImportError:
            print("matFunclib is required for this function!")
            return

        if arg_1 == "roc":
            plt.xlabel('False Positive Rate (FPR)')
            plt.ylabel('True Positive Rate (TPR)')
            plt.title('ROC Curve')
            plt.text(0.5, 0.5, r'AUC={0:.4f}'.format(arg_0._metric_json["AUC"]))
            plt.Func(arg_0.fprs, arg_0.tprs, 'b--')
            plt.axis([0, 1, 0, 1])
            if not arg_2: plt.show()


def Func(arg_0, arg_1=None, arg_2=None):
        """
        Get the confusion matrix for the specified metric

        :param metrics: A string (or list of strings) among metrics listed in :const:`max_metrics`. Defaults to 'f1'.
        :param thresholds: A value (or list of values) between 0 and 1.
        :returns: a list of ConfusionMatrix objects (if there are more than one to return), or a single ConfusionMatrix
            (if there is only one).
        """
        # make lists out of metrics and thresholds arguments
        if arg_1 is None and arg_2 is None:
            arg_1 = ['f1']

        if isinstance(arg_1, list):
            arg_3 = arg_1
        elif arg_1 is None:
            arg_3 = []
        else:
            arg_3 = [arg_1]

        if isinstance(arg_2, list):
            arg_4 = arg_2
        elif arg_2 is None:
            arg_4 = []
        else:
            arg_4 = [arg_2]

        # error check the metrics_list and thresholds_list
        assert_is_type(arg_4, [numeric])
        assert_satisfies(arg_4, all(0 <= arg_5 <= 1 for arg_5 in arg_4))

        if not all(arg_6.lower() in H2OBinomialModelMetrics.max_metrics for arg_6 in arg_3):
            raise ValueError("The only allowable metrics are {}", ', '.join(H2OBinomialModelMetrics.max_metrics))

        # make one big list that combines the thresholds and metric-thresholds
        arg_7 = [arg_0.find_threshold_by_max_metric(arg_6) for arg_6 in arg_3]
        for arg_8 in arg_7:
            arg_4.append(arg_8)
        arg_9 = len(arg_4) - len(arg_7)

        arg_10 = arg_0._metric_json['thresholds_and_metric_scores']
        arg_11 = [float(e[0]) for arg_13, e in enumerate(arg_10.cell_values)]
        arg_12 = []
        for arg_13, arg_5 in enumerate(arg_4):
            arg_14 = arg_0.find_idx_by_threshold(arg_5)
            arg_15 = arg_10.cell_values[arg_14]
            arg_16 = arg_15[11]
            arg_17 = arg_15[12]
            arg_18 = arg_15[13]
            arg_19 = arg_15[14]
            arg_20 = arg_19 + arg_17
            arg_21 = arg_16 + arg_18
            arg_22 = arg_21 - arg_18
            arg_23 = arg_20 - arg_19
            if arg_5 in arg_7:
                arg_6 = arg_3[arg_13 - arg_9]
                arg_24 = "Confusion Matrix (Act/Pred) for max {} @ threshold = {}".format(arg_6, arg_11[arg_14])
            else:
                arg_24 = "Confusion Matrix (Act/Pred) @ threshold = {}".format(arg_11[arg_14])
            arg_12.append(ConfusionMatrix(cm=[[arg_22, arg_18], [arg_23, arg_19]], domains=arg_0._metric_json['domain'],
                                       arg_24=arg_24))

        if len(arg_12) == 1:
            return arg_12[0]
        else:
            return arg_12


def Func():
        """Returns True if a deep water model can be built, or False otherwise."""
        arg_0 = h2o.api("GET /3/ModelBuilders", data={"algo": "deepwater"})
        arg_1 = arg_0["model_builders"]["deepwater"]["visibility"]
        if arg_1 == "Experimental":
            print("Cannot build a Deep Water model - no backend found.")
            return False
        else:
            return True


def Func(arg_0):
    """
    This method will remove data from the summary text file and the dictionary file for tests that occurs before
    the number of months specified by monthToKeep.

    :param monthToKeep:
    :return:
    """
    global g_failed_tests_info_dict
    arg_1 = time.time()      # unit in seconds

    arg_2 = arg_1 - arg_0*30*24*3600 # in seconds

    clean_up_failed_test_dict(arg_2)
    clean_up_summary_text(arg_2)


def Func(arg_0, arg_1):
    """Set site domain and name."""
    arg_2 = arg_0.get_model("sites", "Site")
    arg_2.objects.update_or_create(
        id=settings.SITE_ID,
        defaults={
            "domain": "{{cookiecutter.domain_name}}",
            "name": "{{cookiecutter.project_name}}",
        },
    )


def Func(arg_0, arg_1: arg_2, arg_3: arg_2) -> None:
        """
        Append a header, preserving any duplicate entries.
        """
        arg_4 = arg_1.lower().encode("latin-1")
        arg_5 = arg_3.encode("latin-1")
        arg_0._list.Func((arg_4, arg_5))


def Func(arg_0, arg_1: arg_2.Callable) -> dict:
        """
        Given a function, parse the docstring as YAML and return a dictionary of info.
        """
        arg_4 = arg_1.__doc__
        if not arg_4:
            return {}

        # We support having regular docstrings before the schema
        # definition. Here we return just the schema part from
        # the docstring.
        arg_4 = arg_4.split("---")[-1]

        arg_5 = yaml.safe_load(arg_4)

        if not isinstance(arg_5, dict):
            # A regular docstring (not yaml formatted) can return
            # a simple string here, which wouldn't follow the schema.
            return {}

        return arg_5


def Func(
        arg_0, arg_1: arg_2 = None, arg_3: arg_4.List[arg_2] = None
    ) -> arg_4.List[arg_2]:
        """
        Given `directory` and `packages` arugments, return a list of all the
        directories that should be used for serving static files from.
        """
        arg_6 = []
        if arg_1 is not None:
            arg_6.append(arg_1)

        for arg_7 in arg_3 or []:
            arg_8 = importlib.util.find_spec(arg_7)
            assert arg_8 is not None, f"Package {package!r} could not be found."
            assert (
                arg_8.origin is not None
            ), "Directory 'statics' in package {package!r} could not be found."
            arg_1 = os.path.normpath(os.path.join(arg_8.origin, "..", "statics"))
            assert os.path.isdir(
                arg_1
            ), "Directory 'statics' in package {package!r} could not be found."
            arg_6.append(arg_1)

        return arg_6


async def Func(arg_0, arg_1: arg_2, arg_3: arg_4) -> Response:
        """
        Returns an HTTP response, given the incoming path, method and request headers.
        """
        if arg_3["method"] not in ("GET", "HEAD"):
            return PlainTextResponse("Method Not Allowed", status_code=405)

        if arg_1.startswith(".."):
            # Most clients will normalize the path, so we shouldn't normally
            # get this, but don't allow misbehaving clients to break out of
            # the static files directory.
            return PlainTextResponse("Not Found", status_code=404)

        arg_5, arg_6 = await arg_0.lookup_path(arg_1)

        if arg_6 and stat.S_ISREG(arg_6.st_mode):
            # We have a static file to serve.
            return arg_0.file_response(arg_5, arg_6, arg_3)

        elif arg_6 and stat.S_ISDIR(arg_6.st_mode) and arg_0.html:
            # We're in HTML mode, and have got a directory URL.
            # Check if we have 'index.html' file to serve.
            arg_7 = os.path.join(arg_1, "index.html")
            arg_5, arg_6 = await arg_0.lookup_path(arg_7)
            if arg_6 is not None and stat.S_ISREG(arg_6.st_mode):
                if not arg_3["path"].endswith("/"):
                    # Directory URLs should redirect to always end in "/".
                    arg_8 = URL(arg_3=arg_3)
                    arg_8 = arg_8.replace(arg_1=arg_8.path + "/")
                    return RedirectResponse(arg_8=arg_8)
                return arg_0.file_response(arg_5, arg_6, arg_3)

        if arg_0.html:
            # Check for '404.html' if we're in HTML mode.
            arg_5, arg_6 = await arg_0.lookup_path("404.html")
            if arg_6 is not None and stat.S_ISREG(arg_6.st_mode):
                return arg_0.file_response(
                    arg_5, arg_6, arg_3, status_code=404
                )

        return PlainTextResponse("Not Found", status_code=404)


async def Func(arg_0, arg_1: arg_2) -> None:
        """
        Send ASGI websocket messages, ensuring valid state transitions.
        """
        if arg_0.application_state == WebSocketState.CONNECTING:
            arg_3 = arg_1["type"]
            assert arg_3 in {"websocket.accept", "websocket.close"}
            if arg_3 == "websocket.close":
                arg_0.application_state = WebSocketState.DISCONNECTED
            else:
                arg_0.application_state = WebSocketState.CONNECTED
            await arg_0._Func(arg_1)
        elif arg_0.application_state == WebSocketState.CONNECTED:
            arg_3 = arg_1["type"]
            assert arg_3 in {"websocket.Func", "websocket.close"}
            if arg_3 == "websocket.close":
                arg_0.application_state = WebSocketState.DISCONNECTED
            await arg_0._Func(arg_1)
        else:
            raise RuntimeError('Cannot call "Func" once a close message has been sent.')


def Func(arg_0, arg_1=None):
        """Adds the default_data to data and dumps it to a json."""
        if arg_1 is None:
            arg_1 = {}
        arg_1.update(arg_0.default_data)
        return json.dumps(arg_1)


def Func(arg_0, arg_1, arg_2=None):
    """ Comments last user_id's medias """
    if not arg_0.check_user(arg_1, filter_closed_acc=True):
        return False
    arg_0.logger.info("Going to comment user_%s's feed:" % arg_1)
    arg_1 = arg_0.convert_to_user_id(arg_1)
    arg_3 = arg_0.get_user_medias(arg_1, is_comment=True)
    if not arg_3:
        arg_0.logger.info(
            "None medias received: account is closed or medias have been filtered.")
        return False
    return arg_0.comment_medias(arg_3[:arg_2])


def Func(arg_0=None):
    """Returns login and password stored in `secret.txt`."""
    while not check_secret():
        pass
    while True:
        try:
            with open(SECRET_FILE, "r") as f:
                arg_1 = [line.strip().split(":", 2) for line in f.readlines()]
        except ValueError:
            arg_2 = 'Problem with opening `{}`, will remove the file.'
            raise Exception(arg_2.format(SECRET_FILE))
        if arg_0 is not None:
            for arg_3, arg_4 in arg_1:
                if arg_3 == arg_0.strip():
                    return arg_3, arg_4
        print("Which account do you want to use? (Type number)")
        for arg_5, (arg_3, arg_4) in enumerate(arg_1):
            print("%d: %s" % (arg_5 + 1, arg_3))
        print("%d: %s" % (0, "add another account."))
        print("%d: %s" % (-1, "delete all accounts."))
        try:
            arg_5 = int(sys.stdin.readline())
            if arg_5 == 0:
                add_credentials()
                continue
            elif arg_5 == -1:
                delete_credentials()
                check_secret()
                continue
            elif 0 <= arg_5 - 1 < len(arg_1):
                return arg_1[arg_5 - 1]
        except Exception:
            print("Wrong input, enter the number of the account to use.")


def Func(arg_0, arg_1, arg_2=None, arg_3=True):
    """ Likes last user_id's medias """
    if arg_3:
        if not arg_0.check_user(arg_1):
            return False
    arg_0.logger.info("Liking user_%s's feed:" % arg_1)
    arg_1 = arg_0.convert_to_user_id(arg_1)
    arg_4 = arg_0.get_user_medias(arg_1, arg_3=arg_3)
    if not arg_4:
        arg_0.logger.info(
            "None medias received: account is closed or medias have been filtered.")
        return False
    return arg_0.like_medias(arg_4[:arg_2])


def Func(arg_0, arg_1=False):
    """
        Reads list from file. One line - one item.
        Returns the list if file items.
    """
    try:
        if not check_if_file_exists(arg_0, arg_1=arg_1):
            return []
        with codecs.open(arg_0, "r", encoding="utf-8") as f:
            arg_2 = f.readlines()
            if sys.version_info[0] < 3:
                arg_2 = [str(item.encode('utf8')) for item in arg_2]
            arg_2 = [item.strip() for item in arg_2]
            return [arg_3 for arg_3 in arg_2 if arg_3]
    except Exception as exception:
        print(str(exception))
        return []


def Func(arg_0):
    """
    Finds the max and median long and short position concentrations
    in each time period specified by the index of positions.

    Parameters
    ----------
    positions : pd.DataFrame
        The positions that the strategy takes over time.

    Returns
    -------
    pd.DataFrame
        Columns are max long, max short, median long, and median short
        position concentrations. Rows are timeperiods.
    """

    arg_1 = get_percent_alloc(arg_0)
    arg_1 = arg_1.drop('cash', axis=1)

    arg_2 = arg_1.where(arg_1.applymap(lambda x: x > 0))
    arg_3 = arg_1.where(arg_1.applymap(lambda x: x < 0))

    arg_4 = pd.DataFrame()
    arg_4['max_long'] = arg_2.max(axis=1)
    arg_4['median_long'] = arg_2.median(axis=1)
    arg_4['median_short'] = arg_3.median(axis=1)
    arg_4['max_short'] = arg_3.min(axis=1)

    return arg_4


def Func(arg_0):
    """
    Determines the long and short allocations in a portfolio.

    Parameters
    ----------
    positions : pd.DataFrame
        The positions that the strategy takes over time.

    Returns
    -------
    df_long_short : pd.DataFrame
        Long and short allocations as a decimal
        percentage of the total net liquidation
    """

    arg_1 = arg_0.drop('cash', axis=1)
    arg_2 = arg_1[arg_1 > 0].sum(axis=1).fillna(0)
    arg_3 = arg_1[arg_1 < 0].sum(axis=1).fillna(0)
    arg_4 = arg_0.cash
    arg_5 = arg_2 + arg_3 + arg_4
    arg_6 = pd.DataFrame({'long': arg_2.divide(arg_5, axis='index'),
                           'short': arg_3.divide(arg_5,
                                                  axis='index')})
    arg_6['net exposure'] = arg_6['long'] + arg_6['short']
    return arg_6


def Func(arg_0, arg_1):
    """
    Returns style factor exposure of an algorithm's positions

    Parameters
    ----------
    positions : pd.DataFrame
        Daily equity positions of algorithm, in dollars.
        - See full explanation in create_risk_tear_sheet

    risk_factor : pd.DataFrame
        Daily risk factor per asset.
        - DataFrame with dates as index and equities as columns
        - Example:
                         Equity(24   Equity(62
                           [AAPL])      [ABT])
        2017-04-03	  -0.51284     1.39173
        2017-04-04	  -0.73381     0.98149
        2017-04-05	  -0.90132     1.13981
    """

    arg_2 = arg_0.drop('cash', axis='columns')
    arg_3 = arg_2.abs().sum(axis='columns')

    arg_4 = arg_2.multiply(arg_1) \
        .divide(arg_3, axis='index')
    arg_5 = arg_4.sum(axis='columns',
                                                          skipna=True)

    return arg_5


def Func(arg_0, arg_1=None,
                                arg_2=None):
    """
    Plots DataFrame output of compute_style_factor_exposures as a line graph

    Parameters
    ----------
    tot_style_factor_exposure : pd.Series
        Daily style factor exposures (output of compute_style_factor_exposures)
        - Time series with decimal style factor exposures
        - Example:
            2017-04-24    0.037820
            2017-04-25    0.016413
            2017-04-26   -0.021472
            2017-04-27   -0.024859

    factor_name : string
        Name of style factor, for use in graph title
        - Defaults to tot_style_factor_exposure.name
    """

    if arg_2 is None:
        arg_2 = plt.gca()

    if arg_1 is None:
        arg_1 = arg_0.name

    arg_2.plot(arg_0.index, arg_0,
            label=arg_1)
    arg_3 = arg_0.mean()
    arg_2.axhline(arg_3, linestyle='-.', label='Mean = {:.3}'.format(arg_3))
    arg_2.axhline(0, color='k', linestyle='-')
    arg_4, arg_4, arg_5, arg_6 = plt.axis()
    arg_7 = max(abs(arg_5), abs(arg_6))
    arg_2.set(title='Exposure to {}'.format(arg_1),
           ylabel='{} \n weighted exposure'.format(arg_1),
           ylim=(-arg_7, arg_7))
    arg_2.legend(frameon=True, framealpha=0.5)

    return arg_2


def Func(arg_0, arg_1,
                                    arg_2=arg_3, arg_4=None):
    """
    Plots outputs of compute_sector_exposures as area charts

    Parameters
    ----------
    long_exposures, short_exposures : arrays
        Arrays of long and short sector exposures (output of
        compute_sector_exposures).

    sector_dict : dict or OrderedDict
        Dictionary of all sectors
        - See full description in compute_sector_exposures
    """

    if arg_4 is None:
        arg_4 = plt.gca()

    if arg_2 is None:
        arg_5 = arg_3.values()
    else:
        arg_5 = arg_2.values()

    arg_6 = plt.cm.gist_rainbow(np.linspace(0, 1, 11))

    arg_4.stackplot(arg_0[0].index, arg_0,
                 labels=arg_5, colors=arg_6, alpha=0.8,
                 baseline='zero')
    arg_4.stackplot(arg_0[0].index, arg_1,
                 colors=arg_6, alpha=0.8, baseline='zero')
    arg_4.axhline(0, color='k', linestyle='-')
    arg_4.set(title='Long and short exposures to sectors',
           ylabel='Proportion of long/short exposure in sectors')
    arg_4.legend(loc='upper left', frameon=True, framealpha=0.5)

    return arg_4


def Func(arg_0, arg_1=None, arg_2=None):
    """
    Plots output of compute_sector_exposures as line graphs

    Parameters
    ----------
    net_exposures : arrays
        Arrays of net sector exposures (output of compute_sector_exposures).

    sector_dict : dict or OrderedDict
        Dictionary of all sectors
        - See full description in compute_sector_exposures
    """

    if arg_2 is None:
        arg_2 = plt.gca()

    if arg_1 is None:
        arg_3 = SECTORS.values()
    else:
        arg_3 = arg_1.values()

    arg_4 = plt.cm.gist_rainbow(np.linspace(0, 1, 11))

    for arg_5 in range(len(arg_0)):
        arg_2.plot(arg_0[arg_5], color=arg_4[arg_5], alpha=0.8,
                label=arg_3[arg_5])
    arg_2.set(title='Net exposures to sectors',
           ylabel='Proportion of net exposure \n in sectors')

    return arg_2


def Func(arg_0,
                           arg_1=None,
                           arg_2=None,
                           arg_3=None,
                           arg_4=None,
                           arg_5=None,
                           arg_6=None,
                           arg_7=None,
                           arg_8=False,
                           arg_9=False,
                           arg_10='infer',
                           arg_11=False,
                           arg_12=(1.0, 1.5, 2.0),
                           arg_13=False,
                           arg_14=None,
                           arg_15=None,
                           arg_16=None,
                           arg_17=None,
                           arg_18=None,
                           arg_19=None,
                           arg_20=None,
                           arg_21='AGB',
                           arg_22=True,
                           arg_23=None,
                           arg_24=None,
                           arg_25=True,
                           arg_26=None,
                           arg_27=arg_28):
    """
    Generate a number of tear sheets that are useful
    for analyzing a strategy's performance.

    - Fetches benchmarks if needed.
    - Creates tear sheets for returns, and significant events.
        If possible, also creates tear sheets for position analysis,
        transaction analysis, and Bayesian analysis.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - Time series with decimal returns.
         - Example:
            2015-07-16    -0.012143
            2015-07-17    0.045350
            2015-07-20    0.030957
            2015-07-21    0.004902
    positions : pd.DataFrame, optional
        Daily net position values.
         - Time series of dollar amount invested in each position and cash.
         - Days where stocks are not held can be represented by 0 or NaN.
         - Non-working capital is labelled 'cash'
         - Example:
            index         'AAPL'         'MSFT'          cash
            2004-01-09    13939.3800     -14012.9930     711.5585
            2004-01-12    14492.6300     -14624.8700     27.1821
            2004-01-13    -13853.2800    13653.6400      -43.6375
    transactions : pd.DataFrame, optional
        Executed trade volumes and fill prices.
        - One row per trade.
        - Trades on different names that occur at the
          same time will have identical indicies.
        - Example:
            index                  amount   price    symbol
            2004-01-09 12:18:01    483      324.12   'AAPL'
            2004-01-09 12:18:01    122      83.10    'MSFT'
            2004-01-13 14:12:23    -75      340.43   'AAPL'
    market_data : pd.Panel, optional
        Panel with items axis of 'price' and 'volume' DataFrames.
        The major and minor axes should match those of the
        the passed positions DataFrame (same dates and symbols).
    slippage : int/float, optional
        Basis points of slippage to apply to returns before generating
        tearsheet stats and plots.
        If a value is provided, slippage parameter sweep
        plots will be generated from the unadjusted returns.
        Transactions and positions must also be passed.
        - See txn.adjust_returns_for_slippage for more details.
    live_start_date : datetime, optional
        The point in time when the strategy began live trading,
        after its backtest period. This datetime should be normalized.
    hide_positions : bool, optional
        If True, will not output any symbol names.
    bayesian: boolean, optional
        If True, causes the generation of a Bayesian tear sheet.
    round_trips: boolean, optional
        If True, causes the generation of a round trip tear sheet.
    sector_mappings : dict or pd.Series, optional
        Security identifier to sector mapping.
        Security ids as keys, sectors as values.
    estimate_intraday: boolean or str, optional
        Instead of using the end-of-day positions, use the point in the day
        where we have the most $ invested. This will adjust positions to
        better approximate and represent how an intraday strategy behaves.
        By default, this is 'infer', and an attempt will be made to detect
        an intraday strategy. Specifying this value will prevent detection.
    cone_std : float, or tuple, optional
        If float, The standard deviation to use for the cone plots.
        If tuple, Tuple of standard deviation values to use for the cone plots
         - The cone is a normal distribution with this standard deviation
             centered around a linear regression.
    bootstrap : boolean (optional)
        Whether to perform bootstrap analysis for the performance
        metrics. Takes a few minutes longer.
    turnover_denom : str
        Either AGB or portfolio_value, default AGB.
        - See full explanation in txn.get_turnover.
    factor_returns : pd.Dataframe, optional
        Returns by factor, with date as index and factors as columns
    factor_loadings : pd.Dataframe, optional
        Factor loadings for all days in the date range, with date and
        ticker as index, and factors as columns.
    pos_in_dollars : boolean, optional
        indicates whether positions is in dollars
    header_rows : dict or OrderedDict, optional
        Extra rows to display at the top of the perf stats table.
    set_context : boolean, optional
        If True, set default plotting style context.
         - See plotting.context().
    factor_partitions : dict, optional
        dict specifying how factors should be separated in perf attrib
        factor returns and risk exposures plots
        - See create_perf_attrib_tear_sheet().
    """

    if (arg_14 is None) and (arg_5 is not None) and\
       (arg_2 is not None):
        arg_14 = arg_0.copy()
        arg_0 = txn.adjust_returns_for_slippage(arg_0, arg_1,
                                                  arg_2, arg_5)

    arg_1 = utils.check_intraday(arg_10, arg_0,
                                     arg_1, arg_2)

    create_returns_tear_sheet(
        arg_0,
        arg_1=arg_1,
        arg_2=arg_2,
        arg_6=arg_6,
        arg_12=arg_12,
        arg_4=arg_4,
        arg_13=arg_13,
        arg_21=arg_21,
        arg_26=arg_26,
        arg_22=arg_22)

    create_interesting_times_tear_sheet(arg_0,
                                        arg_4=arg_4,
                                        arg_22=arg_22)

    if arg_1 is not None:
        create_position_tear_sheet(arg_0, arg_1,
                                   arg_11=arg_11,
                                   arg_22=arg_22,
                                   arg_7=arg_7,
                                   arg_10=False)

        if arg_2 is not None:
            create_txn_tear_sheet(arg_0, arg_1, arg_2,
                                  arg_14=arg_14,
                                  arg_10=False,
                                  arg_22=arg_22)
            if arg_9:
                create_round_trip_tear_sheet(
                    arg_0=arg_0,
                    arg_1=arg_1,
                    arg_2=arg_2,
                    arg_7=arg_7,
                    arg_10=False)

            if arg_3 is not None:
                create_capacity_tear_sheet(arg_0, arg_1, arg_2,
                                           arg_3,
                                           liquidation_daily_vol_limit=0.2,
                                           last_n_days=125,
                                           arg_10=False)

        if arg_15 is not None:
            create_risk_tear_sheet(arg_1, arg_15, arg_16,
                                   arg_17, arg_18, arg_19, arg_20)

        if arg_23 is not None and arg_24 is not None:
            create_perf_attrib_tear_sheet(arg_0, arg_1, arg_23,
                                          arg_24, arg_2,
                                          arg_25=arg_25,
                                          arg_27=arg_27)

    if arg_8:
        create_bayesian_tear_sheet(arg_0,
                                   arg_6=arg_6,
                                   arg_4=arg_4,
                                   arg_22=arg_22)


def Func(arg_0, arg_1,
                               arg_2=2, arg_3=False,
                               arg_4=False, arg_5=None,
                               arg_6=None, arg_7='infer'):
    """
    Generate a number of plots for analyzing a
    strategy's positions and holdings.

    - Plots: gross leverage, exposures, top positions, and holdings.
    - Will also print the top positions held.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    show_and_plot_top_pos : int, optional
        By default, this is 2, and both prints and plots the
        top 10 positions.
        If this is 0, it will only plot; if 1, it will only print.
    hide_positions : bool, optional
        If True, will not output any symbol names.
        Overrides show_and_plot_top_pos to 0 to suppress text output.
    return_fig : boolean, optional
        If True, returns the figure that was plotted on.
    sector_mappings : dict or pd.Series, optional
        Security identifier to sector mapping.
        Security ids as keys, sectors as values.
    transactions : pd.DataFrame, optional
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.
    estimate_intraday: boolean or str, optional
        Approximate returns for intraday strategies.
        See description in create_full_tear_sheet.
    """

    arg_1 = utils.check_intraday(arg_7, arg_0,
                                     arg_1, arg_6)

    if arg_3:
        arg_2 = 0
    arg_8 = 7 if arg_5 is not None else 6

    arg_9 = plt.figure(figsize=(14, arg_8 * 6))
    arg_10 = gridspec.GridSpec(arg_8, 3, wspace=0.5, hspace=0.5)
    arg_11 = plt.subplot(arg_10[0, :])
    arg_12 = plt.subplot(arg_10[1, :], sharex=arg_11)
    arg_13 = plt.subplot(arg_10[2, :], sharex=arg_11)
    arg_14 = plt.subplot(arg_10[3, :], sharex=arg_11)
    arg_15 = plt.subplot(arg_10[4, :])
    arg_16 = plt.subplot(arg_10[5, :], sharex=arg_11)

    arg_17 = pos.get_percent_alloc(arg_1)

    plotting.plot_exposures(arg_0, arg_1, arg_21=arg_11)

    plotting.show_and_plot_top_positions(
        arg_0,
        arg_17,
        show_and_plot=arg_2,
        arg_3=arg_3,
        arg_21=arg_12)

    plotting.plot_max_median_position_concentration(arg_1,
                                                    arg_21=arg_13)

    plotting.plot_holdings(arg_0, arg_17, arg_21=arg_14)

    plotting.plot_long_short_holdings(arg_0, arg_17,
                                      arg_21=arg_15)

    plotting.plot_gross_leverage(arg_0, arg_1,
                                 arg_21=arg_16)

    if arg_5 is not None:
        arg_18 = pos.get_sector_exposures(arg_1,
                                                    arg_5)
        if len(arg_18.columns) > 1:
            arg_19 = pos.get_percent_alloc(arg_18)
            arg_19 = arg_19.drop('cash', axis='columns')
            arg_20 = plt.subplot(arg_10[6, :], sharex=arg_11)
            plotting.plot_sector_allocations(arg_0, arg_19,
                                             arg_21=arg_20)

    for arg_21 in arg_9.axes:
        plt.setp(arg_21.get_xticklabels(), visible=True)

    if arg_4:
        return arg_9


def Func(arg_0,
                                  arg_1,
                                  arg_2,
                                  arg_3,
                                  arg_4=None,
                                  arg_5=True,
                                  arg_6=False,
                                  arg_7=arg_8):
    """
    Generate plots and tables for analyzing a strategy's performance.

    Parameters
    ----------
    returns : pd.Series
        Returns for each day in the date range.

    positions: pd.DataFrame
        Daily holdings (in dollars or percentages), indexed by date.
        Will be converted to percentages if positions are in dollars.
        Short positions show up as cash in the 'cash' column.

    factor_returns : pd.DataFrame
        Returns by factor, with date as index and factors as columns

    factor_loadings : pd.DataFrame
        Factor loadings for all days in the date range, with date
        and ticker as index, and factors as columns.

    transactions : pd.DataFrame, optional
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.
         - Default is None.

    pos_in_dollars : boolean, optional
        Flag indicating whether `positions` are in dollars or percentages
        If True, positions are in dollars.

    return_fig : boolean, optional
        If True, returns the figure that was plotted on.

    factor_partitions : dict
        dict specifying how factors should be separated in factor returns
        and risk exposures plots
        - Example:
          {'style': ['momentum', 'size', 'value', ...],
           'sector': ['technology', 'materials', ... ]}
    """
    arg_9, arg_10 = perf_attrib.perf_attrib(
        arg_0, arg_1, arg_2, arg_3, arg_4,
        arg_5=arg_5
    )

    display(Markdown("## Performance Relative to Common Risk Factors"))

    # aggregate perf attrib stats and show summary table
    perf_attrib.show_perf_attrib_stats(arg_0, arg_1, arg_2,
                                       arg_3, arg_4,
                                       arg_5)

    # one section for the returns plot, and for each factor grouping
    # one section for factor returns, and one for risk exposures
    arg_11 = 1 + 2 * max(len(arg_7), 1)
    arg_12 = 0

    arg_13 = plt.figure(figsize=[14, arg_11 * 6])

    arg_14 = gridspec.GridSpec(arg_11, 1,
                           wspace=0.5, hspace=0.5)

    perf_attrib.plot_returns(arg_10,
                             ax=plt.subplot(arg_14[arg_12]))
    arg_12 += 1

    if arg_7 is not None:

        for arg_15, arg_16 in arg_7.iteritems():

            arg_17 = arg_10.columns.intersection(
                arg_16
            )

            perf_attrib.plot_factor_contribution_to_perf(
                arg_10[arg_17],
                ax=plt.subplot(arg_14[arg_12]),
                title=(
                    'Cumulative common {} returns attribution'
                ).format(arg_15)
            )
            arg_12 += 1

        for arg_15, arg_16 in arg_7.iteritems():

            perf_attrib.plot_risk_exposures(
                arg_9[arg_9.columns
                                    .intersection(arg_16)],
                ax=plt.subplot(arg_14[arg_12]),
                title='Daily {} factor exposures'.format(arg_15)
            )
            arg_12 += 1

    else:

        perf_attrib.plot_factor_contribution_to_perf(
            arg_10,
            ax=plt.subplot(arg_14[arg_12])
        )
        arg_12 += 1

        perf_attrib.plot_risk_exposures(
            arg_9,
            ax=plt.subplot(arg_14[arg_12])
        )

    arg_14.tight_layout(arg_13)

    if arg_6:
        return arg_13


def Func(arg_0, arg_1):
    """
    Sums the absolute value of shares traded in each name on each day.
    Adds columns containing the closing price and total daily volume for
    each day-ticker combination.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
        - See full explanation in tears.create_full_tear_sheet
    market_data : pd.Panel
        Contains "volume" and "price" DataFrames for the tickers
        in the passed positions DataFrames

    Returns
    -------
    txn_daily : pd.DataFrame
        Daily totals for transacted shares in each traded name.
        price and volume columns for close price and daily volume for
        the corresponding ticker, respectively.
    """

    arg_0.index.name = 'date'
    arg_4 = pd.DataFrame(arg_0.assign(
        amount=abs(arg_0.amount)).groupby(
        ['symbol', pd.TimeGrouper('D')]).sum()['amount'])
    arg_4['price'] = arg_1['price'].unstack()
    arg_4['volume'] = arg_1['volume'].unstack()

    arg_4 = arg_4.reset_index().set_index('date')

    return arg_4


def Func(arg_0, arg_1,
                                   arg_2=None):
    """
    For each traded name, find the daily transaction total that consumed
    the greatest proportion of available daily bar volume.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.
    market_data : pd.Panel
        Panel with items axis of 'price' and 'volume' DataFrames.
        The major and minor axes should match those of the
        the passed positions DataFrame (same dates and symbols).
    last_n_days : integer
        Compute for only the last n days of the passed backtest data.
    """

    arg_3 = daily_txns_with_bar_data(arg_0, arg_1)
    arg_3.index.name = 'date'
    arg_3 = arg_3.reset_index()

    if arg_2 is not None:
        arg_6 = arg_3.date.max() - pd.Timedelta(days=arg_2)
        arg_3 = arg_3[arg_3.date > arg_6]

    arg_7 = arg_3.assign(
        max_pct_bar_consumed=(
            arg_3.amount/arg_3.volume)*100
    ).sort_values('max_pct_bar_consumed', ascending=False)
    arg_8 = arg_7.groupby('symbol').first()

    return arg_8[['date', 'max_pct_bar_consumed']]


def Func(arg_0):
    """
    Maps a single transaction row to a dictionary.

    Parameters
    ----------
    txn : pd.DataFrame
        A single transaction object to convert to a dictionary.

    Returns
    -------
    dict
        Mapped transaction.
    """

    if isinstance(arg_0['sid'], dict):
        arg_1 = arg_0['sid']['sid']
        arg_2 = arg_0['sid']['symbol']
    else:
        arg_1 = arg_0['sid']
        arg_2 = arg_0['sid']

    return {'sid': arg_1,
            'symbol': arg_2,
            'price': arg_0['price'],
            'order_id': arg_0['order_id'],
            'amount': arg_0['amount'],
            'commission': arg_0['commission'],
            'dt': arg_0['dt']}


def Func(arg_0):
    """
    Extract daily transaction data from set of transaction objects.

    Parameters
    ----------
    transactions : pd.DataFrame
        Time series containing one row per symbol (and potentially
        duplicate datetime indices) and columns for amount and
        price.

    Returns
    -------
    pd.DataFrame
        Daily transaction volume and number of shares.
         - See full explanation in tears.create_full_tear_sheet.
    """

    arg_1 = arg_0.copy()
    arg_1.index = arg_1.index.normalize()
    arg_3 = arg_1.amount.abs()
    arg_4 = arg_1.price
    arg_5 = arg_3 * arg_4
    arg_6 = arg_3.groupby(arg_3.index).sum()
    arg_7 = arg_5.groupby(arg_5.index).sum()
    arg_6.name = "txn_shares"
    arg_7.name = "txn_volume"
    return pd.concat([arg_7, arg_6], axis=1)


def Func(arg_0, arg_1, arg_2,
                                arg_3):
    """
    Apply a slippage penalty for every dollar traded.

    Parameters
    ----------
    returns : pd.Series
        Daily returns of the strategy, noncumulative.
         - See full explanation in create_full_tear_sheet.
    positions : pd.DataFrame
        Daily net position values.
         - See full explanation in create_full_tear_sheet.
    transactions : pd.DataFrame
        Prices and amounts of executed trades. One row per trade.
         - See full explanation in create_full_tear_sheet.
    slippage_bps: int/float
        Basis points of slippage to apply.

    Returns
    -------
    pd.Series
        Time series of daily returns, adjusted for slippage.
    """

    arg_4 = 0.0001 * arg_3
    arg_5 = arg_1.sum(axis=1)
    arg_6 = arg_5 * arg_0
    arg_7 = get_txn_vol(arg_2).txn_volume
    arg_8 = arg_7 * arg_4
    arg_9 = arg_6.add(-arg_8, fill_value=0)
    arg_10 = arg_0 * arg_9 / arg_6

    return arg_10


def Func(arg_0, arg_1=arg_2.Timedelta('8h')):
    """Merge transactions of the same direction separated by less than
    max_delta time duration.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed round_trips. One row per trade.
        - See full explanation in tears.create_full_tear_sheet

    max_delta : pandas.Timedelta (optional)
        Merge transactions in the same direction separated by less
        than max_delta time duration.

    Returns
    -------
    transactions : pd.DataFrame

    """
    def vwap(arg_4):
        if arg_4.amount.sum() == 0:
            warnings.warn('Zero transacted shares, setting vwap to nan.')
            return np.nan
        return (arg_4.amount * arg_4.price).sum() / \
            arg_4.amount.sum()

    arg_5 = []
    for arg_6, arg_7 in arg_0.groupby('symbol'):
        arg_7 = arg_7.sort_index()
        arg_7.index.name = 'dt'
        arg_7 = arg_7.reset_index()

        arg_7['order_sign'] = arg_7.amount > 0
        arg_7['block_dir'] = (arg_7.order_sign.shift(
            1) != arg_7.order_sign).astype(int).cumsum()
        arg_7['block_time'] = ((arg_7.dt.sub(arg_7.dt.shift(1))) >
                           arg_1).astype(int).cumsum()
        arg_10 = (arg_7.groupby(('block_dir',
                                   'block_time'))
                          .apply(vwap))
        arg_10.name = 'price'
        arg_11 = arg_7.groupby(('block_dir', 'block_time')).agg({
            'amount': 'sum',
            'symbol': 'first',
            'dt': 'first'})

        arg_12 = arg_11.join(arg_10)

        arg_5.append(arg_12)

    arg_5 = arg_2.concat(arg_5)
    arg_5 = arg_5.set_index('dt')
    return arg_5


def Func(arg_0,
                        arg_1=None):
    """Group transactions into "round trips". First, transactions are
    grouped by day and directionality. Then, long and short
    transactions are matched to create round-trip round_trips for which
    PnL, duration and returns are computed. Crossings where a position
    changes from long to short and vice-versa are handled correctly.

    Under the hood, we reconstruct the individual shares in a
    portfolio over time and match round_trips in a FIFO-order.

    For example, the following transactions would constitute one round trip:
    index                  amount   price    symbol
    2004-01-09 12:18:01    10       50      'AAPL'
    2004-01-09 15:12:53    10       100      'AAPL'
    2004-01-13 14:41:23    -10      100      'AAPL'
    2004-01-13 15:23:34    -10      200       'AAPL'

    First, the first two and last two round_trips will be merged into a two
    single transactions (computing the price via vwap). Then, during
    the portfolio reconstruction, the two resulting transactions will
    be merged and result in 1 round-trip trade with a PnL of
    (150 * 20) - (75 * 20) = 1500.

    Note, that round trips do not have to close out positions
    completely. For example, we could have removed the last
    transaction in the example above and still generated a round-trip
    over 10 shares with 10 shares left in the portfolio to be matched
    with a later transaction.

    Parameters
    ----------
    transactions : pd.DataFrame
        Prices and amounts of executed round_trips. One row per trade.
        - See full explanation in tears.create_full_tear_sheet

    portfolio_value : pd.Series (optional)
        Portfolio value (all net assets including cash) over time.
        Note that portfolio_value needs to beginning of day, so either
        use .shift() or positions.sum(axis='columns') / (1+returns).

    Returns
    -------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip.  The returns column
        contains returns in respect to the portfolio value while
        rt_returns are the returns in regards to the invested capital
        into that partiulcar round-trip.
    """

    arg_0 = _groupby_consecutive(arg_0)
    arg_2 = []

    for arg_3, arg_4 in arg_0.groupby('symbol'):
        arg_4 = arg_4.sort_index()
        arg_5 = deque()
        arg_6 = deque()
        arg_4['signed_price'] = arg_4.price * \
            np.sign(arg_4.amount)
        arg_4['abs_amount'] = arg_4.amount.abs().astype(int)
        for arg_7, arg_8 in arg_4.iterrows():
            if arg_8.price < 0:
                warnings.warn('Negative price detected, ignoring for'
                              'round-trip.')
                continue

            arg_9 = [arg_8.signed_price] * arg_8.abs_amount
            if (len(arg_5) == 0) or \
               (copysign(1, arg_5[-1]) == copysign(1, arg_8.amount)):
                arg_5.extend(arg_9)
                arg_6.extend([arg_7] * len(arg_9))
            else:
                # Close round-trip
                arg_10 = 0
                arg_11 = 0
                arg_12 = []

                for arg_13 in arg_9:
                    if len(arg_5) != 0 and \
                       (copysign(1, arg_5[-1]) != copysign(1, arg_13)):
                        # Retrieve first dt, stock-price pair from
                        # stack
                        arg_14 = arg_5.popleft()
                        arg_15 = arg_6.popleft()

                        arg_10 += -(arg_13 + arg_14)
                        arg_12.append(arg_15)
                        arg_11 += abs(arg_14)

                    else:
                        # Push additional stock-prices onto stack
                        arg_5.append(arg_13)
                        arg_6.append(arg_7)

                arg_2.append({'pnl': arg_10,
                                   'open_dt': arg_12[0],
                                   'close_dt': arg_7,
                                   'long': arg_13 < 0,
                                   'rt_returns': arg_10 / arg_11,
                                   'symbol': arg_3,
                                   })

    arg_2 = pd.DataFrame(arg_2)

    arg_2['duration'] = arg_2['close_dt'].sub(arg_2['open_dt'])

    if arg_1 is not None:
        # Need to normalize so that we can join
        arg_16 = pd.DataFrame(arg_1,
                          columns=['portfolio_value'])\
            .assign(date=arg_1.index)

        arg_2['date'] = arg_2.close_dt.apply(lambda x:
                                                       x.replace(hour=0,
                                                                 minute=0,
                                                                 second=0))

        arg_17 = arg_2.join(arg_16, on='date', lsuffix='_')

        arg_2['returns'] = arg_17.pnl / arg_17.portfolio_value
        arg_2 = arg_2.drop('date', axis='columns')

    return arg_2


def Func(arg_0):
    """Generate various round-trip statistics.

    Parameters
    ----------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip trade.
        - See full explanation in round_trips.extract_round_trips

    Returns
    -------
    stats : dict
       A dictionary where each value is a pandas DataFrame containing
       various round-trip statistics.

    See also
    --------
    round_trips.print_round_trip_stats
    """

    arg_1 = {}
    arg_1['pnl'] = agg_all_long_short(arg_0, 'pnl', PNL_STATS)
    arg_1['summary'] = agg_all_long_short(arg_0, 'pnl',
                                          SUMMARY_STATS)
    arg_1['duration'] = agg_all_long_short(arg_0, 'duration',
                                           DURATION_STATS)
    arg_1['returns'] = agg_all_long_short(arg_0, 'returns',
                                          RETURN_STATS)

    arg_1['symbols'] = \
        arg_0.groupby('symbol')['returns'].agg(RETURN_STATS).T

    return arg_1


def Func(arg_0, arg_1=False):
    """Print various round-trip statistics. Tries to pretty-print tables
    with HTML output if run inside IPython NB.

    Parameters
    ----------
    round_trips : pd.DataFrame
        DataFrame with one row per round trip trade.
        - See full explanation in round_trips.extract_round_trips

    See also
    --------
    round_trips.gen_round_trip_stats
    """

    arg_2 = gen_round_trip_stats(arg_0)

    print_table(arg_2['summary'], float_format='{:.2f}'.format,
                name='Summary stats')
    print_table(arg_2['pnl'], float_format='${:.2f}'.format, name='PnL stats')
    print_table(arg_2['duration'], float_format='{:.2f}'.format,
                name='Duration stats')
    print_table(arg_2['returns'] * 100, float_format='{:.2f}%'.format,
                name='Return stats')

    if not arg_1:
        arg_2['symbols'].columns = arg_2['symbols'].columns.map(format_asset)
        print_table(arg_2['symbols'] * 100,
                    float_format='{:.2f}%'.format, name='Symbol stats')