Basic implementation
356776
function sanicJoin(array, separator = ',') {
    if (!(array instanceof Array)){
        throw new TypeError('array is not an Array');
    }

    if (!array.length){
        return '';
    }

    if (array.length === 1){
        return array[0];
    }

    let res = String(array[0]), i = 1;
    const iMax = array.length;

    for (; i < iMax; i++){
        res += separator + array[i];
    }

    return res;
}
131306
public function main()
    {
        $this->validate();
        $this->datetimeTaskStart = new \DateTimeImmutable();

        if ($this->describeMainStack()) {
            $this->updateStacks();
        } else {
            $this->creationStacks();
        }

        while (!$this->stackIsReady()) {
            sleep(3);
            if (empty($this->events)) {
                $this->log("Waiting for stack provisioning...");
            }
        }

        $stacks = $this->describeMainStack($e);

        if (null === $stacks) {
            throw $e;
        }

        $outputLog = '';

        if ($stacks[0]['Outputs']) {
            foreach ($stacks[0]['Outputs'] as $row) {
                $outputLog .= PHP_EOL . $row['OutputKey'] . ': ' . $row['OutputValue'];
                if ($output = $this->getOutput($row['OutputKey'])) {
                    /** @var StackOutput $output */
                    $this->project->setProperty($output->getProperty(), $row['OutputValue']);
                }
            }
        }

        $this->log($outputLog);
    }
1304890
def main():
    
    t, kf, t0, major, minor, prod, beta = sympy.symbols(
        't k_f t0 Y Z X beta', negative=False)
    for f in funcs:
        args = [t, kf, prod, major, minor]
        if f in (pseudo_rev, binary_rev):
            args.insert(2, kf/beta)
        expr = f(*args, backend='sympy')
        with open(f.__name__ + '.png', 'wb') as ofh:
            sympy.printing.preview(expr, output='png', filename='out.png',
                                   viewer='BytesIO', outputbuffer=ofh)
        with open(f.__name__ + '_diff.png', 'wb') as ofh:
            sympy.printing.preview(expr.diff(t).subs({t0: 0}).simplify(),
                                   output='png', filename='out.png',
                                   viewer='BytesIO', outputbuffer=ofh)
593069
function main() {
	var len;
	var min;
	var max;
	var f;
	var i;

	min = 1; // 10^min
	max = 6; // 10^max

	for ( i = min; i <= max; i++ ) {
		len = pow( 10, i );
		f = createBenchmark( len );
		bench( pkg+':len='+len, f );
	}
}
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();
    }
725450
function init(entry, target, command, data) {  // {{{2
/**
 * Socket constructor
 *
 * @param entry {Object} Source entry
 * @param target {Number|String|Object} Target entry identification
 * @param command {String} Command name
 * @param [data] {*} Optional data
 *
 * @method constructor
 */

  this.entry = entry;
  this.command = command;
  this.target = target;

  this.data = data || {};
  if (! this.data.entry) {
    this.data.entry = entry.getIdent();
  }
  if (! this.data.caption) {
    this.data.caption = entry.getCaption();
  }

  switch (typeof target) {
  case 'number':
  case 'string':
    this.shard = entry.shard;
    this.targetId = target;
    return connect(this);
  case 'object':
    return connect(this);
  }

  throw O.log.error(entry, 'INVALID_ARGS', arguments);
}
506996
def main():
    

    logging.basicConfig(level=logging.INFO)

    example_sync_client(SyncAPIClient())
    example_async_client(AsyncAPIClient())

    io_loop = ioloop.IOLoop.current()
    io_loop.start()
681397
function (out) {
            out.newBlock("main", 0);
            out.newBlock("classDefinition", 0);
            out.newBlock("prototype", 2);
            out.newBlock("globalVars", 5);
            out.newBlock("initTemplate", 3);
            out.newBlock("classInit", 3);
        }
677166
def main():

    ''' '''

    f = FSM ('INIT', [])
    f.set_default_transition (Error, 'INIT')
    f.add_transition_any  ('INIT', None, 'INIT')
    f.add_transition      ('=',               'INIT',            DoEqual,          'INIT')
    f.add_transition_list (string.digits,     'INIT',            BeginBuildNumber, 'BUILDING_NUMBER')
    f.add_transition_list (string.digits,     'BUILDING_NUMBER', BuildNumber,      'BUILDING_NUMBER')
    f.add_transition_list (string.whitespace, 'BUILDING_NUMBER', EndBuildNumber,   'INIT')
    f.add_transition_list ('+-*/',            'INIT',            DoOperator,       'INIT')

    print()
    print('Enter an RPN Expression.')
    print('Numbers may be integers. Operators are * / + -')
    print('Use the = sign to evaluate and print the expression.')
    print('For example: ')
    print('    167 3 2 2 * * * 1 - =')
    inputstr = (input if PY3 else raw_input)('> ')  # analysis:ignore
    f.process_list(inputstr)
1128929
function addBasicInfoWrapper(basicInfo) {
    Yamaha.prototype[basicInfo] = function(zone) {
        return this.getBasicInfo(zone).then(function(result) {
            return result[basicInfo]();
        });
    };
}
917635
function main()
    {
        $lem = new PHP_ParserGenerator_Data;

        $this->OptInit($_SERVER['argv']);
        if ($this->_version) {
            echo "Lemon version 1.0/PHP_ParserGenerator port version @package_version@\n";
            //exit(0); 
            return;
        }
        if ($this->OptNArgs($_SERVER['argv']) != 1) {
            echo "Exactly one filename argument is required.\n";
            //exit(1);
            return;
        }
        $lem->errorcnt = 0;
        $lem->parser_template = $this->_parser_template;

        /* Initialize the machine */
        $lem->argv0 = $_SERVER['argv'][0];
        $lem->filename = $this->_optArg(0, $_SERVER['argv']);
        $a = pathinfo($lem->filename);
        if (isset($a['extension'])) {
            $ext = '.' . $a['extension'];
            $lem->filenosuffix = substr($lem->filename, 0, strlen($lem->filename) - strlen($ext));
        } else {
            $lem->filenosuffix = $lem->filename;
        }
        $lem->basisflag = $this->_basisflag;
        $lem->has_fallback = 0;
        $lem->nconflict = 0;
        $lem->name = $lem->include_code = $lem->include_classcode = $lem->arg = $lem->tokentype = $lem->start = 0;
        $lem->vartype = 0;
        $lem->stacksize = 0;
        $lem->error = $lem->overflow = $lem->failure = $lem->accept = $lem->tokendest = $lem->tokenprefix = $lem->outname = $lem->extracode = 0;
        $lem->vardest = 0;
        $lem->tablesize = 0;
        PHP_ParserGenerator_Symbol::Symbol_new("$");
        $lem->errsym = PHP_ParserGenerator_Symbol::Symbol_new("error");

        /* Parse the input file */
        $parser = new PHP_ParserGenerator_Parser($this);
        $parser->Parse($lem);
        if ($lem->errorcnt) {
            return;
            // exit($lem->errorcnt);
        }
        if ($lem->rule === 0) {
            printf("Empty grammar.\n");
            return;
            //exit(1);
        }

        /* Count and index the symbols of the grammar */
        $lem->nsymbol = PHP_ParserGenerator_Symbol::Symbol_count();
        PHP_ParserGenerator_Symbol::Symbol_new("{default}");
        $lem->symbols = PHP_ParserGenerator_Symbol::Symbol_arrayof();
        for ($i = 0; $i <= $lem->nsymbol; $i++) {
            $lem->symbols[$i]->index = $i;
        }
        usort($lem->symbols, array('PHP_ParserGenerator_Symbol', 'sortSymbols'));
        for ($i = 0; $i <= $lem->nsymbol; $i++) {
            $lem->symbols[$i]->index = $i;
        }
        // find the first lower-case symbol
        for ($i = 1; ord($lem->symbols[$i]->name[0]) <= ord('Z'); $i++);
        $lem->nterminal = $i;

        /* Generate a reprint of the grammar, if requested on the command line */
        if ($this->_rpflag) {
            $this->Reprint();
        } else {
            /* Initialize the size for all follow and first sets */
            $this->SetSize($lem->nterminal);

            /* Find the precedence for every production rule (that has one) */
            $lem->FindRulePrecedences();

            /* Compute the lambda-nonterminals and the first-sets for every
            ** nonterminal */
            $lem->FindFirstSets();

            /* Compute all LR(0) states.  Also record follow-set propagation
            ** links so that the follow-set can be computed later */
            $lem->nstate = 0;
            $lem->FindStates();
            $lem->sorted = PHP_ParserGenerator_State::State_arrayof();

            /* Tie up loose ends on the propagation links */
            $lem->FindLinks();

            /* Compute the follow set of every reducible configuration */
            $lem->FindFollowSets();

            /* Compute the action tables */
            $lem->FindActions();

            /* Compress the action tables */
            if ($this->_compress===0) {
                $lem->CompressTables();
            }

            /* Reorder and renumber the states so that states with fewer choices
            ** occur at the end. */
            $lem->ResortStates();

            /* Generate a report of the parser generated.  (the "y.output" file) */
            if (!$this->_quiet) {
                $lem->ReportOutput();
            }

            /* Generate the source code for the parser */
            $lem->ReportTable($this->_mhflag);

            /* Produce a header file for use by the scanner.  (This step is
            ** omitted if the "-m" option is used because makeheaders will
            ** generate the file for us.) */
            //if (!$this->_mhflag) {
            //    $this->ReportHeader();
            //}
        }
        if ($this->_statistics) {
            printf(
                "Parser statistics: %d terminals, %d nonterminals, %d rules\n",
                $lem->nterminal,
                $lem->nsymbol - $lem->nterminal,
                $lem->nrule
            );
            printf(
                "                   %d states, %d parser table entries, %d conflicts\n",
                $lem->nstate,
                $lem->tablesize,
                $lem->nconflict
            );
        }
        if ($lem->nconflict) {
            printf("%d parsing conflicts.\n", $lem->nconflict);
        }
        //exit($lem->errorcnt + $lem->nconflict);
        echo $lem->errorcnt + $lem->nconflict;
        return ($lem->errorcnt + $lem->nconflict);
    }
1265364
def main():
    """"""
    from docopt import docopt; arguments = docopt(__doc__, version=package.title() + " v" + version)
    global verbose
    verbose = arguments['--verbose']

    if verbose:
	print("target folder: " + target_folder + " (" + project_path +"/" + target_folder + ")")

    if arguments['init']:
	init_current_directory()

    if arguments['build']:
	if arguments['<file>']:
	    buildFile(arguments['<file>'])
	else:
	    buildAll()

    if arguments['watch']:
	if verbose:
	    print("Watching " + project_path)
        import time
	from watchdog.observers import Observer
	event_handler = MyWatchHandler()
	observer = Observer()
	observer.schedule(event_handler, project_path, recursive=True)
	observer.start()
	try:
	    while True:
	        time.sleep(1)
	except KeyboardInterrupt:
	    observer.stop()
	observer.join()

    if arguments['clean']:
	clean()
165371
def main():
    ''''''
    args = docopt(__doc__, version=__version__)

    if 'bam_coverage' in args:
        bam_coverage(args['<reference>'],
                     args['<alignments>'],
                     int(args['<minmatch>']),
                     min_mapq=int(args['--mapq']),
                     min_len=float(args['--minlen']))
1189245
def main():
    
    startLogging(stdout)
    checker = InMemoryUsernamePasswordDatabaseDontUse()
    checker.addUser("testuser", "examplepass")
    realm = AdditionRealm()
    factory = CredAMPServerFactory(Portal(realm, [checker]))
    reactor.listenTCP(7805, factory)
    reactor.run()
690739
function main() {

    var database = fs.createWriteStream('./lib/database-min.js', { flags: 'w', encoding: 'utf8' });
    var testFile;

    fs.mkdir('./data', 493, function (error) {  // 493 == 0755 (no octal in strict mode.)
        // ignore errors.
    });
    
    database.write("// Do not edit this file, your changes will be lost.\n");
    database.write("module.exports = { \n");
    getJSON('http://alscan.info/agent_groups/groups.json', function (groups) {
        var s = JSON.stringify(groups);
        database.write("groups:" + s + ",\n");
        testFile = fs.createWriteStream('./data/groups.json', { flags: 'w', encoding: 'utf8' });
        testFile.write(s+"\n");
        testFile.end();
        getJSON('http://alscan.info/agent_sources/sources.json', function (sources) {
            var s = JSON.stringify(sources);
            database.write("sources:" + s + ",\n");
            testFile = fs.createWriteStream('./data/sources.json', { flags: 'w', encoding: 'utf8' });
            testFile.write(s+"\n");
            testFile.end();
            getJSON('http://alscan.info/patterns/patterns.json', function (patterns) {
                database.write("patterns:[\n");
                patterns.forEach(function (pattern) {
                    database.write("{p: new RegExp('" + pattern.pattern + "'), x:" + 
                            agentdb.getX(pattern.groupId, pattern.sourceId) + "},");
                });
                database.write("],\n");
                testFile = fs.createWriteStream('./data/patterns.json', { flags: 'w', encoding: 'utf8' });
                testFile.write(JSON.stringify(patterns)+"\n");
                testFile.end();
                getJSON('http://alscan.info/agents/agents.json', function (agents) {
                    var hash = new HashTable(HASH_TABLE_SIZE, HASH_TABLE_SEED, HASH_TABLE_MULTIPLIER);
                    agents.forEach(function (agent) {
                        if (agent.status < 2) {
                            var obj = { a: agent.agent, x: agentdb.getX(agent.groupId, agent.sourceId) };
                            hash.add('a', obj);
                        }
                    });
                    database.write("table:" + JSON.stringify(hash.table) + ",\n");
                    database.write("HASH_TABLE_SIZE:" + HASH_TABLE_SIZE + ",\n");
                    database.write("HASH_TABLE_SEED:" + HASH_TABLE_SEED + ",\n");
                    database.write("HASH_TABLE_MULTIPLIER:" + HASH_TABLE_MULTIPLIER + ",\n");
                    database.write("hash: undefined\n}\n");
                    testFile = fs.createWriteStream('./data/agents.json', { flags: 'w', encoding: 'utf8' });
                    testFile.write(JSON.stringify(agents)+"\n");
                    testFile.end();
                    if (debug) {
                        var history = hash.getHistory();
                        console.log("Hash table history");
                        for (var n=0; n < history.length; n++) {
                            console.log("  Depth=" + n + ", count=" + history[n] + ", percent=" + (history[n] / HASH_TABLE_SIZE));
                        }
                    }
                });
            });
        });
    });
}
875269
def main():
    
    # Parse arguments
    parser = argparse.ArgumentParser(description="Convert rational numbers between bases.")
    parser.add_argument("-n", "--number", default=None,
                        help="The number to convert as a string, else stdin used.")
    parser.add_argument("-i", "--input-base", default=10,
                        help="The input base (default 10).")
    parser.add_argument("-o", "--output-base", default=10,
                        help="The output base (default 10).")
    parser.add_argument("-d", "--max_depth", default=10, type=int,
                        help="The maximum fractional digits (default 10).")
    parser.add_argument("-r", "--recurring", default=True, type=bool,
                        help="Boolean, if True will attempt to find recurring decimals (default True).")
    parser.add_argument("-s", "--string", type=bool,
                        help="Boolean, if True will output number as String, else as tuple (default False).")
    args = parser.parse_args()

    args.input_base = float(args.input_base)
    args.output_base = float(args.output_base)
    if args.input_base == int(args.input_base):
        args.input_base = int(args.input_base)
    if args.output_base == int(args.output_base):
        args.output_base = int(args.output_base)
    if (args.number):
        return base(args.number, args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    elif not sys.stdin.isatty():
        return base(sys.stdin.read().strip(), args.input_base, args.output_base, string=args.string, max_depth=args.max_depth, recurring=args.recurring)
    else:
        raise ValueError("Please input a number!")
621121
public function main() {
    $this->validate();

    $this->callee->setTarget($this->target);
    $this->callee->setInheritAll(true);
    $this->callee->setInheritRefs(true);

    // Extract matching keys from the properties array.
    $keys = [];
    $project = $this->getProject();
    foreach ($project->getProperties() as $name => $value) {
      if (strpos($name, $this->prefix) === 0) {
        $property_children = substr($name, strlen($this->prefix));
        list($key, $property_grandchildren) = explode('.', $property_children, 2);
        $keys[$key] = $key;
      }
    }

    // Remove keys based on the 'omitKeys' attribute.
    $keys = array_diff($keys, $this->omitKeys);

    // Iterate over each extracted key.
    foreach ($keys as $key => $prefix) {
      $prop = $this->callee->createProperty();
      $prop->setOverride(true);
      $prop->setName($this->keyParam);
      $prop->setValue($key);

      $prop = $this->callee->createProperty();
      $prop->setOverride(true);
      $prop->setName($this->prefixParam);
      $prop->setValue($this->prefix);

      $this->callee->main();
    }
  }