Call this method from your index file. It is the main method of Agile Toolkit.
439120
public function main()
    {
        try {
            // Initialize page and all elements from here
            $this->initLayout();
        } catch (Exception $e) {
            if (!($e instanceof Exception_Stop)) {
                return $this->caughtException($e);
            }
            //$this->caughtException($e);
        }

        try {
            $this->hook('post-init');
            $this->hook('afterInit');

            $this->hook('pre-exec');
            $this->hook('beforeExec');

            if (isset($_GET['submit']) && $_POST) {
                $this->hook('submitted');
            }

            $this->hook('post-submit');
            $this->hook('afterSubmit');

            $this->execute();
        } catch (Exception $e) {
            $this->caughtException($e);
        }
        $this->hook('saveDelayedModels');
    }
828714
public void execute() {
        try {
            new JdbcTemplate(dataSource).execute(readResourceContent(SCHEMA_FILE)); // TODO: sql independence
        } catch (IOException e) {
            throw new RuntimeException("Could not create schema for EDBI Index", e);
        }
    }
588476
def main(self):
        
        # Find the target files
        self.targets()
        # Use bbduk to bait the FASTQ reads matching the target sequences
        self.bait()
        # If desired, use bbduk to bait the target sequences with the previously baited FASTQ files
        if self.revbait:
            self.reversebait()
        # Run the bowtie2 read mapping module
        self.mapping()
        # Use samtools to index the sorted bam file
        self.indexing()
        # Parse the results
        self.parsebam()
858942
def method_missing(method, *args)
      if (i = dimension_method_names.find_index(method))
        define_singleton_method(method) do
          dimensions[i]
        end
        send(method)
      elsif (i = metric_method_names.find_index(method))
        define_singleton_method(method) do
          convert_metric(i)
        end
        send(method)
      else
        super
      end
    end
208682
def main():
    
    parser = __build_option_parser()
    args = parser.parse_args()
    analyze_ws = AnalyzeWS(args)
    try:
        analyze_ws.set_file(args.file_[0])
    except IOError:
        print 'IOError raised while reading file. Exiting!'
        sys.exit(3)

    # Start the chosen mode
    if args.to_file or args.to_browser:
        analyze_ws.to_file_mode()
        if args.to_browser:
            analyze_ws.to_browser_mode()
    else:
        analyze_ws.interactive_mode()
1290510
def run(**kwargs):
    """"""
    paths = kwargs.pop('paths', ())
    action = kwargs.pop('action')
    plugin = kwargs.pop('plugin')
    junit_xml = kwargs.pop('junit_xml')
    use_tracked_files = kwargs.pop('use_tracked_files')
    quiet = kwargs.pop('quiet')

    colorama.init(strip=kwargs.pop('no_color'))

    git_dir = current_git_dir()

    if git_dir is None:
        output(NOT_GIT_REPO_MSG)
        exit(1)

    repo_root = os.path.dirname(git_dir)

    files = []
    if paths:
        # We want to look at files in their current state if paths are passed through
        kwargs['include_unstaged_changes'] = True

        # If paths were provided get all the files for each path
        for path in paths:
            for f in list_files(path):
                f = os.path.relpath(f, repo_root)
                if not f.startswith('..'):  # Don't include files outside the repo root.
                    files.append(f)
    elif use_tracked_files:
        # If the use tracked files flag was passed, get a list of all the tracked files
        out, err, code = git.ls_files()
        files = out.splitlines()

        if kwargs.get('include_untracked'):
            out, err, code = git.ls_files(o=True, exclude_standard=True)
            files += out.splitlines()

    if files or paths:
        kwargs['files'] = files

    config = get_config(repo_root)
    runner = Runner(config.cwd, **kwargs)
    results = ResultCollection()

    if runner.unstaged_changes and not quiet:
        output(UNSTAGED_CHANGES_MSG, end='\n\n')

    processes = list(config.actions) + list(config.plugins)
    processes.sort(key=lambda x: x.name)  # Sort the list of processes for consistent results

    if plugin:
        try:
            processes = [config.plugins.get(plugin)]
        except config.plugins.DoesNotExist as e:
            output('{}\nAvailable plugins:'.format(e.message))

            for p in config.plugins:
                output(p.name)
            exit(1)

    if action:
        try:
            processes = [config.actions.get(action)]
        except config.actions.DoesNotExist as e:
            output('{}\nAvailable actions:'.format(e.message))

            for a in config.actions:
                output(a.name)
            exit(1)

    for process in processes:
        result, message = runner.run_process(process)
        results.append(result)

        if not quiet:
            output(message)

    if junit_xml:
        with open(junit_xml, 'w+') as f:
            f.write('{}'.format(results.dump_junit()))

    if not quiet:
        output(results.dump())
        output('#{{bright}}{}\nCompleted in: {}s'.format(''.ljust(79, '-'), round(results.execution_time, 2)))

    if results.has_error:
        exit(1)
    elif results.has_failure:
        exit(2)
776797
def main():
    """"""

    # Hack to make user code available for import
    sys.path.append(".")

    # Run the specified action
    oz.initialize()
    retr = optfn.run(list(oz._actions.values()))

    if retr == optfn.ERROR_RETURN_CODE:
        sys.exit(-1)
    elif retr == None:
        sys.exit(0)
    elif isinstance(retr, int):
        sys.exit(retr)
    else:
        raise Exception("Unexpected return value from action: %s" % retr)
1028972
def call(self, request):
        
        result = None
        try:
            if 'extAction' in request:  # DirectSubmit method
                tid = request['extTID']
                action = request['extAction']
                method = request['extMethod']
            else:
                tid = request['tid']
                action = request['action']
                method = request['method']
            element = self.configuration[action][method]
            if isinstance(element, tuple):  # class level function
                func = getattr(self.instances[element[0]], element[1])
            else:  # module level function
                func = element
            if func.exposed_kind == BASIC:  # basic method
                args = request['data'] or []
                result = func(*args)
            elif func.exposed_kind == LOAD:  # DirectLoad method
                args = request['data'] or []
                result = {'success': True, 'data': func(*args)}
            elif func.exposed_kind == SUBMIT:  # DirectSubmit method
                kwargs = request
                for k in ['extAction', 'extMethod', 'extType', 'extTID', 'extUpload']:
                    if k in kwargs:
                        del kwargs[k]
                try:
                    func(**kwargs)
                    result = {'success': True}
                except FormError as e:
                    result = e.extra
                    result['success'] = False
                    if e.errors:
                        result['errors'] = e.errors
            elif func.exposed_kind == STORE_READ:  # DirectStore read method
                kwargs = request['data'] or {}
                data = func(**kwargs)
                result = {'total': len(data), 'data': data}
            elif func.exposed_kind == STORE_CUD:  # DirectStore create-update-destroy methods
                kwargs = request['data'][0] or {}
                try:
                    result = {'success': True, 'data': func(**kwargs)}
                except Error:
                    result = {'success': False}
        except Exception as e:
            if self.debug:
                return {'type': 'exception', 'message': str(e), 'where': '%s.%s' % (action, method)}
        return {'type': 'rpc', 'tid': tid, 'action': action, 'method': method, 'result': result}
1291821
public Void call() throws TTException {
        emitStartDocument();

        long[] versionsToUse;

        // if there are no versions specified, take the last one, of not version==0
        if (mVersions.length == 0) {
            if (mSession.getMostRecentVersion() > 0) {
                versionsToUse = new long[] {
                    mSession.getMostRecentVersion()
                };
            }// revision 0 = bootstrapped page
            else {
                versionsToUse = new long[0];
            }
        } // if there is any negative number specified, take the entire range of versions, otherwise take the
          // parameter
        else {
            // sort the versions first
            Arrays.sort(mVersions);
            if (mVersions[0] < 0) {
                versionsToUse = new long[(int)mSession.getMostRecentVersion() - 1];

                for (int i = 0; i < versionsToUse.length; i++) {
                    versionsToUse[i] = i + 1;
                }

            }// otherwise take the versions as requested as params
            else {
                int index = Arrays.binarySearch(mVersions, 1);
                versionsToUse = Arrays.copyOfRange(mVersions, index, mVersions.length);
            }
        }

        for (int i = 0; i < versionsToUse.length; i++) {

            INodeReadTrx rtx = new NodeReadTrx(mSession.beginBucketRtx(versionsToUse[i]));

            if (versionsToUse == null || mVersions.length > 1) {
                emitStartManualElement(i);
            }

            rtx.moveTo(mNodeKey);

            final AbsAxis descAxis = new DescendantAxis(rtx, true);

            // Setup primitives.
            boolean closeElements = false;
            long key = rtx.getNode().getDataKey();

            // Iterate over all nodes of the subtree including self.
            while (descAxis.hasNext()) {
                key = descAxis.next();
                ITreeStructData currentStruc = (ITreeStructData)rtx.getNode();

                // Emit all pending end elements.
                if (closeElements) {
                    while (!mStack.empty() && mStack.peek() != currentStruc.getLeftSiblingKey()) {
                        rtx.moveTo(mStack.pop());
                        emitEndElement(rtx);
                        rtx.moveTo(key);
                    }
                    if (!mStack.empty()) {
                        rtx.moveTo(mStack.pop());
                        emitEndElement(rtx);
                    }
                    rtx.moveTo(key);
                    closeElements = false;
                }
                // Emit node.
                emitStartElement(rtx);
                // Push end element to stack if we are a start element with
                // children.
                if (currentStruc.getKind() == IConstants.ELEMENT && currentStruc.hasFirstChild()) {
                    mStack.push(rtx.getNode().getDataKey());
                }

                // Remember to emit all pending end elements from stack if
                // required.
                if (!currentStruc.hasFirstChild() && !currentStruc.hasRightSibling()) {
                    closeElements = true;
                }

            }

            // Finally emit all pending end elements.
            while (!mStack.empty()) {
                rtx.moveTo(mStack.pop());
                emitEndElement(rtx);
            }

            if (versionsToUse == null || mVersions.length > 1) {
                emitEndManualElement(i);
            }
        }
        emitEndDocument();

        return null;
    }
363138
public static void main(String[] args) {
		final String projectName = "org.eclipse.xtext.common.types";
		
		new StandaloneSetup() {{
			registerProject(new File(".project").getAbsoluteFile());
		}};
		
		new DirectoryCleaner() {{
			setDirectory("../"+projectName+"/emf-gen");
		}}.invoke(null);
		
		
		new EcoreGenerator() {{
			setGenModel("platform:/resource/"+projectName+"/model/JavaVMTypes.genmodel");
			addSrcPath("platform:/resource/"+projectName+"/src");
			setLineDelimiter("\n");
		}}.invoke(null);
	}
1088359
public function main()
    {

        // Set a default fetchmode if none was specified
        // (We're doing that here to prevent errors loading the class is PDO is not available.)
        if ($this->fetchMode === null) {
            $this->fetchMode = PDO::FETCH_ASSOC;
        }

        // Initialize the formatters here.  This ensures that any parameters passed to the formatter
        // element get passed along to the actual formatter object
        foreach ($this->formatters as $fe) {
            $fe->prepare($this->getLocation());
        }

        $savedTransaction = [];
        for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
            $savedTransaction[] = clone $this->transactions[$i];
        }

        $savedSqlCommand = $this->sqlCommand;

        $this->sqlCommand = trim($this->sqlCommand);

        try {
            if ($this->srcFile === null && $this->sqlCommand === ""
                && empty($this->filesets) && empty($this->filelists)
                && count($this->transactions) === 0
            ) {
                throw new BuildException(
                    "Source file or fileset/filelist, "
                    . "transactions or sql statement "
                    . "must be set!",
                    $this->getLocation()
                );
            }

            if ($this->srcFile !== null && !$this->srcFile->exists()) {
                throw new BuildException("Source file does not exist!", $this->getLocation());
            }

            // deal with the filesets
            foreach ($this->filesets as $fs) {
                $ds = $fs->getDirectoryScanner($this->project);
                $srcDir = $fs->getDir($this->project);
                $srcFiles = $ds->getIncludedFiles();
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // process filelists
            foreach ($this->filelists as $fl) {
                $srcDir = $fl->getDir($this->project);
                $srcFiles = $fl->getFiles($this->project);
                // Make a transaction for each file
                foreach ($srcFiles as $srcFile) {
                    $t = $this->createTransaction();
                    $t->setSrc(new PhingFile($srcDir, $srcFile));
                }
            }

            // Make a transaction group for the outer command
            $t = $this->createTransaction();
            if ($this->srcFile) {
                $t->setSrc($this->srcFile);
            }
            $t->addText($this->sqlCommand);
            $this->conn = $this->getConnection();

            try {
                $this->statement = null;

                // Initialize the formatters.
                $this->initFormatters();

                try {
                    // Process all transactions
                    for ($i = 0, $size = count($this->transactions); $i < $size; $i++) {
                        if (!$this->isAutocommit()) {
                            $this->log("Beginning transaction", Project::MSG_VERBOSE);
                            $this->conn->beginTransaction();
                        }
                        $this->transactions[$i]->runTransaction();
                        if (!$this->isAutocommit()) {
                            $this->log("Committing transaction", Project::MSG_VERBOSE);
                            $this->conn->commit();
                        }
                    }
                } catch (Exception $e) {
                    $this->closeConnection();
                    throw $e;
                }
            } catch (IOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            } catch (PDOException $e) {
                if (!$this->isAutocommit() && $this->conn !== null && $this->onError == "abort") {
                    try {
                        $this->conn->rollback();
                    } catch (PDOException $ex) {
                    }
                }
                $this->closeConnection();
                throw new BuildException($e->getMessage(), $this->getLocation());
            }

            // Close the formatters.
            $this->closeFormatters();

            $this->log(
                $this->goodSql . " of " . $this->totalSql .
                " SQL statements executed successfully"
            );
        } catch (Exception $e) {
            $this->transactions = $savedTransaction;
            $this->sqlCommand = $savedSqlCommand;
            $this->closeConnection();
            throw $e;
        }
        // finally {
        $this->transactions = $savedTransaction;
        $this->sqlCommand = $savedSqlCommand;
        $this->closeConnection();
    }
203304
public void init() throws IOException {
        File path = resolveIndexDirectoryPath();
        indexTracker = new IndexTracker(path);
        indexDirectory = FSDirectory.open(path);
        tika = new Tika(null, new HtmlParser());
        Analyzer analyzer = new StandardAnalyzer();
        IndexWriterConfig config = new IndexWriterConfig(Version.LATEST, analyzer);
        writer = new IndexWriter(indexDirectory, config);
    }
134382
def call_arg_index(self):
        """"""
        #The function name we are calling should be in el_name by now
        if self._call_index is None:
            if (self.el_section == "body" and
                self.el_call in [ "sub", "fun" ]):
                #Get hold of the element instance of the function being called so
                #we can examine its parameters.
                fncall = self.el_name
                if fncall in self.current_line[:self.pos[1]]:
                    args = self.current_line[:self.pos[1]].split(fncall)[1]
                else:
                    args = ""

                #This handles the case of the bracket-complete.
                if args == "":
                    return 0
                #The nester requires each start bracket to have an end bracket
                if args[-1] != ")":
                    args += ")"

                #Pyparsing handles calls where functions are being called as
                #the values for parameters like function(a, fun(c,d), r).
                try:
                    nl = cache.nester.parseString(args).asList()[0]
                    clean = [n for n in nl if not isinstance(n, list) and n != ","]
                    #We need to specially handle the case where they have started typing the
                    #name of the first parameter but haven't put a ',' in yet. In that case, 
                    #we are still on the first argument.
                    if clean[-1][-1] != ',':
                        self._call_index = len(clean) - 1
                    else:
                        self._call_index = len(clean)
                except:
                    msg.warn("ARG INDEX: lookup failed on bracket parsing.")
            
        return self._call_index
322540
public function main()
    {
        if ($this->file === null && empty($this->filesets)) {
            throw new BuildException("You must specify a file or fileset(s) for the <ReplaceRegexp> task.");
        }

        // compile a list of all files to modify, both file attrib and fileset elements
        // can be used.
        $files = [];

        if ($this->file !== null) {
            $files[] = $this->file;
        }

        if (!empty($this->filesets)) {
            $filenames = [];
            foreach ($this->filesets as $fs) {
                try {
                    $ds = $fs->getDirectoryScanner($this->project);
                    $filenames = $ds->getIncludedFiles(); // get included filenames
                    $dir = $fs->getDir($this->project);
                    foreach ($filenames as $fname) {
                        $files[] = new PhingFile($dir, $fname);
                    }
                } catch (BuildException $be) {
                    $this->log($be->getMessage(), Project::MSG_WARN);
                }
            }
        }

        $this->log("Applying Regexp processing to " . count($files) . " files.");

        // These "slots" allow filters to retrieve information about the currently-being-process files
        $slot = $this->getRegisterSlot("currentFile");
        $basenameSlot = $this->getRegisterSlot("currentFile.basename");

        $filter = new FilterChain($this->project);

        $r = new ReplaceRegexp();
        $r->setRegexps([$this->_regexp]);

        $filter->addReplaceRegexp($r);
        $filters = [$filter];

        foreach ($files as $file) {
            // set the register slots

            $slot->setValue($file->getPath());
            $basenameSlot->setValue($file->getName());

            // 1) read contents of file, pulling through any filters
            $in = null;
            try {
                $contents = "";
                $in = FileUtils::getChainedReader(new FileReader($file), $filters, $this->project);
                while (-1 !== ($buffer = $in->read())) {
                    $contents .= $buffer;
                }
                $in->close();
            } catch (Exception $e) {
                if ($in) {
                    $in->close();
                }
                $this->log("Error reading file: " . $e->getMessage(), Project::MSG_WARN);
            }

            try {
                // now create a FileWriter w/ the same file, and write to the file
                $out = new FileWriter($file);
                $out->write($contents);
                $out->close();
                $this->log("Applying regexp processing to " . $file->getPath(), Project::MSG_VERBOSE);
            } catch (Exception $e) {
                if ($out) {
                    $out->close();
                }
                $this->log("Error writing file back: " . $e->getMessage(), Project::MSG_WARN);
            }
        }
    }
1344271
def init(force):
    """"""
    click.secho('Creating indexes...', fg='green', bold=True, file=sys.stderr)
    with click.progressbar(
            current_search.create(ignore=[400] if force else None),
            length=current_search.number_of_indexes) as bar:
        for name, response in bar:
            bar.label = name
    click.secho('Putting templates...', fg='green', bold=True, file=sys.stderr)
    with click.progressbar(
            current_search.put_templates(ignore=[400] if force else None),
            length=len(current_search.templates.keys())) as bar:
        for response in bar:
            bar.label = response
1194980
public function main()
    {
        $this->validateAttributes();

        $filesToExtract = [];
        if ($this->file !== null) {
            if ($this->forceExtract || !$this->isDestinationUpToDate($this->file)) {
                $filesToExtract[] = $this->file;
            } else {
                $this->log(
                    'Nothing to do: ' . $this->todir->getAbsolutePath() . ' is up to date for ' . $this->file->getCanonicalPath(),
                    Project::MSG_INFO
                );
            }
        }

        foreach ($this->filesets as $compressedArchiveFileset) {
            $compressedArchiveDirScanner = $compressedArchiveFileset->getDirectoryScanner($this->project);
            $compressedArchiveFiles = $compressedArchiveDirScanner->getIncludedFiles();
            $compressedArchiveDir = $compressedArchiveFileset->getDir($this->project);

            foreach ($compressedArchiveFiles as $compressedArchiveFilePath) {
                $compressedArchiveFile = new PhingFile($compressedArchiveDir, $compressedArchiveFilePath);
                if ($compressedArchiveFile->isDirectory()) {
                    throw new BuildException(
                        $compressedArchiveFile->getAbsolutePath() . ' compressed archive cannot be a directory.'
                    );
                }

                if ($this->forceExtract || !$this->isDestinationUpToDate($compressedArchiveFile)) {
                    $filesToExtract[] = $compressedArchiveFile;
                } else {
                    $this->log(
                        'Nothing to do: ' . $this->todir->getAbsolutePath() . ' is up to date for ' . $compressedArchiveFile->getCanonicalPath(),
                        Project::MSG_INFO
                    );
                }
            }
        }

        foreach ($filesToExtract as $compressedArchiveFile) {
            $this->extractArchive($compressedArchiveFile);
        }
    }
1218927
public function main()
    {

        // Call Phing on the file set with the attribute "phingfile"
        if ($this->phingFile !== null or $this->dir !== null) {
            $this->processFile();
        }

        // if no filesets are given stop here; else process filesets
        if (!empty($this->filesets)) {
            // preserve old settings
            $savedDir = $this->dir;
            $savedPhingFile = $this->phingFile;
            $savedTarget = $this->newTarget;

            // set no specific target for files in filesets
            // [HL] I'm commenting this out; I don't know why this should not be supported!
            // $this->newTarget = null;

            foreach ($this->filesets as $fs) {
                $ds = $fs->getDirectoryScanner($this->project);

                $fromDir = $fs->getDir($this->project);
                $srcFiles = $ds->getIncludedFiles();

                foreach ($srcFiles as $fname) {
                    $f = new PhingFile($ds->getbasedir(), $fname);
                    $f = $f->getAbsoluteFile();
                    $this->phingFile = $f->getAbsolutePath();
                    $this->dir = $f->getParentFile();
                    $this->processFile(); // run Phing!
                }
            }

            // side effect free programming ;-)
            $this->dir = $savedDir;
            $this->phingFile = $savedPhingFile;
            $this->newTarget = $savedTarget;

            // [HL] change back to correct dir
            if ($this->dir !== null) {
                chdir($this->dir->getAbsolutePath());
            }
        }

        // Remove any dangling references to help the GC
        foreach ($this->properties as $property) {
            $property->setFallback(null);
        }
    }