make it public for CLI interaction to reuse JobContext
974036
public static void init(String jobId) {
        JobContext parent = current_.get();
        JobContext ctx = new JobContext(parent);
        current_.set(ctx);
        // don't call setJobId(String)
        // as it will trigger listeners -- TODO fix me
        ctx.jobId = jobId;
        if (null == parent) {
            Act.eventBus().trigger(new JobContextInitialized(ctx));
        }
    }
976393
def dump_artifacts(kwargs):
    '''
    
    '''
    private_data_dir = kwargs.get('private_data_dir')
    if not private_data_dir:
        private_data_dir = tempfile.mkdtemp()
        kwargs['private_data_dir'] = private_data_dir

    if not os.path.exists(private_data_dir):
        raise ValueError('private_data_dir path is either invalid or does not exist')

    if 'role' in kwargs:
        role = {'name': kwargs.pop('role')}
        if 'role_vars' in kwargs:
            role['vars'] = kwargs.pop('role_vars')

        play = [{'hosts': kwargs.pop('hosts', 'all'), 'roles': [role]}]

        if kwargs.pop('role_skip_facts', False):
            play[0]['gather_facts'] = False

        kwargs['playbook'] = play

        if 'envvars' not in kwargs:
            kwargs['envvars'] = {}

        roles_path = kwargs.pop('roles_path', None)
        if not roles_path:
            roles_path = os.path.join(private_data_dir, 'roles')
        else:
            roles_path += ':{}'.format(os.path.join(private_data_dir, 'roles'))

        kwargs['envvars']['ANSIBLE_ROLES_PATH'] = roles_path

    obj = kwargs.get('playbook')
    if obj and isplaybook(obj):
        path = os.path.join(private_data_dir, 'project')
        kwargs['playbook'] = dump_artifact(json.dumps(obj), path, 'main.json')

    obj = kwargs.get('inventory')
    if obj and isinventory(obj):
        path = os.path.join(private_data_dir, 'inventory')
        if isinstance(obj, Mapping):
            kwargs['inventory'] = dump_artifact(json.dumps(obj), path, 'hosts.json')
        elif isinstance(obj, string_types):
            if not os.path.exists(obj):
                kwargs['inventory'] = dump_artifact(obj, path, 'hosts')

    for key in ('envvars', 'extravars', 'passwords', 'settings'):
        obj = kwargs.get(key)
        if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
            path = os.path.join(private_data_dir, 'env')
            dump_artifact(json.dumps(obj), path, key)
            kwargs.pop(key)

    for key in ('ssh_key', 'cmdline'):
        obj = kwargs.get(key)
        if obj and not os.path.exists(os.path.join(private_data_dir, 'env', key)):
            path = os.path.join(private_data_dir, 'env')
            dump_artifact(str(kwargs[key]), path, key)
            kwargs.pop(key)
456714
function (job_name, job_obj) {

        //If we're capturing output, we need to explicitly override job.output()
        if (isMaster && capture_output) {
            var output = [];
            job_obj.output = function (out) {
                if (out instanceof Array && job_obj.options.flatten) {
                    for (var i = 0, l = out.length; i < l; i++) {
                        output.push(out[i]);
                    }
                } else {
                    output.push(out);
                }
            };
            var old_callback = callback;
            callback = function (err) {
                old_callback(err, output);
            };
        }

        //Are we distributing work?
        fork = job_obj.options.fork;

        //Initialise the processor
        processor.init(function () {

            //Start the job
            if (isMaster) {
                processor.startJob(job_name, job_obj, callback);
            }

        });
    }
924203
public static void mergeWorkerContext(TracyThreadContext workerTracyThreadContext) {
        TracyThreadContext ctx = threadContext.get();
        if (isValidContext(ctx)) {
            ctx.mergeChildContext(workerTracyThreadContext);
        }
    }
558937
private static RunContext createBottomContext() {
    File spockUserHome = SpockUserHomeUtil.getSpockUserHome();
    DelegatingScript script = new ConfigurationScriptLoader(spockUserHome).loadAutoDetectedScript();
    List<Class<?>> classes = new ExtensionClassesLoader().loadClassesFromDefaultLocation();
    return new RunContext("default", spockUserHome, script, classes);
  }
698123
function(worker)
{
    var self = this;

    this.context     = worker.context;
    this.worker      = worker;
    this.controllers = {};
    this.contexts    = greppy.config.get('app').get('infrastructure');
}
1347014
function RootContext(argv, profileFilenames, view) {
  var self = {
      commands: COMMANDS, // Overwritten when interactive
      profileFilenames: profileFilenames,
      interactive: false,
      argv: argv,
      view: view,
      config: null,
      nick: null,
      privkey: null,
      hubClient: null,
      voxClient: null,
  };

  self.initWithConfig = function(config) {
    if (self.voxClient) {
      throw new Error('Already initialized!');
    }

    self.config = config;
    self.nick = config.nick;

    self.voxClient = new VoxClient({
        config: config,
        agentString: AGENT_STRING,
    });
    return self.voxClient.connect();
  }

  self.reinitWithConfig = function(config) {
    self.close();
    return self.initWithConfig(config);
  }

  self.close = function() {
    if (self.voxClient) {
      self.voxClient.close();
      self.voxClient = null;
    }
  }

  /**
   * Logs connection status events.
   */
  self.listenForConnectionStatusEvents = function() {
    self.voxClient.on('connect', function(info) {
      self.view.log(colors.cyan.dim('Connected: ' + info.interchangeUrl));
    });
    self.voxClient.on('disconnect', function(info) {
      self.view.log(colors.red.dim('Disconnected: ' + info.interchangeUrl));
    });
    self.voxClient.on('error', function(info) {
      self.view.log(colors.red.dim('Connection error: ' + info.interchangeUrl));
    });
    self.voxClient.on('reconnect_failed', function(info) {
      self.view.log(colors.red.dim('Reconnection failed: ' + info.interchangeUrl));
    });
  }

  self.printJson = function(obj_or_name, obj) {
    if (obj !== undefined) {
      self.view.log('%s %s', obj_or_name, JSON.stringify(obj));
    } else {
      self.view.log(JSON.stringify(obj_or_name));
    }
  }

  return self;
}
532435
def communicate(self, job_ids = None):
    """"""
    self.lock()
    # iterate over all jobs
    jobs = self.get_jobs(job_ids)
    for job in jobs:
      job.refresh()
      if job.status in ('queued', 'executing', 'waiting') and job.queue_name != 'local':
        status = qstat(job.id, context=self.context)
        if len(status) == 0:
          job.status = 'failure'
          job.result = 70 # ASCII: 'F'
          logger.warn("The job '%s' was not executed successfully (maybe a time-out happened). Please check the log files." % job)
          for array_job in job.array:
            if array_job.status in ('queued', 'executing'):
              array_job.status = 'failure'
              array_job.result = 70 # ASCII: 'F'


    self.session.commit()
    self.unlock()
1076595
function push(jobProfileString, jobOpt /*jobOptInterface*/, namespace) {
    logger.debug(`Following litteral was pushed \n ${util.format(jobOpt)}`);
    let jobID = uuidv4();
    if (jobOpt.hasOwnProperty('id'))
        if (jobOpt.id)
            jobID = jobOpt.id;
    let workDir;
    if (namespace) {
        try {
            fs.mkdirSync(cacheDir + '/' + namespace);
        }
        catch (err) {
            if (err.code != 'EEXIST') {
                logger.error("Namespace " + cacheDir + '/' + namespace + ' already exists.');
                throw err;
            }
        }
        workDir = cacheDir + '/' + namespace + '/' + jobID;
    }
    else {
        workDir = cacheDir + '/' + jobID;
    }
    /* Building a jobOptInterface litteral out of the jobOpt function parameter */
    let jobTemplate = {
        // "engineHeader": engine.generateHeader(jobID, jobProfileString, workDir),
        "engine": engine,
        "workDir": workDir,
        "emulated": emulator ? true : false,
        "adress": TCPip,
        "port": TCPport,
        "jobProfile": jobProfileString ? jobProfileString : "default"
        // "submitBin": engine.submitBin(),
    };
    if ('exportVar' in jobOpt)
        jobTemplate.exportVar = jobOpt.exportVar;
    if ('modules' in jobOpt)
        jobTemplate.modules = jobOpt.modules;
    if ('script' in jobOpt)
        jobTemplate.script = jobOpt.script;
    if ('cmd' in jobOpt)
        jobTemplate.cmd = jobOpt.cmd;
    if ('inputs' in jobOpt)
        jobTemplate.inputs = jobOpt.inputs;
    if ('tagTask' in jobOpt)
        jobTemplate.tagTask = jobOpt.tagTask;
    if ('ttl' in jobOpt)
        jobTemplate.ttl = jobOpt.ttl;
    if ('socket' in jobOpt)
        jobTemplate.socket = jobOpt.socket;
    logger.debug(`Following jobTemplate was successfully buildt \n ${util.format(jobTemplate)}`);
    let newJob = new jobLib.jobObject(jobTemplate, jobID);
    if ('fromConsumerMS' in jobOpt)
        newJob.fromConsumerMS = jobOpt.fromConsumerMS;
    // 3 outcomes
    // newJob.launch // genuine start
    // newJob.resurrect // load from wareHouse a complete job
    // newJob.melt // replace newJob by an already running job
    //                just copying client socket if fromConsumerMS 
    //
    logger.debug(`Following jobObject was successfully buildt \n ${util.format(newJob)}`);
    newJob.start();
    liveMemory.addJob(newJob);
    newJob.on('inputSet', function () {
        // All input streams were dumped to file(s), we can safely serialize
        let jobSerial = newJob.getSerialIdentity();
        MS_lookup(jobSerial)
            .on('known', function (fStdoutName, fStderrName, workPath) {
            newJob.respawn(fStdoutName, fStderrName, workPath);
            newJob.jEmit("completed", newJob);
            // Repertoir valide
            // Extraire la sortie d'erreur / standard du job et faire lever levent completed
            //logger.info("I CAN RESURRECT YOU : " + validWorkFolder + ' -> ' + jobTemplate.tagTask);
            //_resurrect(newJob, validWorkFolder);
        })
            .on('unknown', function () {
            logger.debug("####No suitable job found in warehouse");
            let previousJobs;
            previousJobs = liveMemory.lookup(newJob);
            if (previousJobs) {
                // let refererJob:jobLib.jobObject = getJob(previousJobs[0].id];
                logger.debug(`${previousJobs.length} suitable living job(s) found, shimmering`);
                melting(previousJobs[0], newJob);
                return;
            }
            logger.debug('No Suitable living jobs found, launching');
            //liveStore(newJob.getSerialIdentity());  
            //jobRegister(newJob);
            liveMemory.jobSet('source', { jobObject: newJob });
            newJob.launch();
            newJob.on('submitted', function (j) {
                liveMemory.jobSet('SUBMITTED', { jobObject: newJob });
                //jobsArray[j.id].status = 'SUBMITTED';
            }).on('jobStart', function (job) {
                engine.list();
                // shall we call dropJob function here ?
            }).on('scriptReadError', function (err, job) {
                logger.error(`ERROR while reading the script : \n ${err}`);
            }).on('scriptWriteError', function (err, job) {
                logger.error(`ERROR while writing the coreScript : \n ${err}`);
            }).on('scriptSetPermissionError', function (err, job) {
                logger.error(`ERROR while trying to set permissions of the coreScript : \n ${err}`);
            });
        });
    });
    exhaustBool = true;
    //console.log(jobsArray);
    return newJob;
}
979062
private void symLinkAndConfigureFiles(JobConf job) throws IOException {
    if (!(job.getBoolean("mapred.used.genericoptionsparser", false))) {
      LOG.warn("Use GenericOptionsParser for parsing the arguments. " +
               "Applications should implement Tool for the same.");
    }

    // get all the command line arguments into the
    // jobconf passed in by the user conf
    String files = job.get("tmpfiles");
    String archives = job.get("tmparchives");
    // "tmpjars" are not needed because its in the classpath

    List<String> filesToSymLink = new ArrayList<String>();
    splitAndAdd(files, filesToSymLink);
    splitAndAdd(archives, filesToSymLink);

    for (String file : filesToSymLink) {
      String target = new Path(file).toUri().getPath();
      String basename = new File(target).getName();
      String linkName = new File(".").getAbsolutePath() + File.separator + basename;
      File toLink = new File(linkName);
      if (toLink.exists()) {
        LOG.info("Symlink " + linkName + " already exists. Delete it.");
        toLink.delete();
      }
      int ret = FileUtil.symLink(target, linkName);
      LOG.info("Creating symlink " + linkName + " -> " + target +
          " returns " + ret + ".");
    }
    // Configure job name
    String originalJar = job.getJar();
    if (originalJar != null) {
      // use jar name if job is not named.
      if ("".equals(job.getJobName())) {
        job.setJobName(new Path(originalJar).getName());
      }
    }
    // Configure username
    configureUserName(job);
  }
1197657
@SuppressWarnings("deprecation")
  public void pushContextData() {
    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINEST)) { 
      logger.entering(CLASS_NAME,"pushContextData",this);
    }

    // will want to run on the calling thread's class loader
    this.newCL = AccessController.doPrivileged(new PrivilegedAction<ClassLoader>() {
        @Override
        public ClassLoader run() {
            ClassLoader old = Thread.currentThread().getContextClassLoader();
            return old;
        }
    });

    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) {
        logger.logp(Level.FINEST, CLASS_NAME, "pushContextData", "thread context class loader [" + this.newCL +"]");
      }
    
    this.contextData = new HashMap();
    
    // push data for other components that we already have hooks into
    ComponentMetaDataAccessorImpl cmdai = ComponentMetaDataAccessorImpl.getComponentMetaDataAccessor();
    ComponentMetaData cmd = cmdai.getComponentMetaData();
    if (cmd != null) {
      this.contextData.put(ComponentMetaData, cmd);
    }  
    
    // each producer service of the Transfer service is accessed in order to get the thread context data
    Iterator<ITransferContextService> TransferIterator = com.ibm.ws.webcontainer.osgi.WebContainer.getITransferContextServices();
    if (TransferIterator != null) { 
      while(TransferIterator.hasNext()){
        ITransferContextService tcs = TransferIterator.next();
        if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) {
          logger.logp(Level.FINEST, CLASS_NAME, "pushContextData", "calling storeState on: " + tcs);
        }
        tcs.storeState(this.contextData);
        asyncContext.storeStateCtxData = this.contextData;
      }
    } else {
      if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled() && logger.isLoggable(Level.FINEST)) {
        logger.logp(Level.FINEST, CLASS_NAME, "pushContextData", "no implmenting services found");
      }
    }
    
    if (com.ibm.ejs.ras.TraceComponent.isAnyTracingEnabled()&&logger.isLoggable (Level.FINEST)) { 
      logger.exiting(CLASS_NAME,"pushContextData",this);
    }
  }
1317050
function makeJobFile(config) {
  var job = {"espruino":{}};
  // assign commandline values
  for (var key in args) {
    switch (key) {
      case 'job': // remove job itself, and others set internally from the results
      case 'espruinoPrefix':
      case 'espruinoPostfix':
        break;
      default: job[key] = args[key];  // otherwise just output each key: value
    }
    // write fields of Espruino.Config passed as config
    for (var k in config) { if (typeof config[k]!=='function') job.espruino[k] = config[k]; };
  }
  // name job file same as code file with json ending or default and save.
  var jobFile = isNextValidJS(args.file) ? args.file.slice(0,args.file.lastIndexOf('.'))+'.json' : "job.json";

  if (!fs.existsSync(jobFile)) {
    log("Creating job file "+JSON.stringify(jobFile));
    fs.writeFileSync(jobFile,JSON.stringify(job,null,2),{encoding:"utf8"});
  } else
    log("WARNING: File "+JSON.stringify(jobFile)+" already exists - not overwriting.");
}
246069
function (jobName, customParams, callback) {
      [jobName, customParams, callback] = doArgs(arguments, ['string', ['object', {}], 'function']);

      this.job_info(jobName, function (error, data) {
        if (error) {
          callback(error, data);
          return;
        }

        const lastResultUrl = data.lastBuild.url;

        doRequest({
          urlPattern: [lastResultUrl + API, jobName]
        }, customParams, callback);
      });
    }
61289
def cli(env, identifier):
    """"""

    mgr = SoftLayer.ObjectStorageManager(env.client)
    credential = mgr.create_credential(identifier)
    table = formatting.Table(['id', 'password', 'username', 'type_name'])
    table.sortby = 'id'
    table.add_row([
        credential['id'],
        credential['password'],
        credential['username'],
        credential['type']['name']
    ])

    env.fout(table)
907757
def cli(context, host, username, password):
    
    context.obj = FritzBox(host, username, password)
722667
def cli(ctx, mac, debug):
    
    if debug:
        logging.basicConfig(level=logging.DEBUG)
    else:
        logging.basicConfig(level=logging.INFO)

    thermostat = Thermostat(mac)
    thermostat.update()
    ctx.obj = thermostat

    if ctx.invoked_subcommand is None:
        ctx.invoke(state)
1034936
def cli(ctx, verbose, fake, install, uninstall, config):
    """"""
    # Create a repo object and remember it as as the context object.  From
    # this point onwards other commands can refer to it by using the
    # @pass_scm decorator.
    ctx.obj = SCMRepo()
    ctx.obj.fake = fake
    ctx.obj.verbose = fake or verbose

    if install:
        do_install(ctx, verbose, fake)
        ctx.exit()
    elif uninstall:
        do_uninstall(ctx, verbose, fake)
        ctx.exit()
    elif config:
        do_edit_settings(fake)
        ctx.exit()
    else:
        if ctx.invoked_subcommand is None:
            # Display help to user if no commands were passed.
            click.echo(format_help(ctx.get_help()))