def run(self,rr,elem,**kw): tplname = elem._meta.app_label + '/' + elem.__class__.__name__ + '/email.html' fn = find_config_file(tplname) logger.info("Using email template %s",fn) tpl = CheetahTemplate(file(fn).read()) #~ tpl.self = elem # doesn't work because Cheetah adds itself a name 'self' tpl.instance = elem html_content = unicode(tpl) from lino.modlib.mails.models import Mail m = Mail(sender=rr.get_user(),subject=elem.get_subject(),body=html_content) m.full_clean() m.save() #~ for t,n,a in elem.get_recipients(): #~ m.recipient_set.create(type=t,address=a,name=n) for t,c in elem.get_mailable_recipients(): r = Recipient(mail=m,type=t,partner=c) r.full_clean() r.save() #~ m.recipient_set.create(type=t,partner=c) a = Attachment(mail=m,owner=elem) a.save() kw.update(open_url=rr.ui.get_detail_url(m)) return rr.ui.success(**kw)
def tecodata(self,site='US-HA1',upload=None,model=None,callback=None,**kwargs): ''' usertasks returns celery tasks perform and the link to the task result page. task_name- string optional pageNumber and nPerPage is optional ''' #db=self.db[self.database][self.collection] if model: if upload: yrs=self.db[self.database]['uploaded_grass'].find({'Site':site,'user':upload}).distinct('year') else: yrs=self.db[self.database]['years'].find_one({'Site':site,'type':model})['years'] else: if upload: yrs=self.db[self.database]['uploaded_data'].find({'Site':site,'user':upload}).distinct('Year') else: #yrs=self.db[self.database][self.collection].find({'Site':site}).distinct('Year') yrs=self.db[self.database]['years'].find_one({'Site':site,'type':'default'})['years'] yrs.sort() nameSpace = dict(years=yrs,site=site,start=yrs[0],end=yrs[-1]) if callback: cherrypy.response.headers['Content-Type'] = "application/json" t = Template(file = templatepath + '/tecodata_call.tmpl', searchList=[nameSpace]) return str(callback) + "(" + json.dumps({'html':t.respond()}) + ")" else: cherrypy.response.headers['Content-Type'] = "text/html" t = Template(file = templatepath + '/tecodata.tmpl', searchList=[nameSpace]) return t.respond()
def search( self, searchQuery="", where="" ): symbols = {} symbols["searchQuery"] = searchQuery symbols["where"] = where symbols["title"] = "" template = Template( file=os.path.join( const.DATA_ROOT, "assets/webui/search.html.tmpl" ), searchList=symbols ) return template.respond()
def on_feed_output(self, feed): try: from Cheetah.Template import Template except: raise PluginError('make_html requires Cheetah template engine') config = feed.config['make_html'] filename = os.path.expanduser(config['template']) output = os.path.expanduser(config['file']) import warnings warnings.simplefilter('ignore', UserWarning) # create the template template = Template(file=filename) # populate it template.accepted = feed.accepted template.rejected = feed.rejected template.entries = feed.entries f = open(output, 'w') f.write(template.respond().encode('utf-8')) f.close()
def usertasks(self,task_name=None,pageNumber=1,nPerPage=1500,callback=None,**kwargs): ''' usertasks returns celery tasks perform and the link to the task result page. task_name- string optional pageNumber and nPerPage is optional ''' db=self.db[self.database][self.collection] try: page=int(pageNumber) perPage=int(nPerPage) except: page=1 perPage=100 try: if cherrypy.request.login: user = cherrypy.request.login else: user = "******" except: pass if not task_name: res=db.find({'user':user}).skip((page-1)* int(nPerPage)).limit(int(nPerPage)).sort([('timestamp',-1)]) rows=db.find({'user':user}).count() else: res=db.find({'user':user,'task_name':task_name}).skip((page-1) * int(nPerPage)).limit(int(nPerPage)).sort([('timestamp',-1)]) rows=db.find({'user':user,'task_name':task_name}).count() ePage= int(math.ceil(float(rows)/float(perPage))) nameSpace = dict(tasks=res,page=page,endPage=ePage)#tresult) #t = Template(file = templatepath + '/usertasks.tmpl', searchList=[nameSpace]) if callback: t = Template(file = templatepath + '/usertasks_call.tmpl', searchList=[nameSpace]) return str(callback) + "(" + json.dumps({'html':t.respond()}) + ")" else: t = Template(file = templatepath + '/usertasks.tmpl', searchList=[nameSpace]) return t.respond()
def three(self, **kwargs): """ Accept webserver parms and show Indexers page """ if kwargs: if 'access' in kwargs: cfg.cherryhost.set(kwargs['access']) cfg.enable_https.set(kwargs.get('enable_https',0)) cfg.autobrowser.set(kwargs.get('autobrowser',0)) cfg.username.set(kwargs.get('web_user', '')) cfg.password.set(kwargs.get('web_pass', '')) if not cfg.username() or not cfg.password(): sabnzbd.interface.set_auth(cherrypy.config) # Create Indexers page info = self.info.copy() info['num'] = '» %s' % T('Step Three') info['number'] = 3 info['newzbin_user'] = cfg.newzbin_username() info['newzbin_pass'] = cfg.newzbin_password.get_stars() info['newzbin_bookmarks'] = cfg.newzbin_bookmarks() info['newzbin_url'] = cfg.newzbin_url() info['matrix_user'] = cfg.matrix_username() info['matrix_apikey'] = cfg.matrix_apikey() info['T'] = Ttemplate template = Template(file=os.path.join(self.__web_dir, 'three.html'), searchList=[info], compilerSettings=sabnzbd.interface.DIRECTIVES) return template.respond()
def four(self, **kwargs): """ Accept Indexers and show Restart screen """ if kwargs: if 'newzbin_user' in kwargs and 'newzbin_pass' in kwargs: cfg.newzbin_username.set(kwargs.get('newzbin_user','')) cfg.newzbin_password.set(kwargs.get('newzbin_pass','')) cfg.newzbin_bookmarks.set(kwargs.get('newzbin_bookmarks', '0')) if 'matrix_user' in kwargs and 'matrix_apikey' in kwargs: cfg.matrix_username.set(kwargs.get('matrix_user','')) cfg.matrix_apikey.set(kwargs.get('matrix_apikey','')) config.save_config() # Show Restart screen info = self.info.copy() info['num'] = '» %s' % T('Step Four') info['number'] = 4 info['helpuri'] = 'http://wiki.sabnzbd.org/' info['session'] = cfg.api_key() info['access_url'], info['urls'] = self.get_access_info() info['T'] = Ttemplate template = Template(file=os.path.join(self.__web_dir, 'four.html'), searchList=[info], compilerSettings=sabnzbd.interface.DIRECTIVES) return template.respond()
def get(self,mode='gallery', pagenum=1): pagenum = int(pagenum) l_skel = Skel() l_skel.title = "Smashed.in :: OverHeards" items_per_page = 10 offset = (pagenum - 1) * items_per_page #Head head_path = os.path.join (os.path.dirname(__file__), 'templates/oh-head.tmpl') l_skel.addtohead(str((Template.compile(file=head_path)(searchList={})))) #body path = os.path.join (os.path.dirname (__file__), 'templates/oh-body.tmpl') if mode == "gallery": meme_query = UserMemeDb.query(UserMemeDb.mode == 'gallery').order(-UserMemeDb.date) else: meme_query = UserMemeDb.query(UserMemeDb.userid == self.user_id).order(-UserMemeDb.date) total_items = meme_query.count() memes = meme_query.fetch (items_per_page, offset=offset) template_values = { "memes" : memes, "currentpage" : pagenum, "totalpagecount" : math.ceil(total_items / float(items_per_page)), "mode" : mode, 'isLoggedIn': '%s' %self.logged_in } l_skel.addtobody (str((Template.compile(file=path)(searchList=template_values)))) self.response.out.write(l_skel.gethtml())
def two(self, **kwargs): """ Accept server and show internal web server page """ # Save server details if kwargs: kwargs['enable'] = 1 sabnzbd.interface.handle_server(kwargs) # Create web server page info = self.info.copy() info['num'] = '» %s' % T('Step Two') info['number'] = 2 info['T'] = Ttemplate host = cfg.cherryhost() info['host'] = host # Allow special operation if host is not one of the defaults if host not in ('localhost','0.0.0.0'): info['custom_host'] = True else: info['custom_host'] = False info['have_ssl'] = bool(sabnzbd.newswrapper.HAVE_SSL) info['enable_https'] = cfg.enable_https() info['autobrowser'] = cfg.autobrowser() info['web_user'] = cfg.username() info['web_pass'] = cfg.password() template = Template(file=os.path.join(self.__web_dir, 'two.html'), searchList=[info], compilerSettings=sabnzbd.interface.DIRECTIVES) return template.respond()
def edit(self, id = 0): # we really want id as an integer. Since GET/POST parameters # are always passed as strings, let's convert it. id = int(id) if id > 0: # if an id is specified, we're editing an existing contact. contact = Contact.get(id) title = "Edit Contact" else: # if no id is specified, we're entering a new contact. contact = None title = "New Contact" # In the following template code, please note that we use # Cheetah's $getVar() construct for the form values. We have # to do this because contact may be set to None (see above). template = Template(''' <h2>$title</h2> <form action="./store" method="POST"> <input type="hidden" name="id" value="$id" /> Last Name: <input name="lastName" value="$getVar('contact.lastName', '')" /><br/> First Name: <input name="firstName" value="$getVar('contact.firstName', '')" /><br/> Phone: <input name="phone" value="$getVar('contact.phone', '')" /><br/> Email: <input name="email" value="$getVar('contact.email', '')" /><br/> URL: <input name="url" value="$getVar('contact.url', '')" /><br/> <input type="submit" value="Store" /> </form> ''', [locals(), globals()]) return template.respond()
def get(self, resource): resid = resource l_skel = Skel() l_skel.title = "Smashed.in :: OverHeards" meme_query = UserMemeDb.query(UserMemeDb.resid == resid) memes = meme_query.fetch(1) meme = memes[0] template_values = { 'memeurl': '/res/download/%s' % meme.blobid, 'conturl': '/oh/%s' % meme.resid, 'localid': '%s' % meme.resid, 'mode' : '%s' %meme.mode, 'shareid': '%s' % meme.shareid, 'currentid': '%s' % meme.resid, 'commentid': '%s' % meme.commentid, 'isLoggedIn': '%s' %self.logged_in, 'tags' : ','.join(meme.tags) } #Head head_path = os.path.join (os.path.dirname(__file__), 'templates/ohview-head.tmpl') l_skel.addtohead(str((Template.compile(file=head_path)(searchList=template_values)))) #body path = os.path.join (os.path.dirname (__file__), 'templates/ohview-body.tmpl') l_skel.addtobody (str((Template.compile(file=path)(searchList=template_values)))) self.response.out.write(l_skel.gethtml())
def infopage(self): t = Template(file=os.path.join(SCRIPTDIR, 'templates', 'info_page.tmpl'), filter=EncodeUnicode) t.admin = '' if config.get_server('tivo_mak') and config.get_server('togo_path'): t.togo = '<br>Pull from TiVos:<br>' else: t.togo = '' for section, settings in config.getShares(): plugin_type = settings.get('type') if plugin_type == 'settings': t.admin += ('<a href="/TiVoConnect?Command=Settings&' + 'Container=' + quote(section) + '">Settings</a><br>') elif plugin_type == 'togo' and t.togo: for tsn in config.tivos: if tsn and 'address' in config.tivos[tsn]: t.togo += ('<a href="/TiVoConnect?' + 'Command=NPL&Container=' + quote(section) + '&TiVo=' + config.tivos[tsn]['address'] + '">' + config.tivos[tsn]['name'] + '</a><br>') self.send_html(str(t))
def test_normalizePreprocessorArgVariants(self): src='%set foo = 12\n%%comment\n$(@foo*10)' class Settings1: tokens = '@ %' Settings1 = Settings1() from Cheetah.Template import TemplatePreprocessor settings = Template._normalizePreprocessorSettings(Settings1) preprocObj = TemplatePreprocessor(settings) def preprocFunc(source, file): return '$(12*10)', None class TemplateSubclass(Template): pass compilerSettings = {'cheetahVarStartToken':'@', 'directiveStartToken':'%', 'commentStartToken':'%%', } for arg in ['@ %', {'tokens':'@ %'}, {'compilerSettings':compilerSettings}, {'compilerSettings':compilerSettings, 'templateInitArgs':{}}, {'tokens':'@ %', 'templateAPIClass':TemplateSubclass}, Settings1, preprocObj, preprocFunc, ]: klass = Template.compile(src, preprocessors=arg) assert str(klass())=='120'
def makeConfiguredParamsHeader( templateName, variableList ): comments = [] template = Template( file=templatesPath() + templateName + '.tmpl' ) p = 0 for var in variableList: p += 1 if var.arrayInfo != None: typ = 'Parameter_Text' default = 'null, Null_Unbounded_String' #'"'+var.arrayInfo.sqlArrayDefaultDeclaration( var.getDefaultAdaValue() )+'"' elif( isIntegerTypeInPostgres( var )): typ = 'Parameter_Integer' default = '0' elif( isBigIntTypeInPostgres( var )): typ = 'Parameter_Bigint' default = '0' elif( var.isStringType() ): typ = 'Parameter_Text' default = 'null, Null_Unbounded_String'; elif( var.isNumericType() ): typ = 'Parameter_Float' default = '0.0' elif ( var.isDateType() ): typ = 'Parameter_Date' default = 'Clock' s = '{:>4d} : {:<24} : {:<18} : {:<20} : {:>8} '.format( p, var.adaName, typ, var.adaType, default ) comments.append( s ) template.n = p template.comments = comments; return str( template );
def output_result(self, methodname, template, result, action_metadata, outf, return_template=False): """ Renders a response body """ from Cheetah.Template import Template # any result with custom serialization if action_metadata.get('return_type') == 'plain': outf.write(str(result)) elif callable(result): outf.write(result()) # JSON with simple serialization (dict -> string) elif action_metadata.get('return_type') == 'json': json.dump(result, outf) # Template elif type(result) is DictType: self.add_globals(result, methodname, action_metadata) if template.endswith('.tmpl'): template_class = self._get_template_class(template[:-5]) tpl_ans = template_class(searchList=[result, self.args]) else: tpl_ans = Template(template, searchList=[result, self.args]) if return_template: return tpl_ans tpl_ans.respond(CheetahResponseFile(outf))
def addSymbolToOrig(conf,inputs,outputs): import sys from Cheetah.Template import Template f=open(conf["main"]["dataPath"]+"/symbols.sym","r") newContent="" str=f.read() f.close() i=0 b=str.split('SYMBOL\n') for a in b: if a!="" and a!='\n': if i+1 < len(b): if newContent!="": newContent+='SYMBOL\n'+a else: newContent+=a else: print >> sys.stderr,a[:len(a)-4] newContent+='SYMBOL\n'+a[:len(a)-5] i+=1 t=Template(file=conf["main"]["templatesPath"]+"/Manager/Styler/Symbols.sym.tmpl",searchList={"conf": conf,"inputs": inputs,"outputs": outputs}) newContent+=t.__str__().replace('SYMBOLSET\n',"") f=open(conf["main"]["dataPath"]+"/symbols.sym","w") f.write(newContent) f.close() outputs["Result"]["value"]=zoo._("Symbol added.") return 3
def application(environ, start_response): connector = MySQLdb.connect(host="192.168.30.10", db="personal", user="******", passwd="vagrant", charset="utf8") cursor = connector.cursor() cursor.execute("SELECT * FROM info") result = cursor.fetchall() start_response('200 OK', [('Content-Type', 'text/html')]) tpl = Template(file="/var/www/wsgi/test/tpl/result.tpl") tpl.data = [] for row in result: if str(row[3]) == "M": tpl.data.append((str(row[0]), str(row[2]), "Man", str(row[4]), str(row[5]))) else: tpl.data.append((str(row[0]), str(row[2]), "Woman", str(row[4]), str(row[5]))) cursor.close() connector.close() return tpl.respond().encode('utf-8')
def test_int(self): from Cheetah.Template import Template t = Template(''' #def intify(val) #return $int(val) #end def''', compilerSettings={'useStackFrames' : False}) self.assertEquals(5, t.intify('5'))
def ignore(self, pn, ver, *args, **kwargs): """Ignore particular version of pkg""" pkgs = Packages.select(AND(Packages.q.packageName == pn, Packages.q.latestReleaseVersion == ver)) print "PN", pn, "VER", ver if pkgs.count() == 0: yield self.error_form("Package not ignored.") pkg = pkgs[0] template = Template(''' <form method="get" action="/ignore_action/"> <div> <b>Ignore version $pkg.latestReleaseVersion of $pkg.packageName</b> <br> <br>This will ignore this particular freshmeat release version, <b>not</b> the entire pacakge.</b><br><br> Freshmeat Release Date: $pkg.latestReleaseDate<br><br> <a href="http://packages.gentoo.org/search/?sstring=$pkg.packageName"> $pkg.portageCategory/$pkg.packageName-$pkg.portageVersion</a> [ <a class="nav" href="http://freshmeat.net/projects/$pkg.packageName/" title="Freshmeat Latest Release">$pkg.latestReleaseVersion</a> ] </div><div><br /> <input type="submit" value="Ignore" /> <input type='hidden' name='pn' value='$pkg.packageName'> <input type='hidden' name='ver' value='$pkg.latestReleaseVersion'> </div> </form> ''', [locals(), globals()]) content = template.respond() yield self.plain_page(content)
def add_known(self, pn, *args, **kwargs): """Show form for editing known matches""" packages = KnownGood.select(KnownGood.q.fmName == pn ) if packages.count(): fullName = "%s/%s" % (packages[0].portageCategory, packages[0].packageName) else: fullName = "No matches found!" template = Template(''' <b>Edit Portage name for:</b> $pn <br><br> If a Freshmeat package name does not match, you can re-map it to a new Gentoo category and package name. <br><br> <table> <tr> <th>Existing match</th> <th>New package category</th> <th>New package name</tr> <tr class="alt"> <td>$fullName </td> <td> <form name='add_known' action="/known_submit" method=post> <input type='input' name='new_cat' value=""></td> <td><input type='input' name='new_pn' value=""></td> <input type='hidden' name='fmpn' value="$pn"> </tr> </table> <center><input type='submit' value="Submit"></center> </form>''', [locals(), globals()]) yield self.plain_page(template.respond())
def generate_download_script(root, arch, tmpl): package_name_list = get_packages_name_list(get_file_list(root, arch)) tmpl = Template(file=tmpl, searchList={'packages':package_name_list}) with open('install_packages.sh', 'w') as f: f.write(tmpl.respond())
def edit(self, id=0): # we really want id as an integer. Since GET/POST parameters # are always passed as strings, let's convert it. id = int(id) if id > 0: # if an id is specified, we're editing an existing book. book = Book.get(id) title = "Edit Book" else: # if no id is specified, we're entering a new book. book = None title = "New Book" template = Template(''' <h2>$title</h2> <form action="./store" method="POST"> <input type="hidden" name="id" value="$id" /> Title: <input name="title" value="$getVar('book.title', '')" /><br/> Author: <input name="author" value="$getVar('book.author', '')" /><br/> <input type="submit" value="Store" /> </form> ''', [locals(), globals()]) return template.respond()
def writeProjectFile( database ): outfile = file( paths.getPaths().etcDir + database.databaseName+'.gpr' , 'w' ); template = Template( file=templatesPath() + 'project_file.tmpl' ) template.date = datetime.datetime.now() template.projectName = adafyName(database.databaseName) outfile.write( str(template) ) outfile.close()
def do_replay_from_yaml (args): print "Replaying using %s" % args.yamlfile replay_file_name = "%s_replay.sh" % args.project replay_file = open (replay_file_name, "w") bpy = skel_bpy.skel_bpy (args.yamlfile) # Generate replay_yaml.sh shell script from Cheetah.Template import Template template_file = open (os.path.expanduser("~/.skel/templates/replay_yaml.tmpl"), 'r') t = Template(file=template_file) t.bpy = bpy # No, I don't like these either. t.yamlfile = args.yamlfile t.project = args.project t.force = args.force replay_file.write (str(t) ) replay_file.close() # Adjust the permissions of the replay script to make it runnable by user os.chmod (replay_file_name, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR) # Run it subprocess.check_call ("./%s" % replay_file_name)
def get_data(self, entry, metadata): template = Template(self.data.decode(self.encoding), compilerSettings=self.settings) template.metadata = metadata template.path = entry.get('realname', entry.get('name')) template.source_path = self.name return template.respond()
def infopage(self): self.send_response(200) self.send_header('Content-type', 'text/html') self.end_headers() t = Template(file=os.path.join(SCRIPTDIR, 'templates', 'info_page.tmpl')) t.admin = '' for section, settings in config.getShares(): if 'type' in settings and settings['type'] == 'admin': t.admin += '<a href="/TiVoConnect?Command=Admin&Container=' + section\ + '">pyTivo Web Configuration</a><br>'\ + '<a href="/TiVoConnect?Command=NPL&Container=' + section\ + '">pyTivo ToGo</a><br>' if t.admin == '': t.admin = '<br><b>No Admin plugin installed in pyTivo.conf</b><br> If you wish to use'\ + ' the admin plugin add the following lines to pyTivo.conf<br><br>'\ + '[Admin]<br>type=admin' t.shares = 'Video shares:<br/>' for section, settings in config.getShares(): if settings.get('type') == 'video': t.shares += '<a href="TiVoConnect?Command=QueryContainer&Container=' + section\ + '">' + section + '</a><br/>' self.wfile.write(t) self.end_headers()
def get_config_from_template(self, tmpl_path, vars_dict): logging.debug("template path is %s", tmpl_path) logging.debug("vars_dict is %s", vars_dict) if not os.path.exists(tmpl_path) or not vars_dict: logging.info("Template dir or vars_dict is None!") return {} searchList = [] copy_vars_dict = deepcopy(vars_dict) for key, value in vars_dict.iteritems(): if isinstance(value, dict): temp = copy_vars_dict[key] del copy_vars_dict[key] searchList.append(temp) searchList.append(copy_vars_dict) # Load base template first if it exists base_config = {} base_tmpl_path = os.path.join(os.path.dirname(tmpl_path), 'base.tmpl') if os.path.isfile(base_tmpl_path) and base_tmpl_path != tmpl_path: base_tmpl = Template(file=base_tmpl_path, searchList=searchList) base_config = json.loads(base_tmpl.respond(), encoding='utf-8') base_config = json.loads(json.dumps(base_config), encoding='utf-8') # Load specific template for current adapter tmpl = Template(file=open(tmpl_path, "r"), searchList=searchList) config = json.loads(tmpl.respond(), encoding='utf-8') config = json.loads(json.dumps(config), encoding='utf-8') # Merge the two outputs config = util.merge_dict(base_config, config) logging.debug("get_config_from_template resulting %s", config) return config
def generate_makefile_from_yaml (args): bpy = skel_bpy.skel_bpy (args.yamlfile) template_file_name = "~/.skel/templates/Makefile.tmpl" outfilename = "Makefile" # Only proceed if outfilename does not already exist, or if -f was used if os.path.exists (outfilename) and not args.force: print "%s exists, aborting. Delete the file or use -f to overwrite." % outfilename return 999 skel_file = open (outfilename, 'w') # Now for the Cheetah magic: from Cheetah.Template import Template template_file = open (os.path.expanduser(template_file_name), 'r') t = Template(file=template_file) t.bpy = bpy t.project = args.project t.bpfile = args.bpfile t.noxml = args.noxml skel_file.write (str(t) )
def gen_suite_with_args (parent_parser): args = pparse_command_line (parent_parser) print "Generating test suite using %s" % args.yamlfile suite_gen_file_name = "%s_gen_suite.sh" % args.project suite_gen_file = open (suite_gen_file_name, "w") plan = skel_test_plan.skel_test_plan (args.yamlfile) # Generate gen_suite.sh shell script from Cheetah.Template import Template template_file = open (os.path.expanduser("~/.skel/templates/create_suite.tmpl"), 'r') t = Template(file=template_file) t.test_plan = plan # No, I don't like these either. t.yamlfile = args.yamlfile t.project = args.project t.force = args.force suite_gen_file.write (str(t) ) suite_gen_file.close() # Adjust the permissions of the replay script to make it runnable by user os.chmod (suite_gen_file_name, stat.S_IXUSR | stat.S_IWUSR | stat.S_IRUSR) # Run it #print "Run ./%s [disabled]" % suite_gen_file_name subprocess.check_call ("./%s" % suite_gen_file_name)
def render_template(plugin, vm, tmplname, context=None): # Import here to avoid having to build-dep on python-cheetah from Cheetah.Template import Template searchList = [] if context: searchList.append(context) searchList.append(vm) tmpldirs = [os.path.expanduser('~/.vmbuilder/%s'), os.path.dirname(__file__) + '/plugins/%s/templates', '/etc/vmbuilder/%s'] if vm.templates: tmpldirs.insert(0,'%s/%%s' % vm.templates) tmpldirs = [dir % plugin for dir in tmpldirs] for dir in tmpldirs: tmplfile = '%s/%s.tmpl' % (dir, tmplname) if os.path.exists(tmplfile): t = Template(file=tmplfile, searchList=searchList) output = t.respond() logging.debug('Output from template \'%s\': %s' % (tmplfile, output)) return output raise VMBuilderException('Template %s.tmpl not found in any of %s' % (tmplname, ', '.join(tmpldirs)))
def page_render_html(json, **argd): action = argd.get("formtype", "overview") R = RecordRender(argd["__environ__"]) DB = PeopleDatabase if action == "overview": # Show the database & a few options records = DB.read_database() rendered_records = R.rendered_record_list(records) return R.render_page(content=rendered_records) if action == "view": # Show the database & a few options record = DB.get_record(argd["personid"]) records = DB.read_database() rendered_records = R.rendered_record_list(records) rendered_record = R.rendered_record(record) return R.render_page(content=rendered_records, dataentry=rendered_record) if action == "edit_new": # Show the database & a form for creating a new person records = DB.read_database() rendered_records = R.rendered_record_list(records) empty_data_entry = R.rendered_record_entry_form({}) configured_form = R.render_configured_form(empty_data_entry) return R.render_page(content=rendered_records, dataentry=configured_form) if action == "create_new": # Take the data sent to us, and use that to fill out an edit form # Note: This is actually filling in an *edit* form at that point, not a *new* user form # If they submit the new form, the surely they should be viewed to be updating the form? # yes... # new_record = make_person( stem="form", **argd) # This also stores them in the database records = DB.read_database() rendered_records = R.rendered_record_list(records) pre_filled_data_entry = R.rendered_record_entry_form(new_record) configured_form = R.render_configured_form(pre_filled_data_entry, nextstep="update") return R.render_page(content=rendered_records, dataentry=configured_form) if action == "edit": record = DB.get_record(argd["personid"]) records = DB.read_database() rendered_records = R.rendered_record_list(records) pre_filled_data_entry = R.rendered_record_entry_form(record) configured_form = R.render_configured_form(pre_filled_data_entry, nextstep="update") return R.render_page(content=rendered_records, dataentry=configured_form) if action == "update": # Take the data sent to us, and use that to fill out an edit form # # Note: This is actually filling in an *edit* form at that point, not a *new* user form # If they submit the new form, the surely they should be viewed to be updating the form? # yes... # record = update_person(stem="form", **argd) records = DB.read_database() rendered_records = R.rendered_record_list(records) pre_filled_data_entry = R.rendered_record_entry_form(record) configured_form = R.render_configured_form(pre_filled_data_entry, nextstep="update", submitlabel="Update") return R.render_page(content=rendered_records, dataentry=configured_form) if action == "delete": # Take the data sent to us, and use that to fill out an edit form # # Note: This is actually filling in an *edit* form at that point, not a *new* user form # If they submit the new form, the surely they should be viewed to be updating the form? # yes... # # Show the database & a few options person = DB.get_record(argd["personid"]) people = DB.read_database() rendered_people = R.rendered_record_list(people) rendered_person = R.rendered_record(person) rendered_person = "<h3> Are you sure you wish to delete this person?</h3><ul>" + str( rendered_person) delete_action = "<a href='/cgi-bin/app/people?formtype=confirm_delete&personid=%s'>%s</a>" % ( person["personid"], "Delete this person") cancel_action = "<a href='/cgi-bin/app/people?formtype=view&personid=%s'>%s</a>" % ( person["personid"], "Cancel deletion") rendered_person += "</ul><h3> %s | %s </h3>" % (delete_action, cancel_action) return R.render_page(content=rendered_people, dataentry=rendered_person) if action == "confirm_delete": # Show the database & a few options record = DB.get_record(argd["personid"]) DB.delete_record(argd["personid"]) records = DB.read_database() rendered_records = R.rendered_record_list(records) # rendered_record = R.rendered_record(record) return R.render_page(content=rendered_records, dataentry="<h1> %s Deleted </h1>" % record["person"]) return str( Template( file='templates/Page.tmpl', searchList=[ argd["__environ__"], { "extra": "", "content": "Sorry, got no idea what you want!", "dataentry": "", "banner": "Not found", # should send back a 404 status then? Or similar? } ]))
for k in exps.keys(): foo = [] f = open('%s/avgstats.txt' % '/tmp/report-%s' % k, 'r') while True: line = f.readline().strip() if not line: break if line.startswith('#'): continue foo.append(line.split()) f.close() stats[k] = foo data.stats = stats # create the report template template = Template(file=templatefile, searchList=data) statsstats = {} for k in exps.keys(): files = glob.glob('/tmp/report-%s/log-*' % k) a = numpy.matrix(numpy.zeros((len(files), 7))) for i in xrange(len(files)): p = files[i] a[i, :] = readDataFromFile(p)[-1, :] foo = numpy.ones((4, 7)) foo[0, :] = numpy.max(a, 0) foo[1, :] = numpy.average(a, 0) foo[2, :] = numpy.min(a, 0) foo[3, :] = numpy.std(a, 0) foo = [['%g' % elem for elem in row] for row in foo.tolist()] statsstats[k] = foo
def matrixmul_opt(mat_a, mat_b, block_size=DEFAULT_BLOCK_SIZE, work_size=DEFAULT_WORK_SIZE, unroll=DEFAULT_UNROLL, spill=DEFAULT_SPILL, prefetch=DEFAULT_PREFETCH): ah, aw = mat_a.shape bh, bw = mat_b.shape assert aw == bh # -- pad input matrices appropriately ah_padded = int(np.ceil(ah / block_size)) * block_size aw_padded = int(np.ceil(aw / block_size)) * (block_size * work_size) mat_a_padded = np.zeros((ah_padded, aw_padded), np.float32) mat_a_padded[:ah, :aw] = mat_a bh_padded = aw_padded bw_padded = int(np.ceil( bw / (block_size * work_size))) * (block_size * work_size) mat_b_padded = np.zeros((bh_padded, bw_padded), np.float32) mat_b_padded[:bh, :bw] = mat_b ch_padded = ah_padded cw_padded = bw_padded # -- upload padded input matrices to the GPU mat_a_gpu = gpuarray.to_gpu(mat_a_padded) mat_b_gpu = gpuarray.to_gpu(mat_b_padded) # -- create empty container matrix for the result (C = A * B) mat_c_gpu = gpuarray.zeros((ch_padded, cw_padded), np.float32) # -- generate and compile the code # prepare the template parameters template_params = { 'BLOCK_SIZE': block_size, 'WORK_SIZE': work_size, 'UNROLL': unroll, 'SPILL': spill, 'PREFETCH': prefetch, 'A_WIDTH': aw_padded, 'A_HEIGHT': ah_padded, 'B_WIDTH': bw_padded, } # run the template engine to get the code kernel_code = Template( file=TEMPLATE_FILENAME, searchList=[template_params], ) # compile the code module = compiler.SourceModule(kernel_code) # get the kernel from the module matrixmul_func = module.get_function("matrixMul") # some info about the module print("number of registers used:", matrixmul_func.num_regs) # block of threads # ATTENTION: block is (threadDim.x, threadDim.y, threadDim.z) # and not (threadDim.z, threadDim.y, threadDim.x) block = block_size, block_size, 1 # grid of blocks # ATTENTION: it's (blockDim.x, blockDim.y) # and not (blockDim.y, blockDim.x) grid = int(cw_padded / block_size / work_size), int(ch_padded / block_size) # -- call the kernel on the GPU # Note that when we use time_kernel=True pycuda will automatically synchronize the kernel # to make sure that the timing is correct. If you time the code yourself, you'll have to # synchronize the current Context. gpu_time = matrixmul_func( # -- output mat_c_gpu, # -- inputs mat_a_gpu, mat_b_gpu, # -- grid of blocks grid=grid, # -- block of threads block=block, # -- time the kernel (approx.) time_kernel=True, ) # get the GPU matrix back to CPU memory mat_c_padded = mat_c_gpu.get() mat_c = mat_c_padded[:ah, :bw] return mat_c, gpu_time
import logging import yaml from Cheetah.Template import Template from threading import Thread # constants for resolution and period day = 0 week = 1 month = 2 PLATANE_HOME = os.path.dirname(__file__) model.schema = yaml.load(file(PLATANE_HOME + '/data/schema', 'r')) model.root = PLATANE_HOME + "/data/root" list_template = Template.compile(file=file(PLATANE_HOME + '/list.html', "r")) task_template = Template.compile(file=file(PLATANE_HOME + '/task.html', "r")) message_template = Template.compile(file=file(PLATANE_HOME + '/message.html', "r")) visualize.tasks_template = Template.compile( file=file(PLATANE_HOME + '/tasks.html', "r")) render_handlers = {} # REST methods def do_get(env, start_response): return handle(env, start_response, get_body) def do_put(env, start_response):
def index(self, num=None): if cherrypy.session.get('login', None) == 'login': raise cherrypy.HTTPRedirect('/database/') else: userForm = Template(file=os.path.join(os.curdir, 'index.tmpl')) return str(userForm)
def STTY(stream): return 'STTY%s' % __stream(stream) def CAPTURE(stream): return 'CAPTURE%s' % __stream(stream) def DISCONNECT(stream): stream = stream.lower() if stream == 'slave': return 'A = disconnect 0' elif stream == 'master': return 'A = disconnect 1' if __name__ == '__main__': if len(sys.argv) < 2: print "Usage %s <file>" % sys.argv[0] sys.exit(1) t = Template(file=sys.argv[1]) t.INPUT = INPUT t.PRINT = PRINT t.TIMEOUT = TIMEOUT t.GET = GET t.STTY = STTY t.CAPTURE = CAPTURE t.DISCONNECT = DISCONNECT print str(t)
elif options.language == 'xml': templates.append(directory + "/../data/DBus-xml.xml") header_ext = ".xml" else: parser.error("Unsupported language: " + options.language) sys.exit(1) if len(templates) == 0: parser.error("Specify language") sys.exit(1) name = None if len(args) >= 2: name = args[1] binding = TopNode(args[0], name, options.backend, header_ext) binding.parse() for template_name in templates: t = Template(file=template_name) t.model = binding s = str(t) ext = os.path.splitext(template_name)[1] f = open(binding.name + ext, 'w+') try: f.write(s) finally: f.close()
def display(conf,inputs,outputs): nameSpace = {'conf': conf,'inputs': inputs, 'outputs': outputs} t = Template(file=conf["lenv"]["cwd"]+"/configuration/display.html",searchList=nameSpace) outputs["Result"]["value"]=t.__str__() return 3
def gen_config_data(self): """ Generate configuration data for repos, ldap, files, packages, and monit. Returns a dict. """ config_data = { 'repo_data': self.handle.get_repo_config_for_system(self.system), 'repos_enabled': self.get_cobbler_resource('repos_enabled'), 'ldap_enabled': self.get_cobbler_resource('ldap_enabled'), 'monit_enabled': self.get_cobbler_resource('monit_enabled') } package_set = set() file_set = set() for mgmtclass in self.mgmtclasses: _mgmtclass = self.handle.find_mgmtclass(name=mgmtclass) for package in _mgmtclass.packages: package_set.add(package) for file in _mgmtclass.files: file_set.add(file) # Generate LDAP data if self.get_cobbler_resource("ldap_enabled"): if self.system.ldap_type in ["", "none"]: utils.die(self.logger, "LDAP management type not set for this system (%s, %s)" % (self.system.ldap_type, self.system.name)) else: template = utils.get_ldap_template(self.system.ldap_type) t = Template(file=template, searchList=[self.host_vars]) print t config_data['ldap_data'] = t.respond() # Generate Package data pkg_data = {} for package in package_set: _package = self.handle.find_package(name=package) if _package is None: raise CX('%s package resource is not defined' % package) else: pkg_data[package] = {} pkg_data[package]['action'] = self.resolve_resource_var(_package.action) pkg_data[package]['installer'] = _package.installer pkg_data[package]['version'] = self.resolve_resource_var(_package.version) if pkg_data[package]['version'] != "": pkg_data[package]["install_name"] = "%s-%s" % (package, pkg_data[package]['version']) else: pkg_data[package]["install_name"] = package config_data['packages'] = pkg_data # Generate File data file_data = {} for file in file_set: _file = self.handle.find_file(name=file) if _file is None: raise CX('%s file resource is not defined' % file) file_data[file] = {} file_data[file]['is_dir'] = _file.is_dir file_data[file]['action'] = self.resolve_resource_var(_file.action) file_data[file]['group'] = self.resolve_resource_var(_file.group) file_data[file]['mode'] = self.resolve_resource_var(_file.mode) file_data[file]['owner'] = self.resolve_resource_var(_file.owner) file_data[file]['path'] = self.resolve_resource_var(_file.path) if not _file.is_dir: file_data[file]['template'] = self.resolve_resource_var(_file.template) try: t = Template(file=file_data[file]['template'], searchList=[self.host_vars]) file_data[file]['content'] = t.respond() except: utils.die(self.logger, "Missing template for this file resource %s" % (file_data[file])) config_data['files'] = file_data return config_data
def read(fname): f = open(os.path.join(dirname, fname), 'r') template = Template(template=f.read()) template.converters["h"] = cgi.escape return template
if conf.keys().count('senv') > 0: lastMap = conf['senv']['last_map'] if toLoad is not None: conf["senv"]["toLoad"] = toLoad #else: # conf['senv']['last_map']="Georeferencer" pass t = None try: tmplName = "" for i in range(1, len(tmpName)): if tmplName != "": tmplName += "/" tmplName += tmpName[i] t = Template(file=conf["main"]["templatesPath"] + "/preview/" + tmplName + ".tmpl", searchList=nameSpace) except: if len(tmpName) > 0: t = Template(file=conf["main"]["templatesPath"] + "/" + tmpName[0] + ".tmpl", searchList=nameSpace) else: conf["lenv"]["message"] = zoo._( "Error loading your template file ") + conf["main"][ "templatesPath"] + "/preview/" + tmplName + ".tmpl" return zoo.SERVICE_SUCCEEDED verif = not (conf.has_key("senv")) if verif: conf["senv"] = {} conf["senv"]["MMID"] = "MM" + str(time.time()).split(".")[0]
entry.update(basic_meta[url]) else: basic_data = metadata.from_container(item) entry.update(basic_data) basic_meta[url] = basic_data data.append(entry) else: data = [] tivoIP = '' TotalItems = 0 ItemStart = 0 ItemCount = 0 FirstAnchor = '' t = Template(NPL_TEMPLATE, filter=EncodeUnicode) t.escape = escape t.quote = quote t.folder = folder t.status = status if tivoIP in queue: t.queue = queue[tivoIP] t.has_tivodecode = has_tivodecode t.tname = tivo_name t.tivoIP = tivoIP t.container = handler.cname t.data = data t.len = len t.TotalItems = int(TotalItems) t.ItemStart = int(ItemStart) t.ItemCount = int(ItemCount)
def main(args): #Much of the argparse/configparser parts taken from #http://blog.vwelch.com/2011/04/combining-configparser-and-argparse.html conf_parser = argparse.ArgumentParser( # Turn off help, so we print all options in response to -h add_help=False) conf_parser.add_argument("-c", "--config-file", dest="configfile", help="Use a different config file than %s" % CONFIG_FILE) args, remaining_argv = conf_parser.parse_known_args() if args.configfile: configfile = args.configfile else: configfile = CONFIG_FILE # Make sure the configfile is a file if not os.path.isfile(configfile): print >> sys.stderr, 'ERROR: %s is not a file' % configfile sys.exit(1) config = ConfigParser.SafeConfigParser() try: config.read([configfile]) except: print >> sys.stderr, 'ERROR: There is an error in the config file' sys.exit(1) defaults = dict(config.items("default")) parser = argparse.ArgumentParser( # Inherit options from config_parser parents=[conf_parser], # print script description with -h/--help description=__doc__, # Don't mess with format of description formatter_class=argparse.RawDescriptionHelpFormatter, ) parser.set_defaults(**defaults) # Now that we've dealt with getting defaults from a config file we can # continue on adding arguments. parser.add_argument( "-i", "--ipaddress", dest="ipaddress", help="Set the ip address for the host in the kickstart", ) parser.add_argument( "-g", "--gateway", dest="gateway", help="Set the gateway for the new host in the kickstart") parser.add_argument( "-n", "--netmask", dest="netmask", help="Set the netmask for the new host in the kickstart") parser.add_argument("-m", "--mode", dest="mode", help="Set a mode, eg. domU_kvm or dom0") parser.add_argument( "-o", "--os", dest="os", help="What os to create a kickstart for, eg. rhel5 or rhel6") parser.add_argument("-k", "--key", dest="key", help="If you have a Redhat install key number") parser.add_argument("-r", "--rootpw", dest="rootpw", help="Hashed root password") parser.add_argument("-t", "--timezone", dest="timezone", help="Timezone in 'American/Edmonton' format") parser.add_argument("-d", "--nameservers", dest="nameservers", help="Nameservers in appropriate kickstart format") parser.add_argument( "--hostname", dest="hostname", help="Set the hostname for the new host in the kickstart") parser.add_argument( "-p", "--template-dir", dest="templatedir", help="Directory where the kickstart template files are located") # Capture args args = parser.parse_args(remaining_argv) # Makes args into a dictionary to feed to searchList d = args.__dict__ # Change to template dir pwd = os.getcwd() try: os.chdir(args.templatedir) except: print >>sys.stderr, \ 'ERROR: Template path %s is not a directory' % templatedir sys.exit(1) # Create template object # - the searchList=[d] is the best! t = Template(file=args.main_template, searchList=[d]) print(t.respond()) os.chdir(pwd) sys.exit(0)
def template(**kw): t = Template(file=path, searchList=[kw]) return t.respond()
def output_cpp(output_file, template_file): global tlm_duration global tlm_period global tlm_packet_list global tlm_max_packet_bytes t = Template(file=template_file) t.tlm_packet_list = tlm_packet_list # Generate schedule code if both duration and period defined if (tlm_duration is not None) and (tlm_period is not None): t.tlm_max_cycles = int(tlm_duration * tlm_period) else: t.tlm_max_cycles = None t.tlm_cycle_max_list = sched_cycle_ids_max(t.tlm_max_cycles) t.tlm_cycle_id_list = sched_cycle_ids(t.tlm_max_cycles) # Create ID to channel mapping t.tlm_cycle_id_arr_size = sched_id_arr_size(t.tlm_cycle_id_list) t.tlm_max_packet_bytes = tlm_max_packet_bytes t.tlm_max_num_chan = sum( [pkt.m_chan is not None for pkt in tlm_packet_list]) # Create duration and period values t.tlm_max_num_freq = sum( [pkt.m_freq is not None for pkt in tlm_packet_list]) if tlm_duration is not None: t.tlm_duration = tlm_duration else: t.tlm_duration = -1.0 # if tlm_period is not None: t.tlm_period = tlm_period else: t.tlm_period = -1 f = open(output_file, "w") print(t, file=f)
$key: $type #end for } configOptions: { #for $key, $type in $configOptions.items(): $key: $type #end for } } collections: Record<string, ZoteroCollection> isJurisM: boolean isZotero: boolean unicode: boolean platform: string paths: { caseSensitive: boolean sep: string } BetterTeX?: boolean BetterCSL?: boolean stringCompare: (a: string, b: string) => number } """ with open(os.path.join(root, 'gen/typings/translator.d.ts'), 'w') as out: out.write(str(Template(template, searchList=[variables.to_dict()])))
def buildCopyright(page): page.meta.copyright = Template(file='./templates/copyright.tmpl') page.meta.copyright.year = str(t.strftime("%Y"))
parser.add_option( "-t", "--template", default='templates/resume.%s.tmpl', help= "Filename of the output format template. Defaults to templates/resume.<extension>.tmpl" ) options, extra_args = parser.parse_args() if len(extra_args) < 1: parser.print_help() exit() return options, extra_args[0] if __name__ == '__main__': options, extension = get_cmd_line_args() contents = yaml.load(open(options.source, 'r').read()) escape_func = getattr(escapes, 'escape_' + extension, lambda x: x) escaped_contents = escape_leaves(escape_func, contents) template = Template(file=options.template % extension, searchList=[escaped_contents]) output_dir = options.output_dir if not os.path.exists(output_dir): os.makedirs(output_dir) open('%s/resume.%s' % (output_dir, extension), 'w').write(str(template))
def buildSwLicense(page): page.meta.swlicense = Template(file='./templates/swlicense.tmpl') page.meta.swlicense.generator = generator page.meta.swlicense.year = str(t.strftime("%Y"))
def buildMeta(conn, cursor, page): page.meta = Template(file='./templates/meta.tmpl') buildImprint(conn, cursor, page) buildSwLicense(page) buildDataLicense(page) buildCopyright(page)
def __repr__(self): return str( Template(self.getWorklistTemplate(), searchList={'e': self.__dict__}))
def buildDataLicense(page): page.meta.license = Template(file='./templates/license.tmpl') page.meta.license.year = str(t.strftime("%Y"))
def test_help(self): klass = Template.compile(source='$foo') t = klass() cmdline = CmdLineIface(t, scriptName='test', cmdLineArgs=['-h']) self.assertRaises(SystemExit, cmdline._processCmdLineArgs)
def buildImprint(conn, cursor, page): page.meta.imprint = Template(file='./templates/imprint.tmpl') page.meta.imprint.generator = generator page.meta.imprint.time = t.strftime("%Y-%m-%d %H:%M") page.meta.imprint.swVersion = swVersion page.meta.imprint.dataAge = osmstat.dataAge(conn, cursor)
def _eval_cheetah(element): from Cheetah.Template import Template namespace = element.get_namespace(**kwds) return str(Template(element.code, namespaces=[namespace]))
def test_env(self): klass = Template.compile(source='$foo') t = klass() cmdline = CmdLineIface(t, scriptName='test', cmdLineArgs=['--env']) cmdline._processCmdLineArgs() assert str(t) == 'test foo'
def render_template(template, input): template = get_template(template) return Template(template, searchList=[input]).__str__()
def a(): return Template("sink")
def get_data(template_file_path, search_list): if not os.path.isabs(template_file_path): template_file_path = os.path.join(TemplateManager.template_dir, template_file_path) tpl = Template(file=template_file_path, searchList=search_list) return str(tpl)
def handle_notification(self, wid): """ Extracts the needed data from the workitem, prepares the email and then sends it :param wid: Workitem :type wid: object """ wid.result = False if not wid.fields.msg: wid.fields.msg = [] subject = wid.params.subject or wid.fields.subject template_body = wid.params.template_body or wid.fields.template_body template_name = wid.params.template or wid.fields.template mail_from = wid.params.mail_from or wid.fields.mail_from \ or self.default_sender mail_to = (wid.fields.mail_to or []) + (wid.params.mail_to or []) mail_cc = (wid.fields.mail_cc or []) + (wid.params.mail_cc or []) wid.fields.mail_to = [] wid.fields.mail_cc = [] if wid.params.extra_msg: wid.fields.msg.append(wid.params.extra_msg) if not subject: raise RuntimeError("Missing mandatory field or param 'subject'") if not (template_body or template_name): raise RuntimeError("Both of field or param 'template_body' and " "'template_name' missing") if template_body and template_name: raise RuntimeError("Both field or param 'template_body' and " "'template_name' defined") if template_name: template_fname = os.path.join(self.email_store, template_name) with open(template_fname) as fil: template_body = fil.read() attachments = [] for attachment in (wid.fields.attachments or []): attachment = os.path.abspath(attachment) if not allowed_file(attachment, self.allowed_attachment_dirs): wid.fields.msg.append("Refusing to attach %s" % attachment) elif not os.path.isfile(attachment): wid.fields.msg.append("Could not find attachment %s" % attachment) else: attachments.append(attachment) mail_to = remove_duplicate_addrs(mail_to) mail_cc = remove_duplicate_addrs(mail_cc, relative_to=mail_to) if not mail_to and not mail_cc: err = "No recipients listed; not sending mail." self.log.info(err) wid.fields.msg.append(err) wid.result = True return searchlist = { 'f': general_map(wid.fields.as_dict(), dicts=ForgivingDict, values=fixup_utf8) } searchlist['req'] = searchlist['f']['req'] or ForgivingDict() # Try the template but if there's an error, re-do with the # more informative errorCatcher and send to the log try: template = Template(template_body, searchList=searchlist) message = unicode(template) except NotFound, err: # You can't set the errorCatcher using a class - this is # pattern a) usage self.log.info( "Error processing template - trying with errorCatcher") template = Template("#errorCatcher BigEcho\n" + template_body, searchList=searchlist) message = unicode(template) self.log.info("Processed template with highlights:") self.log.info(message) raise