Preliminary HFOS application Launcher
434949
def construct_graph(args):
    """"""

    app = Core(args)

    setup_root(app)

    if args['debug']:
        from circuits import Debugger
        hfoslog("Starting circuits debugger", lvl=warn, emitter='GRAPH')
        dbg = Debugger().register(app)
        # TODO: Make these configurable from modules, navdata is _very_ noisy
        # but should not be listed _here_
        dbg.IgnoreEvents.extend([
            "read", "_read", "write", "_write",
            "stream_success", "stream_complete",
            "serial_packet", "raw_data", "stream",
            "navdatapush", "referenceframe",
            "updateposition", "updatesubscriptions",
            "generatevesseldata", "generatenavdata", "sensordata",
            "reset_flood_offenders", "reset_flood_counters",  # Flood counters
            "task_success", "task_done",  # Thread completion
            "keepalive"  # IRC Gateway
        ])

    hfoslog("Beginning graph assembly.", emitter='GRAPH')

    if args['drawgraph']:
        from circuits.tools import graph

        graph(app)

    if args['opengui']:
        import webbrowser
        # TODO: Fix up that url:
        webbrowser.open("http://%s:%i/" % (args['host'], args['port']))

    hfoslog("Graph assembly done.", emitter='GRAPH')

    return app
850185
public void launchSelendroid() {
    launchServer();
    if (config.isGrid()) {
      // Longer timeout to allow for grid registration
      HttpClientUtil.waitForServer(server.getPort(), 3, TimeUnit.MINUTES);
    } else {
      HttpClientUtil.waitForServer(server.getPort(), 20, TimeUnit.SECONDS);
    }
  }
634624
def main(http_port, peer_name, node_name, app_id):
    
    # Create the framework
    framework = pelix.framework.create_framework(
        ('pelix.ipopo.core',
         'pelix.ipopo.waiting',
         'pelix.shell.core',
         'pelix.shell.ipopo',
         'pelix.shell.console',
         'pelix.http.basic',

         # Herald core
         'herald.core',
         'herald.directory',
         'herald.shell',

         # Herald HTTP
         'herald.transports.http.directory',
         'herald.transports.http.discovery_multicast',
         'herald.transports.http.servlet',
         'herald.transports.http.transport',

         # RPC
         'pelix.remote.dispatcher',
         'pelix.remote.registry',
         'herald.remote.discovery',
         'herald.remote.herald_xmlrpc',),
        {herald.FWPROP_NODE_UID: node_name,
         herald.FWPROP_NODE_NAME: node_name,
         herald.FWPROP_PEER_NAME: peer_name,
         herald.FWPROP_APPLICATION_ID: app_id})

    # Start everything
    framework.start()
    context = framework.get_bundle_context()

    # Instantiate components
    with use_waiting_list(context) as ipopo:
        # ... HTTP server
        ipopo.add(pelix.http.FACTORY_HTTP_BASIC, "http-server",
                  {pelix.http.HTTP_SERVICE_PORT: http_port})

        # ... HTTP reception servlet
        ipopo.add(herald.transports.http.FACTORY_SERVLET,
                  "herald-http-servlet")

        # ... HTTP multicast discovery
        ipopo.add(herald.transports.http.FACTORY_DISCOVERY_MULTICAST,
                  "herald-http-discovery-multicast")

    # Start the framework and wait for it to stop
    framework.wait_for_stop()
979396
def hg_hook(ui, repo, node=None, **kwargs):
    """"""
    seen = set()
    paths = []
    if len(repo):
        for rev in range(repo[node], len(repo)):
            for file_ in repo[rev].files():
                file_ = op.join(repo.root, file_)
                if file_ in seen or not op.exists(file_):
                    continue
                seen.add(file_)
                paths.append(file_)

    options = parse_options()
    setup_logger(options)
    if paths:
        process_paths(options, candidates=paths)
75735
def preflight(self, program, start, stop, resolution=None,
                  max_delay=None):
        """"""
        params = self._get_params(start=start, stop=stop,
                                  resolution=resolution,
                                  maxDelay=max_delay)

        def exec_fn(since=None):
            if since:
                params['start'] = since
            return self._transport.preflight(program, params)

        c = computation.Computation(exec_fn)
        self._computations.add(c)
        return c
1372711
def _mkfs(root, fs_format, fs_opts=None):
    '''
    
    '''
    if fs_opts is None:
        fs_opts = {}

    if fs_format in ('ext2', 'ext3', 'ext4'):
        __salt__['extfs.mkfs'](root, fs_format, **fs_opts)
    elif fs_format in ('btrfs',):
        __salt__['btrfs.mkfs'](root, **fs_opts)
    elif fs_format in ('xfs',):
        __salt__['xfs.mkfs'](root, **fs_opts)
194827
def main(argv=None):
    """"""
    arguments = cli_common(__doc__, argv=argv)
    campaign_file = arguments['CAMPAIGN_FILE']
    if arguments['-g']:
        if osp.exists(campaign_file):
            raise Exception('Campaign file already exists')
        with open(campaign_file, 'w') as ostr:
            Generator().write(ostr)
    else:
        node = arguments.get('-n')
        output_dir = arguments.get('--output-dir')
        exclude_nodes = arguments.get('--exclude-nodes')
        srun_tag = arguments.get('--srun')
        driver = CampaignDriver(
            campaign_file,
            node=node,
            output_dir=output_dir,
            srun=srun_tag,
            exclude_nodes=exclude_nodes,
        )
        driver()
        if argv is not None:
            return driver
        campaign_fd = int(arguments.get('--campaign-path-fd') or 1)
        message = (osp.abspath(driver.campaign_path) + '\n').encode()
        os.write(campaign_fd, message)
1228545
public static void main(String[] args) {
    InstancedConfiguration conf = new InstancedConfiguration(ConfigurationUtils.defaults());
    if (!ConfigurationUtils.masterHostConfigured(conf) && args.length > 0) {
      System.out.println(ConfigurationUtils
          .getMasterHostNotConfiguredMessage("Alluxio fsadmin shell"));
      System.exit(1);
    }
    // Reduce the RPC retry max duration to fall earlier for CLIs
    conf.set(PropertyKey.USER_RPC_RETRY_MAX_DURATION, "5s", Source.DEFAULT);
    FileSystemAdminShell fsAdminShell = new FileSystemAdminShell(conf);
    System.exit(fsAdminShell.run(args));
  }
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)
914573
def main():
    
    p = OptionParser(main.__doc__)

    p.add_option("--format", default=" \'6 qseqid sseqid pident length " \
            "mismatch gapopen qstart qend sstart send evalue bitscore\' ",
            help="0-11, learn more with \"blastp -help\". [default: %default]")
    p.add_option("--path", dest="blast_path", default=None,
            help="specify BLAST+ path including the program name")
    p.add_option("--prog", dest="blast_program", default="blastp",
            help="specify BLAST+ program to use. See complete list here: " \
            "http://www.ncbi.nlm.nih.gov/books/NBK52640/#chapter1.Installation"
            " [default: %default]")
    p.set_align(evalue=.01)
    p.add_option("--best", default=1, type="int",
            help="Only look for best N hits [default: %default]")
    p.set_cpus()
    p.add_option("--nprocs", default=1, type="int",
            help="number of BLAST processes to run in parallel. " + \
            "split query.fa into `nprocs` chunks, " + \
            "each chunk uses -num_threads=`cpus`")
    p.set_params()
    p.set_outfile()
    opts, args = p.parse_args()

    if len(args) != 2 or opts.blast_program is None:
        sys.exit(not p.print_help())

    bfasta_fn, afasta_fn = args
    for fn in (afasta_fn, bfasta_fn):
        assert op.exists(fn)

    afasta_fn = op.abspath(afasta_fn)
    bfasta_fn = op.abspath(bfasta_fn)
    out_fh = must_open(opts.outfile, "w")

    extra = opts.extra
    blast_path = opts.blast_path
    blast_program = opts.blast_program

    blast_bin = blast_path or blast_program
    if op.basename(blast_bin) != blast_program:
        blast_bin = op.join(blast_bin, blast_program)

    nprocs, cpus = opts.nprocs, opts.cpus
    if nprocs > 1:
        logging.debug("Dispatch job to %d processes" % nprocs)
        outdir = "outdir"
        fs = split([afasta_fn, outdir, str(nprocs)])
        queries = fs.names
    else:
        queries = [afasta_fn]

    dbtype = "prot" if op.basename(blast_bin) in ("blastp", "blastx") \
        else "nucl"

    db = bfasta_fn
    if dbtype == "prot":
        nin = db + ".pin"
    else:
        nin = db + ".nin"
        nin00 = db + ".00.nin"
        nin = nin00 if op.exists(nin00) else (db + ".nin")

    run_formatdb(infile=db, outfile=nin, dbtype=dbtype)

    lock = Lock()

    blastplus_template = "{0} -db {1} -outfmt {2}"
    blast_cmd = blastplus_template.format(blast_bin, bfasta_fn, opts.format)
    blast_cmd += " -evalue {0} -max_target_seqs {1}".\
        format(opts.evalue, opts.best)
    blast_cmd += " -num_threads {0}".format(cpus)
    if extra:
        blast_cmd += " " + extra.strip()

    args = [(out_fh, blast_cmd, query, lock) for query in queries]
    g = Jobs(target=blastplus, args=args)
    g.run()
870143
def _mkpart(root, fs_format, fs_opts, mount_dir):
    '''
    
    '''
    __salt__['partition.mklabel'](root, 'msdos')
    loop1 = __salt__['cmd.run']('losetup -f')
    log.debug('First loop device is %s', loop1)
    __salt__['cmd.run']('losetup {0} {1}'.format(loop1, root))
    part_info = __salt__['partition.list'](loop1)
    start = six.text_type(2048 * 2048) + 'B'
    end = part_info['info']['size']
    __salt__['partition.mkpart'](loop1, 'primary', start=start, end=end)
    __salt__['partition.set'](loop1, '1', 'boot', 'on')
    part_info = __salt__['partition.list'](loop1)
    loop2 = __salt__['cmd.run']('losetup -f')
    log.debug('Second loop device is %s', loop2)
    start = start.rstrip('B')
    __salt__['cmd.run']('losetup -o {0} {1} {2}'.format(start, loop2, loop1))
    _mkfs(loop2, fs_format, fs_opts)
    __salt__['mount.mount'](mount_dir, loop2)
    __salt__['cmd.run']((
        'grub-install',
        '--target=i386-pc',
        '--debug',
        '--no-floppy',
        '--modules=part_msdos linux',
        '--boot-directory={0}/boot'.format(mount_dir),
        loop1
    ), python_shell=False)
    __salt__['mount.umount'](mount_dir)
    __salt__['cmd.run']('losetup -d {0}'.format(loop2))
    __salt__['cmd.run']('losetup -d {0}'.format(loop1))
    return part_info
984982
public final void pshufhw(XMMRegister dst, Mem src, Immediate imm8)
  {
    emitX86(INST_PSHUFHW, dst, src, imm8);
  }
731152
def install_provisions(ctx, provision, clear_provisions=False, overwrite=False, list_provisions=False):
    """"""

    log("Installing HFOS default provisions")

    # from hfos.logger import verbosity, events
    # verbosity['console'] = verbosity['global'] = events

    from hfos import database
    database.initialize(ctx.obj['dbhost'], ctx.obj['dbname'])

    from hfos.provisions import build_provision_store

    provision_store = build_provision_store()

    def sort_dependencies(items):
        """Topologically sort the dependency tree"""

        g = networkx.DiGraph()
        log('Sorting dependencies')

        for key, item in items:
            log('key: ', key, 'item:', item, pretty=True, lvl=debug)
            dependencies = item.get('dependencies', [])
            if isinstance(dependencies, str):
                dependencies = [dependencies]

            if key not in g:
                g.add_node(key)

            for link in dependencies:
                g.add_edge(key, link)

        if not networkx.is_directed_acyclic_graph(g):
            log('Cycles in provosioning dependency graph detected!', lvl=error)
            log('Involved provisions:', list(networkx.simple_cycles(g)), lvl=error)

        topology = list(networkx.algorithms.topological_sort(g))
        topology.reverse()

        log(topology, pretty=True)

        return topology

    if list_provisions:
        sort_dependencies(provision_store.items())
        exit()

    def provision_item(item):
        """Provision a single provisioning element"""

        method = item.get('method', provisionList)
        model = item.get('model')
        data = item.get('data')

        method(data, model, overwrite=overwrite, clear=clear_provisions)

    if provision is not None:
        if provision in provision_store:
            log("Provisioning ", provision, pretty=True)
            provision_item(provision_store[provision])
        else:
            log("Unknown provision: ", provision, "\nValid provisions are",
                list(provision_store.keys()),
                lvl=error,
                emitter='MANAGE')
    else:
        for name in sort_dependencies(provision_store.items()):
            log("Provisioning", name, pretty=True)
            provision_item(provision_store[name])

    log("Done: Install Provisions")
392229
function configureLocalBrowsers (config) {
  var isMac = /^darwin/.test(process.platform);
  var isWindows = /^win/.test(process.platform);
  var isLinux = !isMac && !isWindows;

  if (isMac) {
    config.browsers = ['Firefox', 'Chrome', 'Safari'];
  }
  else if (isLinux) {
    config.browsers = ['Firefox', 'ChromeHeadless'];
  }
  else if (isWindows) {
    config.browsers = ['Firefox', 'Chrome', 'IE9', 'IE10', 'IE'];

    // NOTE: IE 6, 7, 8 are not supported by Chai
    config.customLaunchers = {
      IE9: {
        base: 'IE',
        'x-ua-compatible': 'IE=EmulateIE9'
      },
      IE10: {
        base: 'IE',
        'x-ua-compatible': 'IE=EmulateIE10'
      }
    };
  }
}
1180584
function fsSize(callback) {

  return new Promise((resolve) => {
    process.nextTick(() => {
      let data = [];
      if (_linux || _freebsd || _openbsd || _darwin) {
        let cmd = '';
        if (_darwin) cmd = 'df -lkP | grep ^/';
        if (_linux) cmd = 'df -lkPT | grep ^/';
        if (_freebsd || _openbsd) cmd = 'df -lkPT';
        exec(cmd, function (error, stdout) {
          if (!error) {
            let lines = stdout.toString().split('\n');
            //lines.splice(0, 1);
            lines.forEach(function (line) {
              if (line !== '') {
                line = line.replace(/ +/g, ' ').split(' ');
                if (line && (line[0].startsWith('/')) || (line[6] && line[6] === '/')) {
                  data.push({
                    'fs': line[0],
                    'type': ((_linux || _freebsd || _openbsd) ? line[1] : 'HFS'),
                    'size': parseInt(((_linux || _freebsd || _openbsd) ? line[2] : line[1])) * 1024,
                    'used': parseInt(((_linux || _freebsd || _openbsd) ? line[3] : line[2])) * 1024,
                    'use': parseFloat((100.0 * ((_linux || _freebsd || _openbsd) ? line[3] : line[2]) / ((_linux || _freebsd || _openbsd) ? line[2] : line[1])).toFixed(2)),
                    'mount': line[line.length - 1]
                  });
                }
              }
            });
          }
          if (callback) {
            callback(data);
          }
          resolve(data);
        });
      }
      if (_sunos) {
        if (callback) { callback(data); }
        resolve(data);
      }
      if (_windows) {
        try {
          util.wmic('logicaldisk get Caption,FileSystem,FreeSpace,Size').then((stdout, error) => {
            let lines = stdout.split('\r\n').filter(line => line.trim() !== '').filter((line, idx) => idx > 0);
            lines.forEach(function (line) {
              if (line !== '') {
                line = line.trim().split(/\s\s+/);
                data.push({
                  'fs': line[0],
                  'type': line[1],
                  'size': line[3],
                  'used': parseInt(line[3]) - parseInt(line[2]),
                  'use': parseFloat((100.0 * (parseInt(line[3]) - parseInt(line[2]))) / parseInt(line[3])),
                  'mount': line[0]
                });
              }
            });
            if (callback) {
              callback(data);
            }
            resolve(data);
          });
        } catch (e) {
          if (callback) { callback(data); }
          resolve(data);
        }
      }
    });
  });
}
116193
def launch_sub(pos, subtree, opts={})

      i = h.fei.merge(
        'subid' => Ruote.generate_subid(h.fei.inspect),
        'expid' => pos)

      if ci = opts[:child_id]
        i['subid'] = "#{i['subid']}k#{ci}"
      end

      #p '=== launch_sub ==='
      #p [ :launcher, h.fei['expid'], h.fei['subid'], h.fei['wfid'] ]
      #p [ :launched, i['expid'], i['subid'], i['wfid'] ]

      forget = opts[:forget]

      register_child(i) unless forget

      variables = (
        forget ? compile_variables : {}
      ).merge!(opts[:variables] || {})

      @context.storage.put_msg(
        'launch',
        'fei' => i,
        'parent_id' => forget ? nil : h.fei,
        'tree' => subtree,
        'workitem' => opts[:workitem] || h.applied_workitem,
        'variables' => variables,
        'forgotten' => forget)
    end
684148
function App() {
    require('colors');

    /**
     * All of the developer defined middlewares.
     *
     * @var {Array}
     * @protected
     */
    this.__middlewares = [];

    /**
     * The filter instance
     * @var {Object}
     */
    this.filter;

    /**
     * The list of loaded service providers.
     *
     * @var {Object}
     * @protected
     */
    this.__loadedProviders = {};

    /**
     * Indicates if the application has "booted".
     *
     * @var {Boolean}
     * @protected
     */
    this.__booted = false;

    /**
     * The array of booting callbacks.
     *
     * @var {Array}
     * @protected
     */
    this.__bootingCallbacks = [];

    /**
     * The array of booted callbacks.
     *
     * @var {Array}
     * @protected
     */
    this.__bootedCallbacks = [];

    /**
     * Node HTTP server reference.
     *
     * @var {Object}
     * @protected
     */
    this.__server;

    /**
     * The application locals object.
     *
     * @var {Object}
     */
    this.locals = {};

    /**
     * Aliases for internal Positron module
     *
     * @type {Object}
     * @protected
     */
    this.__aliases = {};

    var self = this;

    /**
     * Run the application and send the response.
     *
     * @param  request
     * @param  response
     * @return {void}
     */
    this.run = function (request, response) {
        var reqDomain = domain.create();

        reqDomain
            .on('error', self.handleError.bind(self, request, response))
            .run(function () {
                self.__getStackedClient().handle(request, response);
            });
    };

}