Interface for running `wdrizzle` from TEAL or Python command-line.

    This code performs all file ``I/O`` to set up the use of the drizzle code for
    a single exposure to replicate the functionality of the original `wdrizzle`.
547696
def run(configObj, wcsmap=None):
    

    # Insure all output filenames specified have .fits extensions
    if configObj['outdata'][-5:] != '.fits': configObj['outdata'] += '.fits'
    if not util.is_blank(configObj['outweight']) and configObj['outweight'][-5:] != '.fits': configObj['outweight'] += '.fits'
    if not util.is_blank(configObj['outcontext']) and configObj['outcontext'][-5:] != '.fits': configObj['outcontext'] += '.fits'

    # Keep track of any files we need to open
    in_sci_handle = None
    in_wht_handle = None
    out_sci_handle = None
    out_wht_handle = None
    out_con_handle = None

    _wcskey = configObj['wcskey']
    if util.is_blank(_wcskey):
        _wcskey = ' '

    scale_pars = configObj['Data Scaling Parameters']
    user_wcs_pars = configObj['User WCS Parameters']

    # Open the SCI (and WHT?) image
    # read file to get science array
    insci = get_data(configObj['input'])
    expin = fileutil.getKeyword(configObj['input'],scale_pars['expkey'])
    in_sci_phdr = fits.getheader(fileutil.parseFilename(configObj['input'])[0], memmap=False)

    # we need to read in the input WCS
    input_wcs = stwcs.wcsutil.HSTWCS(configObj['input'],wcskey=_wcskey)

    if not util.is_blank(configObj['inweight']):
        inwht = get_data(configObj['inweight']).astype(np.float32)
    else:
        # Generate a default weight map of all good pixels
        inwht = np.ones(insci.shape,dtype=insci.dtype)

    output_exists = False
    outname = fileutil.osfn(fileutil.parseFilename(configObj['outdata'])[0])
    if os.path.exists(outname):
        output_exists = True
    # Output was specified as a filename, so open it in 'update' mode
    outsci = get_data(configObj['outdata'])

    if output_exists:
        # we also need to read in the output WCS from pre-existing output
        output_wcs = stwcs.wcsutil.HSTWCS(configObj['outdata'])

        out_sci_hdr = fits.getheader(outname, memmap=False)
        outexptime = out_sci_hdr['DRIZEXPT']
        if 'ndrizim' in out_sci_hdr:
            uniqid = out_sci_hdr['ndrizim']+1
        else:
            uniqid = 1

    else:  # otherwise, define the output WCS either from user pars or refimage
        if util.is_blank(configObj['User WCS Parameters']['refimage']):
            # Define a WCS based on user provided WCS values
            # NOTE:
            #   All parameters must be specified, not just one or a few
            if not util.is_blank(user_wcs_pars['outscale']):
                output_wcs = wcs_functions.build_hstwcs(
                    user_wcs_pars['raref'], user_wcs_pars['decref'],
                    user_wcs_pars['xrefpix'], user_wcs_pars['yrefpix'],
                    user_wcs_pars['outnx'], user_wcs_pars['outny'],
                    user_wcs_pars['outscale'], user_wcs_pars['orient'] )
            else:
                # Define default WCS based on input image
                applydist = True
                if input_wcs.sip is None or input_wcs.instrument=='DEFAULT':
                    applydist = False
                output_wcs = stwcs.distortion.utils.output_wcs([input_wcs],undistort=applydist)
        else:
            refimage = configObj['User WCS Parameters']['refimage']
            refroot,extroot = fileutil.parseFilename(refimage)
            if extroot is None:
                fimg = fits.open(refroot, memmap=False)
                for i,extn in enumerate(fimg):
                    if 'CRVAL1' in extn.header: # Key on CRVAL1 for valid WCS
                        refwcs = wcsutil.HSTWCS('{}[{}]'.format(refroot,i))
                        if refwcs.wcs.has_cd():
                            extroot = i
                            break
                fimg.close()
                # try to find extension with valid WCS
                refimage = "{}[{}]".format(refroot,extroot)
            # Define the output WCS based on a user specified reference image WCS
            output_wcs = stwcs.wcsutil.HSTWCS(refimage)
        # Initialize values used for combining results
        outexptime = 0.0
        uniqid = 1

    # Set up the output data array and insure that the units for that array is 'cps'
    if outsci is None:
        # Define a default blank array based on definition of output_wcs
        outsci = np.empty(output_wcs.array_shape, dtype=np.float32)
        outsci.fill(np.nan)
    else:
        # Convert array to units of 'cps', if needed
        if outexptime != 0.0:
            np.divide(outsci, outexptime, outsci)
        outsci = outsci.astype(np.float32)

    # Now update output exposure time for additional input file
    outexptime += expin

    outwht = None
    if not util.is_blank(configObj['outweight']):
        outwht = get_data(configObj['outweight'])

    if outwht is None:
        outwht = np.zeros(output_wcs.array_shape, dtype=np.float32)
    else:
        outwht = outwht.astype(np.float32)

    outcon = None
    keep_con = False

    if not util.is_blank(configObj['outcontext']):
        outcon = get_data(configObj['outcontext'])
        keep_con = True
        if outcon is None:
            outcon = np.zeros((1,) + output_wcs.array_shape, dtype=np.int32)
        else:
            outcon = outcon.astype(np.int32)
            planeid = int((uniqid - 1)/ 32)

            # Add a new plane to the context image if planeid overflows
            while outcon.shape[0] <= planeid:
                plane = np.zeros_like(outcon[0])
                outcon = np.append(outcon, plane, axis=0)

    # Interpret wt_scl parameter
    if configObj['wt_scl'] == 'exptime':
        wt_scl = expin
    elif configObj['wt_scl'] == 'expsq':
        wt_scl = expin*expin
    else:
        wt_scl = float(configObj['wt_scl'])

    # Interpret coeffs parameter to determine whether to apply coeffs or not
    undistort = True
    if not configObj['coeffs'] or input_wcs.sip is None or input_wcs.instrument == 'DEFAULT':
        undistort = False
    # turn off use of coefficients if undistort is False (coeffs == False)
    if not undistort:
        input_wcs.sip = None
        input_wcs.cpdis1 = None
        input_wcs.cpdis2 = None
        input_wcs.det2im = None

    wcslin = distortion.utils.output_wcs([input_wcs],undistort=undistort)

    # Perform actual drizzling now...
    _vers = do_driz(insci, input_wcs, inwht,
            output_wcs, outsci, outwht, outcon,
            expin, scale_pars['in_units'],
            wt_scl, wcslin_pscale=wcslin.pscale ,uniqid=uniqid,
            pixfrac=configObj['pixfrac'], kernel=configObj['kernel'],
            fillval=scale_pars['fillval'], stepsize=configObj['stepsize'],
            wcsmap=None)

    out_sci_handle,outextn = create_output(configObj['outdata'])
    if not output_exists:
        # Also, define default header based on input image Primary header
        out_sci_handle[outextn].header = in_sci_phdr.copy()

    # Update header of output image with exptime used to scale the output data
    # if out_units is not counts, this will simply be a value of 1.0
    # the keyword 'exptime' will always contain the total exposure time
    # of all input image regardless of the output units
    out_sci_handle[outextn].header['EXPTIME'] = outexptime

    # create CTYPE strings
    ctype1 = input_wcs.wcs.ctype[0]
    ctype2 = input_wcs.wcs.ctype[1]
    if ctype1.find('-SIP'): ctype1 = ctype1.replace('-SIP','')
    if ctype2.find('-SIP'): ctype2 = ctype2.replace('-SIP','')

    # Update header with WCS keywords
    out_sci_handle[outextn].header['ORIENTAT'] = output_wcs.orientat
    out_sci_handle[outextn].header['CD1_1'] = output_wcs.wcs.cd[0][0]
    out_sci_handle[outextn].header['CD1_2'] = output_wcs.wcs.cd[0][1]
    out_sci_handle[outextn].header['CD2_1'] = output_wcs.wcs.cd[1][0]
    out_sci_handle[outextn].header['CD2_2'] = output_wcs.wcs.cd[1][1]
    out_sci_handle[outextn].header['CRVAL1'] = output_wcs.wcs.crval[0]
    out_sci_handle[outextn].header['CRVAL2'] = output_wcs.wcs.crval[1]
    out_sci_handle[outextn].header['CRPIX1'] = output_wcs.wcs.crpix[0]
    out_sci_handle[outextn].header['CRPIX2'] = output_wcs.wcs.crpix[1]
    out_sci_handle[outextn].header['CTYPE1'] = ctype1
    out_sci_handle[outextn].header['CTYPE2'] = ctype2
    out_sci_handle[outextn].header['VAFACTOR'] = 1.0


    if scale_pars['out_units'] == 'counts':
        np.multiply(outsci, outexptime, outsci)
        out_sci_handle[outextn].header['DRIZEXPT'] = outexptime

    else:
        out_sci_handle[outextn].header['DRIZEXPT'] = 1.0

    # Update header keyword NDRIZIM to keep track of how many images have
    # been combined in this product so far
    out_sci_handle[outextn].header['NDRIZIM'] = uniqid

    #define keywords to be written out to product header
    drizdict = outputimage.DRIZ_KEYWORDS.copy()

    # Update drizdict with current values
    drizdict['VER']['value'] = _vers[:44]
    drizdict['DATA']['value'] = configObj['input'][:64]
    drizdict['DEXP']['value'] = expin
    drizdict['OUDA']['value'] = configObj['outdata'][:64]
    drizdict['OUWE']['value'] = configObj['outweight'][:64]
    drizdict['OUCO']['value'] = configObj['outcontext'][:64]
    drizdict['MASK']['value'] = configObj['inweight'][:64]
    drizdict['WTSC']['value'] = wt_scl
    drizdict['KERN']['value'] = configObj['kernel']
    drizdict['PIXF']['value'] = configObj['pixfrac']
    drizdict['OUUN']['value'] = scale_pars['out_units']
    drizdict['FVAL']['value'] = scale_pars['fillval']
    drizdict['WKEY']['value'] = configObj['wcskey']
    outputimage.writeDrizKeywords(out_sci_handle[outextn].header,uniqid,drizdict)

    # add output array to output file
    out_sci_handle[outextn].data = outsci
    out_sci_handle.close()

    if not util.is_blank(configObj['outweight']):
        out_wht_handle,outwhtext = create_output(configObj['outweight'])
        out_wht_handle[outwhtext].header = out_sci_handle[outextn].header.copy()
        out_wht_handle[outwhtext].data = outwht
        out_wht_handle.close()

    if keep_con:
        out_con_handle,outconext = create_output(configObj['outcontext'])
        out_con_handle[outconext].data = outcon
        out_con_handle.close()
636300
def main(args=sys.argv[1:]):
    """"""
    parser = argparse.ArgumentParser()
    parser.add_argument("filename", nargs=1)
    parser.add_argument("--granule-id", dest="granule_id",
        help=(
            "Optional. Specify a granule to export metadata from."
        )
    )
    parser.add_argument("--single-granule", dest="single_granule",
        action="store_true", default=False,
        help=(
            "When only one granule is contained in the package, include product "
            "metadata from this one granule. Fails when more than one granule "
            "is contained."
        )
    )
    parser.add_argument("--out-file", "-f", dest="out_file",
        help=(
            "Specify an output file to write the metadata to. By default, the "
            "XML is printed on stdout."
        )
    )
    parser.add_argument("--resolution", "-r", dest="resolution", default="10",
        help=(
            "Only produce metadata for bands of this resolution (in meters). "
            "Default is 10."
        )
    )

    parsed = parser.parse_args(args)

    try:
        safe_pkg = s2reader.open(parsed.filename[0])
    except IOError, e:
        parser.error('Could not open SAFE package. Error was "%s"' % e)

    granules = safe_pkg.granules

    granule = None
    if parsed.granule_id:
        granule_dict = dict(
            (granule.granule_identifier, granule) for granule in granules
        )
        try:
            granule = granule_dict[parsed.granule_id]
        except KeyError:
            parser.error('No such granule %r' % parsed.granule_id)

    elif parsed.single_granule:
        if len(granules) > 1:
            parser.error('Package contains more than one granule.')

        granule = granules[0]

    params = _get_product_template_params(safe_pkg, parsed.resolution)

    if granule:
        params.update(_get_granule_template_params(granule, parsed.resolution))
        xml_string = EOOM_TEMPLATE_GRANULE.format(**params)
    else:
        xml_string = EOOM_TEMPLATE_PRODUCT.format(**params)

    if parsed.out_file:
        with open(parsed.out_file, "w") as f:
            f.write(xml_string)
    else:
        print(xml_string)
738497
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(
            # Reload mode.
            #
            # In windows, have to use `spawn_exit` reload mode and force the
            # current process to exit immediately, otherwise will get the
            # error:
            # ```
            # OSError: [WinError 10048] Only one usage of each socket address
            # (protocol/network address/port) is normally permitted
            # ```
            #
            # Notice in `spawn_exit` reload mode, the user will not be able
            # to kill the new process using Ctrl-c.
            #
            reload_mode=('spawn_exit' if sys.platform == 'win32' else 'exec'),
            force_exit=True,
        )

        # 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 request handler
        class HelloHandler(tornado.web.RequestHandler):
            """
            Request handler class.
            """

            def get(self):
                """
                Request handler.

                :return:
                    None.
                """
                # Write response body
                self.write('hello')

        # List of tuples that maps URL pattern to handler
        handler_tuples = [
            ('/', HelloHandler),
        ]

        # Create Tornado app
        tornado_app = tornado.web.Application(
            handler_tuples,
            # Disable Tornado's reloader
            debug=False,
        )

        # Start listening
        tornado_app.listen(server_port, address=server_host)

        # Get event loop
        io_loop = tornado.ioloop.IOLoop.current()

        # Run event loop
        io_loop.start()

    # If have `KeyboardInterrupt`
    except KeyboardInterrupt:
        # Not treat as error
        pass
499950
function Cli(argv) {
  var Cucumber = require('cucumber');
  var Command = require('commander').Command;
  var path = require('path');

  function collect(val, memo) {
    memo.push(val);
    return memo;
  }

  function getProgram() {
    var program = new Command(path.basename(argv[1]));

    program
      .usage('[options] [<DIR|FILE[:LINE]>...]')
      .version(Cucumber.VERSION, '-v, --version')
      .option('-b, --backtrace', 'show full backtrace for errors')
      .option('--compiler <EXTENSION:MODULE>', 'require files with the given EXTENSION after requiring MODULE (repeatable)', collect, [])
      .option('-d, --dry-run', 'invoke formatters without executing steps')
      .option('--fail-fast', 'abort the run on first failure')
      .option('-f, --format <TYPE[:PATH]>', 'specify the output format, optionally supply PATH to redirect formatter output (repeatable)', collect, ['pretty'])
      .option('--name <REGEXP>', 'only execute the scenarios with name matching the expression (repeatable)', collect, [])
      .option('--no-colors', 'disable colors in formatter output')
      .option('--no-snippets', 'hide step definition snippets for pending steps')
      .option('--no-source', 'hide source uris')
      .option('-p, --profile <NAME>', 'specify the profile to use (repeatable)', collect, [])
      .option('-r, --require <FILE|DIR>', 'require files before executing features (repeatable)', collect, [])
      .option('--snippet-syntax <FILE>', 'specify a custom snippet syntax')
      .option('-S, --strict', 'fail if there are any undefined or pending steps')
      .option('-t, --tags <EXPRESSION>', 'only execute the features or scenarios with tags matching the expression (repeatable)', collect, []);

    program.on('--help', function () {
      console.log('  For more details please visit https://github.com/cucumber/cucumber-js#cli\n');
    });

    return program;
  }

  function getConfiguration() {
    var program = getProgram();
    program.parse(argv);
    var profileArgs = Cucumber.Cli.ProfilesLoader.getArgs(program.profile);
    if (profileArgs.length > 0) {
      var fullArgs = argv.slice(0, 2).concat(profileArgs).concat(argv.slice(2));
      program = getProgram();
      program.parse(fullArgs);
    }
    var configuration = Cucumber.Cli.Configuration(program.opts(), program.args);
    return configuration;
  }

  var self = {
    run: function run(callback) {
      var configuration = getConfiguration();
      var runtime = Cucumber.Runtime(configuration);
      var formatters = [createIpcFormatter()].concat(configuration.getFormatters());
      formatters.forEach(function (formatter) {
        runtime.attachListener(formatter);
      });
      try {
        runtime.start(callback);
      } catch (e) {
        console.log(e.stack || e)
        callback(false)
      }
    }
  };
  return self;
}
273868
def main():
    
    parser = optparse.OptionParser(usage="usage: pylon [options] input_file",
                                   version="%prog 0.4.4")

    parser.add_option("-o", "--output", dest="output", metavar="FILE",
        help="Write the solution report to FILE.")

#    parser.add_option("-q", "--quiet", action="store_true", dest="quiet",
#        default=False, help="Print less information.")

    parser.add_option("-v", "--verbose", action="store_true", dest="verbose",
        default=False, help="Print more information.")

#    parser.add_option("-g", "--gui", action="store_true", dest="gui",
#        default=False, help="Use the portable graphical interface to Pylon.")

#    parser.add_option("-n", "--no-report", action="store_true",
#        dest="no_report", default=False, help="Suppress report output.")

    parser.add_option("-d", "--debug", action="store_true", dest="debug",
        default=False, help="Print debug information.")

    parser.add_option("-t", "--input-type", dest="type", metavar="TYPE",
        default="any", help="The argument following the -t is used to "
        "indicate the format type of the input data file. The types which are "
        "currently supported include: matpower, psse [default: %default]"
        " If not specified Pylon will try to determine the type according to "
        "the file name extension and the file header.")

    parser.add_option("-s", "--solver", dest="solver", metavar="SOLVER",
        default="acpf", help="The argument following the -s is used to"
        "indicate the type of routine to use in solving. The types which are "
        "currently supported are: 'dcpf', 'acpf', 'dcopf', 'acopf', 'udopf' "
        "and 'none' [default: %default].")

    parser.add_option("-a", "--algorithm", action="store_true",
        metavar="ALGORITHM", dest="algorithm", default="newton",
        help="Indicates the algorithm type to be used for AC power flow. The "
        "types which are currently supported are: 'newton' and 'fdpf' "
        "[default: %default].")

    parser.add_option("-T", "--output-type", dest="output_type",
        metavar="OUTPUT_TYPE", default="rst", help="Indicates the output "
        "format type.  The type swhich are currently supported include: rst, "
        "matpower, csv, excel and none [default: %default].")

    (options, args) = parser.parse_args()

    if options.verbose:
        logger.setLevel(logging.INFO)
    elif options.debug:
        logger.setLevel(logging.DEBUG)
    else:
        logger.setLevel(logging.ERROR)

    # Output.
    outext = {'psse': '.raw', 'matpower': '.m'}
    if options.output:
        if options.output == "-":
            outfile = sys.stdout
            logger.setLevel(logging.CRITICAL) # must stay quiet
#            options.output_type = "none"
        else:
            outfile = open(options.output, "wb")
    elif options.output_type is not None:
        if options.output_type in outext.keys():
            inname, ext = os.path.splitext(args[0])
            outfile = inname + outext[options.output_type]
        else:
            outfile = sys.stdout
    else:
        outfile = sys.stdout
#        if not options.no_report:
#            logger.setLevel(logging.CRITICAL) # must stay quiet

    # Input.
    if len(args) > 1:
        parser.print_help()
        sys.exit(1)
    elif (len(args) == 0) or (args[0] == "-"):
        filename = ""
        if sys.stdin.isatty():
            # True if the file is connected to a tty device, and False
            # otherwise (pipeline or file redirection).
            parser.print_help()
            sys.exit(1)
        else:
            # Handle piped input ($ cat ehv3.raw | pylon | rst2pdf -o ans.pdf).
            infile = sys.stdin
    else:
        filename = args[0]
        infile = open(filename, "rb")

    if options.type == "any":
        type = detect_data_file(infile, filename)
    else:
        type = options.type

    # Get the case from the input file-like object.
    case = read_case(infile, type)

    if case is not None:
        # Routine (and algorithm) selection.
        if options.solver == "dcpf":
            solver = DCPF(case)
        elif options.solver == "acpf":
            if options.algorithm == "newton":
                solver = NewtonPF(case)
            elif options.algorithm == "fdpf":
                solver = FastDecoupledPF(case)
            else:
                logger.critical("Invalid algorithm [%s]." % options.algorithm)
                sys.exit(1)
        elif options.solver == "dcopf":
            solver = OPF(case, True)
        elif options.solver == "acopf":
            solver = OPF(case, False)
        elif options.solver == "udopf":
            solver = UDOPF(case)
        elif options.solver == "none":
            solver = None
        else:
            logger.critical("Invalid solver [%s]." % options.solver)
#            sys.exit(1)
            solver = None

        # Output writer selection.
        if options.output_type == "matpower":
            writer = MATPOWERWriter(case)
        elif options.output_type == "psse":
            writer = PSSEWriter(case)
        elif options.output_type == "rst":
            writer = ReSTWriter(case)
        elif options.output_type == "csv":
            from pylon.io.excel import CSVWriter
            writer = CSVWriter(case)
        elif options.output_type == "excel":
            from pylon.io.excel import ExcelWriter
            writer = ExcelWriter(case)
        elif options.output_type == "pickle":
            writer = PickleWriter(case)
        else:
            logger.critical("Invalid output type [%s]." % options.output_type)
            sys.exit(1)

        if solver is not None:
            solver.solve()
        if options.output_type != "none":
            writer.write(outfile)
            print('Output file {0} written'.format(outfile))
    else:
        logger.critical("Unable to read case data.")

    # Don't close stdin or stdout.
    if len(args) == 1:
        infile.close()
    if options.output and not (options.output == "-"):
        outfile.close()
905882
def _run(method, cmd, cwd=None, shell=True, universal_newlines=True,
             stderr=STDOUT):
        """"""
        if not cmd:
            error_msg = 'Passed empty text or list'
            raise AttributeError(error_msg)
        if isinstance(cmd, six.string_types):
            cmd = str(cmd)
        if shell:
            if isinstance(cmd, list):
                cmd = ' '.join(cmd)
        else:
            if isinstance(cmd, str):
                cmd = cmd.strip().split()
        out = method(cmd, shell=shell, cwd=cwd, stderr=stderr,
                     universal_newlines=universal_newlines)
        if isinstance(out, bytes):
            out = out.decode('utf-8')
        return str(out).strip()
1112375
def write_AST(wdl_file, outdir=None):
    '''
    
    '''
    if outdir is None:
        outdir = os.getcwd()
    with open(os.path.join(outdir, 'AST.out'), 'w') as f:
        with open(wdl_file, 'r') as wdl:
            wdl_string = wdl.read()
            ast = wdl_parser.parse(wdl_string).ast()
            f.write(ast.dumps(indent=2))
209799
def run_with_retcodes(argv):
    
    logger = logging.getLogger('luigi-interface')
    with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
        retcodes = retcode()

    worker = None
    try:
        worker = luigi.interface._run(argv).worker
    except luigi.interface.PidLockAlreadyTakenExit:
        sys.exit(retcodes.already_running)
    except Exception:
        # Some errors occur before logging is set up, we set it up now
        env_params = luigi.interface.core()
        InterfaceLogging.setup(env_params)
        logger.exception("Uncaught exception in luigi")
        sys.exit(retcodes.unhandled_exception)

    with luigi.cmdline_parser.CmdlineParser.global_instance(argv):
        task_sets = luigi.execution_summary._summary_dict(worker)
        root_task = luigi.execution_summary._root_task(worker)
        non_empty_categories = {k: v for k, v in task_sets.items() if v}.keys()

    def has(status):
        assert status in luigi.execution_summary._ORDERED_STATUSES
        return status in non_empty_categories

    codes_and_conds = (
        (retcodes.missing_data, has('still_pending_ext')),
        (retcodes.task_failed, has('failed')),
        (retcodes.already_running, has('run_by_other_worker')),
        (retcodes.scheduling_error, has('scheduling_error')),
        (retcodes.not_run, has('not_run')),
    )
    expected_ret_code = max(code * (1 if cond else 0) for code, cond in codes_and_conds)

    if expected_ret_code == 0 and \
       root_task not in task_sets["completed"] and \
       root_task not in task_sets["already_done"]:
        sys.exit(retcodes.not_run)
    else:
        sys.exit(expected_ret_code)
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)
518462
def run_code_in_container(cli, image, code, mount, entrypoint):
    
    kwargs = {
        'image': image,
    }

    if entrypoint:
        kwargs['entrypoint'] = '/bin/bash'
        kwargs['command'] = '-c {}'.format(quote(code))
    else:
        kwargs['command'] = '/bin/bash -c {}'.format(quote(code))

    if mount:
        binds = []
        volumes = []

        for m in mount:
            part = m.split(':')

            if len(part) == 3:
                pass
            elif len(part) == 2:
                part.append('rw')
            else:
                raise

            src, target, mode = part
            src = os.path.abspath(os.path.expanduser(src))

            binds.append('{}:{}:{}'.format(src, target, mode))
            volumes.append(target)

        kwargs['host_config'] = cli.create_host_config(binds=binds)
        kwargs['volumes'] = volumes

    container = cli.create_container(**kwargs)
    container_id = container['Id']

    cli.start(container=container_id)

    return container_id
484543
def main():
    
    parser = argparse.ArgumentParser(description='Longclaw CLI')
    subparsers = parser.add_subparsers()
    start = subparsers.add_parser('start', help='Create a Wagtail+Longclaw project')
    start.add_argument('project_name', help='Name of the project')
    start.set_defaults(func=create_project)

    build = subparsers.add_parser('build', help='Build the front-end assets for Longclaw')
    build.set_defaults(func=build_assets)

    args = parser.parse_args()

    # Python 3 lost the default behaviour to fall back to printing
    # help if a subparser is not selected.
    # See: https://bugs.python.org/issue16308
    # So we must explicitly catch the error thrown on py3 if
    # no commands given to longclaw
    try:
        args.func(args)
    except AttributeError:
        parser.print_help()
        sys.exit(0)
1005524
def run_file(self, session, filename):
        
        try:
            with open(filename, "r") as filep:
                for lineno, line in enumerate(filep):
                    line = line.strip()
                    if not line or line.startswith("#"):
                        # Ignore comments and empty lines
                        continue

                    # Print out the executed line
                    session.write_line("[{0:02d}] >> {1}", lineno, line)

                    # Execute the line
                    if not self.execute(line, session):
                        session.write_line(
                            "Command at line {0} failed. Abandon.", lineno + 1
                        )
                        return False

                session.write_line("Script execution succeeded")
        except IOError as ex:
            session.write_line("Error reading file {0}: {1}", filename, ex)
            return False

        return None
464046
def run_file_or_script (script=None, file_name='script_from_command_line',
                        argv=None, params=None, **kwargs):
    """"""
    runner= Ayrton (**kwargs)

    if params is None:
        params= ExecParams ()

    if script is None:
        v= runner.run_file (file_name, argv, params)
    else:
        if not isinstance(script, bytes):
            # the problem here it's that the parser expects the source as bytes
            # so we must encode the source before passing it
            script = script.encode()
        v= runner.run_script (script, file_name, argv, params)

    return v
339357
def zipline_magic(line, cell=None):
    
    load_extensions(
        default=True,
        extensions=[],
        strict=True,
        environ=os.environ,
    )
    try:
        return run.main(
            # put our overrides at the start of the parameter list so that
            # users may pass values with higher precedence
            [
                '--algotext', cell,
                '--output', os.devnull,  # don't write the results by default
            ] + ([
                # these options are set when running in line magic mode
                # set a non None algo text to use the ipython user_ns
                '--algotext', '',
                '--local-namespace',
            ] if cell is None else []) + line.split(),
            '%s%%zipline' % ((cell or '') and '%'),
            # don't use system exit and propogate errors to the caller
            standalone_mode=False,
        )
    except SystemExit as e:
        # https://github.com/mitsuhiko/click/pull/533
        # even in standalone_mode=False `--help` really wants to kill us ;_;
        if e.code:
            raise ValueError('main returned non-zero status code: %d' % e.code)
490050
def command_line_runner():
    
    filename = sys.argv[-1]
    if not filename.endswith(".rst"):
        print("ERROR! Please enter a ReStructuredText filename!")
        sys.exit()
    print(rst_to_json(file_opener(filename)))
763175
def main():
    
    usage = '%prog [options] "<input file>"'
    if '__main__.py' in sys.argv[0]: # python -m pyminifier
        usage = 'pyminifier [options] "<input file>"'
    parser = OptionParser(usage=usage, version=__version__)
    parser.disable_interspersed_args()
    parser.add_option(
        "-o", "--outfile",
        dest="outfile",
        default=None,
        help="Save output to the given file.",
        metavar="<file path>"
    )
    parser.add_option(
        "-d", "--destdir",
        dest="destdir",
        default="./minified",
        help=("Save output to the given directory. "
              "This option is required when handling multiple files. "
              "Defaults to './minified' and will be created if not present. "),
        metavar="<file path>"
    )
    parser.add_option(
        "--nominify",
        action="store_true",
        dest="nominify",
        default=False,
        help="Don't bother minifying (only used with --pyz).",
    )
    parser.add_option(
        "--use-tabs",
        action="store_true",
        dest="tabs",
        default=False,
        help="Use tabs for indentation instead of spaces.",
    )
    parser.add_option(
        "--bzip2",
        action="store_true",
        dest="bzip2",
        default=False,
        help=("bzip2-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    parser.add_option(
        "--gzip",
        action="store_true",
        dest="gzip",
        default=False,
        help=("gzip-compress the result into a self-executing python script.  "
              "Only works on stand-alone scripts without implicit imports.")
    )
    if lzma:
        parser.add_option(
            "--lzma",
            action="store_true",
            dest="lzma",
            default=False,
            help=("lzma-compress the result into a self-executing python script.  "
                  "Only works on stand-alone scripts without implicit imports.")
        )
    parser.add_option(
        "--pyz",
        dest="pyz",
        default=None,
        help=("zip-compress the result into a self-executing python script. "
              "This will create a new file that includes any necessary implicit"
              " (local to the script) modules.  Will include/process all files "
              "given as arguments to pyminifier.py on the command line."),
        metavar="<name of archive>.pyz"
    )
    parser.add_option(
        "-O", "--obfuscate",
        action="store_true",
        dest="obfuscate",
        default=False,
        help=(
            "Obfuscate all function/method names, variables, and classes.  "
            "Default is to NOT obfuscate."
        )
    )
    parser.add_option(
        "--obfuscate-classes",
        action="store_true",
        dest="obf_classes",
        default=False,
        help="Obfuscate class names."
    )
    parser.add_option(
        "--obfuscate-functions",
        action="store_true",
        dest="obf_functions",
        default=False,
        help="Obfuscate function and method names."
    )
    parser.add_option(
        "--obfuscate-variables",
        action="store_true",
        dest="obf_variables",
        default=False,
        help="Obfuscate variable names."
    )
    parser.add_option(
        "--obfuscate-import-methods",
        action="store_true",
        dest="obf_import_methods",
        default=False,
        help="Obfuscate globally-imported mouled methods (e.g. 'Ag=re.compile')."
    )
    parser.add_option(
        "--obfuscate-builtins",
        action="store_true",
        dest="obf_builtins",
        default=False,
        help="Obfuscate built-ins (i.e. True, False, object, Exception, etc)."
    )
    parser.add_option(
        "--replacement-length",
        dest="replacement_length",
        default=1,
        help=(
            "The length of the random names that will be used when obfuscating "
            "identifiers."
        ),
        metavar="1"
    )
    parser.add_option(
        "--nonlatin",
        action="store_true",
        dest="use_nonlatin",
        default=False,
        help=(
            "Use non-latin (unicode) characters in obfuscation (Python 3 only)."
            "  WARNING: This results in some SERIOUSLY hard-to-read code."
        )
    )
    parser.add_option(
        "--prepend",
        dest="prepend",
        default=None,
        help=(
            "Prepend the text in this file to the top of our output.  "
            "e.g. A copyright notice."
        ),
        metavar="<file path>"
    )
    options, files = parser.parse_args()
    if not files:
        parser.print_help()
        sys.exit(2)
    pyminify(options, files)
1170933
def main(args=None):
    
    parser = ArgumentParser()
    parser.add_argument('-v', '--version',
                        action='version', version=CLI_VERSION)

    parsers = parser.add_subparsers(dest='dtype')

    text.create_arg_parser(parsers.add_parser('text'))
    if image is not None:
        image.create_arg_parser(parsers.add_parser('image'))

    if len(sys.argv if args is None else args) <= 1:
        parser.print_help()
        sys.exit(1)

    args = parser.parse_args(args)
    dtype = globals()[args.dtype]
    try:
        set_args(args)
        cmd = getattr(dtype, 'cmd_' + args.command)
        cmd(args)
    except ValueError as err:
        print(str(err), file=sys.stderr)
        sys.exit(1)