Create a classic control environment with basic set of wrappers
333827
def env_maker(environment_id, seed, serial_id, monitor=False, allow_early_resets=False):
    
    env = gym.make(environment_id)
    env.seed(seed + serial_id)

    # Monitoring the env
    if monitor:
        logdir = logger.get_dir() and os.path.join(logger.get_dir(), str(serial_id))
    else:
        logdir = None

    env = Monitor(env, logdir, allow_early_resets=allow_early_resets)

    return env
782754
def cli(ctx, env):
    """"""

    # Set up the environment
    env = copy.deepcopy(env)
    env.load_modules_from_python(routes.ALL_ROUTES)
    env.aliases.update(routes.ALL_ALIASES)
    env.vars['global_args'] = ctx.parent.params
    env.vars['is_shell'] = True
    env.vars['last_exit_code'] = 0

    # Set up prompt_toolkit settings
    app_path = click.get_app_dir('softlayer_shell')
    if not os.path.exists(app_path):
        os.makedirs(app_path)
    complete = completer.ShellCompleter(core.cli)

    while True:
        try:
            line = p_shortcuts.prompt(
                completer=complete,
                complete_while_typing=True,
                auto_suggest=p_auto_suggest.AutoSuggestFromHistory(),
            )

            # Parse arguments
            try:
                args = shlex.split(line)
            except ValueError as ex:
                print("Invalid Command: %s" % ex)
                continue

            if not args:
                continue

            # Run Command
            try:
                # Reset client so that the client gets refreshed
                env.client = None
                core.main(args=list(get_env_args(env)) + args,
                          obj=env,
                          prog_name="",
                          reraise_exceptions=True)
            except SystemExit as ex:
                env.vars['last_exit_code'] = ex.code
            except EOFError:
                return
            except ShellExit:
                return
            except Exception as ex:
                env.vars['last_exit_code'] = 1
                traceback.print_exc(file=sys.stderr)

        except KeyboardInterrupt:
            env.vars['last_exit_code'] = 130
962121
function rc(options, callback) {
  if(typeof options === 'function') {
    callback = options;
    options = null;
  }
  var r = new RunControl(options);
  if(typeof callback === 'function') r.load(callback);
  return r;
}
965960
def main(args=sys.argv[1:]):
    
    parser = argparse.ArgumentParser(description="""Aggregate results of
            nestly runs""")
    subparsers = parser.add_subparsers()
    delim_parser = subparsers.add_parser('delim', help="""Combine control files
            with delimited files.""")
    delim_parser.set_defaults(func=delim)
    key_group = delim_parser.add_mutually_exclusive_group()
    key_group.add_argument('-k', '--keys', help="""Comma separated list of
            keys from the JSON file to include [default: all keys]""",
            type=comma_separated_values)
    key_group.add_argument('-x', '--exclude-keys', help="""Comma separated
            list of keys from the JSON file not to include [default:
            %(default)s]""", type=comma_separated_values)
    delim_parser.add_argument('-m', '--missing-action', choices=('fail',
        'warn'), help="""Action to take when a file is missing [default:
        %(default)s]""", default='fail')
    delim_parser.add_argument('file_template', help="""Template for the
            delimited file to read in each directory [e.g. '{run_id}.csv']""")
    delim_parser.add_argument('control_files', metavar="control.json",
            help="""Control files""", nargs="*")
    delim_parser.add_argument('-d', '--directory', help="""Run on all control
            files under %(metavar)s. May be used in place of specifying control
            files.""", metavar='DIR')
    delim_parser.add_argument('-s', '--separator', default=DEFAULT_SEP,
            help="""Separator [default: %(default)s]""")
    delim_parser.add_argument('-t', '--tab', action='store_const',
            dest='separator', const='\t', help="""Files are tab-separated""")
    delim_parser.add_argument('-o', '--output', default=sys.stdout,
        type=argparse.FileType('w'), help="""Output file [default: stdout]""")

    arguments = parser.parse_args()

    arguments.func(arguments)
1036191
def generate(env):
    """"""
    SCons.Tool.createStaticLibBuilder(env)
    SCons.Tool.createSharedLibBuilder(env)
    SCons.Tool.createProgBuilder(env)

    env['AR'] = 'mwld'
    env['ARCOM'] = '$AR $ARFLAGS -library -o $TARGET $SOURCES'

    env['LIBDIRPREFIX'] = '-L'
    env['LIBDIRSUFFIX'] = ''
    env['LIBLINKPREFIX'] = '-l'
    env['LIBLINKSUFFIX'] = '.lib'

    env['LINK'] = 'mwld'
    env['LINKCOM'] = '$LINK $LINKFLAGS -o $TARGET $SOURCES $_LIBDIRFLAGS $_LIBFLAGS'

    env['SHLINK'] = '$LINK'
    env['SHLINKFLAGS'] = '$LINKFLAGS'
    env['SHLINKCOM']   = shlib_action
    env['SHLIBEMITTER']= shlib_emitter
    env['LDMODULEEMITTER']= shlib_emitter
711579
def generate(env):
    """"""

    if 'CC' not in env:
        env['CC'] = env.Detect(compilers) or compilers[0]

    cc.generate(env)

    if env['PLATFORM'] in ['cygwin', 'win32']:
        env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS')
    else:
        env['SHCCFLAGS'] = SCons.Util.CLVar('$CCFLAGS -fPIC')
    # determine compiler version
    version = detect_version(env, env['CC'])
    if version:
        env['CCVERSION'] = version
296666
function(command) {
            var self    = this,
                control = null,
                output  = new mixitup.CommandMultimix(),
                i       = -1;

            self.callActions('beforeUpdateControls', arguments);

            // Sanitise to defaults

            if (command.filter) {
                output.filter = command.filter.selector;
            } else {
                output.filter = self.state.activeFilter.selector;
            }

            if (command.sort) {
                output.sort = self.buildSortString(command.sort);
            } else {
                output.sort = self.buildSortString(self.state.activeSort);
            }

            if (output.filter === self.config.selectors.target) {
                output.filter = 'all';
            }

            if (output.filter === '') {
                output.filter = 'none';
            }

            h.freeze(output);

            for (i = 0; control = self.controls[i]; i++) {
                control.update(output, self.toggleArray);
            }

            self.callActions('afterUpdateControls', arguments);
        }
701548
def main():
    

    scheme_names = sorted(six.iterkeys(SCHEME))
    version_str = pkg_resources.get_distribution('ansi2html').version
    parser = optparse.OptionParser(
        usage=main.__doc__,
        version="%%prog %s" % version_str)
    parser.add_option(
        "-p", "--partial", dest="partial",
        default=False, action="store_true",
        help="Process lines as them come in.  No headers are produced.")
    parser.add_option(
        "-L", "--latex", dest="latex",
        default=False, action="store_true",
        help="Export as LaTeX instead of HTML.")
    parser.add_option(
        "-i", "--inline", dest="inline",
        default=False, action="store_true",
        help="Inline style without headers or template.")
    parser.add_option(
        "-H", "--headers", dest="headers",
        default=False, action="store_true",
        help="Just produce the <style> tag.")
    parser.add_option(
        "-f", '--font-size', dest='font_size', metavar='SIZE',
        default="normal",
        help="Set the global font size in the output.")
    parser.add_option(
        "-l", '--light-background', dest='light_background',
        default=False, action="store_true",
        help="Set output to 'light background' mode.")
    parser.add_option(
        "-W", '--no-line-wrap', dest='no_line_wrap',
        default=False, action="store_true",
        help="Disable line wrapping.")
    parser.add_option(
        "-a", '--linkify', dest='linkify',
        default=False, action="store_true",
        help="Transform URLs into <a> links.")
    parser.add_option(
        "-u", '--unescape', dest='escaped',
        default=True, action="store_false",
        help="Do not escape XML tags found in the input.")
    parser.add_option(
        "-m", '--markup-lines', dest="markup_lines",
        default=False, action="store_true",
        help="Surround lines with <span id='line-n'>..</span>.")
    parser.add_option(
        '--input-encoding', dest='input_encoding', metavar='ENCODING',
        default='utf-8',
        help="Specify input encoding")
    parser.add_option(
        '--output-encoding', dest='output_encoding', metavar='ENCODING',
        default='utf-8',
        help="Specify output encoding")
    parser.add_option(
        '-s', '--scheme', dest='scheme', metavar='SCHEME',
        default='ansi2html', choices=scheme_names,
        help=("Specify color palette scheme. Default: %%default. Choices: %s"
              % scheme_names))
    parser.add_option(
        '-t', '--title', dest='output_title',
        default='',
        help="Specify output title")

    opts, args = parser.parse_args()

    conv = Ansi2HTMLConverter(
        latex=opts.latex,
        inline=opts.inline,
        dark_bg=not opts.light_background,
        line_wrap=not opts.no_line_wrap,
        font_size=opts.font_size,
        linkify=opts.linkify,
        escaped=opts.escaped,
        markup_lines=opts.markup_lines,
        output_encoding=opts.output_encoding,
        scheme=opts.scheme,
        title=opts.output_title,
    )

    if six.PY3:
        try:
            sys.stdin = io.TextIOWrapper(sys.stdin.detach(), opts.input_encoding, "replace")
        except io.UnsupportedOperation:
            # This only fails in the test suite...
            pass

    def _read(input_bytes):
        if six.PY3:
            return input_bytes
        else:
            return input_bytes.decode(opts.input_encoding)

    def _print(output_unicode, end='\n'):
        if hasattr(sys.stdout, 'buffer'):
            output_bytes = (output_unicode + end).encode(opts.output_encoding)
            sys.stdout.buffer.write(output_bytes)
        elif not six.PY3:
            sys.stdout.write((output_unicode + end).encode(opts.output_encoding))
        else:
            sys.stdout.write(output_unicode + end)

    # Produce only the headers and quit
    if opts.headers:
        _print(conv.produce_headers(), end='')
        return

    full = not bool(opts.partial or opts.inline)
    if six.PY3:
        output = conv.convert("".join(sys.stdin.readlines()), full=full, ensure_trailing_newline=True)
        _print(output, end='')
    else:
        output = conv.convert(six.u("").join(
            map(_read, sys.stdin.readlines())
        ), full=full, ensure_trailing_newline=True)
        _print(output, end='')
1291432
def main(arguments=None):
    
    # setup the command-line util settings
    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="sloancone",
        tunnel=False
    )
    arguments, settings, log, dbConn = su.setup()

    # tab completion for raw_input
    readline.set_completer_delims(' \t\n;')
    readline.parse_and_bind("tab: complete")
    readline.set_completer(tab_complete)

    # unpack remaining cl arguments using `exec` to setup the variable names
    # automatically
    for arg, val in arguments.iteritems():
        if arg[0] == "-":
            varname = arg.replace("-", "") + "Flag"
        else:
            varname = arg.replace("<", "").replace(">", "")
        if isinstance(val, str) or isinstance(val, unicode):
            exec(varname + " = '%s'" % (val,))
        else:
            exec(varname + " = %s" % (val,))
        if arg == "--dbConn":
            dbConn = val
        log.debug('%s = %s' % (varname, val,))

    ## START LOGGING ##
    startTime = times.get_now_sql_datetime()
    log.info(
        '--- STARTING TO RUN THE cl_utils.py AT %s' %
        (startTime,))

    # set options interactively if user requests
    if "interactiveFlag" in locals() and interactiveFlag:

        # load previous settings
        moduleDirectory = os.path.dirname(__file__) + "/resources"
        pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
        try:
            with open(pathToPickleFile):
                pass
            previousSettingsExist = True
        except:
            previousSettingsExist = False
        previousSettings = {}
        if previousSettingsExist:
            previousSettings = pickle.load(open(pathToPickleFile, "rb"))

        # x-raw-input
        # x-boolean-raw-input
        # x-raw-input-with-default-value-from-previous-settings

        # save the most recently used requests
        pickleMeObjects = []
        pickleMe = {}
        theseLocals = locals()
        for k in pickleMeObjects:
            pickleMe[k] = theseLocals[k]
        pickle.dump(pickleMe, open(pathToPickleFile, "wb"))

    # CALL FUNCTIONS/OBJECTS

    if "dbConn" in locals() and dbConn:
        dbConn.commit()
        dbConn.close()
    ## FINISH LOGGING ##
    endTime = times.get_now_sql_datetime()
    runningTime = times.calculate_time_difference(startTime, endTime)
    log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
             (endTime, runningTime, ))

    return
1298667
def execution_environment():
    """"""
    context = {}
    context['conf'] = config()
    if relation_id():
        context['reltype'] = relation_type()
        context['relid'] = relation_id()
        context['rel'] = relation_get()
    context['unit'] = local_unit()
    context['rels'] = relations()
    context['env'] = os.environ
    return context
616756
def main(args=None):
    
    cfg.configureLogger()
    wireHandlers(cfg)
    # get config from a flask standard place not our config yml
    app.run(debug=cfg.runInDebug(), host='0.0.0.0', port=cfg.getPort())
1184988
def generate(env):
    """"""
    cplusplus.generate(env)

    if acc:
        env['CXX']        = acc or 'aCC'
        env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z')
        # determine version of aCC
        line = os.popen(acc + ' -V 2>&1').readline().rstrip()
        if line.find('aCC: HP ANSI C++') == 0:
            env['CXXVERSION'] = line.split()[-1]

        if env['PLATFORM'] == 'cygwin':
            env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS')
        else:
            env['SHCXXFLAGS'] = SCons.Util.CLVar('$CXXFLAGS +Z')
79178
function() {
      // apply controller styles, but only if they are not yet applied
      var scope = this.findStyleScope();
      if (scope && !this.scopeHasNamedStyle(scope, this.localName)) {
        // allow inherited controller styles
        var proto = getPrototypeOf(this), cssText = '';
        while (proto && proto.element) {
          cssText += proto.element.cssTextForScope(STYLE_CONTROLLER_SCOPE);
          proto = getPrototypeOf(proto);
        }
        if (cssText) {
          this.installScopeCssText(cssText, scope);
        }
      }
    }
277424
def init(ciprcfg, env, console):
    
    ciprcfg.create()

    templ_dir = path.join(env.skel_dir, 'default')

    console.quiet('Copying files from %s' % templ_dir)
    for src, dst in util.sync_dir_to(templ_dir, env.project_directory, ignore_existing=True):
        console.quiet('  %s -> %s' % (src, dst))

    src = path.join(env.code_dir, 'cipr.dev.lua')
    dst = path.join(env.project_directory, 'cipr.lua')
    console.quiet('  %s -> %s' % (src, dst))

    shutil.copy(src, dst)
173284
def make_control_flow_handlers(self, cont_n, status_n, expected_return,
                                   has_cont, has_break):
        '''
        
        '''
        if expected_return:
            assign = cont_ass = [ast.Assign(
                [ast.Tuple(expected_return, ast.Store())],
                ast.Name(cont_n, ast.Load(), None))]
        else:
            assign = cont_ass = []

        if has_cont:
            cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
                               [ast.Eq()], [ast.Num(LOOP_CONT)])
            cont_ass = [ast.If(cmpr,
                               deepcopy(assign) + [ast.Continue()],
                               cont_ass)]
        if has_break:
            cmpr = ast.Compare(ast.Name(status_n, ast.Load(), None),
                               [ast.Eq()], [ast.Num(LOOP_BREAK)])
            cont_ass = [ast.If(cmpr,
                               deepcopy(assign) + [ast.Break()],
                               cont_ass)]
        return cont_ass
1343625
def make_app(env, commandadapter=None):
    
    mconfig = import_module('app.config.%s' % env, pass_errors=True)
    if mconfig is None and paths.app_exists():
        print(colored('Configuration for "%s" environment is not found' % env, 'red'))
        return None
    mstart = import_module('app.start')
    mroutes = import_module('app.routes')
    mcontrollers = import_module('app.controllers')
    before = mstart.before

    return Glim(commandadapter, mconfig, mroutes, mcontrollers, env, before)
33203
def load_basic_system_bindings():
    
    registry = Registry()

    suspend_supported = Condition(
        lambda cli: suspend_to_background_supported())

    @registry.add_binding(Keys.ControlZ, filter=suspend_supported)
    def _(event):
        """
        Suspend process to background.
        """
        event.cli.suspend_to_background()

    return registry