Simple entry-point that takes the package name and json output
768196
def main(*args, **kwargs):
    

    parser = argparse.ArgumentParser()
    parser.add_argument('package_name', type=str)
    parser.add_argument('output_filename', type=str)

    parsed_args = parser.parse_args()

    # Find all package requirements
    get_all_requires(parsed_args.package_name)

    # Write tmp results to a file to be read into main app context
    json_file = open(parsed_args.output_filename, 'w')
    json_file.write(json.dumps(all_requires))
396871
def main():
    
    import jsonschema
    parser = argparse.ArgumentParser(version=__version__)
    parser.add_argument(
        '--verbose', action='store_true', default=False,
        help='Turn on verbose output.')
    parser.add_argument(
        '--header', action='store_true', default=False,
        help='Turn on header.')
    parser.add_argument(
        'playbooks', metavar='PLAYBOOKS', type=str, nargs='+',
        help='The playbook(s) to lint.')

    args = parser.parse_args()

    validation_results = {}
    all_valid = True
    # Load the playbook schema
    with open(resource_filename(
            'relent', 'schemas/playbook_schema.json'), 'r') as schema_fp:
        schema = json.load(schema_fp)
        # Do checks against playbooks
        for playbook in args.playbooks:
            try:
                with open(playbook, 'r') as pb:
                    # Schema check
                    jsonschema.validate(json.load(pb), schema)
            except jsonschema.ValidationError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, e.message, list(e.schema_path), str(e))
            except ValueError, e:
                all_valid = False
                validation_results[playbook] = (
                    False, 'JSON is invalid.', str(e), str(e))

    # If all_valid is True then return back happy results
    if all_valid is True:
        if args.verbose or args.header:
            parser._print_message('Found 0 issues.\n')
        raise SystemExit(0)
    else:
        if args.verbose or args.header:
            parser._print_message('Found %s issues.\n\n' % len(
                validation_results))
        for problem_playbook in validation_results.keys():
            parser._print_message('%s: E: %s %s\n' % (
                problem_playbook,
                validation_results[problem_playbook][1],
                validation_results[problem_playbook][2]))
            if args.verbose:
                parser._print_message(
                    validation_results[problem_playbook][3] + '\n--\n')
        raise SystemExit(1)
89478
def _get_main_and_json(directory):
    
    directory = os.path.normpath(os.path.abspath(directory))
    checker_main = os.path.normpath(os.path.join(directory, os.path.pardir, "checker-workflow-wrapping-tool.cwl"))
    if checker_main and os.path.exists(checker_main):
        main_cwl = [checker_main]
    else:
        main_cwl = glob.glob(os.path.join(directory, "main-*.cwl"))
        main_cwl = [x for x in main_cwl if not x.find("-pack") >= 0]
        assert len(main_cwl) == 1, "Did not find main CWL in %s" % directory
    main_json = glob.glob(os.path.join(directory, "main-*-samples.json"))
    assert len(main_json) == 1, "Did not find main json in %s" % directory
    project_name = os.path.basename(directory).split("-workflow")[0]
    return main_cwl[0], main_json[0], project_name
1256443
function pkg(val) {
    var filename = path_1.resolve(exports.cwd, 'package.json');
    if (!val)
        return _pkg || (_pkg = fs_extra_1.readJSONSync(filename));
    fs_extra_1.writeJSONSync(filename, val, { spaces: 2 });
}
486453
def main(raw_args=None):
    """"""
    parser = argparse.ArgumentParser(
        description="poor man's integration testing")
    parser.add_argument(
        'cmds', metavar='cmd', default=['test'], nargs='*',
        help='Run command(s) defined in the configuration file. Each command '
             'is run on each package before proceeding with the next command. '
             '(default: "test")')
    parser.add_argument(
        '-c', '--config', dest='file', type=argparse.FileType('r'),
        default='toll.ini',
        help='ini-style file to read the configuration from')
    parser.add_argument(
        '--start-at', dest='start_at', type=str, default='',
        help='Skip over the packages in the config file listed before this'
             ' one. (It does a substring match to find the first package.)')

    args = parser.parse_args(raw_args)
    config_file = config.parsed_file(args.file)
    commands = config.commands(config_file, args.cmds)
    packages = config.packages(config_file)
    runner = Runner(commands, packages, start_at=args.start_at)
    return runner()
991513
def main():
    """"""
    message_names = set()
    packages = []
    messages = []
    extensions = []
    constants = []

    # Extract everything needed to generate output file
    for info in extract_message_info():
        message_names.add(info.title)
        packages.append(
            'from {0} import {1}'.format(
                BASE_PACKAGE, info.module))
        messages.append(
            'from {0}.{1} import {2}'.format(
                BASE_PACKAGE, info.module, info.title))
        extensions.append(
            'ProtocolMessage.{0}: {1}.{2},'.format(
                info.const, info.module, info.accessor))
        constants.append(
            '{0} = ProtocolMessage.{0}'.format(
                info.const))


    # Look for remaining messages
    for module_name, message_name in extract_unreferenced_messages():
        if message_name not in message_names:
            message_names.add(message_name)
            messages.append('from {0}.{1} import {2}'.format(
                    BASE_PACKAGE, module_name, message_name))

    # Print file output with values inserted
    print(OUTPUT_TEMPLATE.format(
        packages='\n'.join(sorted(packages)),
        messages='\n'.join(sorted(messages)),
        extensions='\n    '.join(sorted(extensions)),
        constants='\n'.join(sorted(constants))))

    return 0
133689
function() {
  var originalPackageJson;
  var cleanPackageJson = function() {
    return gulp.src([__dirname + '/package.json'])
    .pipe($.jsonEditor(function(){
      return originalPackageJson;
    }, {
      'end_with_newline': true
    }))
    .pipe(gulp.dest(__dirname + '/'));
  };

  /* Lazy dependencies installation */
  gulp.task('dirty-install-dep', function() {
    return gulp.src([__dirname + '/package.json'])
    .pipe($.jsonEditor(function(json) {
      var
        tplName = addons.templates[
          (config.modules && config.modules.templates) || 'handlebars'
        ].name,
        styleName = addons.styles[
          (config.modules && config.modules.styles) || 'less'
        ].name;
      originalPackageJson = JSON.parse(JSON.stringify(json));
      json.dependencies[tplName] = lazyDependencies[tplName];
      json.dependencies[styleName] = lazyDependencies[styleName];
      return json;
    }))
    .on('error', handleError)
    .pipe(gulp.dest(__dirname + '/'))
    .pipe($.install())
    .on('error', handleError);
  });
  gulp.task('install-dep', ['dirty-install-dep'], cleanPackageJson);

  /* Lazy dev dependencies installation */
  gulp.task('dirty-install-dev-dep', ['dirty-install-dep'], function() {
    return gulp.src([__dirname + '/package.json'])
    .pipe($.jsonEditor(function(json) {
      addons.dev.forEach(function(moduleName) {
        json.dependencies[moduleName] = lazyDependencies[moduleName];
      });
      return json;
    }))
    .on('error', handleError)
    .pipe(gulp.dest(__dirname + '/'))
    .pipe($.install())
    .on('error', handleError);
  });
  gulp.task('install-dev-dep', ['dirty-install-dev-dep'], cleanPackageJson);
}
1026307
def main():
    """"""
    description = ('PATH can be either the path to a scratch file, or a '
                   'directory containing scratch files. Multiple PATH '
                   'arguments can be provided.')
    parser = OptionParser(usage='%prog -p PLUGIN_NAME [options] PATH...',
                          description=description,
                          version='%prog {}'.format(__version__))
    parser.add_option('-d', '--plugin-dir', metavar='DIR',
                      help=('Specify the path to a directory containing '
                            'plugins. Plugins in this directory take '
                            'precedence over similarly named plugins '
                            'included with Hairball.'))
    parser.add_option('-p', '--plugin', action='append',
                      help=('Use the named plugin to perform analysis. '
                            'This option can be provided multiple times.'))
    parser.add_option('-k', '--kurt-plugin', action='append',
                      help=('Provide either a python import path (e.g, '
                            'kelp.octopi) to a package/module, or the path'
                            ' to a python file, which will be loaded as a '
                            'Kurt plugin. This option can be provided '
                            'multiple times.'))
    parser.add_option('-q', '--quiet', action='store_true',
                      help=('Prevent output from Hairball. Plugins may still '
                            'produce output.'))
    parser.add_option('-C', '--no-cache', action='store_true',
                      help='Do not use Hairball\'s cache.', default=False)
    options, args = parser.parse_args(sys.argv[1:])

    if not options.plugin:
        parser.error('At least one plugin must be specified via -p.')
    if not args:
        parser.error('At least one PATH must be provided.')

    if options.plugin_dir:
        if os.path.isdir(options.plugin_dir):
            sys.path.append(options.plugin_dir)
        else:
            parser.error('{} is not a directory'.format(options.plugin_dir))

    hairball = Hairball(options, args, cache=not options.no_cache)
    hairball.initialize_plugins()
    hairball.process()
    hairball.finalize()
1287588
def main():
    """"""
    import colorama
    import argparse
    import logging
    import sys
    import os

    parser = argparse.ArgumentParser(prog="gulpless",
                                     description="Simple build system.")
    parser.add_argument("-v", "--version",
                        action="version",
                        version="%(prog)s 0.7.6")
    parser.add_argument("-d", "--directory",
                        action="store",
                        default=os.getcwd(),
                        help="Look for `build.py` in this folder (defaults to "
                             "the current directory)")
    parser.add_argument("mode",
                        action="store",
                        choices=["build", "interactive"],
                        default="interactive",
                        metavar="mode",
                        nargs="?",
                        help="If `interactive` (the default), will wait for "
                             "filesystem events and attempt to keep the input "
                             "and output folders in sync. If `build`, it will "
                             "attempt to build all updated files, then exit.")

    args = parser.parse_args()
    os.chdir(args.directory)
    sys.path.append(os.getcwd())

    if os.environ.get("TERM") == "cygwin":
        # colorama doesn't play well with git bash
        del os.environ["TERM"]
        colorama.init()
        os.environ["TERM"] = "cygwin"
    else:
        colorama.init()

    try:
        old, sys.dont_write_bytecode = sys.dont_write_bytecode, True
        import build
    except ImportError:
        sys.exit("No `build.py` found in current folder.")
    finally:
        sys.dont_write_bytecode = old

    try:
        logging.basicConfig(level=build.LOGGING,
                            format="%(message)s")
    except AttributeError:
        logging.basicConfig(level=logging.INFO,
                            format="%(message)s")

    reactor = Reactor(build.SRC, build.DEST)
    for handler in build.HANDLERS:
        reactor.add_handler(handler)
    reactor.run(args.mode == "build")
226950
def main():
    
    about_str = "{} version: {}".format(PROJECT_NAME, VERSION)
    parser = argparse.ArgumentParser(description = about_str)

    parser.add_argument('fileNames', metavar='FILE', nargs='*', help='Input files')

    parser.add_argument('-i', '--inspector', dest='inspector',
        help="""The identifier or fullName of the inspector that will be opened at start up.
                E.g. 'Qt/Table'""")

    parser.add_argument('--list-inspectors', dest='list_inspectors', action = 'store_true',
        help="""Prints a list of available inspectors for the -i option""")


    parser.add_argument('-s', '--select', dest='selectPath',
        help="""Full path name of a repository tree item that will be selected at start-up.
                E.g. 'file/var/fieldname'""")

    parser.add_argument('-p', '--profile', dest='profile', default=DEFAULT_PROFILE,
        help="Can be used to have different persistent settings for different use cases.")

    parser.add_argument('--reset', '--reset-profile', dest='reset_profile', action = 'store_true',
        help="If set, persistent settings will be reset for the current profile.")

    parser.add_argument('--reset-all-profiles', dest='reset_all_profiles', action = 'store_true',
        help="If set, persistent settings will be reset for the all profiles.")

    parser.add_argument('--reset-registry', dest='reset_registry', action = 'store_true',
        help="If set, the registry will be reset to contain only the default plugins.")

    parser.add_argument('--version', action = 'store_true',
        help="Prints the program version.")

    parser.add_argument('-l', '--log-level', dest='log_level', default='warning',
        help="Log level. Only log messages with a level higher or equal than this will be printed. "
             "Default: 'warning'",
        choices=('debug', 'info', 'warning', 'error', 'critical'))

    args = parser.parse_args(remove_process_serial_number(sys.argv[1:]))

    if DEBUGGING:
        logger.info("Setting log level to: {}".format(args.log_level.upper()))
    logger.setLevel(args.log_level.upper())

    if DEBUGGING:
        logger.warn("Debugging flag is on!")

    if args.version:
        print(about_str)
        sys.exit(0)

    if args.list_inspectors:
        printInspectors()
        sys.exit(0)

    logger.info('Started {} {}'.format(PROJECT_NAME, VERSION))
    logger.info("Python version: {}".format(sys.version).replace('\n', ''))
    #logger.info('Using: {}'.format('PyQt' if USE_PYQT else 'PySide'))

    # Imported here so this module can be imported without Qt being installed.
    from argos.qt.misc import ABOUT_QT_BINDINGS
    logger.info("Using {}".format(ABOUT_QT_BINDINGS))

    # Browse will create an ArgosApplication with one MainWindow
    browse(fileNames = args.fileNames,
           inspectorFullName=args.inspector,
           select=args.selectPath,
           profile=args.profile,
           resetProfile=args.reset_profile,
           resetAllProfiles=args.reset_all_profiles,
           resetRegistry=args.reset_registry)
    logger.info('Done {}'.format(PROJECT_NAME))
851395
def main():
    
    parser = argparse.ArgumentParser(
        description='Performs option handling operations from the command-line. Calls JVM start/stop automatically.')
    parser.add_argument("-j", metavar="classpath", dest="classpath", help="additional classpath, jars/directories")
    parser.add_argument("-action", metavar="action", dest="action", required=True,
                        help="The action to perform on the options: join=create single string, "\
                             "split=create array from quoted option, code=generate code from options")
    parser.add_argument("option", nargs=argparse.REMAINDER, help="The option(s) to process")
    parsed = parser.parse_args()
    jars = []
    if parsed.classpath is not None:
        jars = parsed.classpath.split(os.pathsep)

    jvm.start(jars, packages=True)

    try:
        if parsed.action == "join":
            output = "cmdline = \"" + backquote(join_options(parsed.option)) + "\""
        elif parsed.action == "split" and len(parsed.option) == 1:
            output = "options = [\n"
            opts = split_options(parsed.option[0])
            for idx, opt in enumerate(opts):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]"
        elif parsed.action == "code":
            options = parsed.option[:]
            cname = None
            # classname + options?
            if options[0].find(".") > -1:
                cname = options[0]
                options = options[1:]
            output = "options = [ \n"
            for idx, opt in enumerate(options):
                if idx > 0:
                    output += ",\n"
                output += "    \"" + backquote(opt) + "\""
            output += "]\n"
            if cname is not None:
                output += 'handler = OptionHandler(JavaObject.new_instance("' + cname + '"))\n'
                output += 'handler.options = options\n'
        else:
            raise Exception("Unsupported action: " + parsed.action)
        if output is not None:
            print(output)
    except Exception as e:
        print(e)
    finally:
        jvm.stop()
1136380
function(context, pkg, source) {
		source = source || "{}";
		var packageJSON = JSON.parse(source);
		utils.extend(pkg, packageJSON);
		context.packages.push(pkg);
		return pkg;
	}
459507
def from_entrypoint_output(json_encoder, handler_output):
        """"""

        response = {
            'body': '',
            'content_type': 'text/plain',
            'headers': {},
            'status_code': 200,
            'body_encoding': 'text',
        }

        # if the type of the output is a string, just return that and 200
        if isinstance(handler_output, str):
            response['body'] = handler_output

        # if it's a tuple of 2 elements, first is status second is body
        elif isinstance(handler_output, tuple) and len(handler_output) == 2:
            response['status_code'] = handler_output[0]

            if isinstance(handler_output[1], str):
                response['body'] = handler_output[1]
            else:
                response['body'] = json_encoder(handler_output[1])
                response['content_type'] = 'application/json'

        # if it's a dict, populate the response and set content type to json
        elif isinstance(handler_output, dict) or isinstance(handler_output, list):
            response['content_type'] = 'application/json'
            response['body'] = json_encoder(handler_output)

        # if it's a response object, populate the response
        elif isinstance(handler_output, Response):
            if isinstance(handler_output.body, dict):
                response['body'] = json.dumps(handler_output.body)
                response['content_type'] = 'application/json'
            else:
                response['body'] = handler_output.body
                response['content_type'] = handler_output.content_type

            response['headers'] = handler_output.headers
            response['status_code'] = handler_output.status_code
        else:
            response['body'] = handler_output

        if isinstance(response['body'], bytes):
            response['body'] = base64.b64encode(response['body']).decode('ascii')
            response['body_encoding'] = 'base64'

        return response
752546
def main():
    """"""
    desc = 'Generate files to benchmark'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='src',
        help='The directory containing the templates'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='generated',
        help='The output directory'
    )
    parser.add_argument(
        '--seed',
        dest='seed',
        default='13',
        help='The random seed (to ensure consistent regeneration)'
    )

    args = parser.parse_args()

    random.seed(int(args.seed))

    mkdir_p(args.out_dir)

    for template in templates_in(args.src_dir):
        modes = template.modes()

        n_range = template.range()
        for n_value in n_range:
            base = template.instantiate(n_value)
            for mode in modes:
                write_file(
                    os.path.join(
                        args.out_dir,
                        out_filename(template, n_value, mode)
                    ),
                    mode.convert_from(base)
                )
        write_file(
            os.path.join(args.out_dir, '{0}.json'.format(template.name)),
            json.dumps({
                'files': {
                    n: {
                        m.identifier: out_filename(template, n, m)
                        for m in modes
                    } for n in n_range
                },
                'name': template.name,
                'x_axis_label': template.property('x_axis_label'),
                'desc': template.property('desc'),
                'modes': {m.identifier: m.description() for m in modes}
            })
        )
976678
function () {
        var pkgJson = grunt.file.readJSON("package.json");

        if (pkgJson.jspm && pkgJson.jspm.directories && pkgJson.jspm.directories.baseURL) {
            return pkgJson.jspm.directories.baseURL;
        }

        return "";
    }
1068823
def main():
    
    parser = make_parser()
    args = parser.parse_args()
    data_dir = Path(args.data_dir).expand()
    if not data_dir.isdir():  # pylint: disable=no-value-for-parameter
        msg = u"Data directory {dir} does not exist".format(dir=args.data_dir)
        raise ValueError(msg)
    data_filenames = [name for name in data_dir.files()  # pylint: disable=no-value-for-parameter
                      if name.endswith(".json")]
    if not data_filenames:
        msg = u"Data directory {dir} contains no JSON files".format(dir=args.data_dir)
        raise ValueError(msg)
    output_dir = Path(args.output_dir).expand()
    output_dir.makedirs_p()  # pylint: disable=no-value-for-parameter

    return render_html(data_dir, output_dir)
1290776
def _load_package(self, json_line, installed_packages):
        
        if len(json_line) == 0:
            return {}, set([])

        valid_json = False
        try:
            user_package = json.loads(json_line)
            valid_json = True
        except ValueError:
            user_package = {}

        package_name = user_package['name'] if 'name' in user_package else None
        module_name = package_name.replace('-', '_') if package_name is not None else ''
        envs_before = set(registry.list())

        if not valid_json or package_name is None:
            self.cache_needs_update = True
            logger.warn('Unable to load user environments. Try deleting your cache '
                        'file "%s" if this problem persists. \n\nLine: %s', self.cache_path, json_line)
            return {}, set([])
        elif package_name not in installed_packages:
            self.cache_needs_update = True
            logger.warn('The package "%s" does not seem to be installed anymore. User environments from this '
                        'package will not be registered, and the package will no longer be loaded on `import gym`', package_name)
        elif module_name in sys.modules:
            self.cache_needs_update = True
            try:
                reload_module(sys.modules[module_name])
            except ImportError:
                if 'gym' in package_name:   # To avoid uninstalling failing dependencies
                    logger.warn('Unable to reload the module "%s" from package "%s" (%s). This is usually caused by a '
                                'invalid pip package. The package will be uninstalled and no longer be loaded on `import gym`.\n',
                                module_name, package_name, installed_packages[package_name])
                    traceback.print_exc(file=sys.stdout)
                    sys.stdout.write('\n')
                    self._run_cmd('{} uninstall -y {}'.format(pip_exec, package_name))
        else:
            try:
                __import__(module_name)
            except ImportError:
                if 'gym' in package_name:   # To avoid uninstalling failing dependencies
                    self.cache_needs_update = True
                    logger.warn('Unable to import the module "%s" from package "%s" (%s). This is usually caused by a '
                                'invalid pip package. The package will be uninstalled and no longer be loaded on `import gym`.\n',
                                module_name, package_name, installed_packages[package_name])
                    traceback.print_exc(file=sys.stdout)
                    sys.stdout.write('\n')
                    self._run_cmd('{} uninstall -y {}'.format(pip_exec, package_name))

        envs_after = set(registry.list())
        registered_envs = envs_after - envs_before
        if len(registered_envs) > 0:
            self.user_packages[package_name] = user_package
        for new_env in registered_envs:
            new_spec = registry.spec(new_env)
            new_spec.source = user_package['source']
            new_spec.package = '{} ({})'.format(user_package['name'], user_package['version'])
            self.env_ids.add(new_env.lower())
        return user_package, registered_envs