Example #1
0
def main():
    resHTML = '<h2>That resource type does not exist</h2>'
    resHistory = ''
    useCookies = 1
    linkappend = ''
    logged_state = 0
    currentUser = ''
    typeGroup = 'type'
    typeID = ''
    typeName = ''
    uiTheme = ''
    # Get current url
    try:
        url = os.environ['SCRIPT_NAME']
    except KeyError:
        url = ''

    form = cgi.FieldStorage()
    # Get Cookies

    cookies = Cookie.SimpleCookie()
    try:
        cookies.load(os.environ['HTTP_COOKIE'])
    except KeyError:
        useCookies = 0

    if useCookies:
        try:
            currentUser = cookies['userID'].value
        except KeyError:
            currentUser = ''
        try:
            loginResult = cookies['loginAttempt'].value
        except KeyError:
            loginResult = 'success'
        try:
            sid = cookies['gh_sid'].value
        except KeyError:
            sid = form.getfirst('gh_sid', '')
        try:
            uiTheme = cookies['uiTheme'].value
        except KeyError:
            uiTheme = ''
        try:
            galaxy = cookies['galaxy'].value
        except KeyError:
            galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)
    else:
        loginResult = form.getfirst('loginAttempt', '')
        sid = form.getfirst('gh_sid', '')
        galaxy = form.getfirst('galaxy', ghShared.DEFAULT_GALAXY)

    # escape input to prevent sql injection
    sid = dbShared.dbInsertSafe(sid)

    # Get a session

    if loginResult == None:
        loginResult = 'success'

    sess = dbSession.getSession(sid)
    if (sess != ''):
        logged_state = 1
        currentUser = sess
        if (uiTheme == ''):
            uiTheme = dbShared.getUserAttr(currentUser, 'themeName')
        if (useCookies == 0):
            linkappend = 'gh_sid=' + sid
    else:
        if (uiTheme == ''):
            uiTheme = 'crafter'

    path = ['']
    if os.environ.has_key('PATH_INFO'):
        path = os.environ['PATH_INFO'].split('/')[1:]
        path = [p for p in path if p != '']

    if path[0] != '':
        typeID = dbShared.dbInsertSafe(path[0])

        try:
            conn = dbShared.ghConn()
            cursor = conn.cursor()
        except Exception:
            errorstr = "Error: could not connect to database"

        if (cursor):
            cursor.execute(
                'SELECT resourceTypeName, rg1.groupName, rg2.groupName, rt.containerType, CRmin, CRmax, CDmin, CDmax, DRmin, DRmax, FLmin, FLmax, HRmin, HRmax, MAmin, MAmax, PEmin, PEmax, OQmin, OQmax, SRmin, SRmax, UTmin, UTmax, ERmin, ERmax, rt.resourceCategory, rt.resourceGroup FROM tResourceType rt INNER JOIN tResourceGroup rg1 ON rt.resourceCategory = rg1.resourceGroup INNER JOIN tResourceGroup rg2 ON rt.resourceGroup = rg2.resourceGroup WHERE resourceType="'
                + typeID + '";')
            row = cursor.fetchone()
            if (row != None):
                typeName = row[0]
            else:
                # look up group info if not found as a type
                typeGroup = 'group'
                cursor.execute(
                    'SELECT groupName, (SELECT rg.groupName FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS resCat, "" AS resourceGroup, Max(tResourceType.containerType) AS contType, Min(CRmin), Max(CRmax), Min(CDmin), Max(CDmax), Min(DRmin), Max(DRmax), Min(FLmin), Max(FLmax), Min(HRmin), Max(HRmax), Min(MAmin), Max(MAmax), Min(PEmin), Max(PEmax), Min(OQmin), Max(OQmax), Min(SRmin), Max(SRmax), Min(UTmin), Max(UTmax), Min(ERmin), Max(ERmax), (SELECT rgc.resourceCategory FROM tResourceGroupCategory rgc INNER JOIN tResourceGroup rg ON rgc.resourceCategory = rg.resourceGroup WHERE rgc.resourceGroup=tResourceGroup.resourceGroup AND rg.groupLevel = tResourceGroup.groupLevel -1) AS catID FROM tResourceGroup, tResourceType WHERE tResourceGroup.resourceGroup="'
                    + typeID +
                    '" AND tResourceType.resourceType IN (SELECT resourceType FROM tResourceTypeGroup WHERE resourceGroup="'
                    + typeID + '" GROUP BY resourceType);')
                row = cursor.fetchone()
                if (row != None):
                    typeName = row[0]
                else:
                    typeGroup = ''

            favHTML = ''
            if logged_state > 0:
                favCursor = conn.cursor()
                favSQL = ''.join((
                    'SELECT itemID FROM tFavorites WHERE favType=2 AND userID="',
                    currentUser, '" AND favGroup="', typeID, '" AND galaxy=',
                    galaxy))
                favCursor.execute(favSQL)
                favRow = favCursor.fetchone()
                if favRow != None:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16On.png" /></a></div>'
                else:
                    favHTML = '  <div class="inlineBlock" style="width:3%;float:left;"><a alt="Favorite" title="Favorite" style="cursor: pointer;" onclick="toggleFavorite(this, 2, \'' + typeID + '\', $(\'#galaxySel\').val());"><img src="/images/favorite16Off.png" /></a></div>'
                favCursor.close()

            if typeName != '' and typeName != None:
                resHTML = '<div style="font-size:16px;font-weight:bold;">' + favHTML + typeName

                if row != None and row[3] != None:
                    if row[1] != typeName:
                        resHTML += '<div style="float:right;"><img src="/images/resources/' + row[
                            3] + '.png" /></div></div>'
                    else:
                        resHTML += '</div>'
                    # breadcrumb to resource type if not top level category
                    if row[1] != typeName:
                        resHTML += '<h3 style="margin-bottom:12px;">'
                        if row[26] != 'resource':
                            resHTML += '<a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + str(
                                row[26]) + '">' + str(row[1]) + '</a>'
                        else:
                            resHTML += row[1]
                        if typeGroup == 'type':
                            resHTML += ' > <a href="' + ghShared.BASE_SCRIPT_URL + 'resourceType.py/' + row[
                                27] + '">' + row[2] + '</a>'
                        resHTML += ' > ' + typeName + '</h3>'
                    # min/max stats table
                    resHTML += '<table class="resAttr resourceStats"><tr>'
                    resHTML += '<td><td class="header"><span>CR</span></td><td class="header"><span>CD</span></td><td class="header"><span>DR</span></td><td class="header"><span>FL</span></td><td class="header"><span>HR</span></td><td class="header"><span>MA</span></td><td class="header"><span>PE</span></td><td class="header"><span>OQ</span></td><td class="header"><span>SR</span></td><td class="header"><span>UT</span></td><td class="header"><span>ER</span></td></tr>'
                    resHTML += '<tr><td class="header">Min</td><td>' + z2b(
                        row[4]
                    ) + '</td><td>' + z2b(row[6]) + '</td><td>' + z2b(
                        row[8]
                    ) + '</td><td>' + z2b(row[10]) + '</td><td>' + z2b(
                        row[12]) + '</td><td>' + z2b(
                            row[14]) + '</td><td>' + z2b(
                                row[16]) + '</td><td>' + z2b(
                                    row[18]) + '</td><td>' + z2b(
                                        row[20]) + '</td><td>' + z2b(
                                            row[22]) + '</td><td>' + z2b(
                                                row[24]) + '</td></tr>'
                    resHTML += '<tr><td class="header">Max</td><td>' + z2b(
                        row[5]
                    ) + '</td><td>' + z2b(row[7]) + '</td><td>' + z2b(
                        row[9]
                    ) + '</td><td>' + z2b(row[11]) + '</td><td>' + z2b(
                        row[13]) + '</td><td>' + z2b(
                            row[15]) + '</td><td>' + z2b(
                                row[17]) + '</td><td>' + z2b(
                                    row[19]) + '</td><td>' + z2b(
                                        row[21]) + '</td><td>' + z2b(
                                            row[23]) + '</td><td>' + z2b(
                                                row[25]) + '</td></tr>'
                    resHTML += '</table>'
                else:
                    resHTML += '</div>'

            cursor.close()
        conn.close()
    else:
        resHTML = '<h1>Resource Type Groups</h1>'
        resHTML += '<div id="resTypeInfo">You have reached the resource type page.  From here, you can browse to any resource type and view things like: best spawns, schematics, creatures, and min/max stats.</div>'

    creature = max([
        typeID.find('bone_'),
        typeID.find('hide_'),
        typeID.find('meat_'),
        typeID.find('milk_')
    ])
    if typeID == '':
        # Print the plain group list for pre-IE9 because it does not support rotate css
        tmpAgent = os.environ.get("HTTP_USER_AGENT", "unknown")
        if tmpAgent == 'unknown' or (tmpAgent.find("IE") > -1
                                     and tmpAgent.find("MSIE 9.0") == -1):
            resTree = getResourceGroupsPlain()
        else:
            resTree = getResourceTree()
    else:
        resTree = ''
    pictureName = dbShared.getUserAttr(currentUser, 'pictureName')
    # Get reputation to determine editing abilities
    stats = dbShared.getUserStats(currentUser, galaxy).split(",")
    userReputation = int(stats[2])
    print 'Content-type: text/html\n'
    env = Environment(loader=FileSystemLoader('templates'))
    env.globals['BASE_SCRIPT_URL'] = ghShared.BASE_SCRIPT_URL
    env.globals['MOBILE_PLATFORM'] = ghShared.getMobilePlatform(
        os.environ['HTTP_USER_AGENT'])
    template = env.get_template('resourcetype.html')
    print template.render(
        uiTheme=uiTheme,
        loggedin=logged_state,
        currentUser=currentUser,
        loginResult=loginResult,
        linkappend=linkappend,
        url=url,
        pictureName=pictureName,
        imgNum=ghShared.imgNum,
        galaxyList=ghLists.getGalaxyList(),
        typeGroup=typeGroup,
        typeID=typeID,
        resHTML=resHTML,
        creature=creature,
        resTree=resTree,
        editCreatures=(userReputation >=
                       ghShared.MIN_REP_VALS['ADD_CREATURE']),
        resourceType=typeID)
Example #2
0
from flask import render_template, Flask, request, redirect, url_for,\
 send_from_directory, make_response, send_file, Response
from jinja2 import Environment, FileSystemLoader
import config
import astroph

app = Flask(__name__)

env = Environment(loader=FileSystemLoader('templates'),
                  extensions=['jinja2.ext.autoescape'])


@app.route("/")
def hello():
    return env.get_template('main.html').render(body=astroph.doit())


if __name__ == "__main__":
    app.run(debug=config.debug)
Example #3
0
import os
import tornado.ioloop
import tornado.web
import tornado.log
import time
from datetime import datetime, date, timedelta
import requests
# import queries
import json

from jinja2 import \
    Environment, PackageLoader, select_autoescape

ENV = Environment(loader=PackageLoader('monitor', 'templates'),
                  autoescape=select_autoescape(['html', 'xml']))

# since the sensors were removed, the database is unavailable now.
# have to use data imported from json file in stead
datafile = []
with open('./monitor/static/json/api_data_final.json', 'r') as f:
    datafile = json.load(f)


class TemplateHandler(tornado.web.RequestHandler):
    def render_template(self, tpl, context):
        template = ENV.get_template(tpl)
        self.write(template.render(**context))

    def get(self):
        self.set_header('Cache-Control',
                        'no-store, no-cache, must-revalidate, max-age=0')
Example #4
0
 def generate_conf(cls, log_om, rsyslog_template_name, **kwargs):
     jinja2_env = Environment(loader=FileSystemLoader(JINJA_PATH))
     template = jinja2_env.get_template(log_om.template)
     conf = log_om.to_template(**kwargs, ruleset=rsyslog_template_name)
     conf['out_template'] = rsyslog_template_name
     return template.render(conf)
Example #5
0
def generate_cfg_from_template(TEMPLATE_DIR, template, VARS_FILE):
    env = Environment(loader=FileSystemLoader(TEMPLATE_DIR), trim_blocks=True)
    template = env.get_template(template)
    vars_dict = yaml.load(open(VARS_FILE))
    return template.render(vars_dict)
"""
Authors:
Supritha Amudhu
Richa Nahar
"""

from flask import Flask, render_template, send_from_directory, request
import os
from jinja2 import Environment, PackageLoader, select_autoescape

"""
Worked on by Supritha - Snippet to load Jinja2 templates
"""
env = Environment(
    loader=PackageLoader('app', 'templates'),
    autoescape=select_autoescape(['html', 'xml'])
)


from app.index.elastic_search_helper import init_index, load_documents, query_index, load_blacklist

app = Flask(__name__)

"""
Worked on by Supritha - Route to the index page
"""
@app.route('/')
@app.route('/index')
@app.route('/index/')
def render_static():
    return render_template('index.html', index=True)
Example #7
0
def main():

    module = AnsibleModule(argument_spec=dict(
        name=dict(default=None, required=True),
        cmd=dict(default=None, required=True),
        environments=dict(default=None, type='list'),
        environment_file=dict(default=None),
        args=dict(default=None),
        user=dict(default=None),
        description=dict(default=None),
        after=dict(default='network.target syslog.target'),
        wanted_by=dict(default='multi-user.target'),
        alias=dict(default=None),
        type=dict(default='simple',
                  choices=[
                      'simple', 'forking', 'oneshot', 'dbus', 'notify', 'idle'
                  ]),
        restart=dict(default=None,
                     choices=[
                         'always', 'on-success', 'on-failure', 'on-abnormal',
                         'on-abort"', 'on-watchdog'
                     ]),
        restart_secs=dict(default=None),
        notify_access=dict(default=None, choices=['none', 'main', 'all']),
        config_dirs=dict(default=None),
        config_files=dict(default=None),
        kill_signal=dict(default=None),
        state=dict(default='present', choices=['present', 'absent']),
        prestart_script=dict(default=None),
        timeout_start_secs=dict(default='120'),
        timeout_stop_secs=dict(default='120'),
        kill_mode=dict(default=None,
                       choices=['control-group', 'process', 'mixed', 'none']),
        pidfile=dict(default=None),
        limit_nofile=dict(default=None),
        path=dict(default=None)))

    try:
        changed = False
        service_path = None
        if not module.params['path']:
            service_path = '/etc/systemd/system/%s.service' % module.params[
                'name']
        else:
            service_path = module.params['path']

        if module.params['state'] == 'absent':
            if os.path.exists(service_path):
                os.remove(service_path)
                changed = True
            if not changed:
                module.exit_json(changed=False, result="ok")
            else:
                os.system('systemctl daemon-reload')
                module.exit_json(changed=True, result="changed")

        args = ' '
        if module.params['args'] or module.params['config_dirs'] or \
           module.params['config_files']:
            if module.params['args']:
                args += module.params['args']

            if module.params['config_dirs']:
                for directory in module.params['config_dirs'].split(','):
                    args += '--config-dir %s ' % directory

            if module.params['config_files']:
                for filename in module.params['config_files'].split(','):
                    args += '--config-file %s ' % filename

        template_vars = module.params
        template_vars['args'] = args

        env = Environment().from_string(SYSTEMD_TEMPLATE)
        rendered_service = env.render(template_vars)

        if os.path.exists(service_path):
            file_hash = md5(open(service_path, 'rb').read()).hexdigest()
            template_hash = md5(rendered_service).hexdigest()
            if file_hash == template_hash:
                module.exit_json(changed=False, result="ok")

        with open(service_path, "w") as fh:
            fh.write(rendered_service)
        os.system('systemctl daemon-reload')
        module.exit_json(changed=True, result="created")
    except Exception as e:
        formatted_lines = traceback.format_exc()
        module.fail_json(msg="creating the service failed: %s" % (str(e)))
Example #8
0
from tools.ydt.utils import today

path = os.path.realpath(
    os.path.join(os.path.dirname(__file__), '..', 'templates'))

reload(sys)  # Python2.5 初始化后会删除 sys.setdefaultencoding 这个方法,我们需要重新载入
sys.setdefaultencoding('utf-8')

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
# path = BASE_DIR + "/templates"
templateLoader = FileSystemLoader(searchpath=path)

# templateLoader = jinja2.PackageLoader('app.dy_client', "templates")

env = Environment(loader=templateLoader, autoescape=True)

logger = logging.getLogger(__name__)


class ProductController(http.Controller):
    """
    前端数据接口访问
    商品详情
    """
    @http.route('/fbb/introduction', type='http', auth='public')
    def introduction(self, **post):
        """
        商品详情
        :param post:
        :return:
Example #9
0
            os.rename(old, new)
    except:
        return False
    return True


def osdelete(filename):
    try:
        if os.path.exists(filename):
            os.remove(filename)
    except:
        return False
    return True


_ENV = Environment(loader=FileSystemLoader('templates/nft'))


def nftupdate():
    result = True
    try:
        pipe = rdbconn.pipeline()
        # RTP PORTRANGE
        rtpportrange = list(
            map(
                fieldjsonify,
                rdbconn.hmget('cluster:attributes', 'rtp_start_port',
                              'rtp_end_port')))
        # NETALIAS
        netaliasnames = rdbconn.smembers('nameset:netalias')
        for netaliasname in netaliasnames:
Example #10
0
                         add_periodic_callback)
from .core import BokehServer
from .utils import transpose, without_property_validation
from ..compatibility import WINDOWS
from ..diagnostics.progress_stream import color_of
from ..metrics import time
from ..utils import (log_errors, key_split, format_bytes, format_time)

logger = logging.getLogger(__name__)

with open(os.path.join(os.path.dirname(__file__), 'templates',
                       'base.html')) as f:
    template_source = f.read()

from jinja2 import Environment, FileSystemLoader
env = Environment(loader=FileSystemLoader(
    os.path.join(os.path.dirname(__file__), 'templates')))

BOKEH_THEME = Theme(os.path.join(os.path.dirname(__file__), 'theme.yaml'))

template_variables = {'pages': ['main', 'system', 'profile', 'crossfilter']}


class StateTable(DashboardComponent):
    """ Currently running tasks """
    def __init__(self, worker):
        self.worker = worker

        names = [
            'Stored', 'Executing', 'Ready', 'Waiting', 'Connections', 'Serving'
        ]
        self.source = ColumnDataSource({name: [] for name in names})
Example #11
0
addonHandler.initTranslation()

try:
    ADDON_SUMMARY = addonHandler.getCodeAddon().manifest["summary"]
    ADDON_PANEL_TITLE = str(ADDON_SUMMARY)
except:
    ADDON_PANEL_TITLE = ADDON_SUMMARY = 'Access8Math'
try:
    from speech import BreakCommand
except:
    from speech.commands import BreakCommand

from jinja2 import Environment, FileSystemLoader, select_autoescape
TEMPLATES_PATH = os.path.join(PATH, 'templates')
env = Environment(loader=FileSystemLoader(TEMPLATES_PATH),
                  variable_start_string='{|{',
                  variable_end_string='}|}')
#, autoescape=select_autoescape(['html', 'xml']))


def flatten(lines):
    """
	convert tree to linear using generator
	@param lines:
	@type list
	@rtype
	"""
    for line in lines:
        if isinstance(line, Iterable) and not isinstance(line, str):
            for sub in flatten(line):
                yield sub
Example #12
0
from jinja2 import Environment

metric_environment = Environment()


class MetricEnvironment:
    """ Helper class to facilitate parsing a Metric's name or description in a Score Context """
    def render(self, text, score_context):
        """ Render the text in the proper Score Context """
        return metric_environment.from_string(text).render(score_context.data)


MetricEnvironment = MetricEnvironment()
Example #13
0
File: app.py Project: vimfun/small
from random import randrange
import threading

from flask.json import jsonify
from flask import Flask, render_template, request
from jinja2 import Markup, Environment, FileSystemLoader

from pyecharts import options as opts
from pyecharts.charts import Bar, Line
from pyecharts.globals import CurrentConfig
import ecs
import cms

CurrentConfig.GLOBAL_ENV = Environment(loader=FileSystemLoader("./templates"))

app = Flask(__name__, static_folder="templates")


def line_base():  # -> Line:
    line = (Line().add_xaxis(["{}".format(i) for i in range(10)]).add_yaxis(
        series_name="",
        y_axis=[randrange(50, 80) for _ in range(10)],
        is_smooth=True,
        label_opts=opts.LabelOpts(is_show=False),
    ).set_global_opts(
        title_opts=opts.TitleOpts(title="动态数据"),
        xaxis_opts=opts.AxisOpts(type_="value"),
        yaxis_opts=opts.AxisOpts(type_="value"),
    ))
    return line
Example #14
0
# coding: utf-8

# In[1]:

#!/usr/bin/env python
import os
import re
from jinja2 import Environment, FileSystemLoader

PATH = os.path.dirname(os.path.abspath("__file__"))
TEMPLATE_ENVIRONMENT = Environment(
    autoescape=False,
    loader=FileSystemLoader(os.path.join(PATH, 'templates')),
    trim_blocks=False)

def render_template(template_filename, context):
    return TEMPLATE_ENVIRONMENT.get_template(template_filename).render(context)


# ### Rendering Navbar Pages

# In[45]:

#------------------------------------------------------
fname = "index.html"
# iList, actList = new_crawl_directory_for_html('../')
context = {
}

with open(fname, 'w') as f:
Example #15
0
# Copyright (c) 2021 The Toltec Contributors
# SPDX-License-Identifier: MIT
"""
Load the Jinja2 templating engine.
"""
from jinja2 import Environment, PackageLoader

env = Environment(
    loader=PackageLoader("toltec", "templates"),
    autoescape=True,
)
Example #16
0
def load_jinja2_environment(script_paths):
    try:
        from jinja2 import Environment, FileSystemLoader, StrictUndefined, DebugUndefined
    except Exception as e:
        print('base.py error loading jinja2 environment: {}'.format(e))
        raise

    # wrap the FileSystemLoader so we can seed it with script paths and record what it requests
    class AZCGLoader(FileSystemLoader):
        def __init__(self, scripts):
            script_paths = scripts.split(',')
            paths = []
            for script_path in script_paths:
                script_dir = os.path.dirname(script_path)
                if script_dir not in paths:
                    paths.append(script_dir)
            # feed the unique script dirs as input dirs to FileSystemLoader
            super(AZCGLoader, self).__init__(paths)

        def get_source(self, environment, template):
            for searchpath in self.searchpath:
                template_filename = os.path.join(searchpath, template)
                template_file = jinja2.utils.open_if_exists(template_filename)
                if template_file is None:
                    continue
                try:
                    contents = template_file.read().decode(self.encoding)
                finally:
                    template_file.close()

                mtime = os.path.getmtime(template_filename)

                # Record dependency to utility
                RegisterDependencyFile(template_filename)

                # Allow relative template paths to this template, if not already a search path
                template_path = os.path.dirname(template_filename)
                if template_path not in self.searchpath:
                    self.searchpath.append(template_path)

                def uptodate():
                    try:
                        return os.path.getmtime(template_filename) == mtime
                    except OSError:
                        return False

                return contents, template_filename, uptodate
            raise jinja2.exceptions.TemplateNotFound(template)

    jinja_env = Environment(
        loader=AZCGLoader(script_paths),
        # strip whitespace from templates as much as possible
        trim_blocks=True,
        lstrip_blocks=True,
        # throws an exception if variables are undefined. Setting this to DebugUndefined will print the error message into the generated file instead
        undefined=StrictUndefined,
        extensions=[jinja_extensions.error.RaiseExtension, "jinja2.ext.do"])

    jinja_extensions.template.registerExtensions(jinja_env)

    return jinja_env
Example #17
0
def project_init(config):
    if not os.path.isdir(".git"):
        raise click.ClickException(
            "You are not in the root of a Git repository")

    if os.path.isfile("cumulusci.yml"):
        raise click.ClickException(
            "This project already has a cumulusci.yml file")

    context = {}

    # Prep jinja2 environment for rendering files
    env = Environment(
        loader=PackageLoader("cumulusci",
                             os.path.join("files", "templates", "project")),
        trim_blocks=True,
        lstrip_blocks=True,
    )

    # Project and Package Info
    click.echo()
    click.echo(click.style("# Project Info", bold=True, fg="blue"))
    click.echo(
        "The following prompts will collect general information about the project"
    )

    project_name = os.path.split(os.getcwd())[-1:][0]
    click.echo()
    click.echo(
        "Enter the project name.  The name is usually the same as your repository name.  NOTE: Do not use spaces in the project name!"
    )
    context["project_name"] = click.prompt(click.style("Project Name",
                                                       bold=True),
                                           default=project_name)

    click.echo()
    click.echo(
        "CumulusCI uses an unmanaged package as a container for your project's metadata.  Enter the name of the package you want to use."
    )
    context["package_name"] = click.prompt(click.style("Package Name",
                                                       bold=True),
                                           default=project_name)

    click.echo()
    context["package_namespace"] = None
    if click.confirm(click.style("Is this a managed package project?",
                                 bold=True),
                     default=False):
        click.echo(
            "Enter the namespace assigned to the managed package for this project"
        )
        context["package_namespace"] = click.prompt(click.style(
            "Package Namespace", bold=True),
                                                    default=project_name)

    click.echo()
    context["api_version"] = click.prompt(
        click.style("Salesforce API Version", bold=True),
        default=config.global_config.project__package__api_version,
    )

    # Dependencies
    dependencies = []
    click.echo(click.style("# Extend Project", bold=True, fg="blue"))
    click.echo(
        "CumulusCI makes it easy to build extensions of other projects configured for CumulusCI like Salesforce.org's NPSP and EDA.  If you are building an extension of another project using CumulusCI and have access to its Github repository, use this section to configure this project as an extension."
    )
    if click.confirm(
            click.style(
                "Are you extending another CumulusCI project such as NPSP or EDA?",
                bold=True,
            ),
            default=False,
    ):
        click.echo("Please select from the following options:")
        click.echo("  1: EDA (https://github.com/SalesforceFoundation/EDA)")
        click.echo(
            "  2: NPSP (https://github.com/SalesforceFoundation/Cumulus)")
        click.echo(
            "  3: Github URL (provide a URL to a Github repository configured for CumulusCI)"
        )
        selection = click.prompt(click.style("Enter your selection",
                                             bold=True))
        github_url = {
            "1": "https://github.com/SalesforceFoundation/EDA",
            "2": "https://github.com/SalesforceFoundation/Cumulus",
        }.get(selection)
        if github_url is None:
            print(selection)
            github_url = click.prompt(
                click.style("Enter the Github Repository URL", bold=True))
        dependencies.append({"type": "github", "url": github_url})
    context["dependencies"] = dependencies

    # Git Configuration
    git_config = {}
    click.echo()
    click.echo(click.style("# Git Configuration", bold=True, fg="blue"))
    click.echo(
        "CumulusCI assumes your default branch is master, your feature branches are named feature/*, your beta release tags are named beta/*, and your release tags are release/*.  If you want to use a different branch/tag naming scheme, you can configure the overrides here.  Otherwise, just accept the defaults."
    )

    git_default_branch = click.prompt(click.style("Default Branch", bold=True),
                                      default="master")
    if (git_default_branch and git_default_branch !=
            config.global_config.project__git__default_branch):
        git_config["default_branch"] = git_default_branch

    git_prefix_feature = click.prompt(click.style("Feature Branch Prefix",
                                                  bold=True),
                                      default="feature/")
    if (git_prefix_feature and git_prefix_feature !=
            config.global_config.project__git__prefix_feature):
        git_config["prefix_feature"] = git_prefix_feature

    git_prefix_beta = click.prompt(click.style("Beta Tag Prefix", bold=True),
                                   default="beta/")
    if (git_prefix_beta and
            git_prefix_beta != config.global_config.project__git__prefix_beta):
        git_config["prefix_beta"] = git_prefix_beta

    git_prefix_release = click.prompt(click.style("Release Tag Prefix",
                                                  bold=True),
                                      default="release/")
    if (git_prefix_release and git_prefix_release !=
            config.global_config.project__git__prefix_release):
        git_config["prefix_release"] = git_prefix_release

    context["git"] = git_config

    #     test:
    click.echo()
    click.echo(click.style("# Apex Tests Configuration", bold=True, fg="blue"))
    click.echo(
        "The CumulusCI Apex test runner uses a SOQL where clause to select which tests to run.  Enter the SOQL pattern to use to match test class names."
    )

    test_name_match = click.prompt(
        click.style("Test Name Match", bold=True),
        default=config.global_config.project__test__name_match,
    )
    if (test_name_match and test_name_match
            == config.global_config.project__test__name_match):
        test_name_match = None
    context["test_name_match"] = test_name_match

    # Render the cumulusci.yml file
    template = env.get_template("cumulusci.yml")
    with open("cumulusci.yml", "w") as f:
        f.write(template.render(**context))

    # Create src directory
    if not os.path.isdir("src"):
        os.mkdir("src")

    # Create sfdx-project.json
    if not os.path.isfile("sfdx-project.json"):

        sfdx_project = {
            "packageDirectories": [{
                "path": "force-app",
                "default": True
            }],
            "namespace": context["package_namespace"],
            "sourceApiVersion": context["api_version"],
        }
        with open("sfdx-project.json", "w") as f:
            f.write(json.dumps(sfdx_project))

    # Create orgs subdir
    if not os.path.isdir("orgs"):
        os.mkdir("orgs")

    template = env.get_template("scratch_def.json")
    with open(os.path.join("orgs", "beta.json"), "w") as f:
        f.write(
            template.render(
                package_name=context["package_name"],
                org_name="Beta Test Org",
                edition="Developer",
                managed=True,
            ))
    with open(os.path.join("orgs", "dev.json"), "w") as f:
        f.write(
            template.render(
                package_name=context["package_name"],
                org_name="Dev Org",
                edition="Developer",
                managed=False,
            ))
    with open(os.path.join("orgs", "feature.json"), "w") as f:
        f.write(
            template.render(
                package_name=context["package_name"],
                org_name="Feature Test Org",
                edition="Developer",
                managed=False,
            ))
    with open(os.path.join("orgs", "release.json"), "w") as f:
        f.write(
            template.render(
                package_name=context["package_name"],
                org_name="Release Test Org",
                edition="Enterprise",
                managed=True,
            ))

    # create robot folder structure and starter files
    if not os.path.isdir("robot"):
        test_folder = os.path.join("robot", context["project_name"], "tests")
        resource_folder = os.path.join("robot", context["project_name"],
                                       "resources")
        doc_folder = os.path.join("robot", context["project_name"], "doc")

        os.makedirs(test_folder)
        os.makedirs(resource_folder)
        os.makedirs(doc_folder)
        test_src = os.path.join(
            cumulusci.__location__,
            "robotframework",
            "tests",
            "salesforce",
            "create_contact.robot",
        )
        test_dest = os.path.join(test_folder, "create_contact.robot")
        copyfile(test_src, test_dest)

    click.echo(
        click.style(
            "Your project is now initialized for use with CumulusCI",
            bold=True,
            fg="green",
        ))
    click.echo(
        click.style(
            "You can use the project edit command to edit the project's config file",
            fg="yellow",
        ))
Example #18
0
#!/usr/bin/env python
import json
import re
from pathlib import Path
from subprocess import run, CalledProcessError

import click
from dulwich.repo import Repo
from dulwich.porcelain import active_branch, reset
from jinja2 import Environment, FileSystemLoader
from jsonschema import validate
from packaging.specifiers import SpecifierSet
from packaging.version import parse

env = Environment()


def get_version_identifier(version):
    "Get version identifier from version (e.g. refs/tags/v1.0.0 -> v1.0.0)."
    if version.startswith('refs/tags/'):
        return version[len('refs/tags/'):]
    if version.startswith('refs/heads/'):
        return version[len('refs/heads/'):]
    if version.startswith('refs/remotes/'):  # remote branch
        return re.sub(r'refs\/remotes\/(.+?)\/', '', version)
    return version


def get_requirements_for_ref(repo, ref):
    """Get the requirements (from requirements.txt) for a given ref."""
    try:
Example #19
0
    Environment,
    FileSystemLoader,
    PackageLoader,
    Template,
    select_autoescape,
)

from . import LockingDict, config, environment


ENV: Environment = Environment(
    loader=ChoiceLoader(
        [
            FileSystemLoader(
                [os.sep.join([environment.APP_DIRS.user_data_dir, "templates"])],
                followlinks=True,
            ),
            PackageLoader("mkproj", "templates"),
        ]
    ),
    autoescape=select_autoescape(["j2"]),
)


def get_template(section: str, template: str) -> Template:
    template_path: str = "{0}/{1}.j2".format(section, template)
    return ENV.get_template(template_path)


def render(template: Template, task_data: LockingDict) -> str:
    return template.render({"config": config.get_config, "data": task_data.get})
Example #20
0
def cli(metadata_template):
    """Generate the 'metadata.json' file for this app."""
    metadata_dir = Path(__file__).resolve().parent
    output_dir = metadata_dir / 'build'
    root = metadata_dir.parent

    repo = Repo(root)
    versions = {
        parse(get_version_identifier(ref.decode())): ref
        for ref in repo.get_refs()
    }
    requirements = {
        version: get_requirements_for_ref(repo, ref)
        for version, ref in versions.items()
    }

    def get_requirements(spec, version=None):
        spec = SpecifierSet(spec)
        if version is None:
            matching_versions = [
                version for version in sorted(versions) if version in spec
            ]
            matching_requirements = {
                requirements[version]
                for version in matching_versions
            }
            if len(matching_requirements) == 0:
                raise RuntimeError(
                    f"Unable to determine requirements for specifier '{spec}'."
                )
            elif len(matching_requirements) > 1:
                raise RuntimeError(
                    f"Requirements for specifier '{spec}' are not uniform.")
            reqs = matching_requirements.pop()
        else:
            reqs = requirements[parse(version)]

        return json.dumps({str(spec): reqs})[1:-1]

    env = Environment(loader=FileSystemLoader(metadata_dir / 'templates'))
    env.filters['get_requirements'] = get_requirements

    # Writing output...
    output_dir.mkdir(exist_ok=True)

    # index.html
    index_html = output_dir / 'index.html'
    index_html.write_text(env.get_template('index.html').render())
    click.echo(f"Write {index_html.relative_to(Path.cwd())}")

    # metadata.json
    metadata_json = output_dir / 'metadata.json'
    metadata_template = env.get_template(metadata_template)
    try:
        metadata = json.loads(metadata_template.render())
    except json.decoder.JSONDecodeError as error:
        raise RuntimeError(f"{error}\n{metadata_template.render()}")
    validate(
        instance=metadata,
        schema={
            "$ref":
            "https://aiidalab.github.io/aiidalab-registry/schemas/v1/metadata.schema.json"
        })
    metadata_json.write_text(json.dumps(metadata, indent=2))
    click.echo(f"Write {metadata_json.relative_to(Path.cwd())}")
Example #21
0
import os
import semver
import sys

from .lib.common import BASE_DIR
from invoke import task

try:
    from jinja2 import Environment
    from jinja2 import FileSystemLoader
    HAS_JINJA = True
except ImportError:
    HAS_JINJA = False

if HAS_JINJA:
    JINJA_ENV = Environment(loader=FileSystemLoader(BASE_DIR +
                                                    '/devtools/stubs'))

BUILD_DIR = '{0}/local/ansible_collections/_builds'.format(BASE_DIR)

HELP1 = dict(
    version=
    "Version of the collection to build, the version must follow in SemVer format.",
    collection=
    "The collection name to which the modules are upstreamed, DEFAULT: 'f5_modules'."
)


def update_galaxy_file(version, collection):
    # updates galaxy.yml file for collection update
    galaxy_file = '{0}/local/ansible_collections/F5Networks/{1}/galaxy.yml'.format(
        BASE_DIR, collection)
import lorem

from jinja2 import Environment, FileSystemLoader

env = Environment(loader=FileSystemLoader('templates'))

contents = {}

contents['header'] = "My Webpage"
contents['title'] = "Random Page"
contents[
    'introduction'] = "This is a random page containing some results for users"

contents['paragraphs'] = []
for i in range(10):
    new_p = {}
    new_p['title'] = 'Paragraph {}'.format(i)
    new_p['text'] = lorem.paragraph()
    contents['paragraphs'].append(new_p)

template = env.get_template('main.html')
with open('output.html', 'w') as fh:
    fh.write(template.render(contents))
    # You could also have written the following:
    # fh.write(template.render(**contents))
Example #23
0
        return 'год'
    else:
        return 'лет'


parser = argparse.ArgumentParser(
    description='''Программа формирует страницу сайта-магазина по продаже крымских вин
    на основе шаблона template.html и таблицы со списком вин в формате .xlsx'''
)
parser.add_argument(
    '--wine_path', help='''Путь к файлу cо списком продукции''', default='wine.xlsx'
)
wine_path = parser.parse_args().wine_path

env = Environment(
    loader=FileSystemLoader('.'),
    autoescape=select_autoescape(['html', 'xml'])
)

template = env.get_template('template.html')

foundation_year = 1920
company_age = datetime.datetime.today().year - foundation_year

wines_description = pandas.read_excel(wine_path, keep_default_na=False).to_dict(orient='records')
wines_description_by_categories = defaultdict(list)

for wine in wines_description:
    wine_category = wine.pop('Категория')
    wines_description_by_categories[wine_category].append(wine)

wines_description_by_categories_sorted = OrderedDict(
Example #24
0
    def make_site(cls,
                  searchpath="templates",
                  outpath=".",
                  contexts=None,
                  rules=None,
                  encoding="utf8",
                  followlinks=True,
                  extensions=None,
                  staticpaths=None,
                  filters=None,
                  env_globals=None,
                  locale=None,
                  env_kwargs=None,
                  mergecontexts=False):
        """Create a :class:`Site <Site>` object.

        :param searchpath:
            A string representing the absolute path to the directory that the
            Site should search to discover templates. Defaults to
            ``'templates'``.

            If a relative path is provided, it will be coerced to an absolute
            path by prepending the directory name of the calling module. For
            example, if you invoke staticjinja using ``python build.py`` in
            directory ``/foo``, then *searchpath* will be ``/foo/templates``.

        :param outpath:
            A string representing the name of the directory that the Site
            should store rendered files in. Defaults to ``'.'``.

        :param contexts:
            A list of *(regex, context)* pairs. The Site will render templates
            whose name match *regex* using *context*. *context* must be either
            a dictionary-like object or a function that takes either no
            arguments or a single :class:`jinja2.Template` as an argument and
            returns a dictionary representing the context. Defaults to ``[]``.

        :param rules:
            A list of *(regex, function)* pairs. The Site will delegate
            rendering to *function* if *regex* matches the name of a template
            during rendering. *function* must take a
            :class:`jinja2.Environment` object, a filename, and a context as
            parameters and render the template. Defaults to ``[]``.

        :param encoding:
            A string representing the encoding that the Site should use when
            rendering templates. Defaults to ``'utf8'``.

        :param followlinks:
            A boolean describing whether symlinks in searchpath should be
            followed or not. Defaults to ``True``.

        :param extensions:
            A list of :ref:`Jinja extensions <jinja-extensions>` that the
            :class:`jinja2.Environment` should use. Defaults to ``[]``.

        :param staticpaths:
            List of directories to get static files from (relative to
            searchpath).  Defaults to ``None``.

        :param filters:
            A dictionary of Jinja2 filters to add to the Environment.  Defaults
            to ``{}``.

        :param env_globals:
            A mapping from variable names that should be available all the time
            to their values. Defaults to ``{}``.

        :param env_kwargs:
            A dictionary that will be passed as keyword arguments to the
            jinja2 Environment. Defaults to ``{}``.

        :param mergecontexts:
            A boolean value. If set to ``True``, then all matching regex from
            the contexts list will be merged (in order) to get the final
            context.  Otherwise, only the first matching regex is used.
            Defaults to ``False``.
        """
        # Coerce search to an absolute path if it is not already
        if not os.path.isabs(searchpath):
            # TODO: Determine if there is a better way to write do this
            calling_module = inspect.getmodule(inspect.stack()[-1][0])
            # Absolute path to project
            project_path = os.path.realpath(
                os.path.dirname(calling_module.__file__))
            searchpath = os.path.join(project_path, searchpath)

        if env_kwargs is None:
            env_kwargs = {}
        env_kwargs['loader'] = FileSystemLoader(searchpath=searchpath,
                                                encoding=encoding,
                                                followlinks=followlinks)
        env_kwargs.setdefault('extensions', extensions or [])
        environment = Environment(**env_kwargs)
        if filters:
            environment.filters.update(filters)

        if env_globals:
            environment.globals.update(env_globals)

        environment.install_gettext_callables(gettext=gettext.gettext,
                                              ngettext=gettext.ngettext,
                                              newstyle=True)

        print(outpath)

        if locale:
            translations = Translations.load('locale', [locale])

            environment.install_gettext_translations(translations)

            if locale == 'ja_JP':
                locale = 'jp'
            outpath = './' + locale

            print(outpath)

        logger = logging.getLogger(__name__)
        logger.setLevel(logging.INFO)
        logger.addHandler(logging.StreamHandler())

        return cls(
            environment,
            searchpath=searchpath,
            outpath=outpath,
            encoding=encoding,
            logger=logger,
            rules=rules,
            contexts=contexts,
            staticpaths=staticpaths,
            mergecontexts=mergecontexts,
        )
def load_env():
    from jinja2 import Environment, FileSystemLoader, select_autoescape
    return Environment(loader=FileSystemLoader('templates/'),
                       autoescape=select_autoescape(['html']))
Example #26
0
def render_from_template(directory, template_name, **kwargs):
    loader = FileSystemLoader(directory)
    env = Environment(loader=loader)
    template = env.get_template(template_name)
    return template.render(**kwargs)
Example #27
0
    def init_settings(self,
                      ipython_app,
                      kernel_manager,
                      contents_manager,
                      session_manager,
                      kernel_spec_manager,
                      config_manager,
                      log,
                      base_url,
                      default_url,
                      settings_overrides,
                      jinja_env_options=None):

        _template_path = settings_overrides.get(
            "template_path",
            ipython_app.template_file_path,
        )
        if isinstance(_template_path, py3compat.string_types):
            _template_path = (_template_path, )
        template_path = [os.path.expanduser(path) for path in _template_path]

        jenv_opt = {"autoescape": True}
        jenv_opt.update(jinja_env_options if jinja_env_options else {})

        env = Environment(loader=FileSystemLoader(template_path), **jenv_opt)

        sys_info = get_sys_info()
        if sys_info['commit_source'] == 'repository':
            # don't cache (rely on 304) when working from master
            version_hash = ''
        else:
            # reset the cache on server restart
            version_hash = datetime.datetime.now().strftime("%Y%m%d%H%M%S")

        if ipython_app.ignore_minified_js:
            log.warn("""The `ignore_minified_js` flag is deprecated and no 
                longer works.  Alternatively use `npm run build:watch` when
                working on the notebook's Javascript and LESS""")
            warnings.warn(
                "The `ignore_minified_js` flag is deprecated and will be removed in Notebook 6.0",
                DeprecationWarning)

        settings = dict(
            # basics
            log_function=log_request,
            base_url=base_url,
            default_url=default_url,
            template_path=template_path,
            static_path=ipython_app.static_file_path,
            static_custom_path=ipython_app.static_custom_path,
            static_handler_class=FileFindHandler,
            static_url_prefix=url_path_join(base_url, '/static/'),
            static_handler_args={
                # don't cache custom.js
                'no_cache_paths':
                [url_path_join(base_url, 'static', 'custom')],
            },
            version_hash=version_hash,
            ignore_minified_js=ipython_app.ignore_minified_js,

            # rate limits
            iopub_msg_rate_limit=ipython_app.iopub_msg_rate_limit,
            iopub_data_rate_limit=ipython_app.iopub_data_rate_limit,
            rate_limit_window=ipython_app.rate_limit_window,

            # authentication
            cookie_secret=ipython_app.cookie_secret,
            login_url=url_path_join(base_url, '/login'),
            login_handler_class=ipython_app.login_handler_class,
            logout_handler_class=ipython_app.logout_handler_class,
            password=ipython_app.password,

            # managers
            kernel_manager=kernel_manager,
            contents_manager=contents_manager,
            session_manager=session_manager,
            kernel_spec_manager=kernel_spec_manager,
            config_manager=config_manager,

            # IPython stuff
            jinja_template_vars=ipython_app.jinja_template_vars,
            nbextensions_path=ipython_app.nbextensions_path,
            websocket_url=ipython_app.websocket_url,
            mathjax_url=ipython_app.mathjax_url,
            config=ipython_app.config,
            config_dir=ipython_app.config_dir,
            jinja2_env=env,
            terminals_available=False,  # Set later if terminals are available
        )

        # allow custom overrides for the tornado web app.
        settings.update(settings_overrides)
        return settings
Example #28
0
 def getTemplate(self, dic):
     self.env = Environment(loader=PackageLoader(self.module_path, 'app' +
                                                 '/' + self.name))
     tem = self.env.get_template(self.name + '.html')
     return tem.render(dic)
    os.system('lftp -c "source conf/' + mirror + '.conf && find -l . && exit" > lists/'  + mirror + '.txt')
    txt_editor("lists/" + mirror + ".txt", "lists/" + mirror + "_list.txt")

    os.system("diff -u lists/original_list.txt lists/" + mirror + "_list.txt > webpage/" + mirrors[mirror]['diffFile'])

    if os.stat(mirrors[mirror]['diffFile']).st_size==0:
        if mirrors[mirror]['updated'] == False:
            mirrors[mirror]['lastUpdate'] = now.strftime("%Y-%m-%d %H:%M")
        mirrors[mirror]['updated'] = True
    else:
        mirrors[mirror]['updated'] = False

# Update time
config_data['lastRun'] = now.strftime("%Y-%m-%d %H:%M")
template_name = config_data['template']

# Save data
file = open('./config.yaml', 'w')
yaml.dump(config_data, file, Dumper=yaml.RoundTripDumper)

# Load Jinja2 template
env = Environment(loader = FileSystemLoader('./'), trim_blocks=True, lstrip_blocks=True)
template = env.get_template('templates/' + template_name +'/template.j2')

# Update template files in the webpage folder
os.system('cp -r templates/' + template_name +'/* webpage/ ; rm webpage/template.j2')

# Render the template with data and save in webpage/index.html
file = open('webpage/index.html', 'w')
file.write(template.render(config_data))
Example #30
0
 def __init__(self, environment=None):
     if environment is None:
         environment = Environment()
     self.environment = environment
     self.register_environment_functions()