check if the main entry point exists. If not, try the bower.json main.
170562
function(pjson, dir) {
    var main = pjson.main || '';
    var libDir = pjson.directories && (pjson.directories.dist || pjson.directories.lib) || '.';

    // convert to windows-style paths if necessary
    main = path.normalize(main);
    libDir = path.normalize(libDir);

    if (main.indexOf('!') !== -1) {
      return;
    }

    function checkMain(main, libDir) {
      if (!main) {
        return Promise.resolve(false);
      }

      if (main.substr(main.length - 3, 3) === '.js') {
        main = main.substr(0, main.length - 3);
      }

      return new Promise(function(resolve) {
        fs.exists(path.resolve(dir, libDir || '.', main) + '.js', function(exists) {
          resolve(exists);
        });
      });
    }

    return checkMain(main, libDir)
    .then(function(hasMain) {
      if (hasMain) {
        return;
      }

      return asp(fs.readFile)(path.resolve(dir, 'bower.json'))
      .then(function(bowerJson) {
        try {
          bowerJson = JSON.parse(bowerJson);
        } catch(e) {
          return;
        }

        main = bowerJson.main || '';
        if (main instanceof Array) {
          main = main[0];
        }

        return checkMain(main);
      }, function() {})
      .then(function(hasBowerMain) {
        if (!hasBowerMain) {
          return;
        }

        pjson.main = main;
      });
    });
  }
182081
def main(self):
        '''
        
        '''
        self.status = self.parent.status
        self.modules = self.parent.executed_modules

        # A special exception for the extractor module, which should be allowed to
        # override the verbose setting, e.g., if --matryoshka has been
        # specified
        if hasattr(self, "extractor") and self.extractor.config.verbose:
            self.config.verbose = self.config.display.verbose = True

        if not self.config.files:
            binwalk.core.common.debug("No target files specified, module %s terminated" % self.name)
            return False

        self.reset_dependencies()

        try:
            self.init()
        except KeyboardInterrupt as e:
            raise e
        except Exception as e:
            self.error(exception=e)
            return False

        try:
            self.config.display.format_strings(self.HEADER_FORMAT, self.RESULT_FORMAT)
        except KeyboardInterrupt as e:
            raise e
        except Exception as e:
            self.error(exception=e)
            return False

        self._plugins_pre_scan()

        try:
            retval = self.run()
        except KeyboardInterrupt as e:
            raise e
        except Exception as e:
            self.error(exception=e)
            return False

        self._plugins_post_scan()

        return retval
1132305
def main():
    ''' 

    '''
    import sys
    from bokeh.command.bootstrap import main as _main

   # Main entry point (see setup.py)
    _main(sys.argv)
1229441
def main():
    """"""
    parser, args = parser_factory()
    try:
        action_runner(parser, args)

    # this is our uncaught handler so yes we want to actually
    # catch every error. the format may vary based on the error handler tho
    except Exception as uncaught:  # pylint: disable=broad-except
        unhandled(uncaught, args)
        sys.exit(1)
1083431
def main():
    
    try:
        # Get the `src` directory's absolute path
        src_path = os.path.dirname(
            # `aoiklivereload` directory's absolute path
            os.path.dirname(
                # `demo` directory's absolute path
                os.path.dirname(
                    # This file's absolute path
                    os.path.abspath(__file__)
                )
            )
        )

        # If the `src` directory path is not in `sys.path`
        if src_path not in sys.path:
            # Add to `sys.path`.
            #
            # This aims to save user setting PYTHONPATH when running this demo.
            #
            sys.path.append(src_path)

        # Import reloader class
        from aoiklivereload import LiveReloader

        # Create reloader
        reloader = LiveReloader()

        # Start watcher thread
        reloader.start_watcher_thread()

        # Server host
        server_host = '0.0.0.0'

        # Server port
        server_port = 8000

        # Get message
        msg = '# ----- Run server -----\nHost: {}\nPort: {}'.format(
            server_host, server_port
        )

        # Print message
        print(msg)

        # Create Sanic app
        sanic_app = Sanic()

        # Create request handler
        @sanic_app.route('/')
        async def hello_handler(request):  # pylint: disable=unused-variable
            """
            Request handler.

            :return:
                Response body.
            """
            # Return response body
            return text('hello')

        # Run server.
        #
        # Notice `KeyboardInterrupt` will be caught inside `sanic_app.run`.
        #
        sanic_app.run(
            host=server_host,
            port=server_port,
        )

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
1225059
def main():
    
    options = build_parser()
    try:
        run(**options)
    except RuntimeError as ex:
        msg = (
            "An error occurred running dockerstache: {} "
            "please see logging info above for details"

        ).format(ex)
        LOGGER.error(msg)
        sys.exit(1)
724867
def main():
    """"""
    parser = argparse.ArgumentParser()
    subparsers = parser.add_subparsers()

    appengine.register_commands(subparsers)
    requirements.register_commands(subparsers)
    pylint.register_commands(subparsers)

    args = parser.parse_args()
    args.func(args)
1252548
function main(options = util.getDefaultOptions()) {
  createLogger(options.debug);
  log.info(`Preparing '${options.sdk}' schemas in version '${options.version || 'latest'}'...`);

  let allLibs = {};

  // do the downloading and encapsulate in Promise
  const dlPromise = new Promise((resolve, reject) => {
    download.allLibsFile(options)
      .then((allLibsJSON) => {
        allLibs = allLibsJSON;
        download.schemas(options, allLibs)
          .then((values) => {
            resolve(values);
          })
          .catch((e) => {
            reject(e);
          });
      })
      .catch((e) => {
        reject(e);
      });
  });


  dlPromise.then(() => {
    log.info('Yay, all schema files were successfully downloaded!');
    if (options.upgrade) {
      upgrade(options, allLibs);
    }
    if (options.link) {
      link(options, allLibs);
    }
  }, (e) => {
    log.error('Damn... Something went all wrong while downloading the schema files!');
    log.error(`Are you sure the version '${options.version}' is still available on '${options.sdk}' download pages?`);
    log.error(e);
  });
}
40709
def main(args, options, parser):
    '''
    '''

    from spython.main.parse import ( DockerRecipe, SingularityRecipe )

    # We need something to work with
    if not args.files:
        parser.print_help()
        sys.exit(1)

    # Get the user specified input and output files
    outfile = None    
    if len(args.files) > 1:
        outfile = args.files[1]

    # Choose the recipe parser
    parser = SingularityRecipe
    if args.input == "docker":
        parser = DockerRecipe
    elif args.input == "singularity":
        parser = SingularityRecipe(args.files[0])
    else:
        if "dockerfile" in args.files[0].lower():
            parser = DockerRecipe

    # Initialize the chosen parser
    parser = parser(args.files[0])

    # By default, discover entrypoint / cmd from Dockerfile
    entrypoint = "/bin/bash"
    force = False

    if args.entrypoint is not None:
        entrypoint = args.entrypoint
        force = True

    # If the user specifies an output file, save to it
    if outfile is not None:
        parser.save(outfile, runscript=entrypoint, force=force)

    # Otherwise, convert and print to screen
    else:
        recipe = parser.convert(runscript=entrypoint, force=True)
        print(recipe)
1034731
async function main() {
  // Initialize the application.
  process.title = 'Which.js';

  // Parse the command line arguments.
  program.name('which')
    .description('Find the instances of an executable in the system path.')
    .version(packageVersion, '-v, --version')
    .option('-a, --all', 'list all instances of executables found (instead of just the first one)')
    .option('-s, --silent', 'silence the output, just return the exit code (0 if any executable is found, otherwise 1)')
    .arguments('<command>').action(command => program.executable = command)
    .parse(process.argv);

  if (!program.executable) {
    program.outputHelp();
    process.exitCode = 64;
    return;
  }

  // Run the program.
  let executables = await which(program.executable, {all: program.all});
  if (!program.silent) {
    if (!Array.isArray(executables)) executables = [executables];
    for (const path of executables) console.log(path);
  }
}
1298359
def main() -> None:
    """"""

    # Make sure we have access to self
    if 'self' not in globals():
        print("Run 'set locals_in_py true' and then rerun this script")
        return

    # Make sure the user passed in an output file
    if len(sys.argv) != 2:
        print("Usage: {} <output_file>".format(os.path.basename(sys.argv[0])))
        return

    # Open the output file
    outfile_path = os.path.expanduser(sys.argv[1])
    try:
        outfile = open(outfile_path, 'w')
    except OSError as e:
        print("Error opening {} because: {}".format(outfile_path, e))
        return

    # Write the help summary
    header = '{0}\nSUMMARY\n{0}\n'.format(ASTERISKS)
    outfile.write(header)

    result = app('help -v')
    outfile.write(result.stdout)

    # Get a list of all commands and help topics and then filter out duplicates
    all_commands = set(self.get_all_commands())
    all_topics = set(self.get_help_topics())
    to_save = list(all_commands | all_topics)
    to_save.sort()

    for item in to_save:
        is_command = item in all_commands
        add_help_to_file(item, outfile, is_command)

        if is_command:
            # Add any sub-commands
            for subcmd in get_sub_commands(getattr(self.cmd_func(item), 'argparser', None)):
                full_cmd = '{} {}'.format(item, subcmd)
                add_help_to_file(full_cmd, outfile, is_command)

    outfile.close()
    print("Output written to {}".format(outfile_path))
1227650
def main():
    
    version = 'Python Exist %s' % __version__
    arguments = docopt(__doc__, version=version)
    ExistCli(arguments)
1152395
function _main() {
  // Detect path to `tsconfig.app.json`.
  const ngConfig = parse(readFileSync(NG_JSON, 'utf8'));
  const tsConfigPath = join(ROOT_DIR, ngConfig.projects.site.architect.build.options.tsConfig);

  // Enable Ivy in TS config.
  console.log(`\nModifying \`${tsConfigPath}\`...`);
  const oldTsConfigStr = readFileSync(tsConfigPath, 'utf8');
  const oldTsConfigObj = parse(oldTsConfigStr);
  const newTsConfigObj = extend(true, oldTsConfigObj, NG_COMPILER_OPTS);
  const newTsConfigStr = `${JSON.stringify(newTsConfigObj, null, 2)}\n`;
  console.log(`\nNew config: ${newTsConfigStr}`);
  writeFileSync(tsConfigPath, newTsConfigStr);

  // Run ngcc.
  const ngccArgs = '--loglevel debug --properties es2015 module';
  console.log(`\nRunning ngcc (with args: ${ngccArgs})...`);
  exec(`yarn ivy-ngcc ${ngccArgs}`);

  // Done.
  console.log('\nReady to build with Ivy!');
  console.log('(To switch back to ViewEngine (with packages from npm), undo the changes in ' +
              `\`${tsConfigPath}\` and run \`yarn aio-use-npm && yarn example-use-npm\`.)`);
}
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)
497791
def cli_main():
    """"""
    SearchContext.commit()
    args = parser.parse_args()
    # open up a browser
    firefox_remote = Remote("http://127.0.0.1:4444/wd/hub", DesiredCapabilities.FIREFOX)
    with contextlib.closing(firefox_remote):
        context = SearchContext.from_instances([FastSearch(), Browser(firefox_remote)])
        search = Search(parent=context)

        if args.fast:
            with context.use(FastSearch, Browser):
                main(search, args.query)
        else:
            with context.use(Browser):
                main(search, args.query)
763009
def main() -> None:
    """"""
    try:
        _real_main()
    except GuesslangError as error:
        LOGGER.critical("Failed: %s", error)
        sys.exit(-1)
    except KeyboardInterrupt:
        LOGGER.critical("Cancelled!")
        sys.exit(-2)
171119
def main():
    """""""
    parser = argparse.ArgumentParser(description='Do something awesome')
    parser.add_argument('input_file', nargs=1,
                        type=argparse.FileType('r'))
    parser.add_argument('-o', '--outfile', nargs='?',
                        type=argparse.FileType('w'), default=sys.stdout)
    args = parser.parse_args()

    print(json_to_csv(args.input_file[0].read()), file=args.outfile)