creates a minimal tetra project
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
1320770
def project(dest, app_bundle, force, dev,
            admin, api, celery, graphene, mail, oauth,
            security, session, sqlalchemy, webpack):
    
    if os.path.exists(dest) and os.listdir(dest) and not force:
        if not click.confirm(f'WARNING: Project directory {dest!r} exists and is '
                             f'not empty. It will be DELETED!!! Continue?'):
            click.echo(f'Exiting.')
            sys.exit(1)

    # build up a list of dependencies
    # IMPORTANT: keys here must match setup.py's `extra_requires` keys
    ctx = dict(dev=dev, admin=admin, api=api, celery=celery, graphene=graphene,
               mail=mail, oauth=oauth, security=security or oauth, session=security or session,
               sqlalchemy=security or sqlalchemy, webpack=webpack)
    ctx['requirements'] = [k for k, v in ctx.items() if v]

    # remaining ctx vars
    ctx['app_bundle_module_name'] = app_bundle

    # copy the project template into place
    copy_file_tree(PROJECT_TEMPLATE, dest, ctx, [
        (option, files)
        for option, files
        in [('api', ['app/serializers']),
            ('celery', ['app/tasks',
                        'celery_app.py']),
            ('graphene', ['app/graphql']),
            ('mail', ['templates/email']),
            ('security', ['app/models/role.py',
                          'app/models/user.py',
                          'db/fixtures/Role.yaml',
                          'db/fixtures/User.yaml']),
            ('webpack', ['assets',
                         'package.json',
                         'webpack']),
            ]
        if not ctx[option]
    ])

    click.echo(f'Successfully created a new project at: {dest}')
761511
def generate_project(self):
        
        # checks needed properties
        if not self.name or not self.destdir or \
               not os.path.isdir(self.destdir):
            raise ValueError("Empty or invalid property values: run with 'help' command")

        _log("Generating project '%s'" % self.name)
        _log("Destination directory is: '%s'" % self.destdir)

        top = os.path.join(self.destdir, self.name)
        src = os.path.join(top, self.src_name)
        resources = os.path.join(top, self.res_name)
        utils = os.path.join(src, "utils")

        if self.complex:
            models = os.path.join(src, "models")
            ctrls = os.path.join(src, "ctrls")
            views = os.path.join(src, "views")
        else: models = ctrls = views = src

        res = self.__generate_tree(top, src, resources, models, ctrls, views, utils)
        res = self.__generate_classes(models, ctrls, views) or res
        res = self.__mksrc(os.path.join(utils, "globals.py"), templates.glob) or res

        if self.complex: self.templ.update({'model_import' : "from models.application import ApplModel",
                                            'ctrl_import' : "from ctrls.application import ApplCtrl",
                                            'view_import' : "from views.application import ApplView"})
        else: self.templ.update({'model_import' : "from ApplModel import ApplModel",
                                 'ctrl_import' : "from ApplCtrl import ApplCtrl",
                                 'view_import' : "from ApplView import ApplView"})

        res = self.__mksrc(os.path.join(top, "%s.py" % self.name), templates.main) or res

        # builder file
        if self.builder:
            res = self.__generate_builder(resources) or res

        if self.dist_gtkmvc3: res = self.__copy_framework(os.path.join(resources, "external")) or res

        if not res: _log("No actions were taken")
        else: _log("Done")
        return res
634983
def lib(names, sources=[], requirements=[], default_build=[], usage_requirements=[]):
    """"""
    assert is_iterable_typed(names, basestring)
    assert is_iterable_typed(sources, basestring)
    assert is_iterable_typed(requirements, basestring)
    assert is_iterable_typed(default_build, basestring)
    assert is_iterable_typed(usage_requirements, basestring)
    if len(names) > 1:
        if any(r.startswith('<name>') for r in requirements):
            get_manager().errors()("When several names are given to the 'lib' rule\n" +
                                   "it is not allowed to specify the <name> feature.")

        if sources:
            get_manager().errors()("When several names are given to the 'lib' rule\n" +
                                   "it is not allowed to specify sources.")

    project = get_manager().projects().current()
    result = []

    for name in names:
        r = requirements[:]

        # Support " lib a ; " and " lib a b c ; " syntax.
        if not sources and not any(r.startswith("<name>") for r in requirements) \
           and not any(r.startswith("<file") for r in requirements):
            r.append("<name>" + name)

        result.append(targets.create_typed_metatarget(name, "LIB", sources,
                                                      r,
                                                      default_build,
                                                      usage_requirements))
    return result
878528
public void createWithDepth(int allowableDepth, TreeGP manager, TGPInitializationStrategy initializationStrategy){

      final int constantCount = manager.getConstants().size();
      for(int i=0; i < constantCount; ++i){
         constantSet.add(new Terminal("c" + i, manager.constant(i), manager.constantText(i), true), manager.constantWeight(i));
      }

      final int registerCount = manager.getVariableCount();
      for(int i=0; i < registerCount; ++i) {
         variableSet.add(new Terminal("v" + i, 0.0, "", false), 1.0);
      }

      final int operatorCount = manager.getOperatorSet().size();
      for(int i=0; i < operatorCount; ++i) {
         Primitive operator = manager.getOperatorSet().get(i);
         operatorSet.add(operator, manager.getOperatorSet().getWeight(i));
      }

      root = TreeGenerator.createWithDepth(this, allowableDepth, manager, initializationStrategy);
      calcLength();
      calcDepth();
   }
123613
public function actionCreate()
    {
        if (empty($this->type)) {
            Console::clearScreenBeforeCursor();
            $this->type = $this->select('Do you want to create an app or module Block?', [
                self::TYPE_APP => 'Creates a project block inside your @app Namespace (casual).',
                self::TYPE_MODULE => 'Creating a block inside a later specified Module.',
            ]);
        }

        if ($this->type == self::TYPE_MODULE && count($this->getModuleProposal()) === 0) {
            return $this->outputError('Your project does not have Project-Modules registered!');
        }

        if (empty($this->moduleName) && $this->type == self::TYPE_MODULE) {
            $this->moduleName = $this->select('Choose a module to create the block inside:', $this->getModuleProposal());
        }

        if (empty($this->blockName)) {
            $this->blockName = $this->prompt('Insert a name for your Block (e.g. HeadTeaser):', ['required' => true]);
        }
        
        if ($this->isContainer === null) {
            $this->isContainer = $this->confirm("Do you want to add placeholders to your block that serve as a container for nested blocks?", false);
        }
        
        if ($this->cacheEnabled === null) {
            $this->cacheEnabled = $this->confirm("Do you want to enable the caching for this block or not?", true);
        }
        
        if ($this->config === null) {
            $this->config = [
                'vars' => [], 'cfgs' => [], 'placeholders' => [],
            ];
    
            $doConfigure = $this->confirm('Would you like to configure this Block? (vars, cfgs, placeholders)', false);
    
            if ($doConfigure) {
                $doVars = $this->confirm('Add new Variable (vars)?', false);
                $i = 1;
                while ($doVars) {
                    $item = $this->varCreator('Variabel (vars) #'.$i, 'var');
                    $this->phpdoc[] = '{{vars.'.$item['var'].'}}';
                    $this->viewFileDoc[] = '$this->varValue(\''.$item['var'].'\');';
                    $this->config['vars'][] = $item;
                    $doVars = $this->confirm('Add one more?', false);
                    ++$i;
                }
                $doCfgs = $this->confirm('Add new Configuration (cfgs)?', false);
                $i = 1;
                while ($doCfgs) {
                    $item = $this->varCreator('Configration (cfgs) #'.$i, 'cfg');
                    $this->phpdoc[] = '{{cfgs.'.$item['var'].'}}';
                    $this->viewFileDoc[] = '$this->cfgValue(\''.$item['var'].'\');';
                    $this->config['cfgs'][] = $item;
                    $doCfgs = $this->confirm('Add one more?', false);
                    ++$i;
                }
                $doPlaceholders = $this->confirm('Add new Placeholder (placeholders)?', false);
                $i = 1;
                while ($doPlaceholders) {
                    $item = $this->placeholderCreator('Placeholder (placeholders) #'.$i);
                    $this->phpdoc[] = '{{placeholders.'.$item['var'].'}}';
                    $this->viewFileDoc[] = '$this->placeholderValue(\''.$item['var'].'\');';
                    $this->config['placeholders'][] = $item;
                    $doPlaceholders = $this->confirm('Add one more?', false);
                    ++$i;
                }
            }
        }
        
        $folder = $this->getFileBasePath() . DIRECTORY_SEPARATOR . 'blocks';
        $filePath = $folder . DIRECTORY_SEPARATOR . $this->blockName . '.php';
        
        sort($this->phpdoc);
        
        $content = $this->view->render('@cms/views/commands/block/create_block', [
            'namespace' => $this->getFileNamespace(),
            'className' => $this->blockName,
            'name' => Inflector::camel2words($this->blockName),
            'type' => $this->type,
            'module' => $this->moduleName,
            'isContainer' => $this->isContainer,
            'cacheEnabled' => $this->cacheEnabled,
            'config' => $this->config,
            'phpdoc' => $this->phpdoc,
            'extras' => $this->extras,
            'luyaText' => $this->getGeneratorText('block/create'),
        ]);

        if ($this->dryRun) {
            return $content;
        }
        
        if (FileHelper::createDirectory($folder) && FileHelper::writeFile($filePath, $content)) {
            
            // generate view file based on block object view context
            $object = Yii::createObject(['class' => $this->getFileNamespace() . '\\' . $this->blockName]);
            $viewsFolder = Yii::getAlias($object->getViewPath());
            $viewFilePath = $viewsFolder . DIRECTORY_SEPARATOR . $object->getViewFileName('php');
            if (FileHelper::createDirectory($viewsFolder) && FileHelper::writeFile($viewFilePath, $this->generateViewFile($this->blockName))) {
                $this->outputInfo('View file for the block has been created: ' . $viewFilePath);
            }
            
            return $this->outputSuccess("Block {$this->blockName} has been created: " . $filePath);
        }
        
        return $this->outputError("Error while creating block '$filePath'");
    }
3022
def create_empty(cls, tstart, tstop, fill=0.0, nside=64):
        """"""
        cth_edges = np.linspace(0, 1.0, 41)
        domega = utils.edge_to_width(cth_edges) * 2.0 * np.pi
        hpx = HPX(nside, True, 'CEL', ebins=cth_edges)
        data = np.ones((len(cth_edges) - 1, hpx.npix)) * fill
        return cls(data, hpx, cth_edges, tstart=tstart, tstop=tstop)
562066
function createCompiled(bench, decompilable, deferred, body) {
        var fn = bench.fn,
            fnArg = deferred ? getFirstArgument(fn) || 'deferred' : '';

        templateData.uid = uid + uidCounter++;

        _.assign(templateData, {
          'setup': decompilable ? getSource(bench.setup) : interpolate('m#.setup()'),
          'fn': decompilable ? getSource(fn) : interpolate('m#.fn(' + fnArg + ')'),
          'fnArg': fnArg,
          'teardown': decompilable ? getSource(bench.teardown) : interpolate('m#.teardown()')
        });

        // Use API of chosen timer.
        if (timer.unit == 'ns') {
          _.assign(templateData, {
            'begin': interpolate('s#=n#()'),
            'end': interpolate('r#=n#(s#);r#=r#[0]+(r#[1]/1e9)')
          });
        }
        else if (timer.unit == 'us') {
          if (timer.ns.stop) {
            _.assign(templateData, {
              'begin': interpolate('s#=n#.start()'),
              'end': interpolate('r#=n#.microseconds()/1e6')
            });
          } else {
            _.assign(templateData, {
              'begin': interpolate('s#=n#()'),
              'end': interpolate('r#=(n#()-s#)/1e6')
            });
          }
        }
        else if (timer.ns.now) {
          _.assign(templateData, {
            'begin': interpolate('s#=n#.now()'),
            'end': interpolate('r#=(n#.now()-s#)/1e3')
          });
        }
        else {
          _.assign(templateData, {
            'begin': interpolate('s#=new n#().getTime()'),
            'end': interpolate('r#=(new n#().getTime()-s#)/1e3')
          });
        }
        // Define `timer` methods.
        timer.start = createFunction(
          interpolate('o#'),
          interpolate('var n#=this.ns,${begin};o#.elapsed=0;o#.timeStamp=s#')
        );

        timer.stop = createFunction(
          interpolate('o#'),
          interpolate('var n#=this.ns,s#=o#.timeStamp,${end};o#.elapsed=r#')
        );

        // Create compiled test.
        return createFunction(
          interpolate('window,t#'),
          'var global = window, clearTimeout = global.clearTimeout, setTimeout = global.setTimeout;\n' +
          interpolate(body)
        );
      }
635258
def extern_project_multi(self, context_handle, val, field_str_ptr, field_str_len):
    """"""
    c = self._ffi.from_handle(context_handle)
    obj = c.from_value(val[0])
    field_name = self.to_py_str(field_str_ptr, field_str_len)

    return c.vals_buf(tuple(c.to_value(p) for p in getattr(obj, field_name)))
1336867
def create_runtime(self,
                       env,            # type: MutableMapping[Text, Text]
                       runtime_context  # type: RuntimeContext
                      ):  # type: (...) -> Tuple[List, Optional[Text]]
        
        any_path_okay = self.builder.get_requirement("DockerRequirement")[1] \
            or False
        runtime = [u"singularity", u"--quiet", u"exec", u"--contain", u"--pid",
                   u"--ipc"]
        if _singularity_supports_userns():
            runtime.append(u"--userns")
        runtime.append(u"--bind")
        runtime.append(u"{}:{}:rw".format(
            docker_windows_path_adjust(os.path.realpath(self.outdir)),
            self.builder.outdir))
        runtime.append(u"--bind")
        tmpdir = "/tmp"  # nosec
        runtime.append(u"{}:{}:rw".format(
            docker_windows_path_adjust(os.path.realpath(self.tmpdir)), tmpdir))

        self.add_volumes(self.pathmapper, runtime, any_path_okay=True,
                         secret_store=runtime_context.secret_store,
                         tmpdir_prefix=runtime_context.tmpdir_prefix)
        if self.generatemapper is not None:
            self.add_volumes(
                self.generatemapper, runtime, any_path_okay=any_path_okay,
                secret_store=runtime_context.secret_store,
                tmpdir_prefix=runtime_context.tmpdir_prefix)

        runtime.append(u"--pwd")
        runtime.append(u"%s" % (docker_windows_path_adjust(self.builder.outdir)))

        if runtime_context.custom_net:
            raise UnsupportedRequirement(
                "Singularity implementation does not support custom networking")
        elif runtime_context.disable_net:
            runtime.append(u"--net")

        env["SINGULARITYENV_TMPDIR"] = tmpdir
        env["SINGULARITYENV_HOME"] = self.builder.outdir

        for name, value in self.environment.items():
            env["SINGULARITYENV_{}".format(name)] = str(value)
        return (runtime, None)
361779
def generate(env):
    """"""

    env['MIDL']          = 'MIDL.EXE'
    env['MIDLFLAGS']     = SCons.Util.CLVar('/nologo')
    env['MIDLCOM']       = '$MIDL $MIDLFLAGS /tlb ${TARGETS[0]} /h ${TARGETS[1]} /iid ${TARGETS[2]} /proxy ${TARGETS[3]} /dlldata ${TARGETS[4]} $SOURCE 2> NUL'
    env['BUILDERS']['TypeLibrary'] = midl_builder
643385
def main():
    """"""
    if len(sys.argv) < 3:
        print('Usage: <project-name> <filetype> <list-of-path to traverse>')
        print('\tfiletype can be python/cpp/all')
        exit(-1)
    _HELPER.project_name = sys.argv[1]
    file_type = sys.argv[2]
    allow_type = []
    if file_type == 'python' or file_type == 'all':
        allow_type += [x for x in PYTHON_SUFFIX]
    if file_type == 'cpp' or file_type == 'all':
        allow_type += [x for x in CXX_SUFFIX]
    allow_type = set(allow_type)
    if os.name != 'nt':
        sys.stderr = codecs.StreamReaderWriter(sys.stderr,
                                               codecs.getreader('utf8'),
                                               codecs.getwriter('utf8'),
                                               'replace')
    for path in sys.argv[3:]:
        if os.path.isfile(path):
            process(path, allow_type)
        else:
            for root, dirs, files in os.walk(path):
                for name in files:
                    process(os.path.join(root, name), allow_type)

    nerr = _HELPER.print_summary(sys.stderr)
    sys.exit(nerr > 0)
1116617
def main():
    

    # register specific rst directives
    # small trick here: get_language will reveal languages.en
    labels = languages.get_language('en').labels
    # add the label
    languages.en.labels["todo"] = "Todo"
    # add node
    add_node(todo,
             html=(visit_todo, depart_todo),
             latex=(visit_todo, depart_todo),
             text=(visit_todo, depart_todo))
    # nodes._add_node_class_names(['todo'])

    # register the new directive todo
    directives.register_directive('todo', Todo)

    # add the label
    languages.en.labels["done"] = "Done"
    # add node
    add_node(done,
             html=(visit_done, depart_done),
             latex=(visit_done, depart_done),
             text=(visit_done, depart_done))
    # nodes._add_node_class_names(['todo'])

    # register the new directive todo
    directives.register_directive('done', Done)

    # Check if the directory is under git, if not, create the repo
    try:
        Repo()
    except InvalidGitRepositoryError:
        Repo.init()

    # add view path from module localisation
    views_path = attowiki_distro_path() + '/views/'
    bottle.TEMPLATE_PATH.insert(0, views_path)

    app = bottle.Bottle()

    # All the Urls of the project
    # index or __index__
    app.route('/', method='GET')(views.view_page)
    # new page
    app.route('/', method='POST')(views.view_page)
    # meta pages
    app.route('/__index__')(views.view_meta_index)
    app.route('/__cheatsheet__')(views.view_meta_cheat_sheet)
    app.route('/__history__/<gitref>/<name>.__source__')(
        views.view_history_source)
    app.route('/__history__/<gitref>/<name>.__diff__')(views.view_history_diff)
    app.route('/__history__/<gitref>/<name>')(views.view_history)
    app.route('/__<admonition_name>__')(views.view_meta_admonition)

    # export pdf
    app.route('/pdf/<name>')(views.view_pdf)

    # new page
    app.route('/edit/')(views.view_edit)
    # edit an existing page
    app.route('/edit/<name>')(views.view_edit)

    # cancel the edition of an existing page
    app.route('/cancel-edit/')(views.view_cancel_edit)
    app.route('/cancel-edit/<name>')(views.view_cancel_edit)

    # meta page for one single document
    app.route('/<name>.__source__')(views.view_history_source)
    app.route('/<name>.__diff__')(views.view_history_diff)
    app.route('/<name>.__<admonition_name>__')(views.view_meta_admonition)
    # view an existing page
    app.route('/<name>', method='GET')(views.view_page)

    # write new content to an existing page
    app.route('/<name>', method='POST')(views.view_page)
    # write new content to an existing page (without commit - for quick save)
    app.route('/<name>', method='PUT')(views.view_quick_save_page)

    # for devt purpose: set bottle in debug mode
    bottle.debug(True)  # this line may be commented in production mode

    # run locally by default
    import argparse
    cmd_parser = argparse.ArgumentParser(
        description="usage: %prog package.module:app")
    cmd_parser.add_argument('-u', '--user', help='user name for auth',
                            default=None)
    cmd_parser.add_argument('-p', '--password', help='password for auth',
                            default=None)
    cmd_parser.add_argument('host', help='host to bind',
                            default='localhost', nargs='?')
    cmd_parser.add_argument('port', help='bind port',
                            default='8080', nargs='?')
    args = cmd_parser.parse_args()
    attowiki.user = args.user
    attowiki.password = args.password
    if ':' in args.host:
        args.host, args.port = args.host.rsplit(':', 1)
    bottle.run(app, host=args.host, port=args.port)
1140529
def create(cls, path_name=None, name=None, project_id=None,
               log_modified_at=None, crawlable=True):
        """"""
        result = cls(path_name, name, project_id, log_modified_at, crawlable)

        db.session.add(result)
        db.session.commit()

        crawl_result(result, True)

        return result
285600
def create_package(ctx, opts, owner, repo, package_type, skip_errors, **kwargs):
    """"""
    click.echo(
        "Creating a new %(package_type)s package ... "
        % {"package_type": click.style(package_type, bold=True)},
        nl=False,
    )

    context_msg = "Failed to create package!"
    with handle_api_exceptions(
        ctx, opts=opts, context_msg=context_msg, reraise_on_error=skip_errors
    ):
        with maybe_spinner(opts):
            slug_perm, slug = api_create_package(
                package_format=package_type, owner=owner, repo=repo, **kwargs
            )

    click.secho("OK", fg="green")

    click.echo(
        "Created: %(owner)s/%(repo)s/%(slug)s (%(slug_perm)s)"
        % {
            "owner": click.style(owner, fg="magenta"),
            "repo": click.style(repo, fg="magenta"),
            "slug": click.style(slug, fg="green"),
            "slug_perm": click.style(slug_perm, bold=True),
        }
    )

    return slug_perm, slug
401353
async function createTmpDirs(projectName) {
	const {path: tmpDirPath} = await createTmpDir(projectName);

	const sourcePath = path.join(tmpDirPath, "src"); // dir will be created by writing project resources below
	await makeDir(sourcePath, {fs});
	const targetPath = path.join(tmpDirPath, "target"); // dir will be created by jsdoc itself
	await makeDir(targetPath, {fs});

	const tmpPath = path.join(tmpDirPath, "tmp"); // dir needs to be created by us
	await makeDir(tmpPath, {fs});

	return {
		sourcePath,
		targetPath,
		tmpPath
	};
}
793962
def create_engine(
        database,
        minsize=1,
        maxsize=10,
        loop=None,
        dialect=_dialect,
        paramstyle=None,
        **kwargs):
    
    coro = _create_engine(
        database=database,
        minsize=minsize,
        maxsize=maxsize,
        loop=loop,
        dialect=dialect,
        paramstyle=paramstyle,
        **kwargs
    )
    return _EngineContextManager(coro)