Main setup function, should be called from both peer -changed and -joined
    hooks with the same parameters.
960387
def ssh_authorized_peers(peer_interface, user, group=None,
                         ensure_local_user=False):
    
    if ensure_local_user:
        ensure_user(user, group)
    priv_key, pub_key = get_keypair(user)
    hook = hook_name()
    if hook == '%s-relation-joined' % peer_interface:
        relation_set(ssh_pub_key=pub_key)
    elif hook == '%s-relation-changed' % peer_interface or \
            hook == '%s-relation-departed' % peer_interface:
        hosts = []
        keys = []

        for r_id in relation_ids(peer_interface):
            for unit in related_units(r_id):
                ssh_pub_key = relation_get('ssh_pub_key',
                                           rid=r_id,
                                           unit=unit)
                priv_addr = relation_get('private-address',
                                         rid=r_id,
                                         unit=unit)
                if ssh_pub_key:
                    keys.append(ssh_pub_key)
                    hosts.append(priv_addr)
                else:
                    log('ssh_authorized_peers(): ssh_pub_key '
                        'missing for unit %s, skipping.' % unit)
        write_authorized_keys(user, keys)
        write_known_hosts(user, hosts)
        authed_hosts = ':'.join(hosts)
        relation_set(ssh_authorized_hosts=authed_hosts)
532589
function setupHandlers() {

    function terminate(err) {
        util.log('Uncaught Error: ' + err.message);
        console.log(err.stack);
        if (proc.shutdownHook) {
            proc.shutdownHook(err, gracefulShutdown);
        }
    }

    process.on('uncaughtException', terminate);

    process.addListener('SIGINT', gracefulShutdown);

    process.addListener('SIGHUP', function () {
        util.log('RECIEVED SIGHUP signal, reloading log files...');
        reload(argv);
    });

}
218061
function main (argv, conf) {
  if (!conf.repo) {
    console.error("[Github-Todos] Mandatory option 'repo' not set, where am I supposed to create issues?");
    console.error("[Github-Todos] Run 'github-todos config repo \"<GITHUB USER OR ORG>/<REPOSITORY>\"' to enable hook");
    process.exit(1);
  }

  if (argv.range) {

    // Extract target SHA
    var targetCommit = _.last(argv.range.split(".."));
    return git.run("rev-parse '" + targetCommit + "'").then(function (sha) {
      return analyzeRange(argv.range, sha.trim(), conf);
    });

  } else {

    // Receive git-hook data from stdin
    return new Promise(function (resolve, reject) {
      var analyzing = [];

      process.stdin.on("data", function (chunk) {
        var info = chunk.toString("utf8").split(/\s+/);
        var promise = onCommitRange(info[1], info[3], conf);
        analyzing.push(promise);
      });

      process.stdin.on("close", function () {
        Promise.all(analyzing).then(resolve, reject);
      });
    });

  }
}
685651
function setupByLink() {
    console.warn("symlink doesn't resolve __dirname.");

    const srcTaskDir = path.join(__dirname, 'tasks');

    // detect target package
    const targets = [];
    const PACKAGES_DIR = path.join(__dirname, '..');
    fs.readdirSync(PACKAGES_DIR)
    .forEach((filePath) => {
        const absPath = path.join(PACKAGES_DIR, filePath);
        if (fs.statSync(absPath).isDirectory()) {
            if (/^cdp-/.test(filePath)) {
                // check project.config.js
                try {
                    const config = require(path.join(absPath, 'project.config'));
                    if (config.required_tasks) {
                        targets.push({
                            path: absPath,
                            required_tasks: config.required_tasks,
                            task_dir: config.dir.task,
                        });
                    }
                } catch (error) {
                    return; // next
                }
            }
        }
    });

    // link
    targets.forEach((target) => {
        const dstTaskDir = path.join(target.path, target.task_dir);
        if (!fs.existsSync(dstTaskDir)) {
            // create tasks dir
            fs.mkdirSync(dstTaskDir);
        }

        target.required_tasks.forEach((task) => {
            const src = path.join(srcTaskDir, task);
            const dst = path.join(dstTaskDir, task);
            if (!fs.existsSync(src)) {
                console.error('task not found: ' + task);
                process.exit(1);
            }
            if (fs.existsSync(dst)) {
                fs.unlinkSync(dst);
            }
            fs.symlinkSync(src, dst, 'file');
        });
    });
}
1026090
def bind
      Spinach.hooks.tap do |hooks|
        hooks.before_run { |*args| before_run(*args) }
        hooks.after_run { |*args| after_run(*args) }
        hooks.before_feature { |*args| before_feature_run(*args) }
        hooks.after_feature { |*args| after_feature_run(*args) }
        hooks.on_undefined_feature { |*args| on_feature_not_found(*args) }
        hooks.before_scenario { |*args| before_scenario_run(*args) }
        hooks.around_scenario { |*args, &block| around_scenario_run(*args, &block) }
        hooks.after_scenario { |*args| after_scenario_run(*args) }
        hooks.on_successful_step { |*args| on_successful_step(*args) }
        hooks.on_undefined_step { |*args| on_undefined_step(*args) }
        hooks.on_pending_step { |*args| on_pending_step(*args) }
        hooks.on_failed_step { |*args| on_failed_step(*args) }
        hooks.on_error_step { |*args| on_error_step(*args) }
        hooks.on_skipped_step { |*args| on_skipped_step(*args) }

        hooks.before_feature { |*args| set_current_feature(*args) }
        hooks.after_feature { |*args| clear_current_feature(*args) }
        hooks.before_scenario { |*args| set_current_scenario(args.first) }
        hooks.after_scenario { |*args| clear_current_scenario(args.first) }
      end
    end
56987
def setup(*methods, &block)
      methods.each do |method|
        if method.to_s =~ /^setup_(with_controller|fixtures|controller_request_and_response)$/
          prepend_before { __send__ method }
        else
          before         { __send__ method }
        end
      end
      before(&block) if block
    end
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();
}
71373
def init(ctx):
    
    # install hooks
    git = ctx.obj['vcs']
    click.echo("Installing hooks...", nl=False)
    for old in ['commit-msg']:
        path = os.path.join(git.path, '.git/hooks', old)
        if os.path.exists(path):
            os.remove(path)
    for new in ['pre-commit', 'pre-push']:
        git.install_hook(new, hooks_manager.get_hook(new))
    click.echo("Done.")

    # add a config file if one does not exist
    config_path = os.path.join(git.path, 'eci.yaml')
    if not os.path.exists(config_path):
        click.echo("Placing a trivial config file in your project...", nl=False)
        with open(config_path, 'w') as f:
            f.write(yaml.safe_dump(
                {'tests': ['echo please modify to run your tests', 'true']}))
        click.echo("Done.")

    # initialize lock
    locking.init(git)

    # update installed version
    click.echo("Updating installed version...", nl=False)
    set_installed_version(git, easyci.__version__)
    click.echo("Done.")
860198
def _run_hooks(self, name, module):
        
        hooks = self.post_load_hooks.pop(name, [])

        for hook in hooks:
            hook(module)
925411
async def main():
    
    # Create Client from endpoint string in Duniter format
    client = Client(BMAS_ENDPOINT)
    tasks = []

    # Get the node summary infos by dedicated method (with json schema validation)
    print("\nCall bma.node.summary:")
    task = asyncio.ensure_future(client(bma.node.summary))
    tasks.append(task)

    # Get the money parameters located in the first block
    print("\nCall bma.blockchain.parameters:")
    task = asyncio.ensure_future(client(bma.blockchain.parameters))
    tasks.append(task)

    responses = await asyncio.gather(*tasks)
    # you now have all response bodies in this variable
    print("\nResponses:")
    print(responses)

    # Close client aiohttp session
    await client.close()
297592
def main(arguments=None):
    
    # setup the command-line util settings

    dev_flag = False

    su = tools(
        arguments=arguments,
        docString=__doc__,
        logLevel="DEBUG",
        options_first=False,
        projectName="rockAtlas"
    )
    arguments, settings, log, dbConn = su.setup()

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

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

    if init:
        from os.path import expanduser
        home = expanduser("~")
        filepath = home + "/.config/rockAtlas/rockAtlas.yaml"
        try:
            cmd = """open %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass
        try:
            cmd = """start %(filepath)s""" % locals()
            p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
        except:
            pass

    # CALL FUNCTIONS/OBJECTS
    if bookkeeping:
        from rockAtlas.bookkeeping import bookkeeper
        bk = bookkeeper(
            log=log,
            settings=settings,
            fullUpdate=fullFlag
        )
        bk.clean_all()

    if astorb:
        from rockAtlas.orbital_elements import astorb
        oe = astorb(
            log=log,
            settings=settings
        )
        oe.refresh()

    if pyephem:

        from rockAtlas.positions import pyephemPositions
        pyeph = pyephemPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        pyeph.get(singleSnapshot=oneFlag)

    if orbfit:
        from rockAtlas.positions import orbfitPositions
        oe = orbfitPositions(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        oe.get(singleExposure=oneFlag)

    if cache:
        from rockAtlas.phot import download
        data = download(
            log=log,
            settings=settings,
            dev_flag=dev_flag
        )
        data.get(days=days)

    if dophot:
        from rockAtlas.phot import dophotMatch
        dp = dophotMatch(
            log=log,
            settings=settings
        )
        dp.get()

    if cycle:
        from rockAtlas.phot import download
        from rockAtlas.positions import pyephemPositions
        from rockAtlas.positions import orbfitPositions
        from rockAtlas.phot import dophotMatch
        from fundamentals.mysql import readquery

        # INITIAL ACTIONS
        # SETUP ALL DATABASE CONNECTIONS
        from rockAtlas import database
        db = database(
            log=log,
            settings=settings
        )
        dbConns, dbVersions = db.connect()
        atlas3DbConn = dbConns["atlas3"]
        atlas4DbConn = dbConns["atlas4"]
        atlasMoversDBConn = dbConns["atlasMovers"]

        while True:

            if dev_flag:
                o = " and dev_flag = 1"
            else:
                o = " "

            sqlQuery = u"""
                select distinct floor(mjd) from (
select mjd from atlas_exposures where dophot_match = 0 %(o)s
union all
select mjd from day_tracker where processed = 0 %(o)s) as a;
            """ % locals()
            rows = readquery(
                log=log,
                sqlQuery=sqlQuery,
                dbConn=atlasMoversDBConn,
                quiet=False
            )

            if len(rows) == 0:
                if dev_flag:
                    print "Processing of the ATLAS development dataset is now complete and up to date"
                else:
                    print "Processing of ATLAS data is now complete and up to date"
                break

            start_time = time.time()

            data = download(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            data.get(days=days)

            print "%d seconds to download ATLAS cache of %s days\n" % (time.time() - start_time, days)
            start_time = time.time()

            pyeph = pyephemPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            pyeph.get()

            print "%d seconds to generate pyephem snapshots\n" % (time.time() - start_time,)
            start_time = time.time()

            oe = orbfitPositions(
                log=log,
                settings=settings,
                dev_flag=dev_flag
            )
            oe.get()

            print "%d seconds to generate orbfit positions\n" % (time.time() - start_time,)
            start_time = time.time()

            dp = dophotMatch(
                log=log,
                settings=settings
            )
            dp.get()

            print "%d seconds to extract dophot measurements\n" % (time.time() - start_time,)
            start_time = time.time()

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

    return
1069123
public function add()
	{
		// Get the hook we're setting
		$trigger = $this->arguments->getOpt(3);
		$hook    = $this->arguments->getOpt(4);

		// Delete the primary args so they aren't added as top level config values
		$this->arguments->deleteOpt(3);
		$this->arguments->deleteOpt(4);

		// Set the new hooks argument
		$this->arguments->setOpt('hooks', array($trigger => array($hook)));

		// Redirect back to the basic configuration set method
		App::get('client')->call('configuration', 'set', $this->arguments, $this->output);
	}
246651
@Setup
    public void setup() {
        proxyInterceptor = MethodDelegation.to(ByteBuddyProxyInterceptor.class);
        accessInterceptor = MethodDelegation.to(ByteBuddyAccessInterceptor.class);
        prefixInterceptor = MethodDelegation.to(ByteBuddyPrefixInterceptor.class);
        baseClassDescription = TypePool.Default.ofSystemLoader().describe(baseClass.getName()).resolve();
        proxyClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyProxyInterceptor.class.getName()).resolve();
        accessClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyAccessInterceptor.class.getName()).resolve();
        prefixClassDescription = TypePool.Default.ofSystemLoader().describe(ByteBuddyPrefixInterceptor.class.getName()).resolve();
        proxyInterceptorDescription = MethodDelegation.to(proxyClassDescription);
        accessInterceptorDescription = MethodDelegation.to(accessClassDescription);
        prefixInterceptorDescription = MethodDelegation.to(prefixClassDescription);
    }
23346
def _setup_eventloop(self):
        
        if os.name == 'nt':
            self.eventloop = asyncio.ProactorEventLoop()
        else:
            self.eventloop = asyncio.new_event_loop()
        asyncio.set_event_loop(self.eventloop)
        if os.name == 'posix' and isinstance(threading.current_thread(), threading._MainThread):
            asyncio.get_child_watcher().attach_loop(self.eventloop)
918767
@Setup(Level.Trial)
  public void setup() throws Exception {
    super.setup(ExecutorType.DIRECT,
        ExecutorType.DIRECT,
        MessageSize.SMALL,
        MessageSize.SMALL,
        FlowWindowSize.LARGE,
        ChannelType.NIO,
        maxConcurrentStreams,
        channelCount);
    callCounter = new AtomicLong();
    completed = new AtomicBoolean();
    startUnaryCalls(maxConcurrentStreams, callCounter, completed, 1);
  }
966789
def _run_hooks(config, hooks, args, environ):
    """"""
    skips = _get_skips(environ)
    cols = _compute_cols(hooks, args.verbose)
    filenames = _all_filenames(args)
    filenames = filter_by_include_exclude(filenames, '', config['exclude'])
    classifier = Classifier(filenames)
    retval = 0
    for hook in hooks:
        retval |= _run_single_hook(classifier, hook, args, skips, cols)
        if retval and config['fail_fast']:
            break
    if retval and args.show_diff_on_failure and git.has_diff():
        if args.all_files:
            output.write_line(
                'pre-commit hook(s) made changes.\n'
                'If you are seeing this message in CI, '
                'reproduce locally with: `pre-commit run --all-files`.\n'
                'To run `pre-commit` as part of git workflow, use '
                '`pre-commit install`.',
            )
        output.write_line('All changes made by hooks:')
        subprocess.call(('git', '--no-pager', 'diff', '--no-ext-diff'))
    return retval
790896
def run_hooks(self, name, event=None, context=None):
        
        hooks = {
            "pre:setup": lambda p: p.pre_setup(self),
            "post:setup": lambda p: p.post_setup(self),
            "pre:invoke": lambda p: p.pre_invoke(event, context),
            "post:invoke": lambda p: p.post_invoke(event, context),
            "pre:report": lambda p: p.pre_report(self.report),
            "post:report": lambda p: p.post_report(self.report),
        }

        if name in hooks:
            for p in self.plugins:
                if p.enabled:
                    try:
                        hooks[name](p)
                    except Exception as e:
                        logger.error(
                            "IOpipe plugin %s hook raised error" % (name, str(e))
                        )
                        logger.exception(e)