Main FHapi constructor function..
505594
function FHapi(cfg) {

  var api = {
    getVersion: function() {
      //Getting The Version of fh-mbaas-api
      return packageJSON.version;
    },
    cache: require('./cache')(cfg),
    db: require('./db')(cfg),
    events: new EventEmitter(),
    forms: require('./forms')(cfg),
    log: false,
    stringify: false,
    parse: false,
    push: require('./push')(cfg),
    call: require('./call')(cfg),
    util: false,
    redisPort: cfg.redis.port || '6379',
    redisHost: cfg.redis.host || 'localhost',
    session: require('./session')(cfg),
    stats: require('./stats')(cfg),
    sync: sync,
    act: require('./act')(cfg),
    service: require('./act')(cfg),
    sec: sec.security,
    auth: require('./auth')(cfg),
    host: require('./host'),
    permission_map: require('fh-db').permission_map,
    hash: function(opts, callback) {
      var p = {
        act: 'hash',
        params: opts
      };
      sec.security(p, callback);
    },
    web: require('./web')(cfg)
  };

  api.sync.setEventEmitter(api.events);

  var redisUrl = 'redis://' + api.redisHost + ':' + api.redisPort;

  getDBUrl(api, function(err, connectionString) {
    if (err) {
      console.warn('Warning! Could not get a mongodb connection string. Sync will not work. (', err, ')');
      return;
    } else if (!connectionString) {
      console.warn('Warning! Could not get a mongodb connection string. Sync will not work. If running in a Dynofarm/FeedHenry MBaaS, ensure the database is upgraded');
      return;
    }
    var poolSize = parseInt(process.env.SYNC_MONGODB_POOLSIZE) || 50;
    api.sync.connect(connectionString, {poolSize: poolSize}, redisUrl, function(err) {
      if (err) {
        console.error('Error starting the sync server (', err, ')');
      }
    });
  });

  api.mbaasExpress = function(opts) {
    opts = opts || {};
    opts.api = api;
    return require('fh-mbaas-express')(opts);
  };

  api.shutdown = function(cb) {
    // Sync service has a setInterval loop running which will prevent fh-mbaas-api from exiting cleanly.
    // Call stopAll to ensure Sync exits clenaly.
    api.sync.stopAll(cb);
  };

  return api;
}
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);
        }
    }
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 );
	}
}
785749
static function init() {

		switch( PHP_SAPI ) {
		// Ideally we want to be runnning as CLI
		case 'cli':
			break;
		// Special conditions to ensure CGI runs as CLI
		case 'cgi':
			// Ensure resource constants are defined
			if( ! defined('STDERR') ){
				define( 'STDERR', fopen('php://stderr', 'w') );
			}
			if( ! defined('STDOUT') ){
				define( 'STDOUT', fopen('php://stdout', 'w') );
			}
			break;
		default:
			echo "Command line only\n";
			exit(1);
		}
		
		// Default error logger function
		PLUG::set_error_logger( array(__CLASS__,'format_logline') );
		
		// parse command line arguments from argv global
		global $argv, $argc;
		// first cli arg is always current script. second arg will be script arg passed to shell wrapper
		for( $i = 1; $i < $argc; $i++ ){
			$arg = $argv[ $i ];
			
			// Each command line argument may take following forms:
			//  1. "Any single argument", no point parsing this unless it follows #2 below
			//  2. "-aBCD", one or more switches, parse into 'a'=>true, 'B'=>true, and so on
			//  3. "-a value", flag used with following value, parsed to 'a'=>'value'
			//  4. "--longoption", GNU style long option, parse into 'longoption'=>true
			//  5. "--longoption=value", as above, but parse into 'longoption'=>'value'
			//  6."any variable name = any value" 
			
			$pair = explode( '=', $arg, 2 );
			if( isset($pair[1]) ){
				$name = trim( $pair[0] );
				if( strpos($name,'--') === 0 ){
					// #5. trimming "--" from option, tough luck if you only used one "-"
					$name = trim( $name, '-' );
				}
				// else is #6, any pair
				$name and self::$args[$name] = trim( $pair[1] );
			}
			
			else if( strpos($arg,'--') === 0 ){
				// #4. long option, no value
				$name = trim( $arg, "-\n\r\t " );
				$name and self::$args[ $name ] = true;
			}
			
			else if( $arg && $arg{0} === '-' ){
				$flags = preg_split('//', trim($arg,"-\n\r\t "), -1, PREG_SPLIT_NO_EMPTY );
				foreach( $flags as $flag ){
					self::$args[ $flag ] = true;
				}
				// leave $flag set incase a value follows.
				continue;
			}

			// else is a standard argument. use as value only if it follows a flag, e.g "-a apple"
			else if( isset($flag) ){
				self::$args[ $flag ] = trim( $arg );
			}

			// dispose of last flag
			unset( $flag );
			// next arg 
		}
	}
1130938
function main() {
  var server = new grpc.Server();
  server.addService(services.GreeterService, {sayHello: sayHello});
  server.bind('0.0.0.0:50051', grpc.ServerCredentials.createInsecure());
  server.start();
}
122411
public function main()
    {
        $this->ini = new IniFileConfig();
        $readFile = null;
        $writeFile = null;

        if (null !== $this->source && null === $this->dest) {
            $readFile = $this->source;
        } elseif (null !== $this->dest && null === $this->source) {
            $readFile = $this->dest;
        } else {
            $readFile = $this->source;
        }

        if (null !== $this->dest) {
            $writeFile = $this->dest;
        } elseif (null !== $this->source) {
            $writeFile = $this->source;
        } else {
            $writeFile = $this->dest;
        }

        if ($readFile === null && $writeFile === null) {
            $msg = "Neither source nor dest is set";
            if ($this->haltonerror) {
                throw new BuildException($msg);
            }
            $this->log($msg, Project::MSG_ERR);
            return;
        }

        if (!$this->checkReadFile($readFile)) {
            return;
        }

        if (!$this->checkWriteFile($writeFile)) {
            return;
        }

        $this->enumerateGets();
        $this->enumerateSets();
        $this->enumerateRemoves();

        if (count($this->sets) || count($this->removals)) {
            try {
                $this->ini->write($writeFile);
                $this->log("Wrote to $writeFile");
            } catch (Exception $ex) {
                $msg = $ex->getMessage();
                if ($this->haltonerror) {
                    throw new BuildException($msg);
                }
                $this->log($msg, Project::MSG_ERR);
            }
        }
    }
1337272
def main():
    ""
    try:
        args = docopt.docopt(__doc__, version=__about__.__version__)
    except docopt.DocoptExit:
        if len(sys.argv) > 1:
            print(f"{Fore.RED}Invalid command syntax, "
                  f"check help:{Fore.RESET}\n")
        print(__doc__)
        sys.exit(1)

    print_all = False
    if not (args["--int-width"] or args["--int-height"] or args["--decimal"]):
        print_all = True

    width    = float(args["WIDTH"])
    height   = float(args["HEIGHT"])

    as_int_   = as_int(width, height)
    as_float_ = as_float(width, height)

    if args["--ndigits"]:
        as_float_ = round(as_float_, int(args["--ndigits"]))

    to_print = []

    if args["--int-width"] or print_all:
        to_print.append(f"{Fore.BLUE}{as_int_[0]!s}")

    if args["--int-height"] or print_all:
        to_print.append(f"{Fore.BLUE}{as_int_[1]!s}")

    if args["--decimal"] or print_all:
        to_print.append(f"{Fore.MAGENTA}{as_float_!s}")

    print(" ".join(to_print))
1156598
def main():
    """"""

    fcodes = collections.OrderedDict((
        ('f.i', protocol.FLG_FORMAT_FDI),
        ('fi', protocol.FLG_FORMAT_FI),
        ('f.i.c', protocol.FLG_FORMAT_FDIDC),
        ('f.ic', protocol.FLG_FORMAT_FDIC),
        ('fi.c', protocol.FLG_FORMAT_FIDC),
        ('fic', protocol.FLG_FORMAT_FIC), ))

    def make_parser():
        # command line parsing

        parser = argparse.ArgumentParser()

        # positional args
        parser.add_argument('uri', metavar='URI', nargs='?', default='/',
                            help='[owserver:]//hostname:port/path')

        # optional args for temperature scale
        parser.set_defaults(t_flags=protocol.FLG_TEMP_C)
        tempg = parser.add_mutually_exclusive_group()
        tempg.add_argument('-C', '--Celsius', const=protocol.FLG_TEMP_C,
                           help='Celsius(default) temperature scale',
                           dest='t_flags', action='store_const', )
        tempg.add_argument('-F', '--Fahrenheit', const=protocol.FLG_TEMP_F,
                           help='Fahrenheit temperature scale',
                           dest='t_flags', action='store_const', )
        tempg.add_argument('-K', '--Kelvin', const=protocol.FLG_TEMP_K,
                           help='Kelvin temperature scale',
                           dest='t_flags', action='store_const', )
        tempg.add_argument('-R', '--Rankine', const=protocol.FLG_TEMP_R,
                           help='Rankine temperature scale',
                           dest='t_flags', action='store_const', )

        # optional arg for address format
        parser.set_defaults(format='f.i')
        parser.add_argument('-f', '--format', choices=fcodes,
                            help='format for 1-wire unique serial IDs display')

        # optional arg for output format
        tempg = parser.add_mutually_exclusive_group()
        tempg.add_argument('--hex', action='store_true',
                           help='write data in hex format')
        tempg.add_argument('-b', '--binary', action='store_true',
                           help='output binary data')

        # debug output
        parser.add_argument('-d', '--debug', action='store_true',
                            help='debug output')

        return parser

    def print_data(data):
        # format and print data

        if args.binary:
            if sys.version_info < (3, ):
                sys.stdout.write(data)
            else:
                sys.stdout.buffer.write(data)
        else:
            if args.hex:
                data = hexlify(data)
            else:
                try:
                    data = data.decode('ascii')
                except UnicodeDecodeError:
                    data = repr(data)
            print(data)

    #
    # main program starts here
    #

    #
    # parse command line arguments
    #
    parser = make_parser()
    args = parser.parse_args()

    #
    # parse args.uri and substitute defaults
    #
    urlc = urlsplit(args.uri, scheme='owserver', allow_fragments=False)
    assert urlc.fragment == ''
    if urlc.scheme != 'owserver':
        parser.error("Invalid URI scheme '{0}:'".format(urlc.scheme))
    if urlc.query:
        parser.error("Invalid URI, query component '?{0}' not allowed"
                     .format(urlc.query))
    try:
        host = urlc.hostname or 'localhost'
        port = urlc.port or 4304
    except ValueError as error:
        parser.error("Invalid URI: invalid net location '//{0}/'"
                     .format(urlc.netloc))

    #
    # create owserver proxy object
    #
    try:
        owproxy = protocol.proxy(
            host, port, flags=args.t_flags | fcodes[args.format],
            verbose=args.debug, )
    except protocol.ConnError as error:
        print("Unable to open connection to '{0}:{1}'\nSystem error: {2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)
    except protocol.ProtocolError as error:
        print("'{0}:{1}' not an owserver?\nProtocol error: {2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)

    #
    # query owserver and print results
    #
    try:
        if urlc.path.endswith('/'):
            for path in owproxy.dir(urlc.path, bus=True):
                print(path)
        else:
            data = owproxy.read(urlc.path)
            print_data(data)
    except protocol.OwnetError as error:
        print("Remote server error: {2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)
    except protocol.ProtocolError as error:
        print("'{0}:{1}' buggy?\nProtocol error: {2}"
              .format(host, port, error), file=sys.stderr)
        sys.exit(1)
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)
411753
static function start($flag = 0, array $ignoreFunctions = array())
    {
        if (self::$sample) {
            throw new \RuntimeException('The profiler has been started');
        }

        self::$sample = new XhprofSample($flag, $ignoreFunctions);

        xhprof_enable($flag, $ignoreFunctions);
    }
810377
public function main()
    {
        if ($this->prefix != null && $this->regex != null) {
            throw new BuildException("Please specify either prefix or regex, but not both", $this->getLocation());
        }

        //copy the properties file
        $allProps = [];

        /* load properties from file if specified, otherwise use Phing's properties */
        if ($this->inFile == null) {
            // add phing properties
            $allProps = $this->getProject()->getProperties();
        } elseif ($this->inFile != null) {
            if ($this->inFile->exists() && $this->inFile->isDirectory()) {
                $message = "srcfile is a directory!";
                $this->failOnErrorAction(null, $message, Project::MSG_ERR);
                return;
            }

            if ($this->inFile->exists() && !$this->inFile->canRead()) {
                $message = "Can not read from the specified srcfile!";
                $this->failOnErrorAction(null, $message, Project::MSG_ERR);
                return;
            }

            try {
                $props = new Properties();
                $props->load(new PhingFile($this->inFile));
                $allProps = $props->getProperties();
            } catch (IOException $ioe) {
                $message = "Could not read file " . $this->inFile->getAbsolutePath();
                $this->failOnErrorAction($ioe, $message, Project::MSG_WARN);
                return;
            }
        }

        $os = null;
        try {
            if ($this->destfile == null) {
                $os = Phing::getOutputStream();
                $this->saveProperties($allProps, $os);
                $this->log($os, Project::MSG_INFO);
            } else {
                if ($this->destfile->exists() && $this->destfile->isDirectory()) {
                    $message = "destfile is a directory!";
                    $this->failOnErrorAction(null, $message, Project::MSG_ERR);
                    return;
                }

                if ($this->destfile->exists() && !$this->destfile->canWrite()) {
                    $message = "Can not write to the specified destfile!";
                    $this->failOnErrorAction(null, $message, Project::MSG_ERR);
                    return;
                }
                $os = new FileOutputStream($this->destfile);
                $this->saveProperties($allProps, $os);
            }
        } catch (IOException $ioe) {
            $this->failOnErrorAction($ioe);
        }
    }
353534
def main() -> None:
    """""""
    parser = argparse.ArgumentParser(description=__doc__)
    parser.add_argument("--outdir", help="output directory", default=os.path.dirname(__file__))
    args = parser.parse_args()

    outdir = pathlib.Path(args.outdir)
    if not outdir.exists():
        raise FileNotFoundError("Output directory is missing: {}".format(outdir))

    for contracts in [0, 1, 5, 10]:
        if contracts == 0:
            pth = outdir / "functions_100_with_no_contract.py"
        elif contracts == 1:
            pth = outdir / "functions_100_with_1_contract.py"
        else:
            pth = outdir / "functions_100_with_{}_contracts.py".format(contracts)

        text = generate_functions(functions=100, contracts=contracts, disabled=False)
        pth.write_text(text)

    for contracts in [1, 5, 10]:
        if contracts == 1:
            pth = outdir / "functions_100_with_1_disabled_contract.py"
        else:
            pth = outdir / "functions_100_with_{}_disabled_contracts.py".format(contracts)

        text = generate_functions(functions=100, contracts=contracts, disabled=True)
        pth.write_text(text)

    for invariants in [0, 1, 5, 10]:
        if invariants == 0:
            pth = outdir / "classes_100_with_no_invariant.py"
        elif invariants == 1:
            pth = outdir / "classes_100_with_1_invariant.py"
        else:
            pth = outdir / "classes_100_with_{}_invariants.py".format(invariants)

        text = generate_classes(classes=100, invariants=invariants, disabled=False)
        pth.write_text(text)

    for invariants in [1, 5, 10]:
        if invariants == 1:
            pth = outdir / "classes_100_with_1_disabled_invariant.py"
        else:
            pth = outdir / "classes_100_with_{}_disabled_invariants.py".format(invariants)

        text = generate_classes(classes=100, invariants=invariants, disabled=True)
        pth.write_text(text)
36184
function start_gifmerge_process($fp)
	{
		if($this->mod == 'C_FILE')
		{
			if(!$this->fin = fopen($fp, 'rb'))
			{
				if($this->debug) print "Error file open: $fp\<br>";
				return;
			}
		}
		else if($this->mod == 'C_MEMORY')
		{
			$this->ch  = 0;
			$this->fin = $fp;
		}
		$this->getbytes (6);
		if(!$this->arrcmp($this->buffer, $this->gif, 3))
		{
			if($this->debug) print "Isn't GIF file!\n<br>";
			return;
		}
		$this->getbytes (7);
		if($this->first) $this->logical_screen_descriptor = $this->buffer;
		$this->global_color_table_sizecode = $this->buffer[4] & 0x07;
		$this->global_color_table_size = 2 << $this->global_color_table_sizecode;
		if($this->buffer[4] & 0x80)
		{
			$this->getbytes((3 * $this->global_color_table_size));
			for($i = 0; $i < ((3 * $this->global_color_table_size)); $i++)
			{
				$this->global_in[$i] = $this->buffer[$i];
			}
			if($this->out_color_table_size == 0)
			{
				$this->out_color_table_size = $this->global_color_table_size;
				$out_color_table_sizecode = $this->global_color_table_sizecode;
				$this->global_out = $this->global_in;
			}
			if($this->global_color_table_size != $this->out_color_table_size || $this->arrcmp($this->global_out, $this->global_in, (3 * $this->global_color_table_size)))
			{
				$this->use_global_in = true;
			}
		}
		for($loop = true; $loop;)
		{
			$this->getbytes(1);
			switch ($this->buffer[0])
			{
				case 0x21:
					$this->read_extension();
					break;
				case 0x2c:
					$this->read_image_descriptor();
					break;
				case 0x3b:
					$loop = false;
				break;
				default:
            		if($this->debug) printf("Unrecognized byte code 0x%x, truncating file!\n<br>", $this->buffer[0]);
						$loop = false;
			}
		}
		if($this->mod == 'C_FILE')
			fclose($this->fin);
	}
1335519
def main():
    """"""
    args = parse_arguments()
    print(args)
    print("action" + args.action)
    print("pid" + args.pid)
    print("directory" + args.directory)
    print("fileprefix" + args.fileprefix)
1184719
public function main()
    {
        // if composer autoloader is not yet loaded, load it here
        @include_once 'vendor/autoload.php';
        if (!class_exists('\\JShrink\\Minifier')) {
            throw new BuildException(
                'JsMinTask depends on JShrink being installed and on include_path.',
                $this->getLocation()
            );
        }

        if (empty($this->targetDir)) {
            throw new BuildException('Attribute "targetDir" is required');
        }

        foreach ($this->filesets as $fs) {
            try {
                $this->processFileSet($fs);
            } catch (BuildException $be) {
                // directory doesn't exist or is not readable
                if ($this->failonerror) {
                    throw $be;
                } else {
                    $this->log($be->getMessage(), Project::MSG_WARN);
                }
            }
        }
    }
481749
def main():
  """"""
  parser = argparse.ArgumentParser(
      description='Reads in a .xls file and generates a units module for '
                  'OpenHTF.',
      prog='python units_from_xls.py')
  parser.add_argument('xlsfile', type=str,
                      help='the .xls file to parse')
  parser.add_argument(
      '--outfile',
      type=str,
      default=os.path.join(os.path.dirname(__file__), os.path.pardir,
                           'openhtf','util', 'units.py'),
      help='where to put the generated .py file.')
  args = parser.parse_args()

  if not os.path.exists(args.xlsfile):
    print('Unable to locate the file "%s".' % args.xlsfile)
    parser.print_help()
    sys.exit()

  unit_defs = unit_defs_from_sheet(
      xlrd.open_workbook(args.xlsfile).sheet_by_name(SHEET_NAME),
      COLUMN_NAMES)

  _, tmp_path = mkstemp()
  with open(tmp_path, 'w') as new_file:
    new_file.write(PRE)
    new_file.writelines(
        [line.encode('utf8', 'replace') for line in unit_defs])
    new_file.write(POST)
    new_file.flush()

  os.remove(args.outfile)
  shutil.move(tmp_path, args.outfile)
534038
function construct() {
      var args = Array.prototype.slice.call(arguments);
      function Fn() {
        return main.Type.apply(this, args);
      }
      Fn.prototype = main.Type.prototype;
      return new Fn();
    }