plots using inquirer prompts

    Arguments:
        goodFormat {dict} -- module : [results for module]
433180
def howPlotAsk(goodFormat):
    '''
    '''
    plotAnswer = askPlot()
    if "Save" in plotAnswer['plotQ']:
        exportPlotsPath = pathlib.Path(askSave())
        if "Show" in plotAnswer['plotQ']:
            plotter(exportPlotsPath, True, goodFormat)
        else:
            plotter(exportPlotsPath, False, goodFormat)
    elif "Show" in plotAnswer['plotQ']:
        plotter(None, True, goodFormat)
263267
def pretty_params(data, indent=2):
    
    data_to_print = _series_data_filter(data)
    print(json.dumps(data_to_print, indent=indent))
322201
def format_parameters(params):
    ''''''

    if not params:
        return {}

    # expect multiple invocations of --parameters but fall back
    # to ; delimited if only one --parameters is specified
    if len(params) == 1:
        if params[0].find(';') != -1:  # found
            params = params[0].split(';')
        else:
            params = params[0].split(',')

    parameters = {}
    for p in params:
        try:
            (n, v) = p.split('=', 1)
        except ValueError:
            msg = '%s(%s). %s.' % ('Malformed parameter', p,
                                   'Use the key=value format')
            raise exc.CommandError(msg)

        if n not in parameters:
            parameters[n] = v
        else:
            if not isinstance(parameters[n], list):
                parameters[n] = [parameters[n]]
            parameters[n].append(v)

    return parameters
1090109
def plot(self, figure_list):
        '''
        

        '''

        #TODO: be smarter about how we plot ScriptIterator
        if self._current_subscript_stage is not None:
            if self._current_subscript_stage['current_subscript'] is not None:
                self._current_subscript_stage['current_subscript'].plot(figure_list)

        if (self.is_running is False) and not (self.data == {} or self.data is None):

            script_names = list(self.settings['script_order'].keys())
            script_indices = [self.settings['script_order'][name] for name in script_names]
            _, sorted_script_names = list(zip(*sorted(zip(script_indices, script_names))))

            last_script = self.scripts[sorted_script_names[-1]]

            last_script.force_update()  # since we use the last script plot function we force it to refresh

            axes_list = last_script.get_axes_layout(figure_list)

            # catch error is _plot function doens't take optional data argument
            try:
                last_script._plot(axes_list, self.data)
            except TypeError as err:
                print((warnings.warn('can\'t plot average script data because script.plot function doens\'t take data as optional argument. Plotting last data set instead')))
                print((err.message))
                last_script.plot(figure_list)
1312809
def interact_gridsearch_result_images(show_result_func, cfgdict_list,
                                      cfglbl_list, cfgresult_list,
                                      score_list=None, fnum=None, figtitle='',
                                      unpack=False, max_plots=25, verbose=True,
                                      precision=3, scorelbl='score',
                                      onclick_func=None):
    
    assert callable(show_result_func), 'NEED FUNCTION GOT: %r' % (show_result_func,)

    import utool as ut
    import plottool as pt
    from plottool import plot_helpers as ph
    from plottool import interact_helpers as ih
    if verbose:
        print('Plotting gridsearch results figtitle=%r' % (figtitle,))
    if score_list is None:
        score_list = [None] * len(cfgdict_list)
    else:
        # sort by score if available
        sortx_list = ut.list_argsort(score_list, reverse=True)
        score_list = ut.take(score_list, sortx_list)
        cfgdict_list = ut.take(cfgdict_list, sortx_list)
        cfglbl_list = ut.take(cfglbl_list, sortx_list)
        cfgresult_list = ut.take(cfgresult_list, sortx_list)
    # Dont show too many results only the top few
    score_list = ut.listclip(score_list, max_plots)

    # Show the config results
    fig = pt.figure(fnum=fnum)
    # Get plots for each of the resutls
    nRows, nCols = pt.get_square_row_cols(len(score_list), fix=True)
    next_pnum = pt.make_pnum_nextgen(nRows, nCols)
    for cfgdict, cfglbl, cfgresult, score in zip(cfgdict_list, cfglbl_list,
                                                  cfgresult_list,
                                                  score_list):
        if score is not None:
            cfglbl += '\n' + scorelbl + '=' + ut.repr2(score, precision=precision)
        pnum = next_pnum()
        try:
            if unpack:
                show_result_func(*cfgresult, fnum=fnum, pnum=pnum)
            else:
                show_result_func(cfgresult, fnum=fnum, pnum=pnum)
        except Exception as ex:
            if isinstance(cfgresult, tuple):
                #print(ut.repr4(cfgresult))
                print(ut.depth_profile(cfgresult))
                print(ut.list_type_profile(cfgresult))
            ut.printex(ex, 'error showing', keys=['cfgresult', 'fnum', 'pnum'])
            raise
        #pt.imshow(255 * cfgresult, fnum=fnum, pnum=next_pnum(), title=cfglbl)
        ax = pt.gca()
        pt.set_title(cfglbl, ax=ax)  # , size)
        ph.set_plotdat(ax, 'cfgdict', cfgdict)
        ph.set_plotdat(ax, 'cfglbl', cfglbl)
        ph.set_plotdat(ax, 'cfgresult', cfgresult)
    # Define clicked callback
    def on_clicked(event):
        print('\n[pt] clicked gridsearch axes')
        if event is None or event.xdata is None or event.inaxes is None:
            print('out of axes')
            pass
        else:
            ax = event.inaxes
            plotdat_dict = ph.get_plotdat_dict(ax)
            print(ut.repr4(plotdat_dict))
            cfglbl = ph.get_plotdat(ax, 'cfglbl', None)
            cfgdict = ph.get_plotdat(ax, 'cfgdict', {})
            cfgresult = ph.get_plotdat(ax, 'cfgresult', {})
            infostr_list = [
                ('cfglbl = %s' % (cfglbl,)),
                '',
                ('cfgdict = ' + ut.repr4(cfgdict, sorted_=True)),
            ]
            # Call a user defined function if given
            if onclick_func is not None:
                if unpack:
                    onclick_func(*cfgresult)
                else:
                    onclick_func(cfgresult)
            infostr = ut.msgblock('CLICKED', '\n'.join(infostr_list))
            print(infostr)
    # Connect callbacks
    ih.connect_callback(fig, 'button_press_event', on_clicked)
    pt.set_figtitle(figtitle)
1097551
def _get_module(self, parser, module):
        
        dt = []
        lines = parser.clean_data(module)
        header = lines[0]
        for data in lines[1:]:
            if data[0].startswith("#"):  # some modules have two headers
                header = data
                continue
            if data[0].find("-") > -1:  # expand positions 1-3 to 1, 2, 3
                f, s = map(int, data[0].split("-"))
                for pos in range(f, s):
                    dt.append([str(pos)] + data[1:])
            else:
                dt.append(data)
        dt = pd.DataFrame(dt)
        dt.columns = [h.replace(" ", "_") for h in header]
        dt['sample'] = self.sample
        return dt
273752
function promptUser() {

    return inquirer.prompt([
        {
            type: "list",
            name: "purpose",
            message: "How would you like to use ESLint?",
            default: "problems",
            choices: [
                { name: "To check syntax only", value: "syntax" },
                { name: "To check syntax and find problems", value: "problems" },
                { name: "To check syntax, find problems, and enforce code style", value: "style" }
            ]
        },
        {
            type: "list",
            name: "moduleType",
            message: "What type of modules does your project use?",
            default: "esm",
            choices: [
                { name: "JavaScript modules (import/export)", value: "esm" },
                { name: "CommonJS (require/exports)", value: "commonjs" },
                { name: "None of these", value: "none" }
            ]
        },
        {
            type: "list",
            name: "framework",
            message: "Which framework does your project use?",
            default: "react",
            choices: [
                { name: "React", value: "react" },
                { name: "Vue.js", value: "vue" },
                { name: "None of these", value: "none" }
            ]
        },
        {
            type: "checkbox",
            name: "env",
            message: "Where does your code run?",
            default: ["browser"],
            choices: [
                { name: "Browser", value: "browser" },
                { name: "Node", value: "node" }
            ]
        },
        {
            type: "list",
            name: "source",
            message: "How would you like to define a style for your project?",
            default: "guide",
            choices: [
                { name: "Use a popular style guide", value: "guide" },
                { name: "Answer questions about your style", value: "prompt" },
                { name: "Inspect your JavaScript file(s)", value: "auto" }
            ],
            when(answers) {
                return answers.purpose === "style";
            }
        },
        {
            type: "list",
            name: "styleguide",
            message: "Which style guide do you want to follow?",
            choices: [
                { name: "Airbnb (https://github.com/airbnb/javascript)", value: "airbnb" },
                { name: "Standard (https://github.com/standard/standard)", value: "standard" },
                { name: "Google (https://github.com/google/eslint-config-google)", value: "google" }
            ],
            when(answers) {
                answers.packageJsonExists = npmUtils.checkPackageJson();
                return answers.source === "guide" && answers.packageJsonExists;
            }
        },
        {
            type: "input",
            name: "patterns",
            message: "Which file(s), path(s), or glob(s) should be examined?",
            when(answers) {
                return (answers.source === "auto");
            },
            validate(input) {
                if (input.trim().length === 0 && input.trim() !== ",") {
                    return "You must tell us what code to examine. Try again.";
                }
                return true;
            }
        },
        {
            type: "list",
            name: "format",
            message: "What format do you want your config file to be in?",
            default: "JavaScript",
            choices: ["JavaScript", "YAML", "JSON"]
        },
        {
            type: "confirm",
            name: "installESLint",
            message(answers) {
                const verb = semver.ltr(answers.localESLintVersion, answers.requiredESLintVersionRange)
                    ? "upgrade"
                    : "downgrade";

                return `The style guide "${answers.styleguide}" requires eslint@${answers.requiredESLintVersionRange}. You are currently using eslint@${answers.localESLintVersion}.\n  Do you want to ${verb}?`;
            },
            default: true,
            when(answers) {
                return answers.source === "guide" && answers.packageJsonExists && hasESLintVersionConflict(answers);
            }
        }
    ]).then(earlyAnswers => {

        // early exit if no style guide is necessary
        if (earlyAnswers.purpose !== "style") {
            const config = processAnswers(earlyAnswers);
            const modules = getModulesList(config);

            return askInstallModules(modules, earlyAnswers.packageJsonExists)
                .then(() => writeFile(config, earlyAnswers.format));
        }

        // early exit if you are using a style guide
        if (earlyAnswers.source === "guide") {
            if (!earlyAnswers.packageJsonExists) {
                log.info("A package.json is necessary to install plugins such as style guides. Run `npm init` to create a package.json file and try again.");
                return void 0;
            }
            if (earlyAnswers.installESLint === false && !semver.satisfies(earlyAnswers.localESLintVersion, earlyAnswers.requiredESLintVersionRange)) {
                log.info(`Note: it might not work since ESLint's version is mismatched with the ${earlyAnswers.styleguide} config.`);
            }
            if (earlyAnswers.styleguide === "airbnb" && earlyAnswers.framework !== "react") {
                earlyAnswers.styleguide = "airbnb-base";
            }

            const config = ConfigOps.merge(processAnswers(earlyAnswers), getConfigForStyleGuide(earlyAnswers.styleguide));
            const modules = getModulesList(config);

            return askInstallModules(modules, earlyAnswers.packageJsonExists)
                .then(() => writeFile(config, earlyAnswers.format));

        }

        if (earlyAnswers.source === "auto") {
            const combinedAnswers = Object.assign({}, earlyAnswers);
            const config = processAnswers(combinedAnswers);
            const modules = getModulesList(config);

            return askInstallModules(modules).then(() => writeFile(config, earlyAnswers.format));
        }

        // continue with the style questions otherwise...
        return inquirer.prompt([
            {
                type: "list",
                name: "indent",
                message: "What style of indentation do you use?",
                default: "tab",
                choices: [{ name: "Tabs", value: "tab" }, { name: "Spaces", value: 4 }]
            },
            {
                type: "list",
                name: "quotes",
                message: "What quotes do you use for strings?",
                default: "double",
                choices: [{ name: "Double", value: "double" }, { name: "Single", value: "single" }]
            },
            {
                type: "list",
                name: "linebreak",
                message: "What line endings do you use?",
                default: "unix",
                choices: [{ name: "Unix", value: "unix" }, { name: "Windows", value: "windows" }]
            },
            {
                type: "confirm",
                name: "semi",
                message: "Do you require semicolons?",
                default: true
            },
            {
                type: "list",
                name: "format",
                message: "What format do you want your config file to be in?",
                default: "JavaScript",
                choices: ["JavaScript", "YAML", "JSON"]
            }
        ]).then(answers => {
            const totalAnswers = Object.assign({}, earlyAnswers, answers);

            const config = processAnswers(totalAnswers);
            const modules = getModulesList(config);

            return askInstallModules(modules).then(() => writeFile(config, answers.format));
        });
    });
}
523383
def show(args):
    
    domain = check_infile(args.infile)
    action = True
    try:
        print(json.dumps(set_json(domain, action, filename=args.infile),
                         sort_keys=True, indent=2))
    except UnicodeDecodeError as e:
        sys.stderr.write("ERROR: \"%s\" is invalid format file.\n"
                         % args.infile)
        exit(1)
181966
def plotter_cls(self):
        """"""
        ret = self._plotter_cls
        if ret is None:
            self._logger.debug('importing %s', self.module)
            mod = import_module(self.module)
            plotter = self.plotter_name
            if plotter not in vars(mod):
                raise ImportError("Module %r does not have a %r plotter!" % (
                    mod, plotter))
            ret = self._plotter_cls = getattr(mod, plotter)
            _versions.update(get_versions(key=lambda s: s == self._plugin))
        return ret
1259471
def return_json_response(self, context, **request_kwargs):
        '''
        
        '''
        outline_dict = model_to_dict(self.object)
        logger.debug(str(outline_dict))
        logger.debug("Attepting to switch tags from queryset to name...")
        logger.debug(str(self.object.tags.names()))
        outline_dict.pop('tags')
        outline_dict['tags'] = list(self.object.tags.names())
        logger.debug(str(outline_dict))
        if self.object.series:
            outline_dict['series'] = model_to_dict(self.object.series)
            outline_dict['series']['tags'] = list(self.object.series.tags.names())
            logger.debug('Adding series... {}'.format(outline_dict['series']))
        if self.object.characterinstance_set.count():
            outline_dict['characters'] = []
            for cint in self.object.characterinstance_set.all():
                character_dict = model_to_dict(cint.character)
                character_dict['outline_key'] = cint.pk
                character_dict['tags'] = list(cint.character.tags.names())
                character_dict['role_properties'] = {
                    'main_character': cint.main_character,
                    'pov_character': cint.pov_character,
                    'protagonist': cint.protagonist,
                    'antagonist': cint.antagonist,
                    'villain': cint.villain,
                    'obstacle': cint.obstacle,
                }
                outline_dict['characters'].append(character_dict)
        if self.object.locationinstance_set.count():
            outline_dict['locations'] = []
            for lint in self.object.locationinstance_set.all():
                location_dict = model_to_dict(lint.location)
                location_dict['tags'] = list(lint.location.tags.names())
                location_dict['outline_key'] = lint.pk
                outline_dict['locations'].append(location_dict)
        if self.object.arc_set.count():
            outline_dict['arcs'] = []
            for arc in self.object.arc_set.all():
                arc_dict = model_to_dict(arc)
                arc_dict['nodes'] = ArcElementNode.dump_bulk(parent=arc.arc_root_node)
                outline_dict['arcs'].append(arc_dict)
        outline_dict['story_tree'] = StoryElementNode.dump_bulk(parent=self.object.story_tree_root)
        logger.debug("Sending response via JSON: {}".format(outline_dict))
        response = JsonResponse(outline_dict)
        response['Content-Disposition'] = 'attachment; filename="{}.json"'.format(slugify(self.object.title))
        return response
590092
def getFormatArgs(startFormat, startArgs, endFormat, endArgs, args, kwargs):
    
    debugArgs = startArgs[:]
    for a in args:
        debugArgs.append(ellipsize(a))

    for items in kwargs.items():
        debugArgs.extend(items)
    debugArgs.extend(endArgs)
    debugFormat = startFormat \
              + ', '.join(('%s', ) * len(args)) \
              + (kwargs and ', ' or '') \
              + ', '.join(('%s=%r', ) * len(kwargs)) \
              + endFormat
    return debugFormat, debugArgs
1031947
def _getPlotData(self):
        
        resultsByClass = self.resultsByClass

        try:
            if resultsByClass['Uncertain'] == 0:  # remove uncertain tag if present and = 0
                resultsByClass.pop('Uncertain', None)
        except KeyError:
            pass

        plotData = list(zip(*resultsByClass.items()))  # (labels, ydata)

        return plotData
87200
def cli_common(doc, **kwargs):
    
    arguments = docopt(doc, version='hpcbench ' + __version__, **kwargs)
    setup_logger(arguments['-v'], arguments['--log'])
    load_components()
    try:
        import matplotlib
    except ImportError:
        pass
    else:
        matplotlib.use('PS')
    return arguments
190503
function promptUser(callback) {
  inquirer.prompt([
    {
      type: 'list',
      name: 'format',
      message: 'What format do you want your config file to be in?',
      default: 'JSON',
      choices: ['JSON', 'YAML']
    }
  ], function(answers) {
    var config = processAnswers(answers);
    writeFile(config, answers.format === 'JSON', callback);
  });
}
1212437
def _format_args():
        """"""
        if request and request.args.get('prettyprint'):
            return dict(
                indent=2,
                separators=(', ', ': '),
            )
        else:
            return dict(
                indent=None,
                separators=(',', ':'),
            )
50991
function p() {

    // global promise object to wait for all plot options to be completed before writing
    this.promises = [];
    // global array for options to plot
    this.optArray = [];

    // simple plot
    this.plot = function(seriesArr, title, yLabel, xLabel) {
        // console.log("plotting")
        var defer = q.defer();
        this.promises.push(defer.promise);

        title = title || false;
        yLabel = yLabel || false;
        xLabel = xLabel || false;

        var opt = _.cloneDeep(tmpOpt),
        set = _.set.bind(null, opt);

        set('series', seriesArr);
        set('title.text', title);
        set('yAxis.title.text', yLabel);
        set('xAxis.title.text', xLabel);

        // setTimeout(function() {}, 2000);
        this.optArray.push(opt);
        defer.resolve();
        return opt;
    };

    // advance plot = specify your own highcharts options
    this.advPlot = function(opt) {
        var defer = q.defer();
        this.promises.push(defer.promise);
        this.optArray.push(opt);
        defer.resolve();

        return opt;
    };

    // write highchart options to json for rendering
    // if autosave is true, charts will save on view
    this.write = function(autosave) {
        var defer = q.defer();
        for (var i = 0; i < this.optArray.length; i++) {
            _.set(this.optArray[i], 'chart.renderTo', 'hchart' + i);
            _.set(this.optArray[i], 'autosave', autosave);
        }
        fs.writeFile(__dirname + '/src/options.json', JSON.stringify(this.optArray), defer.resolve);

        return defer.promise;
    };

    // serialize optArray and write to
    this.serialize = function(autosave) {
        var defer = q.defer();

        q.all(this.promises)
        .then(this.write(autosave))
        .then(defer.resolve());

        return defer.promise;
    };

    // finally, render after all plots specified
    // if autosave is true, charts will save on view
    this.render = function(autosave) {
        var gulpplot = require(__dirname + '/../gulpfile.js').gulpplot;
        
        this.serialize(autosave)
        .then(gulpplot)
    };

    this.dynrender = function() {
        this.serialize()
        // .then(dyngulpplot)
    };
}
143570
def do_plot(self, arg):
        
        usable, filename, append = self._redirect_split(arg)
        self.curargs["xscale"] = None
        self.curargs["yscale"] = None
        self._plot_generic(filename)