One stub can be used for both Export RPC and Config RPC.
519399
private static TraceServiceGrpc.TraceServiceStub getTraceServiceStub(
      String endPoint, Boolean useInsecure, SslContext sslContext) {
    ManagedChannelBuilder<?> channelBuilder;
    if (useInsecure) {
      channelBuilder = ManagedChannelBuilder.forTarget(endPoint).usePlaintext();
    } else {
      channelBuilder =
          NettyChannelBuilder.forTarget(endPoint)
              .negotiationType(NegotiationType.TLS)
              .sslContext(sslContext);
    }
    ManagedChannel channel = channelBuilder.build();
    return TraceServiceGrpc.newStub(channel);
  }
765116
function exportFilesystemToArchive (opts, cb) {
  return maybe(cb, async function () {
    assert(opts && typeof opts === 'object', 'opts object is required')

    // core arguments, srcPath and dstArchive
    var srcPath = opts.srcPath
    var dstArchive = opts.dstArchive
    assert(srcPath && typeof srcPath === 'string', 'srcPath is required')
    assert(dstArchive && typeof dstArchive === 'object', 'dstArchive is required')

    // options
    var dstPath = typeof opts.dstPath === 'string' ? opts.dstPath : '/'
    var ignore = Array.isArray(opts.ignore) ? opts.ignore : DEFAULT_IGNORE
    var inplaceImport = opts.inplaceImport === true
    var dryRun = opts.dryRun === true

    // ensure we have the archive's private key
    if (!dstArchive.writable && !dryRun) {
      throw new ArchiveNotWritableError()
    }

    // make source the source exists
    var srcStat
    try {
      srcStat = await fse.stat(srcPath)
    } catch (e) {
      throw new SourceNotFoundError(e.toString())
    }

    // if reading from a directory, and not doing an implace-import,
    // then put the dstPath at a subpath so that the folder's contents dont
    // get imported in-place into the archive
    if (srcStat.isDirectory() && !inplaceImport) {
      dstPath = path.join(dstPath, path.basename(srcPath))
    }

    // make sure the destination is a folder
    var dstStat
    try { dstStat = await stat(dstArchive, dstPath) } catch (e) {}
    if (!dstStat) {
      try { dstStat = await stat(dstArchive, path.dirname(dstPath)) } catch (e) {}
    }
    if (!dstStat || !dstStat.isDirectory()) {
      throw new ParentFolderDoesntExistError()
    }

    // dont overwrite directories with files
    if (!srcStat.isDirectory() && dstStat.isDirectory()) {
      dstPath = path.join(dstPath, path.basename(srcPath))
    }

    const statThenExport = async function (srcPath, dstPath) {
      // apply ignore filter
      if (ignore && match(ignore, srcPath)) {
        return
      }

      // export by type
      var srcStat = await fse.stat(srcPath)
      if (srcStat.isFile()) {
        await exportFile(srcPath, srcStat, dstPath)
      } else if (srcStat.isDirectory()) {
        await exportDirectory(srcPath, dstPath)
      }
    }

    const exportFile = async function (srcPath, srcStat, dstPath) {
      // fetch dest stats
      var dstFileStats = null
      try {
        dstFileStats = await stat(dstArchive, dstPath)
      } catch (e) {}

      // track the stats
      stats.fileCount++
      stats.totalSize += srcStat.size || 0
      if (dstFileStats) {
        if (dstFileStats.isDirectory()) {
          // delete the directory-tree
          if (!dryRun) await rmdir(dstArchive, dstPath, {recursive: true})
          stats.removedFolders.push(dstPath)
          stats.addedFiles.push(dstPath)
        } else {
          stats.updatedFiles.push(dstPath)
        }
      } else {
        stats.addedFiles.push(dstPath)
      }

      // write the file
      if (dryRun) return
      return new Promise((resolve, reject) => {
        pump(
          fse.createReadStream(srcPath),
          dstArchive.createWriteStream(dstPath),
          err => {
            if (err) reject(err)
            else resolve()
          }
        )
      })
    }

    const exportDirectory = async function (srcPath, dstPath) {
      // make sure the destination folder exists
      var dstStat
      try { dstStat = await stat(dstArchive, dstPath) } catch (e) {}
      if (!dstStat) {
        if (!dryRun) await mkdir(dstArchive, dstPath)
        stats.addedFolders.push(dstPath)
      } else if (dstStat.isFile()) {
        // a file is at the same location, remove it and add the folder
        if (!dryRun) {
          await unlink(dstArchive, dstPath)
          await mkdir(dstArchive, dstPath)
        }
        stats.addedFolders.push(dstPath)
        stats.removedFiles.push(dstPath)
        if (dryRun) {
          // dont recurse on a dry run -- not possible because the actual changes arent being made
          return
        }
      }

      // list the directory
      var fileNames = await fse.readdir(srcPath)

      // recurse into each
      var promises = fileNames.map(name => {
        return statThenExport(path.join(srcPath, name), path.join(dstPath, name))
      })
      await Promise.all(promises)
    }

    // recursively export
    var stats = {
      addedFiles: [],
      addedFolders: [],
      updatedFiles: [],
      removedFiles: [],
      removedFolders: [],
      skipCount: 0,
      fileCount: 0,
      totalSize: 0
    }
    await statThenExport(srcPath, dstPath)
    return stats
  })
}
263039
function bundle(entryPoints, config, callback) {
    const entryPointsMap = {};
    entryPoints.forEach((module) => {
        entryPointsMap[module.name] = module;
    });
    const allMentionedModulesMap = {};
    entryPoints.forEach((module) => {
        allMentionedModulesMap[module.name] = true;
        (module.include || []).forEach(function (includedModule) {
            allMentionedModulesMap[includedModule] = true;
        });
        (module.exclude || []).forEach(function (excludedModule) {
            allMentionedModulesMap[excludedModule] = true;
        });
    });
    const code = require('fs').readFileSync(path.join(__dirname, '../../src/vs/loader.js'));
    const r = vm.runInThisContext('(function(require, module, exports) { ' + code + '\n});');
    const loaderModule = { exports: {} };
    r.call({}, require, loaderModule, loaderModule.exports);
    const loader = loaderModule.exports;
    config.isBuild = true;
    config.paths = config.paths || {};
    if (!config.paths['vs/nls']) {
        config.paths['vs/nls'] = 'out-build/vs/nls.build';
    }
    if (!config.paths['vs/css']) {
        config.paths['vs/css'] = 'out-build/vs/css.build';
    }
    loader.config(config);
    loader(['require'], (localRequire) => {
        const resolvePath = (path) => {
            const r = localRequire.toUrl(path);
            if (!/\.js/.test(r)) {
                return r + '.js';
            }
            return r;
        };
        for (const moduleId in entryPointsMap) {
            const entryPoint = entryPointsMap[moduleId];
            if (entryPoint.append) {
                entryPoint.append = entryPoint.append.map(resolvePath);
            }
            if (entryPoint.prepend) {
                entryPoint.prepend = entryPoint.prepend.map(resolvePath);
            }
        }
    });
    loader(Object.keys(allMentionedModulesMap), () => {
        const modules = loader.getBuildInfo();
        const partialResult = emitEntryPoints(modules, entryPointsMap);
        const cssInlinedResources = loader('vs/css').getInlinedResources();
        callback(null, {
            files: partialResult.files,
            cssInlinedResources: cssInlinedResources,
            bundleData: partialResult.bundleData
        });
    }, (err) => callback(err, null));
}
174415
def export_pipeline(conf, args):
    """"""
    # Export the source pipeline and save it to file
    src = conf.config['instances'][args.src_instance]
    src_url = api.build_pipeline_url(build_instance_url(src))
    src_auth = tuple([conf.creds['instances'][args.src_instance]['user'],
                      conf.creds['instances'][args.src_instance]['pass']])
    verify_ssl = src.get('verify_ssl', True)
    export_json = api.export_pipeline(src_url, args.src_pipeline_id, src_auth, verify_ssl)
    with open(args.out, 'w') as outFile:
        outFile.write(json.dumps(export_json, indent=4, sort_keys=False))
        return (0, '')
1163492
def fromimportunreg(
        cls, bundle, cid, rsid, import_ref, exception, endpoint
    ):
        # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ImportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
        
        return RemoteServiceAdminEvent(
            typ=RemoteServiceAdminEvent.IMPORT_UNREGISTRATION,
            bundle=bundle,
            cid=cid,
            rsid=rsid,
            import_ref=import_ref,
            exception=exception,
            endpoint=endpoint,
        )
1064718
function(action, channel, imports, sysImports, contentParts, next, invokeOverride) {
    var self = this,
    errStr,
    parsingError = false,
    schemePtr,
    mixedTypes = [ 'mixed', 'array', 'object' ]

    if (this.actions[action].invoke) {

      if (!channel.config) {
        channel.config = {};
      }

      if (!contentParts) {
        contentParts = {
          _files : []
        }
      }

      try {

        // apply channel config defaults into imports, if required
        // fields don't already exist
        var actionSchema = this.getAction(action),
          missingFields = (actionSchema.imports && actionSchema.imports.required && actionSchema.imports.required.length) ? actionSchema.imports.required : [];

        // apply config defaults
        var configDefaults = this.getActionConfigDefaults(action),
          configSchema = this.getActionConfig(action).properties,
          importSchema = this.getActionImports(action).properties;

        _.each(configDefaults, function(value, key) {
          if (!channel.config[key]) {
            channel.config[key] = value;
          }
        });

        // transpose from config to imports (no need to reference channel.config in pods)
        _.each(channel.config, function(value, key) {
          // convert to boolean if not already
          if (configSchema[key] && 'boolean' === configSchema[key].type) {
            channel.config[key] = helper.isTruthy(value) ? true : false;
          }

          if (!imports[key]) {
            imports[key] = channel.config[key];
          }
        });

        // derive import defaults
        var importDefaults = this.getActionImportDefaults(action);
        _.each(importDefaults, function(value, key) {
          if (!imports[key]) {
            imports[key] = value;
          }
        });

        for (var k in imports) {
          // trim empty import
          if (imports.hasOwnProperty(k) && '' === imports[k]) {
            delete imports[k];
            continue;
          }

          if (missingFields.length && missingFields.indexOf(k) > -1  ){
        	   missingFields.splice(missingFields.indexOf(k) ,1);
          }

        var mixed;
		    if(
          importSchema[k] && importSchema[k].type
          || configSchema[k] && configSchema[k].type
          ) {
			  	p_errStr = null;
			  	value = imports[k];

          if (importSchema[k]) {
            schemePtr = importSchema[k];
          } else if (configSchema[k]) {
            schemePtr = configSchema[k];
          }

          type = schemePtr.type.toLowerCase();

          //
          if ('number' === type) {
            pValue = helper.stringToFloat(value);
            if (0 !== pValue && !pValue) {
              p_errStr = k + ': String cannot be converted to Number';
            } else {
              imports[k] = pValue;
            }

          } else if ('integer' === type) {
            pValue = helper.stringToInt(value);
            if (0 !== pValue && !pValue) {
              p_errStr = k + ': String cannot be converted to Integer';
            } else {
              imports[k] = pValue;
            }

          } else if ('boolean' === type) {

            var pValue = helper.stringToBoolean(value);

            if (pValue == null) {
              p_errStr = k + ': String cannot be converted to Boolean';
            } else {
              imports[k] = pValue;
            }

          } else if (-1 !== mixedTypes.indexOf(type) ) {
            if ('object' === type && helper.isObject(value)) {
              imports[k] = value;

            } else if ('array' === type && helper.isArray(value)) {
              imports[k] = value;

            } else {
              pValue = helper.stringToJson(value);

              if (pValue) {
                imports[k] = pValue;

              } else if(!pValue){
                imports[k] = value;

              } else {
                p_errStr = k + ': String cannot be converted to '
                  + (('mixed' === type || 'object' === type) ? 'Object' : 'Array') ;
              }
            }
          }

        	if(p_errStr){
        		parsingError = true;
        		self.log(p_errStr, channel, 'error');
        		next.call(self, p_errStr);
        	}
			  }
      }

      if(missingFields.length){
        errStr = 'Missing Required Field(s):' + missingFields.join();
        self.log(errStr, channel, 'error');
        next.call(self, errStr)
      }

      if (!missingFields.length && !parsingError) {
        var invokeMethod = 'invoke' === this.getTriggerType() ? 'invoke' : 'trigger';

        // @deprecate -- when all trigger actions support 'trigger' method
        if (invokeOverride || !this.actions[action][invokeMethod]) {
          invokeMethod = 'invoke';
        }

        //
        this.actions[action][invokeMethod](imports, channel, sysImports, contentParts, function(err, exports) {
          if (err) {
            self.log(err, channel, 'error');
          }
          next.apply(self, arguments);
        });
      }
     } catch (e) {
       errStr = 'EXCEPT ' + e.toString();
       self.log(errStr, channel, 'error');
 	  	 next.call(self, errStr);
     }
    }
  }
505165
function mergeConf(env, conf, key, ENV, fn) {
  fetch(conf, key, function(err, layout) {
    if (err) return fn(err);

    fetch(layout, 'default', function(err, defaults) {
      if (err) return fn(err);

      debug('  default', defaults);
      merge(ENV, defaults);
      debug('    ', ENV);

      fetch(layout, env, function(err, envs) {
        if (err) return fn(err);

        debug('  ' + env, envs);
        merge(ENV, envs);
        debug('    ', ENV);

        fn();
      });
    });
  });
}
340470
private void incrementPortsIfDuplicateName(String configName, ProcessConfigBean config) {
        int startedCount = getNumberOfInstancesStarted(configName);

        int debugPort = config.getDebugPort();
        if ( debugPort != -1) {
            config.setDebugPort(debugPort + startedCount);
        }

        int remotingPort = config.getRemotingPort();
        if (remotingPort != -1) {
            config.setRemotingPort(remotingPort + startedCount);
        }
    }
370177
def create_datastore_write_config(mapreduce_spec):
  
  force_writes = parse_bool(mapreduce_spec.params.get("force_writes", "false"))
  if force_writes:
    return datastore_rpc.Configuration(force_writes=force_writes)
  else:
    # dev server doesn't support force_writes.
    return datastore_rpc.Configuration()
682266
def BuildServiceStub(self, cls):
    

    def _ServiceStubInit(stub, rpc_channel):
      stub.rpc_channel = rpc_channel
    self.cls = cls
    cls.__init__ = _ServiceStubInit
    for method in self.descriptor.methods:
      setattr(cls, method.name, self._GenerateStubMethod(method))
1316645
async function build(previousFileSizes) {
  console.log(`${manifest.name}: Creating an optimized production build...`)

  // a project can opt to start
  let webpackConfig = get(manifest, 'skypager.webpack.merge') === false ? {} : config

  if (get(manifest, 'skypager.webpack.build')) {
    console.log(`Using custom wepack config`)
    let configToMerge = require(path.resolve(
      path.dirname(paths.appPackageJson),
      get(manifest, 'skypager.webpack.build')
    ))

    if (typeof configToMerge === 'function') {
      configToMerge = await Promise.resolve(configToMerge(argv.env || 'production', argv, config))
    }

    if (!isArray(configToMerge)) {
      // we won't try and merge webpack config if it is an array
      webpackConfig = configMerge(webpackConfig, configToMerge)
    } else {
      console.log('Using multiple webpack configs')
    }
  }

  const compiler = webpack(webpackConfig)

  return new Promise((resolve, reject) => {
    compiler.run((err, stats) => {
      if (err) {
        return reject(err)
      }

      const messages = formatWebpackMessages(stats.toJson({}, true))
      if (messages.errors.length) {
        // Only keep the first error. Others are often indicative
        // of the same problem, but confuse the reader with noise.
        if (messages.errors.length > 1) {
          messages.errors.length = 1
        }
        console.log(`Build failed in ${manifest.name}`)
        return reject(new Error(messages.errors.join('\n\n')))
      }
      if (
        process.env.CI &&
        (typeof process.env.CI !== 'string' || process.env.CI.toLowerCase() !== 'false') &&
        messages.warnings.length
      ) {
        console.log(
          chalk.yellow(
            '\nTreating warnings as errors because process.env.CI = true.\n' +
              'Most CI servers set it automatically.\n'
          )
        )
        return reject(new Error(messages.warnings.join('\n\n')))
      }
      return resolve({
        stats,
        previousFileSizes,
        warnings: messages.warnings,
      })
    })
  })
}
1282116
def fromexportunreg(
        cls, bundle, exporterid, rsid, export_ref, exception, endpoint
    ):
        # type: (Bundle, Tuple[str, str], Tuple[Tuple[str, str], int], ExportReference, Optional[Tuple[Any, Any, Any]], EndpointDescription) -> RemoteServiceAdminEvent
        
        return RemoteServiceAdminEvent(
            typ=RemoteServiceAdminEvent.EXPORT_UNREGISTRATION,
            bundle=bundle,
            cid=exporterid,
            rsid=rsid,
            export_ref=export_ref,
            exception=exception,
            endpoint=endpoint,
        )
502305
function runSpac(schemaFilePath, namespace, outputDir) {
  var spacPath = pathMod.resolve(pathMod.join(__dirname, '../spac/spac.js'));
  var spac = childProcess.fork(
      spacPath,
      [
        '--schema=' + schemaFilePath,
        '--namespace=' + namespace,
        '--outputdir=' + outputDir,
        '--nocombine=true'
      ]);

  return new Promise(function(resolve, reject) {
    spac.on('close', function(code) {
      if (code == 0) {
        resolve();
      } else {
        var error = new Error(
            'ERROR: unable to generate code from ' + schemaFilePath + '\r\n');
        log(error);
        reject(error);
      }
    });
  });
}
1098476
static OcAgentMetricsServiceExportRpcHandler create(MetricsServiceStub stub) {
    OcAgentMetricsServiceExportRpcHandler exportRpcHandler =
        new OcAgentMetricsServiceExportRpcHandler();
    ExportResponseObserver exportResponseObserver = new ExportResponseObserver(exportRpcHandler);
    try {
      StreamObserver<ExportMetricsServiceRequest> exportRequestObserver =
          stub.export(exportResponseObserver);
      exportRpcHandler.setExportRequestObserver(exportRequestObserver);
    } catch (StatusRuntimeException e) {
      exportRpcHandler.onComplete(e);
    }
    return exportRpcHandler;
  }
756865
function exportResolverMap(backing: SchemaBacking) {
  backing.validate();
  return reduce(
    backing.types,
    (rmap, config, name) => {
      const fields = reduce(
        config.fields,
        (fmap, field, fieldName) => {
          if (_.isFunction(field.resolve)) {
            fmap[fieldName] = field.resolve;
          }
          return fmap;
        },
        {},
        true,
      );
      return _.keys(fields).length ? _.merge(rmap, { [name]: fields }) : rmap;
    },
    {},
    true,
  );
}
71431
@Override
    public void checkProcessorConfig(Properties properties) {
        String exportClientClass = properties.getProperty(EXPORT_TO_TYPE);
        Preconditions.checkNotNull(exportClientClass, "export to type is undefined or custom export plugin class missing.");

        try {
            final Class<?> clientClass = Class.forName(exportClientClass);
            ExportClientBase client = (ExportClientBase) clientClass.newInstance();
            client.configure(properties);
        } catch(Throwable t) {
            throw new RuntimeException(t);
        }
    }
189029
function Export(clazz, name, context) {
    if (name === void 0) { name = clazz.name; }
    if (context === void 0) { context = context_constanst_1.SERVICE_FACTORY_DEFAULT_CONTEXT; }
    // Export clazz if name is set
    service_factory_1.ServiceFactory.export(clazz, name, context);
    /**
     * Modify constructor
     */
    return function (constructor) {
        // Preserve original
        var original = constructor;
        // Construct function
        function construct(constructor) {
            // Create constructor
            var c = function () {
                return constructor.apply(this);
            };
            // Assign prototype
            c.prototype = constructor.prototype;
            // Create new instance
            return service_factory_1.ServiceFactory.export(c, name, context);
        }
        // Constructor behaviour
        var f = function () {
            return construct(original);
        };
        // Copy prototype
        f.prototype = original.prototype;
        // Return new 
        return f;
    };
}