This file is indexed.

/usr/lib/python2.7/dist-packages/chameleon/benchmark.py is in python-chameleon 2.24-1.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  1
  2
  3
  4
  5
  6
  7
  8
  9
 10
 11
 12
 13
 14
 15
 16
 17
 18
 19
 20
 21
 22
 23
 24
 25
 26
 27
 28
 29
 30
 31
 32
 33
 34
 35
 36
 37
 38
 39
 40
 41
 42
 43
 44
 45
 46
 47
 48
 49
 50
 51
 52
 53
 54
 55
 56
 57
 58
 59
 60
 61
 62
 63
 64
 65
 66
 67
 68
 69
 70
 71
 72
 73
 74
 75
 76
 77
 78
 79
 80
 81
 82
 83
 84
 85
 86
 87
 88
 89
 90
 91
 92
 93
 94
 95
 96
 97
 98
 99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
import unittest
import time
import os
import re
from .utils import text_

re_amp = re.compile(r'&(?!([A-Za-z]+|#[0-9]+);)')

BIGTABLE_ZPT = """\
<table xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<tr tal:repeat="row python: options['table']">
<td tal:repeat="c python: row.values()">
<span tal:define="d python: c + 1"
tal:attributes="class python: 'column-' + str(d)"
tal:content="python: d" />
</td>
</tr>
</table>"""

MANY_STRINGS_ZPT = """\
<table xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<tr tal:repeat="i python: xrange(1000)">
<td tal:content="string: number ${i}" />
</tr>
</table>
"""

HELLO_WORLD_ZPT = """\
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal">
<body>
<h1>Hello, world!</h1>
</body>
</html>
"""

I18N_ZPT = """\
<html xmlns="http://www.w3.org/1999/xhtml"
xmlns:tal="http://xml.zope.org/namespaces/tal"
xmlns:i18n="http://xml.zope.org/namespaces/i18n">
  <body>
    <div tal:repeat="i python: xrange(10)">
      <div i18n:translate="">
        Hello world!
      </div>
      <div i18n:translate="hello_world">
        Hello world!
      </div>
      <div i18n:translate="">
        <sup>Hello world!</sup>
      </div>
    </div>
  </body>
</html>
"""


def benchmark(title):
    def decorator(f):
        def wrapper(*args):
            print(
                "==========================\n " \
                "%s\n==========================" % \
                title)
            return f(*args)
        return wrapper
    return decorator


def timing(func, *args, **kwargs):
    t1 = t2 = time.time()
    i = 0
    while t2 - t1 < 3:
        func(**kwargs)
        func(**kwargs)
        func(**kwargs)
        func(**kwargs)
        i += 4
        t2 = time.time()
    return float(10 * (t2 - t1)) / i


START = 0
END = 1
TAG = 2


def yield_tokens(table=None):
    index = []
    tag = index.append
    _re_amp = re_amp
    tag(START)
    yield "<", "html", "", ">\n"
    for r in table:
        tag(START)
        yield "<", "tr", "", ">\n"

        for c in r.values():
            d = c + 1
            tag(START)
            yield "<", "td", "", ">\n"

            _tmp5 = d
            if not isinstance(_tmp5, unicode):
                _tmp5 = str(_tmp5)
            if ('&' in _tmp5):
                if (';' in _tmp5):
                    _tmp5 = _re_amp.sub('&amp;', _tmp5)
                else:
                    _tmp5 = _tmp5.replace('&', '&amp;')
            if ('<' in _tmp5):
                _tmp5 = _tmp5.replace('<', '&lt;')
            if ('>' in _tmp5):
                _tmp5 = _tmp5.replace('>', '&gt;')
            if ('"' in _tmp5):
                _tmp5 = _tmp5.replace('"', '&quot;')
            _tmp5 = "column-%s" % _tmp5

            _tmp = d
            if (_tmp.__class__ not in (str, unicode, int, float, )):
                raise
            if (_tmp is not None):
                if not isinstance(_tmp, unicode):
                    _tmp = str(_tmp)
                if ('&' in _tmp):
                    if (';' in _tmp):
                        _tmp = _re_amp.sub('&amp;', _tmp)
                    else:
                        _tmp = _tmp.replace('&', '&amp;')
                if ('<' in _tmp):
                    _tmp = _tmp.replace('<', '&lt;')
                if ('>' in _tmp):
                    _tmp = _tmp.replace('>', '&gt;')
            tag(START)

            t = ["classicism"]

            yield "<", "span", " ", t[0], '="', _tmp5, '"', ">\n"
            tag(END)
            yield "</", "span", ">\n"
            tag(END)
            yield "</", "td", ">\n"
        tag(END)
        yield "</", "tr", ">\n"
    tag(END)
    yield "</", "html", ">\n"


def yield_tokens_dict_version(**kwargs):
    index = []
    tag = index.append
    _re_amp = re_amp
    tag(START)
    yield "<", "html", "", ">\n"

    for r in kwargs['table']:
        kwargs['r'] = r
        tag(START)
        yield "<", "tr", "", ">\n"

        for c in kwargs['r'].values():
            kwargs['d'] = c + 1
            tag(START)
            yield "<", "td", "", ">\n"

            _tmp5 = kwargs['d']
            if not isinstance(_tmp5, unicode):
                _tmp5 = str(_tmp5)
            if ('&' in _tmp5):
                if (';' in _tmp5):
                    _tmp5 = _re_amp.sub('&amp;', _tmp5)
                else:
                    _tmp5 = _tmp5.replace('&', '&amp;')
            if ('<' in _tmp5):
                _tmp5 = _tmp5.replace('<', '&lt;')
            if ('>' in _tmp5):
                _tmp5 = _tmp5.replace('>', '&gt;')
            if ('"' in _tmp5):
                _tmp5 = _tmp5.replace('"', '&quot;')
            _tmp5 = "column-%s" % _tmp5

            _tmp = kwargs['d']
            if (_tmp.__class__ not in (str, unicode, int, float, )):
                raise
            if (_tmp is not None):
                if not isinstance(_tmp, unicode):
                    _tmp = str(_tmp)
                if ('&' in _tmp):
                    if (';' in _tmp):
                        _tmp = _re_amp.sub('&amp;', _tmp)
                    else:
                        _tmp = _tmp.replace('&', '&amp;')
                if ('<' in _tmp):
                    _tmp = _tmp.replace('<', '&lt;')
                if ('>' in _tmp):
                    _tmp = _tmp.replace('>', '&gt;')
            tag(START)

            t = ["classicism"]

            yield "<", "span", " ", t[0], '="', _tmp5, '"', ">\n"
            tag(END)
            yield "</", "span", ">\n"
            tag(END)
            yield "</", "td", ">\n"
        tag(END)
        yield "</", "tr", ">\n"
    tag(END)
    yield "</", "html", ">\n"


def yield_stream(table=None):
    _re_amp = re_amp
    yield START, ("html", "", "\n"), None
    for r in table:
        yield START, ("tr", "", "\n"), None

        for c in r.values():
            d = c + 1
            yield START, ("td", "", "\n"), None

            _tmp5 = d
            if not isinstance(_tmp5, unicode):
                _tmp5 = str(_tmp5)
            if ('&' in _tmp5):
                if (';' in _tmp5):
                    _tmp5 = _re_amp.sub('&amp;', _tmp5)
                else:
                    _tmp5 = _tmp5.replace('&', '&amp;')
            if ('<' in _tmp5):
                _tmp5 = _tmp5.replace('<', '&lt;')
            if ('>' in _tmp5):
                _tmp5 = _tmp5.replace('>', '&gt;')
            if ('"' in _tmp5):
                _tmp5 = _tmp5.replace('"', '&quot;')
            _tmp5 = "column-%s" % _tmp5

            _tmp = d
            if (_tmp.__class__ not in (str, unicode, int, float, )):
                raise
            if (_tmp is not None):
                if not isinstance(_tmp, unicode):
                    _tmp = str(_tmp)
                if ('&' in _tmp):
                    if (';' in _tmp):
                        _tmp = _re_amp.sub('&amp;', _tmp)
                    else:
                        _tmp = _tmp.replace('&', '&amp;')
                if ('<' in _tmp):
                    _tmp = _tmp.replace('<', '&lt;')
                if ('>' in _tmp):
                    _tmp = _tmp.replace('>', '&gt;')
            yield START, ("span", "", _tmp, " ", "class", _tmp5), None

            yield END, ("span", "", "\n"), None
            yield END, ("td", "", "\n"), None
        yield END, ("tr", "", "\n"), None
    yield END, ("html", "", "\n"), None

from itertools import chain


def bigtable_python_tokens(table=None, renderer=None):
    iterable = renderer(table=table)
    stream = chain(*iterable)
    return "".join(stream)


def bigtable_python_stream(table=None, renderer=None):
    stream = renderer(table=table)
    return "".join(stream_output(stream))


def bigtable_python_stream_with_filter(table=None, renderer=None):
    stream = renderer(table=table)
    return "".join(stream_output(uppercase_filter(stream)))


def uppercase_filter(stream):
    for kind, data, pos in stream:
        if kind is START:
            data = (data[0], data[1], data[2].upper(),) + data[3:]
        elif kind is END:
            data = (data[0], data[1], data[2].upper())
        elif kind is TAG:
            raise NotImplemented
        yield kind, data, pos


def stream_output(stream):
    for kind, data, pos in stream:
        if kind is START:
            tag = data[0]
            yield "<%s" % tag
            l = len(data)

            # optimize for common cases
            if l == 3:
                pass
            elif l == 6:
                yield '%s%s="%s"' % (data[3], data[4], data[5])
            else:
                i = 3
                while i < l:
                    yield '%s%s="%s"' % (data[i], data[i + 1], data[i + 2])
                    i += 3
            yield "%s>%s" % (data[1], data[2])
        elif kind is END:
            yield "</%s%s>%s" % data
        elif kind is TAG:
            raise NotImplemented


class Benchmarks(unittest.TestCase):
    table = [dict(a=1, b=2, c=3, d=4, e=5, f=6, g=7, h=8, i=9, j=10) \
             for x in range(1000)]

    def setUp(self):
        # set up i18n component
        from zope.i18n import translate
        from zope.i18n.interfaces import INegotiator
        from zope.i18n.interfaces import ITranslationDomain
        from zope.i18n.negotiator import Negotiator
        from zope.i18n.simpletranslationdomain import SimpleTranslationDomain
        from zope.i18n.tests.test_negotiator import Env
        from zope.tales.tales import Context

        self.env = Env(('klingon', 'da', 'en', 'fr', 'no'))

        class ZopeI18NContext(Context):

            def translate(self, msgid, domain=None, context=None,
                          mapping=None, default=None):
                context = self.vars['options']['env']
                return translate(msgid, domain, mapping,
                                 context=context, default=default)

        def _getContext(self, contexts=None, **kwcontexts):
            if contexts is not None:
                if kwcontexts:
                    kwcontexts.update(contexts)
                else:
                    kwcontexts = contexts
            return ZopeI18NContext(self, kwcontexts)

        def _pt_getEngineContext(namespace):
            self = namespace['template']
            engine = self.pt_getEngine()
            return _getContext(engine, namespace)

        import zope.component
        zope.component.provideUtility(Negotiator(), INegotiator)
        catalog = SimpleTranslationDomain('domain')
        zope.component.provideUtility(catalog, ITranslationDomain, 'domain')
        self.files = os.path.abspath(os.path.join(__file__, '..', 'input'))

    @staticmethod
    def _chameleon(body, **kwargs):
        from .zpt.template import PageTemplate
        return PageTemplate(body, **kwargs)

    @staticmethod
    def _zope(body):
        from zope.pagetemplate.pagetemplatefile import PageTemplate
        template = PageTemplate()
        template.pt_edit(body, 'text/xhtml')
        return template

    @benchmark(text_("BIGTABLE [python]"))
    def test_bigtable(self):
        options = {'table': self.table}

        t_chameleon = timing(self._chameleon(BIGTABLE_ZPT), options=options)
        print("chameleon:         %7.2f" % t_chameleon)

        t_chameleon_utf8 = timing(
            self._chameleon(BIGTABLE_ZPT, encoding='utf-8'), options=options)
        print("chameleon (utf-8): %7.2f" % t_chameleon_utf8)

        t_tokens = timing(
            bigtable_python_tokens, table=self.table, renderer=yield_tokens)
        print("token:             %7.2f" % t_tokens)

        t_tokens_dict_version = timing(
            bigtable_python_tokens, table=self.table,
            renderer=yield_tokens_dict_version)
        print("token (dict):      %7.2f" % t_tokens_dict_version)

        t_stream = timing(
            bigtable_python_stream, table=self.table, renderer=yield_stream)
        print("stream:            %7.2f" % t_stream)

        t_zope = timing(self._zope(BIGTABLE_ZPT), table=self.table)
        print("zope.pagetemplate: %7.2f" % t_zope)
        print("                  %7.1fX" % (t_zope / t_chameleon))

        print("--------------------------")
        print("check: %d vs %d" % (
            len(self._chameleon(BIGTABLE_ZPT)(options=options)),
            len(self._zope(BIGTABLE_ZPT)(table=self.table))))
        print("--------------------------")

    @benchmark(text_("MANY STRINGS [python]"))
    def test_many_strings(self):
        t_chameleon = timing(self._chameleon(MANY_STRINGS_ZPT))
        print("chameleon:         %7.2f" % t_chameleon)
        t_zope = timing(self._zope(MANY_STRINGS_ZPT))
        print("zope.pagetemplate: %7.2f" % t_zope)
        print("                  %7.1fX" % (t_zope / t_chameleon))

        print("--------------------------")
        print("check: %d vs %d" % (
            len(self._chameleon(MANY_STRINGS_ZPT)()),
            len(self._zope(MANY_STRINGS_ZPT)())))
        print("--------------------------")

    @benchmark(text_("HELLO WORLD"))
    def test_hello_world(self):
        t_chameleon = timing(self._chameleon(HELLO_WORLD_ZPT)) * 1000
        print("chameleon:         %7.2f" % t_chameleon)
        t_zope = timing(self._zope(HELLO_WORLD_ZPT)) * 1000
        print("zope.pagetemplate: %7.2f" % t_zope)
        print("                  %7.1fX" % (t_zope / t_chameleon))

        print("--------------------------")
        print("check: %d vs %d" % (
            len(self._chameleon(HELLO_WORLD_ZPT)()),
            len(self._zope(HELLO_WORLD_ZPT)())))
        print("--------------------------")

    @benchmark(text_("I18N"))
    def test_i18n(self):
        from zope.i18n import translate
        t_chameleon = timing(
            self._chameleon(I18N_ZPT),
            translate=translate,
            language="klingon") * 1000
        print("chameleon:         %7.2f" % t_chameleon)
        t_zope = timing(self._zope(I18N_ZPT), env=self.env) * 1000
        print("zope.pagetemplate: %7.2f" % t_zope)
        print("                  %7.1fX" % (t_zope / t_chameleon))

    @benchmark(text_("COMPILATION"))
    def test_compilation(self):
        template = self._chameleon(HELLO_WORLD_ZPT)

        def chameleon_cook_and_render(template=template):
            template.cook(HELLO_WORLD_ZPT)
            template()

        t_chameleon = timing(chameleon_cook_and_render) * 1000
        print("chameleon:         %7.2f" % t_chameleon)

        template = self._zope(HELLO_WORLD_ZPT)

        def zope_cook_and_render(templte=template):
            template._cook()
            template()

        t_zope = timing(zope_cook_and_render) * 1000
        print("zope.pagetemplate: %7.2f" % t_zope)
        print("                    %0.3fX" % (t_zope / t_chameleon))


def start():
    result = unittest.TestResult()
    test = unittest.makeSuite(Benchmarks)
    test.run(result)

    for error in result.errors:
        print("Error in %s...\n" % error[0])
        print(error[1])

    for failure in result.failures:
        print("Failure in %s...\n" % failure[0])
        print(failure[1])