예제 #1
0
파일: views.py 프로젝트: nidhimj22/game
def startgame(request):
    newplayer = Player()
    newplayer.age = request.POST.get("age", "")
    newplayer.email = request.POST.get("email", "")
    newplayer.country = request.POST.get("country", "")
    newplayer.occupation = request.POST.get("occupation", "")
    newplayer.gender = request.POST.get("gender", "")
    newplayer.education = request.POST.get("education", "")
    newplayer.majorstudy = request.POST.get("majorfield", "")
    newplayer.save()
    request.session['playerid'] = newplayer.id

    request.session['hackermoves'] = []
    request.session['analystmoves'] = []
    # flag=random.randint(1,2)
    # if flag is 1:
    request.session["profile"] = "Hacker"
    # else:
    #request.session["profile"] = "Analyst"

    request.session['gamematrix'] = 1  #random.randint(1,3)

    if request.session['gamematrix'] is 2:
        request.session['trials'] = research.trials2
        attack_mat = research.attack_mat2
        defence_mat = research.defence_mat2
        request.session['base'] = research.base2
        request.session['p'] = research.p2
        request.session['q'] = research.q2

    elif request.session['gamematrix'] is 3:
        request.session['trials'] = research.trials3
        attack_mat = research.attack_mat3
        request.session['base'] = research.base3
        defence_mat = research.defence_mat3
        request.session['p'] = research.p3
        request.session['q'] = research.q3

    else:
        request.session['trials'] = research.trials1
        attack_mat = research.attack_mat1
        request.session['base'] = research.base1
        defence_mat = research.defence_mat1
        request.session['p'] = research.p1
        request.session['q'] = research.q1

    request.session['h1'] = attack_mat[0][0]
    request.session['h2'] = attack_mat[0][1]
    request.session['h3'] = attack_mat[1][0]
    request.session['h4'] = attack_mat[1][1]

    request.session['a1'] = defence_mat[0][0]
    request.session['a2'] = defence_mat[0][1]
    request.session['a3'] = defence_mat[1][0]
    request.session['a4'] = defence_mat[1][1]

    request.session['trialnumber'] = 1
    request.session["extra_h"] = 0  #extra hacker score
    request.session["extra_a"] = 0  #extra analyst score
    request.session["score_h"] = request.session['base']  #hacker score
    request.session["score_a"] = request.session['base']  #analyst score
    request.session["choice_h"] = "None"  #prev_move of hacker
    request.session["choice_a"] = "None"  #prev move of analsyt

    pageTemplate = get_template("startgame.html")
    c = template.Context(request.session)
    return HttpResponse(pageTemplate.render(c))
예제 #2
0
파일: custom.py 프로젝트: xspager/django
 def test_filter(self):
     t = template.Template("{% load custom %}{{ string|trim:5 }}")
     self.assertEqual(
         t.render(template.Context({"string":
                                    "abcdefghijklmnopqrstuvwxyz"})),
         "abcde")
 def test_handles_none_price_gracefully(self):
     self.template.render(template.Context({
         'price': None
     }))
예제 #4
0
def bench_django():
    django_template = django.Template(source)
    django_template.render(django.Context(data))
예제 #5
0
파일: custom.py 프로젝트: xspager/django
    def test_inclusion_tags_from_template(self):
        c = template.Context({'value': 42})

        t = template.Template(
            '{% load custom %}{% inclusion_no_params_from_template %}')
        self.assertEqual(
            t.render(c),
            'inclusion_no_params_from_template - Expected result\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_param_from_template 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_param_from_template - Expected result: 37\n')

        t = template.Template(
            '{% load custom %}{% inclusion_explicit_no_context_from_template 37 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_explicit_no_context_from_template - Expected result: 37\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_no_params_with_context_from_template %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_no_params_with_context_from_template - Expected result (context value: 42)\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_params_and_context_from_template 37 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_params_and_context_from_template - Expected result (context value: 42): 37\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_two_params_from_template 37 42 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_two_params_from_template - Expected result: 37, 42\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_default_from_template 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_default_from_template - Expected result: 37, hi\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_default_from_template 37 42 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_default_from_template - Expected result: 37, 42\n')

        t = template.Template(
            '{% load custom %}{% inclusion_unlimited_args_from_template 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args_from_template - Expected result: 37, hi\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_unlimited_args_from_template 37 42 56 89 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_only_unlimited_args_from_template %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_only_unlimited_args_from_template - Expected result: \n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_only_unlimited_args_from_template 37 42 56 89 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_only_unlimited_args_from_template - Expected result: 37, 42, 56, 89\n'
        )
 def test_handles_no_translation(self):
     with translation.override(None, deactivate=True):
         self.template.render(template.Context({
             'price': D('10.23'),
         }))
예제 #7
0
파일: styleguide.py 프로젝트: zspencer/calc
    def render(self, context):
        html = SafeString(dedent(self.nodelist.render(context)).strip())

        t = context.template.engine.get_template('styleguide_example.html')

        return t.render(template.Context({'html': html}))
예제 #8
0
 def render_tag(self, tag, context={}):
     t = template.Template('{% load webmedia_tags %}' + tag)
     content = t.render(template.Context(context))
     return content
예제 #9
0
def home(request):
    notifications = Notification.recent(10)
    activities = []
    for notif in notifications:
        t = template.Template(notif['tmpl'])
        
        obj_uuid = notif['object_uuid']
        object = None
        if notif['object_type'] == OBJ_RESOURCE:
            object = Resource.find(obj_uuid)
            if object:
                object_dict = object.to_dict()
            else:
                object_dict = {'name': obj_uuid}
        elif notif['object_type'] == OBJ_COLLECTION:
            object = Collection.find(obj_uuid)
            if object:
                object_dict = object.to_dict()
            else:
                object_dict = {'name': obj_uuid}
        elif notif['object_type'] == OBJ_USER:
            object = User.find(obj_uuid)
            if object:
                object_dict = object.to_dict()
            else:
                # User has been deleted it can't be find by uuid
                # look in payload of the message to get the name
                if notif['operation'] in [OP_CREATE, OP_UPDATE]:
                    name = notif['payload']['post']['name']
                else: # OP_DELETE
                    name = notif['payload']['pre']['name']
                object_dict = {'name': name}
        elif notif['object_type'] == OBJ_GROUP:
            object = Group.find(obj_uuid)
            if object:
                object_dict = object.to_dict()
            else:
                # User has been deleted it can't be find by uuid
                # look in payload of the message to get the name
                if notif['operation'] in [OP_CREATE, OP_UPDATE]:
                    name = notif['payload']['post']['name']
                else: # OP_DELETE
                    name = notif['payload']['pre']['name']
                object_dict = {'uuid': obj_uuid,
                               'name': name}
        user_dict = {}
        if notif['username']:
            user = User.find(notif['username'])
            if user:
                user_dict = user.to_dict()
            

        variables = {
            'user': user_dict,
            'when': notif['when'],
            'object': object_dict
        }
        
        ctx = template.Context(variables)
        activities.append({'html': t.render(ctx)})
    
    return render(request, 'activity/index.html', {'activities': activities})
예제 #10
0
 def test_google_analytics(self):
     "Tag should expand into correct JavaScript snippet"
     text = ('{% load google %}' '{% google_analytics "XXXX" %}')
     t = template.Template(text)
     output = t.render(template.Context())
     self.assertIn("_gaq.push(['_setAccount', 'XXXX']);", output)
예제 #11
0
    def test_inclusion_tags(self):
        c = template.Context({'value': 42})

        t = template.Template('{% load custom %}{% inclusion_no_params %}')
        self.assertEqual(t.render(c),
                         'inclusion_no_params - Expected result\n')

        t = template.Template('{% load custom %}{% inclusion_one_param 37 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_param - Expected result: 37\n')

        t = template.Template(
            '{% load custom %}{% inclusion_explicit_no_context 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_explicit_no_context - Expected result: 37\n')

        t = template.Template(
            '{% load custom %}{% inclusion_no_params_with_context %}')
        self.assertEqual(
            t.render(c),
            'inclusion_no_params_with_context - Expected result (context value: 42)\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_params_and_context 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_params_and_context - Expected result (context value: 42): 37\n'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_two_params 37 42 %}')
        self.assertEqual(t.render(c),
                         'inclusion_two_params - Expected result: 37, 42\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_default 37 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_default - Expected result: 37, hi\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_default 37 two="hello" %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_default - Expected result: 37, hello\n')

        t = template.Template(
            '{% load custom %}{% inclusion_one_default one=99 two="hello" %}')
        self.assertEqual(
            t.render(c),
            'inclusion_one_default - Expected result: 99, hello\n')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load custom %}{% inclusion_one_default 99 two="hello" three="foo" %}'
        )

        t = template.Template(
            '{% load custom %}{% inclusion_one_default 37 42 %}')
        self.assertEqual(t.render(c),
                         'inclusion_one_default - Expected result: 37, 42\n')

        t = template.Template(
            '{% load custom %}{% inclusion_unlimited_args 37 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args - Expected result: 37, hi\n')

        t = template.Template(
            '{% load custom %}{% inclusion_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args - Expected result: 37, 42, 56, 89\n')

        t = template.Template(
            '{% load custom %}{% inclusion_only_unlimited_args %}')
        self.assertEqual(
            t.render(c), 'inclusion_only_unlimited_args - Expected result: \n')

        t = template.Template(
            '{% load custom %}{% inclusion_only_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'inclusion_only_unlimited_args - Expected result: 37, 42, 56, 89\n'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_two_params' received too many positional arguments",
            template.Template,
            '{% load custom %}{% inclusion_two_params 37 42 56 %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' received too many positional arguments",
            template.Template,
            '{% load custom %}{% inclusion_one_default 37 42 56 %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template, '{% load custom %}{% inclusion_one_default %}')

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load custom %}{% inclusion_unlimited_args %}')

        t = template.Template(
            '{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}'
        )
        self.assertEqual(
            t.render(c),
            'inclusion_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4\n'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load custom %}{% inclusion_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'
        )

        six.assertRaisesRegex(
            self, template.TemplateSyntaxError,
            "'inclusion_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load custom %}{% inclusion_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'
        )
예제 #12
0
파일: admin.py 프로젝트: hdknr/djuploader
def _T(src, **ctx):
    return _S(template.Template(src).render(template.Context(ctx)))
예제 #13
0
    def testSaveDataForm(self):
        request = rf.post('/form/', TEST_FORM_POST_DATA)
        form = forms.create_form(request,
                                 form="personal-information",
                                 submission="myForm")

        # Make sure there's no submission object yet
        # Removed, now we always expect to be a submission
        # object attached.
        #self.assertRaises(AttributeError, getattr, form, 'submission')

        # Validate the form to populate cleaned_data for the save function
        form.is_valid()
        if form.errors:
            self.fail(form.errors)

        # Try saving the form
        form.save()

        # Verify the data was input correctly
        self.assertValidSave(data=TEST_FORM_POST_DATA, submission="myForm")

        # Test creation of another bound form tied to a existing Submission
        request = rf.get('/')
        form = forms.create_form(request,
                                 form="personal-information",
                                 submission="myForm")

        # Make sure template rendering doesn't throw errors
        x = template.Template("{% for field in form %}{{ field }}{% endfor %}")
        c = template.Context({"form": form})
        x.render(c)

        # Ensure Unicode encoding is being returned from models correctly
        answers = Answer.objects.all()

        for value in answers:
            try:
                value.__unicode__()
            except UnicodeEncodeError:
                self.fail(
                    "UnicodeEncodeError: 'ascii' codec can't encode character... Make sure you are using unicode() in every model's __unicode__() function, NOT str()"
                )

        # Test re-submission of form with different data to make sure that edits work.
        # Tests for regression of data integrity bug where a checked checkbox
        # could never be un-checked because it would not exist in the form POST.
        request = rf.post('/form/', TEST_FORM_POST_DATA2)
        form = forms.create_form(request,
                                 form="personal-information",
                                 submission="myForm")

        # Validate the form to populate cleaned_data for the save function
        form.is_valid()
        if form.errors:
            self.fail(form.errors)

        # Try saving the form
        form.save()

        # Verify the data was input correctly
        self.assertValidSave(data=TEST_FORM_POST_DATA2, submission="myForm")
예제 #14
0
def send_nightly():
    # get the list of all results generated in the last 24 hours
    timerange = datetime.datetime.now(pytz.UTC) - datetime.timedelta(days=1)
    resultsList = models.Results.objects.filter(timeStamp__gt=timerange)
        
    resultsAll=[]
    rType=[]
    rNew=[]
    info=[]
  
    for result in resultsList:
        if (result.status == 'Completed' and 'INJECTED' not in result.resultsName):
            exp = result.experiment
            pstore = result.getPluginStore()            
            [firstPk, firstType] = find_first_result(exp,pstore)

            resultsAll.append(result)            
            rNew.append(result.pk in firstPk)
            rType.append(get_result_type(result,pstore))
 
            # Here's a bunch of random other things we want to track, all stuffed into this extraInfo dict array
            extraInfo = {}

            # pull the Q20 estimated bases from the quality metrics table
            try:
                qmetrics = result.qualitymetrics_set.all()[0]
                extraInfo["q20"] = qmetrics.q20_bases
            except:
                extraInfo["q20"] = "-"

            # if we have a paired end run, lets get that report path
            if get_result_type(result,pstore) == 'paired':
                extraInfo["paired"] = paired_end_stats(result.get_report_path())
            else:
                extraInfo["paired"] = ""

            # track the FPS set on Proton instruments
            try:
                overclock = exp.log["overclock"]
                oc = int(overclock)
                if oc == 1:
                    extraInfo["fps"] = "15"
                elif oc == 2:
                    extraInfo["fps"] = "30"
                else:
                    extraInfo["fps"] = "-"
            except:
                extraInfo["fps"] = "-"

            # track the status of the covereage plugin
            try:
                # pluginDict = ast.literal_eval(pstore["coverageAnalysis"])
                pluginDict = pstore["coverageAnalysis"]
                if pluginDict is not None:
                    if "Target base coverage at 20x" in pluginDict.keys():
                        extraInfo["cov"] = pluginDict["Target base coverage at 20x"]
                    else:
                        extraInfo["cov"] = pluginDict["Genome base coverage at 20x"]
            except:
                extraInfo["cov"] = " "

            # track the duplicate rate
            val = 0
            try:
                if result.best_lib_metrics.duplicate_reads is not None:
                    try:
                        val = result.best_lib_metrics.duplicate_reads / result.best_lib_metrics.total_mapped_reads
                    except:
                        val = 0 # assuming total_mapped_reads was 0 here
                    # round to tenths
                    val = int(val * 1000.0)
                    val = float(val) / 10.0
                    extraInfo["dup"] = str(val*100.0) + "%"
            except:
                extraInfo["dup"] = ' '

            # track the variant caller SNP & InDel accuracy
            try:
                # pluginDict = ast.literal_eval(pstore["validateVariantCaller"])
                pluginDict = pstore["validateVariantCaller"]
                if pluginDict is not None:
                    SNPAccuracy = round(float(pluginDict["InDel_ConsensusAccuracy-AllPos"]) * 100.0, 4)
                    InDelAccuracy = round(float(pluginDict["SNP_ConsensusAccuracy-AllPos"]) * 100.0, 4)
                    extraInfo["vc"] = str(SNPAccuracy) + "% : " + str(InDelAccuracy) + "%"
            except:
                extraInfo["vc"] = " "

            # track the systematic error
            try:
                # pluginDict = ast.literal_eval(pstore["SystematicErrorAnalysis"])
                pluginDict = pstore["SystematicErrorAnalysis"]
                if pluginDict is not None:
                    # print 'Got syserr plugin info: %s' % pluginDict
                    # print 'object is type: %s' % type(pluginDict)
                    if pluginDict["barcoded"]:
                        # print 'it is barcoded'
                        bc = pluginDict["barcodes"]
                        val = 1.0
                        for name in bc:
                            if '-' not in bc[name]["positions-with-sse"]:
                                bcval = float(bc[name]["positions-with-sse"])
                                if bcval < val and bcval > 0.0:
                                    val = bcval
                    else:
                        # print 'it is not barcoded'
                        val = float(pluginDict["positions-with-sse"])
                    # print 'plugin val: %s' % val
                    if val > 0.0:
                        val = val * 100.0
                        extraInfo["syserr"] = str(val) + "%"
                    else:
                        extraInfo["syserr"] = " "
                    # print 'plugin syserr is: %s' % extraInfo["syserr"]
            except:
                extraInfo["syserr"] = " "

            # track coverage uniforimity & 20x coverage
            try:
                # pluginDict = ast.literal_eval(pstore["SystematicErrorAnalysis"])
                pluginDict = pstore["coverageAnalysisLite"]
                if pluginDict is not None:
                    bestCov20 = 0.0
                    bestUnif = 0.0
                    if pluginDict["barcoded"] ==  'true' or pluginDict["barcoded"] == 'True':
                        # print 'it is barcoded'
                        bc = pluginDict["barcodes"]
                        for name in bc:
                            if "Target base coverage at 20x" in bc[name].keys():
                                cov20txt = bc[name]["Target base coverage at 20x"]
                            else:
                                cov20txt = bc[name]["Genome base coverage at 20x"]
                            cov20 = float(cov20txt.rstrip('%'))
                            uniftxt = bc[name]["Uniformity of base coverage"]
                            unif = float(uniftxt.rstrip('%'))
                            if (unif < 100.0) and (unif > 0.0):
                                if cov20 > bestCov20:
                                    bestCov20 = cov20
                                    bestUnif = unif
                                
                    else:
                        # print 'it is not barcoded'
                        if "Target base coverage at 20x" in pluginDict.keys():
                            cov20txt = pluginDict["Target base coverage at 20x"]
                        else:
                            cov20txt = pluginDict["Genome base coverage at 20x"]
                        bestCov20 = float(cov20txt.rstrip('%'))
                        uniftxt = pluginDict["Uniformity of base coverage"]
                        bestUnif = float(uniftxt.rstrip('%'))
                    # print 'plugin val: %s' % val
                    if bestCov20 > 0.0:
                        extraInfo["cov20"] = str(bestCov20) + "%"
                        extraInfo["unif"] = str(bestUnif) + "%"
                    else:
                        extraInfo["cov20"] = " "
                        extraInfo["unif"] = " "
                    # print 'plugin syserr is: %s' % extraInfo["syserr"]
            except:
                extraInfo["cov20"] = " "
                extraInfo["unif"] = " "

            info.append(extraInfo)

    #sort by chipType
    if len(resultsAll) > 1:
      try: 
        resultsAll, rType, rNew, info = zip(*sorted(zip(resultsAll,rType,rNew,info), key=lambda r:r[0].experiment.chipType))
      except:
        pass
    
    
    gc = models.GlobalConfig.get()
    web_root = gc.web_root
    if len(web_root) > 0:
        if web_root[-1] == '/':
            web_root = web_root[:len(web_root)-1]

    if len(gc.site_name) is 0:
        site_name = "<set site name in Global Configs on Admin Tab>"
    else:
        site_name = gc.site_name
     
    lbms = [res.best_lib_metrics for res in resultsAll]
    tfms = [res.best_metrics for res in resultsAll]
    #links = [web_root+res.reportLink for res in resultsAll]
    links = [web_root+"/report/"+str(res.pk) for res in resultsAll]
 
    #find the sum of the q20 bases
    hqBaseSum = 0
    for res,n,tp in zip(resultsAll,rNew,rType):
        if n and (not tp=='thumb') and (not tp=='paired') and res.best_lib_metrics:
            if res.best_lib_metrics.align_sample == 0:
                hqBaseSum = hqBaseSum + res.best_lib_metrics.q20_mapped_bases
            if res.best_lib_metrics.align_sample == 1:
                hqBaseSum = hqBaseSum + res.best_lib_metrics.extrapolated_mapped_bases_in_q20_alignments
            if res.best_lib_metrics.align_sample == 2:
                hqBaseSum = hqBaseSum + res.best_lib_metrics.q20_mapped_bases
    
    tmpl = loader.get_template(TEMPLATE_NAME)
    ctx = template.Context({"reportsOldThumb":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='thumb' and not n],
                            "reportsOldWhole":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='full' and not n],
                            "reportsNew":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='full' and n],
                            "reportsThumbsNew":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='thumb' and n],
                            "reportsAmplNew":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='ampl' and n],
                            "reportsPairNew":
                                [(r,t,lb,l,i) for r,t,lb,l,i,tp,n in zip(resultsAll,tfms,lbms,links,info,rType,rNew) if tp=='paired' and n],
                            "webroot":web_root,
                            "sitename":site_name,
                            "hq_base_num_new":hqBaseSum,
                            "use_precontent":True,
                            "use_content2":True})
    html = tmpl.render(ctx)
    text = reports_to_text(resultsAll)
    subTitle = "[Report Summary] for %s %s, %s-%s-%s" % (site_name,"%a","%m","%d","%y")
    #subTitle = "[Report Summary] %a, %m-%d-%y"
    subject = datetime.datetime.now().strftime(subTitle)
    outfile = open('/tmp/out.html', 'w')
    outfile.write(html)
    outfile.close() 
    return send_html(SENDER,RECIPS,subject,html,text)
예제 #15
0
def error404(request, template_name='404.html'):
    t = template.loader.get_template(template_name)
    context = template.Context({
        'STATIC_URL': settings.STATIC_URL,
    })
    return http.HttpResponseNotFound(t.render(context))
예제 #16
0
def render_actions(actions):
    t = template.Template("""{% load lib_tags %}
{% for a in actions %}{% render_link a %}{% endfor %}
""")
    return t.render(template.Context(dict(actions=actions)))
예제 #17
0
def error500(request, template_name='500.html'):
    t = template.loader.get_template(template_name)
    context = template.Context({
        'STATIC_URL': settings.STATIC_URL,
    })
    return http.HttpResponseServerError(t.render(context))
 def render(self, context):
     return template.Template(nodelist.render(context)).render(
         template.Context(context))
def render(template_string, ctx):
    tpl = template.Template(template_string)
    return tpl.render(template.Context(ctx))
예제 #20
0
 def render():
     data = {'title': 'Just a test', 'user': '******',
             'items': ['Number %d' % num for num in range(1, 15)]}
     return tmpl.render(template.Context(data))
예제 #21
0
def render(contents, extra_context=None):
    contents = '{% load ttag_test %}' + contents
    return template.Template(contents).render(template.Context(extra_context))
예제 #22
0
 def render(self, context):
     return self.template.render(template.Context({'keycodes': self.keycodes}))
예제 #23
0
파일: custom.py 프로젝트: xspager/django
    def test_simple_tags(self):
        c = template.Context({'value': 42})

        t = template.Template('{% load custom %}{% no_params %}')
        self.assertEqual(t.render(c), 'no_params - Expected result')

        t = template.Template('{% load custom %}{% one_param 37 %}')
        self.assertEqual(t.render(c), 'one_param - Expected result: 37')

        t = template.Template('{% load custom %}{% explicit_no_context 37 %}')
        self.assertEqual(t.render(c),
                         'explicit_no_context - Expected result: 37')

        t = template.Template('{% load custom %}{% no_params_with_context %}')
        self.assertEqual(
            t.render(c),
            'no_params_with_context - Expected result (context value: 42)')

        t = template.Template('{% load custom %}{% params_and_context 37 %}')
        self.assertEqual(
            t.render(c),
            'params_and_context - Expected result (context value: 42): 37')

        t = template.Template('{% load custom %}{% simple_two_params 37 42 %}')
        self.assertEqual(t.render(c),
                         'simple_two_params - Expected result: 37, 42')

        t = template.Template('{% load custom %}{% simple_one_default 37 %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% simple_one_default 37 two="hello" %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, hello')

        t = template.Template(
            '{% load custom %}{% simple_one_default one=99 two="hello" %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 99, hello')

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'simple_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load custom %}{% simple_one_default 99 two="hello" three="foo" %}'
        )

        t = template.Template(
            '{% load custom %}{% simple_one_default 37 42 %}')
        self.assertEqual(t.render(c),
                         'simple_one_default - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args 37 %}')
        self.assertEqual(t.render(c),
                         'simple_unlimited_args - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'simple_unlimited_args - Expected result: 37, 42, 56, 89')

        t = template.Template(
            '{% load custom %}{% simple_only_unlimited_args %}')
        self.assertEqual(t.render(c),
                         'simple_only_unlimited_args - Expected result: ')

        t = template.Template(
            '{% load custom %}{% simple_only_unlimited_args 37 42 56 89 %}')
        self.assertEqual(
            t.render(c),
            'simple_only_unlimited_args - Expected result: 37, 42, 56, 89')

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'simple_two_params' received too many positional arguments",
            template.Template,
            '{% load custom %}{% simple_two_params 37 42 56 %}')

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'simple_one_default' received too many positional arguments",
            template.Template,
            '{% load custom %}{% simple_one_default 37 42 56 %}')

        t = template.Template(
            '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 %}'
        )
        self.assertEqual(
            t.render(c),
            'simple_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'simple_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load custom %}{% simple_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 %}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'simple_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load custom %}{% simple_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" %}'
        )
예제 #24
0
 def test_context_proc_required(self):
     context = template.Context()
     old_debug = settings.DEBUG
     settings.DEBUG = True
     self.assertRaises(SiteTreeError, self.sitetree.menu, 'tree1', 'trunk', context)
     settings.DEBUG = old_debug
예제 #25
0
파일: custom.py 프로젝트: xspager/django
    def test_assignment_tags(self):
        c = template.Context({'value': 42})

        t = template.Template(
            '{% load custom %}{% assignment_no_params as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_no_params - Expected result')

        t = template.Template(
            '{% load custom %}{% assignment_one_param 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_param - Expected result: 37')

        t = template.Template(
            '{% load custom %}{% assignment_explicit_no_context 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_explicit_no_context - Expected result: 37'
        )

        t = template.Template(
            '{% load custom %}{% assignment_no_params_with_context as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_no_params_with_context - Expected result (context value: 42)'
        )

        t = template.Template(
            '{% load custom %}{% assignment_params_and_context 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_params_and_context - Expected result (context value: 42): 37'
        )

        t = template.Template(
            '{% load custom %}{% assignment_two_params 37 42 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_two_params - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, hi')

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 two="hello" as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, hello'
        )

        t = template.Template(
            '{% load custom %}{% assignment_one_default one=99 two="hello" as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 99, hello'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_default' received unexpected keyword argument 'three'",
            template.Template,
            '{% load custom %}{% assignment_one_default 99 two="hello" three="foo" as var %}'
        )

        t = template.Template(
            '{% load custom %}{% assignment_one_default 37 42 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_one_default - Expected result: 37, 42')

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args 37 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args - Expected result: 37, hi'
        )

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args - Expected result: 37, 42, 56, 89'
        )

        t = template.Template(
            '{% load custom %}{% assignment_only_unlimited_args as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_only_unlimited_args - Expected result: '
        )

        t = template.Template(
            '{% load custom %}{% assignment_only_unlimited_args 37 42 56 89 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_only_unlimited_args - Expected result: 37, 42, 56, 89'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 as %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_param' tag takes at least 2 arguments and the second last argument must be 'as'",
            template.Template,
            '{% load custom %}{% assignment_one_param 37 ass var %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_two_params' received too many positional arguments",
            template.Template,
            '{% load custom %}{% assignment_two_params 37 42 56 as var %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_default' received too many positional arguments",
            template.Template,
            '{% load custom %}{% assignment_one_default 37 42 56 as var %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_one_default' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load custom %}{% assignment_one_default as var %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_unlimited_args' did not receive value\(s\) for the argument\(s\): 'one'",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args as var %}The result is: {{ var }}'
        )

        t = template.Template(
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 56 eggs="scrambled" four=1|add:3 as var %}The result is: {{ var }}'
        )
        self.assertEqual(
            t.render(c),
            'The result is: assignment_unlimited_args_kwargs - Expected result: 37, 42, 56 / eggs=scrambled, four=4'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_unlimited_args_kwargs' received some positional argument\(s\) after some keyword argument\(s\)",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 40|add:2 eggs="scrambled" 56 four=1|add:3 as var %}The result is: {{ var }}'
        )

        self.assertRaisesRegexp(
            template.TemplateSyntaxError,
            "'assignment_unlimited_args_kwargs' received multiple values for keyword argument 'eggs'",
            template.Template,
            '{% load custom %}{% assignment_unlimited_args_kwargs 37 eggs="scrambled" eggs="scrambled" as var %}The result is: {{ var }}'
        )
예제 #26
0
def get_mock_context(app=None, path=None, user_authorized=False, tree_item=None, put_var=None):
    ctx = template.Context({'request': MockRequest(path, user_authorized),
                            't2_root2_title': 'my_real_title', 'art_id': 10, 'tree_item': tree_item,
                            'somevar_str': 'articles_list', 'somevar_list': ['a', 'b'], 'put_var': put_var}, current_app=app)
    return ctx
 def test_renders_price_correctly(self):
     out = self.template.render(template.Context({
         'price': D('10.23'),
     }))
     self.assertTrue('£10.23' in out)
예제 #28
0
파일: views.py 프로젝트: paglian/afip-query
def afip_query_form(request):
    html_tmpl = """
<html>
    <head><title>{{title}}</title></head>
    <body>
        <h2>{{title}}</h2>
        <p>
        <form name="input" action="" method="get">
            Escribe tu consulta: <input type="text" name="query" text="{{query}}">
            <input type="submit" value="Buscar!">
        </form>
        </p>

        {%if query %}
        <p>
            {%if results %}
            Resultados para la consulta &quot;<b>{{ query }}</b>&quot;:
                <ul>
                    {% for r in results %}
                    <li>{{r.0}}/100 - <a href="{{ afip_url }}{{ r.1 }}" target="_blank">{{ r.2 }}</a></li>
                    {% endfor %}
                </ul>
            {% else %}
                No se encontraron resultados para la consulta '{{query}}'
            {% endif %}
        </p>
        {% endif %}

        {%if did_you_mean %}
        <p>
            <em>Quizo decir:
            <a href="/?query={{ did_you_mean }}">{{ did_you_mean }}</a> ?
            </em>
        </p>
        {% endif %}
    </body>
</html>
"""

    query = ""
    results = []
    did_you_mean = ""

    if 'query' in request.GET:
        query = request.GET['query']
        try:
            fa = FaqQuery('../../backend/faqs/afip_mono_faq_full.json')
            all_results = fa.query(query)
            for r in all_results:
                score = int(float(r[0]) * 100)
                if score > 10:
                    r[0] = score
                    results.append(r)

            # Spell check
            scquery = fa.spell_check(query)
            if scquery != query:
                did_you_mean = scquery
        except:
            raise

    t = template.Template(html_tmpl)
    c = template.Context({
        'title': 'Consulta Monotributo AFIP',
        'afip_url':
        'http://www.afip.gob.ar/genericos/guiavirtual/consultas_detalle.aspx?id=',
        'query': query,
        'results': results,
        'did_you_mean': did_you_mean,
    })

    return HttpResponse(t.render(c))
 def test_handles_string_price_gracefully(self):
     self.template.render(template.Context({
         'price': ''
     }))
예제 #30
0
    attr does not exist, here, we return `default` even if attr evaluates to
    None or False.
    """
    value = getattr(obj, name, default)
    if value:
        return value
    else:
        return default


context = template.Context({
    'DJANGO_SETTINGS_MODULE': os.environ['DJANGO_SETTINGS_MODULE'],
    'HOSTNAME': socket.getfqdn(),
    'PROJECT_PATH': os.path.realpath(
        _getattr(settings, 'ROOT_PATH', PROJECT_PATH)),
    'STATIC_PATH': os.path.realpath(
        _getattr(settings, 'STATIC_ROOT', STATIC_PATH)),
    'SSLCERT': '/etc/pki/tls/certs/ca.crt',
    'SSLKEY': '/etc/pki/tls/private/ca.key',
    'CACERT': None,
    'PROCESSES': multiprocessing.cpu_count() + 1,
})

context['PROJECT_ROOT'] = os.path.dirname(context['PROJECT_PATH'])
context['PROJECT_DIR_NAME'] = os.path.basename(
    context['PROJECT_PATH'].split(context['PROJECT_ROOT'])[1])
context['PROJECT_NAME'] = context['PROJECT_DIR_NAME']

context['WSGI_FILE'] = os.path.join(
    context['PROJECT_PATH'], 'wsgi/horizon.wsgi')

VHOSTNAME = context['HOSTNAME'].split('.')