Helper for creating mock files
760644
function createFiles (num, dir) {
  for (var i = 0; i < num; i++) {
    grunt.file.write(path.join(dir, 'test-' + i + '.js'), 'var test = ' + i + ';');
  }
}
1336975
def make_files(self):
        

        # get the files from the template
        files = []
        try:
            files = self.files()
        except AttributeError:
            self.term.print_info(u"No file in the template. Weird, but why not?")

        # get the substitutes intersecting the template and the cli
        try:
            for key in self.substitutes().keys():
                if key not in self.substitutes_dict:
                    self.substitutes_dict[key] = self.substitutes()[key]

        except AttributeError:
            self.term.print_info(u"No substitute in the template.")

        working_dir = os.getcwd()
        # iteratively create the files
        for directory, name, template_file in files:
            if directory:
                filepath = working_dir + '/' + directory + '/' + name
                filename = directory + '/' + name
            else:
                filepath = working_dir + '/' + name
                filename = name

            # open the file to write into
            try:
                output = open(filepath, 'w')
            except IOError:
                self.term.print_error_and_exit(u"Can't create destination"\
                                                " file: {0}".format(filepath))

            # open the template to read from
            if template_file:
                input_file = join(dirname(__file__), template_file + '.txt')

                # write each line of input file into output file,
                # templatized with substitutes
                try:
                    with open(input_file, 'r') as line:
                        template_line = Template(line.read())
                        try:
                            output.write(template_line.
                                safe_substitute(self.substitutes_dict).encode('utf-8'))
                        except TypeError:
                            output.write(template_line.
                                safe_substitute(self.substitutes_dict))
                    output.close()
                except IOError:
                    self.term.print_error_and_exit(u"Can't create template file"\
                                                   ": {0}".format(input_file))
            else:
                output.close() # the file is empty, but still created

            self.term.print_info(u"Creating file '{0}'"
                             .format(self.term.text_in_color(filename, TERM_YELLOW)))
254546
def GenerateClient(args):

    """"""

    codegen = _GetCodegenFromFlags(args)
    if codegen is None:
        logging.error('Failed to create codegen, exiting.')
        return 128
    _WriteGeneratedFiles(args, codegen)
    if args.init_file != 'none':
        _WriteInit(codegen)
932469
def createArchiveExample(fileName):
    
    print('*' * 80)
    print('Create archive')
    print('*' * 80)

    archive = CombineArchive()
    archive.addFile(
        fileName,  # filename
        "./models/model.xml",  # target file name
        KnownFormats.lookupFormat("sbml"),  # look up identifier for SBML models
        True  # mark file as master
    )

    # add metadata to the archive itself
    description = OmexDescription()
    description.setAbout(".")
    description.setDescription("Simple test archive including one SBML model")
    description.setCreated(OmexDescription.getCurrentDateAndTime())

    creator = VCard()
    creator.setFamilyName("Bergmann")
    creator.setGivenName("Frank")
    creator.setEmail("fbergman@caltech.edu")
    creator.setOrganization("Caltech")

    description.addCreator(creator)

    archive.addMetadata(".", description)

    # add metadata to the added file
    location = "./models/model.xml"
    description = OmexDescription()
    description.setAbout(location)
    description.setDescription("SBML model")
    description.setCreated(OmexDescription.getCurrentDateAndTime())
    archive.addMetadata(location, description)

    # write the archive
    out_file = "out.omex"
    archive.writeToFile(out_file)

    print('Archive created:', out_file)
1193407
function createOutputFolder(next) {
    var defPath         = path.join(getConfig('output.folder'), 'definition-files'),
        defPathCustom   = path.join(getConfig('output.folder'), 'definition-files-custom');

    fs.remove(defPath, function (err) {
        if (err) { next(err); }
        fs.createFile(path.join(defPath, '_Dont_add_or_edit_any_files'), function (err) {
            if (err) { next(err); }
            fs.mkdirs(defPathCustom, function (err) {
                if (err) { next(err); }
                next(null);
            });
        });
    });
}
554195
def create_mock_project
      @project_path = File.join("spec", "data", "test-project")
      Tetra::Project.init(@project_path, false)
      @project = Tetra::Project.new(@project_path)
    end
309836
def upload_files_and_create_package(
    ctx,
    opts,
    package_type,
    owner_repo,
    dry_run,
    no_wait_for_sync,
    wait_interval,
    skip_errors,
    sync_attempts,
    **kwargs
):
    """"""
    # pylint: disable=unused-argument
    owner, repo = owner_repo

    # 1. Validate package create parameters
    validate_create_package(
        ctx=ctx,
        opts=opts,
        owner=owner,
        repo=repo,
        package_type=package_type,
        skip_errors=skip_errors,
        **kwargs
    )

    # 2. Validate file upload parameters
    md5_checksums = {}
    for k, v in kwargs.items():
        if not v or not k.endswith("_file"):
            continue

        md5_checksums[k] = validate_upload_file(
            ctx=ctx,
            opts=opts,
            owner=owner,
            repo=repo,
            filepath=v,
            skip_errors=skip_errors,
        )

    if dry_run:
        click.echo()
        click.secho("You requested a dry run so skipping upload.", fg="yellow")
        return

    # 3. Upload any arguments that look like files
    for k, v in kwargs.items():
        if not v or not k.endswith("_file"):
            continue

        kwargs[k] = upload_file(
            ctx=ctx,
            opts=opts,
            owner=owner,
            repo=repo,
            filepath=v,
            skip_errors=skip_errors,
            md5_checksum=md5_checksums[k],
        )

    # 4. Create the package with package files and additional arguments
    _, slug = create_package(
        ctx=ctx,
        opts=opts,
        owner=owner,
        repo=repo,
        package_type=package_type,
        skip_errors=skip_errors,
        **kwargs
    )

    if no_wait_for_sync:
        return

    # 5. (optionally) Wait for the package to synchronise
    wait_for_package_sync(
        ctx=ctx,
        opts=opts,
        owner=owner,
        repo=repo,
        slug=slug,
        wait_interval=wait_interval,
        skip_errors=skip_errors,
        attempts=sync_attempts,
    )
898183
def CreateMock(self, class_to_mock):
    

    new_mock = MockObject(class_to_mock)
    self._mock_objects.append(new_mock)
    return new_mock
741165
def init_mock(self, release):
        """"""
        root = '/var/lib/mock/%s' % release['mock']
        if not os.path.isdir(root):
            self.mock_cmd(release, '--init')
            self.log.info('mock chroot initialized')
        else:
            if release.get('mock_clean'):
                self.mock_cmd(release, '--clean')
                self.mock_cmd(release, '--init')
                self.log.info('mock chroot cleaned & initialized')
            else:
                self.mock_cmd(release, '--update')
                self.log.info('mock chroot updated')
983270
void generateEisCode(Definition def)
   {
      try
      {
         String clazzName = this.getClass().getPackage().getName() + ".code.TestEisCodeGen";
         String javaFile = def.getDefaultValue() + "Handler.java";
         FileWriter fw = Utils.createTestFile(javaFile, def.getRaPackage(), def.getOutputDir());

         Class<?> clazz = Class.forName(clazzName, true, Thread.currentThread().getContextClassLoader());
         AbstractCodeGen codeGen = (AbstractCodeGen) clazz.newInstance();

         codeGen.generate(def, fw);

         fw.flush();
         fw.close();
      }
      catch (Exception e)
      {
         e.printStackTrace();
      }
   }
1120557
def main(argv=None):
    
    @contextmanager
    def tmpdir():
        """ Create a self-deleting temporary directory. """
        path = mkdtemp()
        try:
            yield path
        finally:
            rmtree(path)
        return

    def test():
        """ Execute the test suite. """
        install = "{:s} install -r requirements-test.txt"
        check_call(install.format(pip).split())
        pytest = join(path, "bin", "py.test")
        test = "{:s} test/".format(pytest)
        check_call(test.split())
        uninstall = "{:s} uninstall -y -r requirements-test.txt"
        check_call(uninstall.format(pip).split())
        return

    args = _cmdline(argv)
    path = join(abspath(args.root), args.name)
    with tmpdir() as tmp:
        clone = "git clone {:s} {:s}".format(args.repo, tmp)
        check_call(clone.split())
        chdir(tmp)
        checkout = "git checkout {:s}".format(args.checkout)
        check_call(checkout.split())
        virtualenv = "virtualenv {:s}".format(path)
        check_call(virtualenv.split())
        pip = join(path, "bin", "pip")
        install = "{:s} install -U -r requirements.txt .".format(pip)
        check_call(install.split())
        if args.test:
            test()
    return 0
904360
def create(cls, env=None, args=None):
    
    env = {k: v for k, v in (os.environ if env is None else env).items()
           if k.startswith('PANTS_')}
    args = tuple(sys.argv if args is None else args)

    flags = set()
    short_flags = set()

    def filecontent_for(path):
      return FileContent(ensure_text(path), read_file(path, binary_mode=True))

    def capture_the_flags(*args, **kwargs):
      for arg in args:
        flags.add(arg)
        if len(arg) == 2:
          short_flags.add(arg)
        elif kwargs.get('type') == bool:
          flags.add('--no-{}'.format(arg[2:]))

    GlobalOptionsRegistrar.register_bootstrap_options(capture_the_flags)

    def is_bootstrap_option(arg):
      components = arg.split('=', 1)
      if components[0] in flags:
        return True
      for flag in short_flags:
        if arg.startswith(flag):
          return True
      return False

    # Take just the bootstrap args, so we don't choke on other global-scope args on the cmd line.
    # Stop before '--' since args after that are pass-through and may have duplicate names to our
    # bootstrap options.
    bargs = tuple(filter(is_bootstrap_option, itertools.takewhile(lambda arg: arg != '--', args)))

    config_file_paths = cls.get_config_file_paths(env=env, args=args)
    config_files_products = [filecontent_for(p) for p in config_file_paths]
    pre_bootstrap_config = Config.load_file_contents(config_files_products)

    initial_bootstrap_options = cls.parse_bootstrap_options(env, bargs, pre_bootstrap_config)
    bootstrap_option_values = initial_bootstrap_options.for_global_scope()

    # Now re-read the config, post-bootstrapping. Note the order: First whatever we bootstrapped
    # from (typically pants.ini), then config override, then rcfiles.
    full_configpaths = pre_bootstrap_config.sources()
    if bootstrap_option_values.pantsrc:
      rcfiles = [os.path.expanduser(str(rcfile)) for rcfile in bootstrap_option_values.pantsrc_files]
      existing_rcfiles = list(filter(os.path.exists, rcfiles))
      full_configpaths.extend(existing_rcfiles)

    full_config_files_products = [filecontent_for(p) for p in full_configpaths]
    post_bootstrap_config = Config.load_file_contents(
      full_config_files_products,
      seed_values=bootstrap_option_values
    )

    env_tuples = tuple(sorted(iteritems(env), key=lambda x: x[0]))
    return cls(env_tuples=env_tuples, bootstrap_args=bargs, args=args, config=post_bootstrap_config)
603054
def _create_command_file(self, expect, send):
		
		shutit = self.shutit
		random_id = shutit_util.random_id()
		fname = shutit_global.shutit_global_object.shutit_state_dir + '/tmp_' + random_id
		working_str = send
		# truncate -s must be used as --size is not supported everywhere (eg busybox)
		assert not self.sendline(ShutItSendSpec(self,
		                                        send=' truncate -s 0 '+ fname,
		                                        ignore_background=True)), shutit_util.print_debug()
		self.expect(expect)
		size = shutit_global.shutit_global_object.line_limit
		while working_str:
			curr_str = working_str[:size]
			working_str = working_str[size:]
			assert not self.sendline(ShutItSendSpec(self,
			                                        send=' ' + shutit.get_command('head') + ''' -c -1 >> ''' + fname + """ << 'END_""" + random_id + """'\n""" + curr_str + """\nEND_""" + random_id,
		                                            ignore_background=True)), shutit_util.print_debug()
			self.expect(expect)
		assert not self.sendline(ShutItSendSpec(self,
		                                        send=' chmod +x ' + fname,
		                                        ignore_background=True)), shutit_util.print_debug()
		self.expect(expect)
		return fname
809428
def build_mock_repository(conn_, file_path_list, verbose):
    
    for file_path in file_path_list:
        ext = _os.path.splitext(file_path)[1]
        if not _os.path.exists(file_path):
            raise ValueError('File name %s does not exist' % file_path)
        if ext == '.mof':
            conn_.compile_mof_file(file_path)
        elif ext == '.py':
            try:
                with open(file_path) as fp:
                    # the exec includes CONN and VERBOSE
                    globalparams = {'CONN': conn_, 'VERBOSE': verbose}
                    # pylint: disable=exec-used
                    exec(fp.read(), globalparams, None)

            except Exception as ex:
                exc_type, exc_value, exc_traceback = _sys.exc_info()
                tb = repr(traceback.format_exception(exc_type, exc_value,
                                                     exc_traceback))
                raise ValueError(
                    'Exception failure of "--mock-server" python script %r '
                    'with conn %r Exception: %r\nTraceback\n%s' %
                    (file_path, conn, ex, tb))

        else:
            raise ValueError('Invalid suffix %s on "--mock-server" '
                             'global parameter %s. Must be "py" or "mof".'
                             % (ext, file_path))

    if verbose:
        conn_.display_repository()
752546
def main():
    """"""
    desc = 'Generate files to benchmark'
    parser = argparse.ArgumentParser(description=desc)
    parser.add_argument(
        '--src',
        dest='src_dir',
        default='src',
        help='The directory containing the templates'
    )
    parser.add_argument(
        '--out',
        dest='out_dir',
        default='generated',
        help='The output directory'
    )
    parser.add_argument(
        '--seed',
        dest='seed',
        default='13',
        help='The random seed (to ensure consistent regeneration)'
    )

    args = parser.parse_args()

    random.seed(int(args.seed))

    mkdir_p(args.out_dir)

    for template in templates_in(args.src_dir):
        modes = template.modes()

        n_range = template.range()
        for n_value in n_range:
            base = template.instantiate(n_value)
            for mode in modes:
                write_file(
                    os.path.join(
                        args.out_dir,
                        out_filename(template, n_value, mode)
                    ),
                    mode.convert_from(base)
                )
        write_file(
            os.path.join(args.out_dir, '{0}.json'.format(template.name)),
            json.dumps({
                'files': {
                    n: {
                        m.identifier: out_filename(template, n, m)
                        for m in modes
                    } for n in n_range
                },
                'name': template.name,
                'x_axis_label': template.property('x_axis_label'),
                'desc': template.property('desc'),
                'modes': {m.identifier: m.description() for m in modes}
            })
        )
453269
def mock_chroot(self, release, cmd, **kwargs):
        """"""
        return self.mock_cmd(release, '--chroot', cmd, **kwargs)
270585
public static synchronized void generate() {
        LOGGER.debug("Generating documentation of test documentation included in pythonlib directories.");
        try {
            IS_RUNNING = true;
            List<File> pythonLibDirectories = findPythonLibDirectories(ROOT_SCRIPT_DIRECTORY);

            List<File> pythonScriptFiles = findPythonScripts(pythonLibDirectories);
            for (File script : pythonScriptFiles) {
                if (hasToGenerateDocumentation(script)) {
                    GenerateTestStepsModulesDoc.generate(script.getAbsolutePath());
                }
            }
            ALREADY_RUN = true;
        } catch (Exception ex) {
            ex.printStackTrace();
        } finally {
            IS_RUNNING = false;
        }
    }