WebError-0.10.3/000775 000765 000024 00000000000 11466345335 013245 5ustar00benstaff000000 000000 WebError-0.10.3/.hgignore000664 000765 000024 00000000202 11466344257 015044 0ustar00benstaff000000 000000 # Automatically generated by `hgimportsvn` syntax:glob .svn .coverage *.pyc *.egg-info ez_setup *.egg-info *.egg test_logger.log WebError-0.10.3/.hgtags000664 000765 000024 00000000735 11335430037 014515 0ustar00benstaff000000 000000 641409089c70fa587f9535f2752eb0424dbf9d65 v0.8a 2812e5d66cbbdeb54594d46a0da768459038bcfa v0.8 018397c549de6366aebd1c2a4ddd809997e14ef2 v0.9 4abb0b1bcb8d95efe79de71c96002b580582560e v0.9.1 02d8a5923a5c899bee2464af450ac0f1268b5e20 v0.10 a7942bc0fd124522de37c1f33e11e2463afaeb0e v0.10 b78d1b83347b515a9b838b4e88756baa8d67e68b v0.10.1 602a4d02080667d9a7adf9830140d75e64e54c36 v0.10.2 602a4d02080667d9a7adf9830140d75e64e54c36 v0.10.2 19525cc8a25c6beb9dda23fb893b303af033cceb v0.10.2 WebError-0.10.3/CHANGELOG000664 000765 000024 00000002355 11466345271 014463 0ustar00benstaff000000 000000 WebError Changelog ================== 0.10.3 (11/9/2010) * Don't require simplejson on Python 2.6 0.10.2 (2/12/2010) * Fix bug when displaying UTF-8 type errors. * Fix bug when emailing data with UTF-8. 0.10.1 (12/29/2008) * Fix view source when __file__ is .pyo or $py.class. 0.10 (12/18/2008) * Fix indentation of code lines in the traceback view. * Enable syntax highlighting in view source. * Fix a case where the response could become unicode; fix the docstring patching when using python -O 0.9.1 (10/28/2008) * Python 2.6 compatibility * Making main page links more accessible to browsers with no JS on per Pylons Trac ticket #489. 0.9 (07/08/2008) * Switched to using Pygments for highlighting. * Added better handling of exceptions that don't cleanly convert to str(). * Added dependency library listings for XML output. 0.8 (06/12/2008) * Added fairly basic pdbcapture system. * Fixed errors in unicode handling and exception displaying. * Updated JS to use jQuery where applicable. Updated jQuery lib and added jQuery hotkeys plugin. * Refactored to a flatter layout. 0.8a (02/27/2008) * Fixed error in email due to restructuring of project. * Added xml formattor output. * Added try/except in case an objects repr throws an exception. WebError-0.10.3/LICENSE000600 000765 000024 00000004277 11012136673 014240 0ustar00benstaff000000 000000 EXCEPT FOR JQUERY, ALL CODE IS LICENSED AS FOLLOWS: Copyright (c) 2008 Ben Bangert, Ian Bicking Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. JQUERY IS LICENSED UNDER THE MIT LICENSE: Copyright (c) 2008 John Resig, http://jquery.com/ Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. WebError-0.10.3/MANIFEST.in000664 000765 000024 00000000126 11003174504 014763 0ustar00benstaff000000 000000 recursive-include weberror/eval-media * recursive-include weberror eval_template.html WebError-0.10.3/PKG-INFO000664 000765 000024 00000001445 11466345335 014346 0ustar00benstaff000000 000000 Metadata-Version: 1.0 Name: WebError Version: 0.10.3 Summary: Web Error handling and exception catching Home-page: UNKNOWN Author: Ben Bangert, Ian Bicking, Mark Ramm Author-email: UNKNOWN License: MIT Description: UNKNOWN Keywords: wsgi Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware WebError-0.10.3/README000600 000765 000024 00000000000 10723213331 014062 0ustar00benstaff000000 000000 WebError-0.10.3/setup.cfg000600 000765 000024 00000000171 11466345335 015053 0ustar00benstaff000000 000000 [egg_info] tag_build = tag_date = 0 tag_svn_revision = 0 [nosetests] verbosity = 2 verbose = True with-doctest = True WebError-0.10.3/setup.py000664 000765 000024 00000003254 11466345133 014757 0ustar00benstaff000000 000000 from setuptools import setup, find_packages import sys version = '0.10.3' install_requires = [ 'WebOb', 'Tempita', 'Pygments', 'Paste>=1.7.1', ] if sys.version_info[:2] < (2, 6): install_requires.append('simplejson') setup(name='WebError', version=version, description="Web Error handling and exception catching", long_description="""\ """, classifiers=[ "Development Status :: 5 - Production/Stable", "Intended Audience :: Developers", "License :: OSI Approved :: MIT License", "Programming Language :: Python", "Topic :: Internet :: WWW/HTTP", "Topic :: Internet :: WWW/HTTP :: Dynamic Content", "Topic :: Software Development :: Libraries :: Python Modules", "Topic :: Internet :: WWW/HTTP :: WSGI", "Topic :: Internet :: WWW/HTTP :: WSGI :: Application", "Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware", ], keywords='wsgi', author='Ben Bangert, Ian Bicking, Mark Ramm', author_email='', url='', license='MIT', packages=find_packages(exclude=['ez_setup', 'examples', 'tests']), include_package_data=True, package_data = { 'weberror.evalexception': [ "*.html.tmpl", "media/*" ] }, zip_safe=False, install_requires=install_requires, test_suite='nose.collector', tests_require=['nose', 'webtest', 'Paste'], entry_points=""" [paste.filter_app_factory] main = weberror.evalexception:make_general_exception error_catcher = weberror.errormiddleware:make_error_middleware evalerror = weberror.evalexception:make_eval_exception """, ) WebError-0.10.3/tests/000775 000765 000024 00000000000 11466345335 014407 5ustar00benstaff000000 000000 WebError-0.10.3/weberror/000775 000765 000024 00000000000 11466345335 015074 5ustar00benstaff000000 000000 WebError-0.10.3/WebError.egg-info/000775 000765 000024 00000000000 11466345335 016466 5ustar00benstaff000000 000000 WebError-0.10.3/WebError.egg-info/dependency_links.txt000700 000765 000024 00000000001 11466345333 022521 0ustar00benstaff000000 000000 WebError-0.10.3/WebError.egg-info/entry_points.txt000700 000765 000024 00000000345 11466345333 021753 0ustar00benstaff000000 000000 [paste.filter_app_factory] main = weberror.evalexception:make_general_exception error_catcher = weberror.errormiddleware:make_error_middleware evalerror = weberror.evalexception:make_eval_exception WebError-0.10.3/WebError.egg-info/not-zip-safe000700 000765 000024 00000000001 10722702726 020676 0ustar00benstaff000000 000000 WebError-0.10.3/WebError.egg-info/paster_plugins.txt000700 000765 000024 00000000014 10722702726 022243 0ustar00benstaff000000 000000 PasteScript WebError-0.10.3/WebError.egg-info/PKG-INFO000700 000765 000024 00000001445 11466345333 017554 0ustar00benstaff000000 000000 Metadata-Version: 1.0 Name: WebError Version: 0.10.3 Summary: Web Error handling and exception catching Home-page: UNKNOWN Author: Ben Bangert, Ian Bicking, Mark Ramm Author-email: UNKNOWN License: MIT Description: UNKNOWN Keywords: wsgi Platform: UNKNOWN Classifier: Development Status :: 5 - Production/Stable Classifier: Intended Audience :: Developers Classifier: License :: OSI Approved :: MIT License Classifier: Programming Language :: Python Classifier: Topic :: Internet :: WWW/HTTP Classifier: Topic :: Internet :: WWW/HTTP :: Dynamic Content Classifier: Topic :: Software Development :: Libraries :: Python Modules Classifier: Topic :: Internet :: WWW/HTTP :: WSGI Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Application Classifier: Topic :: Internet :: WWW/HTTP :: WSGI :: Middleware WebError-0.10.3/WebError.egg-info/requires.txt000700 000765 000024 00000000043 11466345333 021050 0ustar00benstaff000000 000000 WebOb Tempita Pygments Paste>=1.7.1WebError-0.10.3/WebError.egg-info/SOURCES.txt000700 000765 000024 00000002311 11466345333 020334 0ustar00benstaff000000 000000 .hgignore .hgtags CHANGELOG LICENSE MANIFEST.in README setup.cfg setup.py WebError.egg-info/PKG-INFO WebError.egg-info/SOURCES.txt WebError.egg-info/dependency_links.txt WebError.egg-info/entry_points.txt WebError.egg-info/not-zip-safe WebError.egg-info/paster_plugins.txt WebError.egg-info/requires.txt WebError.egg-info/top_level.txt tests/__init__.py tests/evaldemo.py tests/test_config.ini tests/test_error_middleware.py tests/test_formatter.py tests/test_reporter.py tests/reporter_output/.testdir weberror/__init__.py weberror/collector.py weberror/errormiddleware.py weberror/eval_template.html weberror/evalcontext.py weberror/evalexception.py weberror/formatter.py weberror/pdbcapture.py weberror/reporter.py weberror/eval-media/debug.js weberror/eval-media/jquery-1.2.1.min.js weberror/eval-media/jquery-1.2.3.pack.js weberror/eval-media/jquery.scrollTo-min.js weberror/eval-media/jquery.scrollTo.js weberror/eval-media/minus.jpg weberror/eval-media/plus.jpg weberror/eval-media/traceback.css weberror/exceptions/__init__.py weberror/exceptions/errormiddleware.py weberror/util/__init__.py weberror/util/errorapp.py weberror/util/escaping.py weberror/util/serial_number_generator.py weberror/util/source_encoding.pyWebError-0.10.3/WebError.egg-info/top_level.txt000700 000765 000024 00000000011 11466345333 021175 0ustar00benstaff000000 000000 weberror WebError-0.10.3/weberror/__init__.py000600 000765 000024 00000000002 10723213331 017144 0ustar00benstaff000000 000000 # WebError-0.10.3/weberror/collector.py000664 000765 000024 00000047443 11466344242 017444 0ustar00benstaff000000 000000 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php ############################################################################## # # Copyright (c) 2001, 2002 Zope Corporation and Contributors. # All Rights Reserved. # # This software is subject to the provisions of the Zope Public License, # Version 2.0 (ZPL). A copy of the ZPL should accompany this distribution. # THIS SOFTWARE IS PROVIDED "AS IS" AND ANY AND ALL EXPRESS OR IMPLIED # WARRANTIES ARE DISCLAIMED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED # WARRANTIES OF TITLE, MERCHANTABILITY, AGAINST INFRINGEMENT, AND FITNESS # FOR A PARTICULAR PURPOSE. # ############################################################################## ## Originally zExceptions.ExceptionFormatter from Zope; ## Modified by Ian Bicking, Imaginary Landscape, 2005 """ An exception collector that finds traceback information plus supplements """ import sys import traceback import time try: from cStringIO import StringIO except ImportError: from StringIO import StringIO import linecache from weberror.util import source_encoding, serial_number_generator DEBUG_EXCEPTION_FORMATTER = True DEBUG_IDENT_PREFIX = 'E-' FALLBACK_ENCODING = 'UTF-8' __all__ = ['collect_exception', 'ExceptionCollector'] class ExceptionCollector(object): """ Produces a data structure that can be used by formatters to display exception reports. Magic variables: If you define one of these variables in your local scope, you can add information to tracebacks that happen in that context. This allows applications to add all sorts of extra information about the context of the error, including URLs, environmental variables, users, hostnames, etc. These are the variables we look for: ``__traceback_supplement__``: You can define this locally or globally (unlike all the other variables, which must be defined locally). ``__traceback_supplement__`` is a tuple of ``(factory, arg1, arg2...)``. When there is an exception, ``factory(arg1, arg2, ...)`` is called, and the resulting object is inspected for supplemental information. ``__traceback_info__``: This information is added to the traceback, usually fairly literally. ``__traceback_hide__``: If set and true, this indicates that the frame should be hidden from abbreviated tracebacks. This way you can hide some of the complexity of the larger framework and let the user focus on their own errors. By setting it to ``'before'``, all frames before this one will be thrown away. By setting it to ``'after'`` then all frames after this will be thrown away until ``'reset'`` is found. In each case the frame where it is set is included, unless you append ``'_and_this'`` to the value (e.g., ``'before_and_this'``). Note that formatters will ignore this entirely if the frame that contains the error wouldn't normally be shown according to these rules. ``__traceback_reporter__``: This should be a reporter object (see the reporter module), or a list/tuple of reporter objects. All reporters found this way will be given the exception, innermost first. ``__traceback_decorator__``: This object (defined in a local or global scope) will get the result of this function (the CollectedException defined below). It may modify this object in place, or return an entirely new object. This gives the object the ability to manipulate the traceback arbitrarily. The actually interpretation of these values is largely up to the reporters and formatters. ``collect_exception(*sys.exc_info())`` will return an object with several attributes: ``frames``: A list of frames ``exception_formatted``: The formatted exception, generally a full traceback ``exception_type``: The type of the exception, like ``ValueError`` ``exception_value``: The string value of the exception, like ``'x not in list'`` ``identification_code``: A hash of the exception data meant to identify the general exception, so that it shares this code with other exceptions that derive from the same problem. The code is a hash of all the module names and function names in the traceback, plus exception_type. This should be shown to users so they can refer to the exception later. (@@: should it include a portion that allows identification of the specific instance of the exception as well?) The list of frames goes innermost first. Each frame has these attributes; some values may be None if they could not be determined. ``modname``: the name of the module ``filename``: the filename of the module ``lineno``: the line of the error ``revision``: the contents of __version__ or __revision__ ``name``: the function name ``supplement``: an object created from ``__traceback_supplement__`` ``supplement_exception``: a simple traceback of any exception ``__traceback_supplement__`` created ``traceback_info``: the str() of any ``__traceback_info__`` variable found in the local scope (@@: should it str()-ify it or not?) ``traceback_hide``: the value of any ``__traceback_hide__`` variable ``traceback_log``: the value of any ``__traceback_log__`` variable ``__traceback_supplement__`` is thrown away, but a fixed set of attributes are captured; each of these attributes is optional. ``object``: the name of the object being visited ``source_url``: the original URL requested ``line``: the line of source being executed (for interpreters, like ZPT) ``column``: the column of source being executed ``expression``: the expression being evaluated (also for interpreters) ``warnings``: a list of (string) warnings to be displayed ``getInfo``: a function/method that takes no arguments, and returns a string describing any extra information ``extraData``: a function/method that takes no arguments, and returns a dictionary. The contents of this dictionary will not be displayed in the context of the traceback, but globally for the exception. Results will be grouped by the keys in the dictionaries (which also serve as titles). The keys can also be tuples of (importance, title); in this case the importance should be ``important`` (shows up at top), ``normal`` (shows up somewhere; unspecified), ``supplemental`` (shows up at bottom), or ``extra`` (shows up hidden or not at all). These are used to create an object with attributes of the same names (``getInfo`` becomes a string attribute, not a method). ``__traceback_supplement__`` implementations should be careful to produce values that are relatively static and unlikely to cause further errors in the reporting system -- any complex introspection should go in ``getInfo()`` and should ultimately return a string. Note that all attributes are optional, and under certain circumstances may be None or may not exist at all -- the collector can only do a best effort, but must avoid creating any exceptions itself. Formatters may want to use ``__traceback_hide__`` as a hint to hide frames that are part of the 'framework' or underlying system. There are a variety of rules about special values for this variables that formatters should be aware of. TODO: More attributes in __traceback_supplement__? Maybe an attribute that gives a list of local variables that should also be collected? Also, attributes that would be explicitly meant for the entire request, not just a single frame. Right now some of the fixed set of attributes (e.g., source_url) are meant for this use, but there's no explicit way for the supplement to indicate new values, e.g., logged-in user, HTTP referrer, environment, etc. Also, the attributes that do exist are Zope/Web oriented. More information on frames? cgitb, for instance, produces extensive information on local variables. There exists the possibility that getting this information may cause side effects, which can make debugging more difficult; but it also provides fodder for post-mortem debugging. However, the collector is not meant to be configurable, but to capture everything it can and let the formatters be configurable. Maybe this would have to be a configuration value, or maybe it could be indicated by another magical variable (which would probably mean 'show all local variables below this frame') """ show_revisions = 0 def __init__(self, limit=None): self.limit = limit def getLimit(self): limit = self.limit if limit is None: limit = getattr(sys, 'tracebacklimit', None) return limit def getRevision(self, globals): if not self.show_revisions: return None revision = globals.get('__revision__', None) if revision is None: # Incorrect but commonly used spelling revision = globals.get('__version__', None) if revision is not None: try: revision = str(revision).strip() except: revision = '???' return revision def collectSupplement(self, supplement, tb): result = {} for name in ('object', 'source_url', 'line', 'column', 'expression', 'warnings'): result[name] = getattr(supplement, name, None) func = getattr(supplement, 'getInfo', None) if func: result['info'] = func() else: result['info'] = None func = getattr(supplement, 'extraData', None) if func: result['extra'] = func() else: result['extra'] = None return SupplementaryData(**result) def collectLine(self, tb, extra_data): f = tb.tb_frame lineno = tb.tb_lineno co = f.f_code filename = co.co_filename name = co.co_name locals = f.f_locals globals = f.f_globals data = {} data['modname'] = globals.get('__name__', None) data['filename'] = filename data['lineno'] = lineno data['revision'] = self.getRevision(globals) data['name'] = name data['tbid'] = id(tb) data['locals'] = locals # Output a traceback supplement, if any. if '__traceback_supplement__' in locals: # Use the supplement defined in the function. tbs = locals['__traceback_supplement__'] elif globals.has_key('__traceback_supplement__'): # Use the supplement defined in the module. # This is used by Scripts (Python). tbs = globals['__traceback_supplement__'] else: tbs = None if tbs is not None: factory = tbs[0] args = tbs[1:] try: supp = factory(*args) data['supplement'] = self.collectSupplement(supp, tb) if data['supplement'].extra: for key, value in data['supplement'].extra.items(): extra_data.setdefault(key, []).append(value) except: if DEBUG_EXCEPTION_FORMATTER: out = StringIO() traceback.print_exc(file=out) text = out.getvalue() data['supplement_exception'] = text # else just swallow the exception. try: tbi = locals.get('__traceback_info__', None) if tbi is not None: data['traceback_info'] = str(tbi) except: pass marker = [] for name in ('__traceback_hide__', '__traceback_log__', '__traceback_decorator__'): try: tbh = locals.get(name, globals.get(name, marker)) if tbh is not marker: data[name[2:-2]] = tbh except: pass return data def collectExceptionOnly(self, etype, value): return traceback.format_exception_only(etype, value) def collectException(self, etype, value, tb, limit=None): # The next line provides a way to detect recursion. __exception_formatter__ = 1 frames = [] ident_data = [] traceback_decorators = [] if limit is None: limit = self.getLimit() n = 0 extra_data = {} while tb is not None and (limit is None or n < limit): if tb.tb_frame.f_locals.get('__exception_formatter__'): # Stop recursion. @@: should make a fake ExceptionFrame frames.append('(Recursive formatException() stopped)\n') break data = self.collectLine(tb, extra_data) frame = ExceptionFrame(**data) frames.append(frame) if frame.traceback_decorator is not None: traceback_decorators.append(frame.traceback_decorator) ident_data.append(frame.modname or '?') ident_data.append(frame.name or '?') tb = tb.tb_next n = n + 1 ident_data.append(str(etype)) ident = serial_number_generator.hash_identifier( ' '.join(ident_data), length=5, upper=True, prefix=DEBUG_IDENT_PREFIX) result = CollectedException( frames=frames, exception_formatted=self.collectExceptionOnly(etype, value), exception_type=etype, exception_value=self.safeStr(value), identification_code=ident, date=time.localtime(), extra_data=extra_data) if etype is ImportError: extra_data[('important', 'sys.path')] = [sys.path] for decorator in traceback_decorators: try: new_result = decorator(result) if new_result is not None: result = new_result except: pass return result def safeStr(self, obj): try: return str(obj) except UnicodeEncodeError: try: return unicode(obj).encode(FALLBACK_ENCODING, 'replace') except UnicodeEncodeError: # This is when something is really messed up, but this can # happen when the __str__ of an object has to handle unicode return repr(obj) except: try: extra = ' (exception showing exception: %s)' % str(sys.exc_info()[1]) except: extra = '' return repr(obj) + extra limit = 200 class Bunch(object): """ A generic container """ def __init__(self, **attrs): for name, value in attrs.items(): setattr(self, name, value) def __repr__(self): name = '<%s ' % self.__class__.__name__ try: name += ' '.join(['%s=%r' % (name, str(value)[:30]) for name, value in self.__dict__.items() if not name.startswith('_')]) except: name += ' UNABLE TO GET REPRESENTATION' return name + '>' class CollectedException(Bunch): """ This is the result of collection the exception; it contains copies of data of interest. """ # A list of frames (ExceptionFrame instances), innermost last: frames = [] # The result of traceback.format_exception_only; this looks # like a normal traceback you'd see in the interactive interpreter exception_formatted = None # The *string* representation of the type of the exception # (@@: should we give the # actual class? -- we can't keep the # actual exception around, but the class should be safe) # Something like 'ValueError' exception_type = None # The string representation of the exception, from ``str(e)``. exception_value = None # An identifier which should more-or-less classify this particular # exception, including where in the code it happened. identification_code = None # The date, as time.localtime() returns: date = None # A dictionary of supplemental data: extra_data = {} class SupplementaryData(Bunch): """ The result of __traceback_supplement__. We don't keep the supplement object around, for fear of GC problems and whatnot. (@@: Maybe I'm being too superstitious about copying only specific information over) """ # These attributes are copied from the object, or left as None # if the object doesn't have these attributes: object = None source_url = None line = None column = None expression = None warnings = None # This is the *return value* of supplement.getInfo(): info = None class ExceptionFrame(Bunch): """ This represents one frame of the exception. Each frame is a context in the call stack, typically represented by a line number and module name in the traceback. """ # The name of the module; can be None, especially when the code # isn't associated with a module. modname = None # The filename (@@: when no filename, is it None or '?'?) filename = None # Line number lineno = None # The value of __revision__ or __version__ -- but only if # show_revision = True (by defaut it is false). (@@: Why not # collect this?) revision = None # The name of the function with the error (@@: None or '?' when # unknown?) name = None # A SupplementaryData object, if __traceback_supplement__ was found # (and produced no errors) supplement = None # If accessing __traceback_supplement__ causes any error, the # plain-text traceback is stored here supplement_exception = None # The str() of any __traceback_info__ value found traceback_info = None # The value of __traceback_hide__ traceback_hide = False # The value of __traceback_decorator__ traceback_decorator = None # The id() of the traceback scope, can be used to reference the # scope for use elsewhere tbid = None # The filename's source code encoding _source_encoding = None def get_source_line(self, context=0): """ Return the source of the current line of this frame. You probably want to .strip() it as well, as it is likely to have leading whitespace. If context is given, then that many lines on either side will also be returned. E.g., context=1 will give 3 lines. """ if not self.filename or not self.lineno: return None lines = [] for lineno in range(self.lineno-context, self.lineno+context+1): lines.append(linecache.getline(self.filename, lineno)) return ''.join(lines) def _get_source_encoding(self): if self._source_encoding: return self._source_encoding lines = [linecache.getline(self.filename, 1), linecache.getline(self.filename, 2)] self._source_encoding = \ source_encoding.parse_encoding(lines) or 'ascii' return self._source_encoding source_encoding = property(_get_source_encoding) if hasattr(sys, 'tracebacklimit'): limit = min(limit, sys.tracebacklimit) col = ExceptionCollector() def collect_exception(t, v, tb, limit=None): """ Collection an exception from ``sys.exc_info()``. Use like:: try: blah blah except: exc_data = collect_exception(*sys.exc_info()) """ return col.collectException(t, v, tb, limit=limit) WebError-0.10.3/weberror/errormiddleware.py000664 000765 000024 00000043350 11335430006 020623 0ustar00benstaff000000 000000 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Error handler middleware """ import sys import traceback import cgi try: from cStringIO import StringIO except ImportError: from StringIO import StringIO from weberror import formatter, collector, reporter from paste import wsgilib from paste import request from paste.util import import_string import types __all__ = ['ErrorMiddleware', 'handle_exception'] class _NoDefault(object): def __repr__(self): return '' NoDefault = _NoDefault() class ErrorMiddleware(object): """ Error handling middleware Usage:: error_catching_wsgi_app = ErrorMiddleware(wsgi_app) Settings: ``debug``: If true, then tracebacks will be shown in the browser. ``error_email``: an email address (or list of addresses) to send exception reports to ``error_log``: a filename to append tracebacks to ``show_exceptions_in_wsgi_errors``: If true, then errors will be printed to ``wsgi.errors`` (frequently a server error log, or stderr). ``from_address``, ``smtp_server``, ``error_subject_prefix``, ``smtp_username``, ``smtp_password``, ``smtp_use_tls``: variables to control the emailed exception reports ``error_message``: When debug mode is off, the error message to show to users. ``xmlhttp_key``: When this key (default ``_``) is in the request GET variables (not POST!), expect that this is an XMLHttpRequest, and the response should be more minimal; it should not be a complete HTML page. Environment Configuration: ``paste.throw_errors``: If this setting in the request environment is true, then this middleware is disabled. This can be useful in a testing situation where you don't want errors to be caught and transformed. ``paste.expected_exceptions``: When this middleware encounters an exception listed in this environment variable and when the ``start_response`` has not yet occurred, the exception will be re-raised instead of being caught. This should generally be set by middleware that may (but probably shouldn't be) installed above this middleware, and wants to get certain exceptions. Exceptions raised after ``start_response`` have been called are always caught since by definition they are no longer expected. """ def __init__(self, application, global_conf=None, debug=NoDefault, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=NoDefault, from_address=None, smtp_server=None, smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix=None, error_message=None, xmlhttp_key=None, reporters=None): from paste.util import converters self.application = application # @@: global_conf should be handled elsewhere in a separate # function for the entry point if global_conf is None: global_conf = {} if debug is NoDefault: debug = converters.asbool(global_conf.get('debug')) if show_exceptions_in_wsgi_errors is NoDefault: show_exceptions_in_wsgi_errors = converters.asbool(global_conf.get('show_exceptions_in_wsgi_errors')) self.debug_mode = converters.asbool(debug) if error_email is None: error_email = (global_conf.get('error_email') or global_conf.get('admin_email') or global_conf.get('webmaster_email') or global_conf.get('sysadmin_email')) self.error_email = converters.aslist(error_email) self.error_log = error_log self.show_exceptions_in_wsgi_errors = show_exceptions_in_wsgi_errors if from_address is None: from_address = global_conf.get('error_from_address') if from_address is None: if self.error_email: from_address = self.error_email[0] else: from_address = 'errors@localhost' self.from_address = from_address if smtp_server is None: smtp_server = global_conf.get('smtp_server', 'localhost') self.smtp_server = smtp_server self.smtp_username = smtp_username or global_conf.get('smtp_username') self.smtp_password = smtp_password or global_conf.get('smtp_password') self.smtp_use_tls = smtp_use_tls or converters.asbool(global_conf.get('smtp_use_tls')) self.error_subject_prefix = error_subject_prefix or '' if error_message is None: error_message = global_conf.get('error_message') self.error_message = error_message if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key reporters = reporters or global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) self.reporters = reporters or [] def __call__(self, environ, start_response): """ The WSGI application interface. """ # We want to be careful about not sending headers twice, # and the content type that the app has committed to (if there # is an exception in the iterator body of the response) if environ.get('paste.throw_errors'): return self.application(environ, start_response) environ['paste.throw_errors'] = True try: __traceback_supplement__ = Supplement, self, environ sr_checker = ResponseStartChecker(start_response) app_iter = self.application(environ, sr_checker) return self.make_catching_iter(app_iter, environ, sr_checker) except: exc_info = sys.exc_info() try: start_response('500 Internal Server Error', [('content-type', 'text/html; charset=utf8')], exc_info) # @@: it would be nice to deal with bad content types here response = self.exception_handler(exc_info, environ) if isinstance(response, unicode): response = response.encode('utf8') return [response] finally: # clean up locals... exc_info = None def make_catching_iter(self, app_iter, environ, sr_checker): if isinstance(app_iter, (list, tuple)): # These don't raise return app_iter return CatchingIter(app_iter, environ, sr_checker, self) def exception_handler(self, exc_info, environ): simple_html_error = False if self.xmlhttp_key: get_vars = wsgilib.parse_querystring(environ) if dict(get_vars).get(self.xmlhttp_key): simple_html_error = True return handle_exception( exc_info, environ['wsgi.errors'], html=True, debug_mode=self.debug_mode, error_email=self.error_email, error_log=self.error_log, show_exceptions_in_wsgi_errors=self.show_exceptions_in_wsgi_errors, error_email_from=self.from_address, smtp_server=self.smtp_server, smtp_username=self.smtp_username, smtp_password=self.smtp_password, smtp_use_tls=self.smtp_use_tls, error_subject_prefix=self.error_subject_prefix, error_message=self.error_message, simple_html_error=simple_html_error, reporters=self.reporters) class ResponseStartChecker(object): def __init__(self, start_response): self.start_response = start_response self.response_started = False def __call__(self, *args): self.response_started = True self.start_response(*args) class CatchingIter(object): """ A wrapper around the application iterator that will catch exceptions raised by the a generator, or by the close method, and display or report as necessary. """ def __init__(self, app_iter, environ, start_checker, error_middleware): self.app_iterable = app_iter self.app_iterator = iter(app_iter) self.environ = environ self.start_checker = start_checker self.error_middleware = error_middleware self.closed = False def __iter__(self): return self def next(self): __traceback_supplement__ = ( Supplement, self.error_middleware, self.environ) if self.closed: raise StopIteration try: return self.app_iterator.next() except StopIteration: self.closed = True close_response = self._close() if close_response is not None: return close_response else: raise StopIteration except: self.closed = True close_response = self._close() exc_info = sys.exc_info() response = self.error_middleware.exception_handler( exc_info, self.environ) if close_response is not None: response += ( '
Error in .close():
%s' % close_response) if not self.start_checker.response_started: self.start_checker('500 Internal Server Error', [('content-type', 'text/html')], exc_info) return response def close(self): # This should at least print something to stderr if the # close method fails at this point if not self.closed: self._close() def _close(self): """Close and return any error message""" if not hasattr(self.app_iterable, 'close'): return None try: self.app_iterable.close() return None except: close_response = self.error_middleware.exception_handler( sys.exc_info(), self.environ) return close_response class Supplement(object): """This is a supplement used to display standard WSGI information in the traceback. Additional configuration information can be added under a Configuration section by populating the environ['weberror.config'] variable with a dictionary to include. """ def __init__(self, middleware, environ): self.middleware = middleware self.environ = environ self.source_url = request.construct_url(environ) def extraData(self): data = {} cgi_vars = data[('extra', 'CGI Variables')] = {} wsgi_vars = data[('extra', 'WSGI Variables')] = {} hide_vars = ['paste.config', 'wsgi.errors', 'wsgi.input', 'wsgi.multithread', 'wsgi.multiprocess', 'wsgi.run_once', 'wsgi.version', 'wsgi.url_scheme'] for name, value in self.environ.items(): if name.upper() == name: if value: cgi_vars[name] = value elif name not in hide_vars: wsgi_vars[name] = value if self.environ['wsgi.version'] != (1, 0): wsgi_vars['wsgi.version'] = self.environ['wsgi.version'] proc_desc = tuple([int(bool(self.environ[key])) for key in ('wsgi.multiprocess', 'wsgi.multithread', 'wsgi.run_once')]) wsgi_vars['wsgi process'] = self.process_combos[proc_desc] wsgi_vars['application'] = self.middleware.application if 'weberror.config' in self.environ: data[('extra', 'Configuration')] = dict(self.environ['weberror.config']) return data process_combos = { # multiprocess, multithread, run_once (0, 0, 0): 'Non-concurrent server', (0, 1, 0): 'Multithreaded', (1, 0, 0): 'Multiprocess', (1, 1, 0): 'Multi process AND threads (?)', (0, 0, 1): 'Non-concurrent CGI', (0, 1, 1): 'Multithread CGI (?)', (1, 0, 1): 'CGI', (1, 1, 1): 'Multi thread/process CGI (?)', } def handle_exception(exc_info, error_stream, html=True, debug_mode=False, error_email=None, error_log=None, show_exceptions_in_wsgi_errors=False, error_email_from='errors@localhost', smtp_server='localhost', smtp_username=None, smtp_password=None, smtp_use_tls=False, error_subject_prefix='', error_message=None, simple_html_error=False, reporters=None, ): """ For exception handling outside of a web context Use like:: import sys import paste import paste.error_middleware try: do stuff except: paste.error_middleware.exception_handler( sys.exc_info(), paste.CONFIG, sys.stderr, html=False) If you want to report, but not fully catch the exception, call ``raise`` after ``exception_handler``, which (when given no argument) will reraise the exception. """ reported = False exc_data = collector.collect_exception(*exc_info) extra_data = '' if error_email: rep = reporter.EmailReporter( to_addresses=error_email, from_address=error_email_from, smtp_server=smtp_server, smtp_username=smtp_username, smtp_password=smtp_password, smtp_use_tls=smtp_use_tls, subject_prefix=error_subject_prefix) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if reporters: for rep in reporters: rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: ## FIXME: should this be true? reported = True if error_log: rep = reporter.LogReporter( filename=error_log) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True if show_exceptions_in_wsgi_errors: rep = reporter.FileReporter( file=error_stream) rep_err = send_report(rep, exc_data, html=html) if rep_err: extra_data += rep_err else: reported = True else: error_stream.write('Error - %s: %s\n' % ( exc_data.exception_type, exc_data.exception_value)) if html: if debug_mode and simple_html_error: return_error = formatter.format_html( exc_data, include_hidden_frames=False, include_reusable=False, show_extra_data=False) reported = True elif debug_mode and not simple_html_error: error_html = formatter.format_html( exc_data, include_hidden_frames=True, include_reusable=False) head_html = '' return_error = error_template( head_html, error_html, extra_data) extra_data = '' reported = True else: msg = error_message or ''' An error occurred. See the error logs for more information. (Turn debug on to display exception reports here) ''' return_error = error_template('', msg, '') else: return_error = None if not reported and error_stream: err_report = formatter.format_text(exc_data, show_hidden_frames=True)[0] err_report += '\n' + '-'*60 + '\n' error_stream.write(err_report) if extra_data: error_stream.write(extra_data) return return_error def send_report(rep, exc_data, html=True): try: rep.report(exc_data) except: output = StringIO() traceback.print_exc(file=output) if html: return """

Additionally an error occurred while sending the %s report:

%s

""" % ( cgi.escape(str(rep)), output.getvalue()) else: return ( "Additionally an error occurred while sending the " "%s report:\n%s" % (str(rep), output.getvalue())) else: return '' def error_template(head_html, exception, extra): return ''' Server Error %s

Server Error

%s %s ''' % (head_html, exception, extra) def make_error_middleware(app, global_conf, **kw): return ErrorMiddleware(app, global_conf=global_conf, **kw) doc_lines = (ErrorMiddleware.__doc__ or '').splitlines(True) for i in range(len(doc_lines)): if doc_lines[i].strip().startswith('Settings'): make_error_middleware.__doc__ = ''.join(doc_lines[i:]) break del i, doc_lines WebError-0.10.3/weberror/eval-media/000775 000765 000024 00000000000 11466345335 017100 5ustar00benstaff000000 000000 WebError-0.10.3/weberror/eval_template.html000664 000765 000024 00000011405 11126232531 020567 0ustar00benstaff000000 000000 Server Error {{head_html|html}}

There is no source code to display. Click a 'view' link in the Traceback tab to load source code.
{{for extra_data_item in extra_data:}}

Extra Data

{{extra_data_item|html}} {{endfor}}
{{template_data|html}}

WebError Traceback:

{{exc_name}}: {{formatted_exc_value|html}}
View as:   Interactive (full)  |  Text (full)  |  XML (full)
{{traceback_body|html}}
Extra Features
>>Display the lines of code near each part of the traceback
Show a debug prompt to allow you to directly debug the code at the traceback
{{repost_button|html}}


WebError-0.10.3/weberror/evalcontext.py000664 000765 000024 00000003646 11003221406 017766 0ustar00benstaff000000 000000 from cStringIO import StringIO import traceback import threading import pdb import sys exec_lock = threading.Lock() class EvalContext(object): """ Class that represents a interactive interface. It has its own namespace. Use eval_context.exec_expr(expr) to run commands; the output of those commands is returned, as are print statements. This is essentially what doctest does, and is taken directly from doctest. """ def __init__(self, namespace, globs): self.namespace = namespace self.globs = globs def exec_expr(self, s): out = StringIO() exec_lock.acquire() save_stdout = sys.stdout try: debugger = _OutputRedirectingPdb(save_stdout) debugger.reset() pdb.set_trace = debugger.set_trace sys.stdout = out try: code = compile(s, '', "single", 0, 1) exec code in self.namespace, self.globs debugger.set_continue() except KeyboardInterrupt: raise except: traceback.print_exc(file=out) debugger.set_continue() finally: sys.stdout = save_stdout exec_lock.release() return out.getvalue() # From doctest class _OutputRedirectingPdb(pdb.Pdb): """ A specialized version of the python debugger that redirects stdout to a given stream when interacting with the user. Stdout is *not* redirected when traced code is executed. """ def __init__(self, out): self.__out = out pdb.Pdb.__init__(self) def trace_dispatch(self, *args): # Redirect stdout to the given stream. save_stdout = sys.stdout sys.stdout = self.__out # Call Pdb's trace dispatch method. try: return pdb.Pdb.trace_dispatch(self, *args) finally: sys.stdout = save_stdout WebError-0.10.3/weberror/evalexception.py000664 000765 000024 00000072613 11164461161 020314 0ustar00benstaff000000 000000 """Exception-catching middleware that allows interactive debugging. This middleware catches all unexpected exceptions. A normal traceback, like produced by ``weberror.exceptions.errormiddleware.ErrorMiddleware`` is given, plus controls to see local variables and evaluate expressions in a local context. This can only be used in single-process environments, because subsequent requests must go back to the same process that the exception originally occurred in. Threaded or non-concurrent environments both work. This shouldn't be used in production in any way. That would just be silly. If calling from an XMLHttpRequest call, if the GET variable ``_`` is given then it will make the response more compact (and less Javascripty), since if you use innerHTML it'll kill your browser. You can look for the header X-Debug-URL in your 500 responses if you want to see the full debuggable traceback. Also, this URL is printed to ``wsgi.errors``, so you can open it up in another browser window. """ import httplib import sys import os import cgi import traceback from cStringIO import StringIO import pprint import itertools import time import re import types import urllib from pkg_resources import resource_filename from paste import fileapp from paste import registry from paste import request from paste import urlparser from paste.util import import_string import evalcontext from weberror import errormiddleware, formatter, collector from weberror.util import escaping from tempita import HTMLTemplate from webob import Request, Response from webob import exc limit = 200 def html_quote(v): """ Escape HTML characters, plus translate None to '' """ if v is None: return '' return cgi.escape(str(v), 1) def preserve_whitespace(v, quote=True): """ Quote a value for HTML, preserving whitespace (translating newlines to ``
`` and multiple spaces to use `` ``). If ``quote`` is true, then the value will be HTML quoted first. """ if quote: v = html_quote(v) v = v.replace('\n', '
\n') v = re.sub(r'()( +)', _repl_nbsp, v) v = re.sub(r'(\n)( +)', _repl_nbsp, v) v = re.sub(r'^()( +)', _repl_nbsp, v) return '%s' % v def _repl_nbsp(match): if len(match.group(2)) == 1: return ' ' return match.group(1) + ' ' * (len(match.group(2))-1) + ' ' def simplecatcher(application): """ A simple middleware that catches errors and turns them into simple tracebacks. """ def simplecatcher_app(environ, start_response): try: return application(environ, start_response) except: out = StringIO() traceback.print_exc(file=out) start_response('500 Server Error', [('content-type', 'text/html')], sys.exc_info()) res = out.getvalue() return ['

Error

%s
' % html_quote(res)] return simplecatcher_app def wsgiapp(): """ Turns a function or method into a WSGI application. """ def decorator(func): def wsgiapp_wrapper(*args): # we get 3 args when this is a method, two when it is # a function :( if len(args) == 3: environ = args[1] start_response = args[2] args = [args[0]] else: environ, start_response = args args = [] def application(environ, start_response): form = request.parse_formvars(environ, include_get_vars=True) status = '200 OK' form['environ'] = environ try: res = func(*args, **form.mixed()) except ValueError, ve: status = '500 Server Error' res = 'There was an error: %s' % \ html_quote(ve) start_response(status, [('content-type', 'text/html')]) return [res] app = simplecatcher(application) return app(environ, start_response) wsgiapp_wrapper.exposed = True return wsgiapp_wrapper return decorator def get_debug_info(func): """ A decorator (meant to be used under ``wsgiapp()``) that resolves the ``debugcount`` variable to a ``DebugInfo`` object (or gives an error if it can't be found). """ def debug_info_replacement(self, req): if 'debugcount' not in req.params: return exc.HTTPBadRequest( "You must provide a debugcount parameter") debugcount = req.params['debugcount'] try: debugcount = int(debugcount) except ValueError, e: return exc.HTTPBadRequest( "Invalid value for debugcount (%r): %s" % (debugcount, e)) if debugcount not in self.debug_infos: return exc.HTTPServerError( "Debug %s not found (maybe it has expired, or the server was restarted)" % debugcount) req.debug_info = self.debug_infos[debugcount] return func(self, req) debug_info_replacement.exposed = True return debug_info_replacement debug_counter = itertools.count(int(time.time())) def get_debug_count(req): """ Return the unique debug count for the current request """ if hasattr(req, 'environ'): environ = req.environ else: environ = req # XXX: Legacy support for Paste restorer if 'paste.evalexception.debug_count' in environ: return environ['paste.evalexception.debug_count'] elif 'weberror.evalexception.debug_count' in environ: return environ['weberror.evalexception.debug_count'] else: next = debug_counter.next() environ['weberror.evalexception.debug_count'] = next environ['paste.evalexception.debug_count'] = next return next class InvalidTemplate(Exception): pass class EvalException(object): """Handles capturing an exception and turning it into an interactive exception explorer""" def __init__(self, application, global_conf=None, error_template_filename=None, xmlhttp_key=None, media_paths=None, templating_formatters=None, head_html='', footer_html='', reporters=None, libraries=None, **params): self.libraries = libraries or [] self.application = application self.debug_infos = {} self.templating_formatters = templating_formatters or [] self.head_html = HTMLTemplate(head_html) self.footer_html = HTMLTemplate(footer_html) if error_template_filename is None: error_template_filename = resource_filename( "weberror", "eval_template.html" ) if xmlhttp_key is None: if global_conf is None: xmlhttp_key = '_' else: xmlhttp_key = global_conf.get('xmlhttp_key', '_') self.xmlhttp_key = xmlhttp_key self.media_paths = media_paths or {} self.error_template = HTMLTemplate.from_filename(error_template_filename) if reporters is None: reporters = [] self.reporters = reporters def __call__(self, environ, start_response): ## FIXME: print better error message (maybe fall back on ## normal middleware, plus an error message) assert not environ['wsgi.multiprocess'], ( "The EvalException middleware is not usable in a " "multi-process environment") # XXX: Legacy support for Paste restorer environ['weberror.evalexception'] = environ['paste.evalexception'] = \ self req = Request(environ) if req.path_info_peek() == '_debug': return self.debug(req)(environ, start_response) else: return self.respond(environ, start_response) def debug(self, req): assert req.path_info_pop() == '_debug' next_part = req.path_info_pop() method = getattr(self, next_part, None) if method is None: return exc.HTTPNotFound('Nothing could be found to match %r' % next_part) if not getattr(method, 'exposed', False): return exc.HTTPForbidden('Access to %r is forbidden' % next_part) return method(req) def relay(self, req): """Relay a request to a remote machine for JS proxying""" host = req.GET['host'] conn = httplib.HTTPConnection(host) headers = req.headers # Re-assemble the query string query_str = {} for param, val in req.GET.iteritems(): if param in ['host', 'path']: continue query_str[param] = val query_str = urllib.urlencode(query_str) # Transport a GET or a POST if req.method == 'GET': conn.request("GET", '%s?%s' % (req.GET['path'], query_str), headers=headers) elif req.method == 'POST': conn.request("POST", req.GET['path'], req.body, headers=headers) # Handle the response and pull out the headers to proxy back resp = conn.getresponse() res = Response() for header, value in resp.getheaders(): if header.lower() in ['server', 'date']: continue res.headers[header] = value res.body = resp.read() return res relay.exposed=True def post_traceback(self, req): """Post the long XML traceback to the host and path provided""" debug_info = req.debug_info long_xml_er = formatter.format_xml(debug_info.exc_data, show_hidden_frames=True, show_extra_data=False, libraries=self.libraries)[0] host = req.GET['host'] headers = req.headers conn = httplib.HTTPConnection(host) headers = {'Content-Length':len(long_xml_er), 'Content-Type':'application/xml'} conn.request("POST", req.GET['path'], long_xml_er, headers=headers) resp = conn.getresponse() res = Response() for header, value in resp.getheaders(): if header.lower() in ['server', 'date']: continue res.headers[header] = value res.body = resp.read() return res post_traceback = get_debug_info(post_traceback) def media(self, req): """Static path where images and other files live""" first_part = req.path_info_peek() if first_part in self.media_paths: req.path_info_pop() path = self.media_paths[first_part] else: path = resource_filename("weberror", "eval-media") app = urlparser.StaticURLParser(path) return app media.exposed = True def summary(self, req): """ Returns a JSON-format summary of all the cached exception reports """ res = Response(content_type='text/x-json') data = []; items = self.debug_infos.values() items.sort(lambda a, b: cmp(a.created, b.created)) data = [item.json() for item in items] res.body = repr(data) return res summary.exposed = True def view(self, req): """ View old exception reports """ id = int(req.path_info_pop()) if id not in self.debug_infos: return exc.HTTPServerError( "Traceback by id %s does not exist (maybe " "the server has been restarted?)" % id) debug_info = self.debug_infos[id] return debug_info.wsgi_application view.exposed = True def make_view_url(self, environ, base_path, count): return base_path + '/view/%s' % count #@get_debug_info def show_frame(self, req): tbid = int(req.params['tbid']) frame = req.debug_info.frame(tbid) vars = frame.tb_frame.f_locals if vars: registry.restorer.restoration_begin(req.debug_info.counter) try: local_vars = make_table(vars) finally: registry.restorer.restoration_end() else: local_vars = 'No local vars' res = Response(content_type='text/html') res.body = input_form.substitute(tbid=tbid, debug_info=req.debug_info) + local_vars return res show_frame = get_debug_info(show_frame) #@get_debug_info def exec_input(self, req): input = req.params.get('input') if not input.strip(): return '' input = input.rstrip() + '\n' frame = req.debug_info.frame(int(req.params['tbid'])) vars = frame.tb_frame.f_locals glob_vars = frame.tb_frame.f_globals context = evalcontext.EvalContext(vars, glob_vars) registry.restorer.restoration_begin(req.debug_info.counter) try: output = context.exec_expr(input) finally: registry.restorer.restoration_end() input_html = formatter.str2html(input) res = Response(content_type='text/html') res.write( '>>> ' '%s
\n%s' % (preserve_whitespace(input_html, quote=False), preserve_whitespace(output))) return res exec_input = get_debug_info(exec_input) def source_code(self, req): location = req.params['location'] module_name, lineno = location.split(':', 1) module = sys.modules.get(module_name) if module is None: # Something weird indeed res = Response(content_type='text/html', charset='utf8') res.body = 'The module %s does not have an entry in sys.modules' % module_name return res filename = module.__file__ if filename[-4:] in ('.pyc', '.pyo'): filename = filename[:-1] elif filename.endswith('$py.class'): filename = '%s.py' % filename[:-9] f = open(filename, 'rb') source = f.read() f.close() html = ( ('
Module: %s file: %s
' '' % (module_name, filename, formatter.pygments_css)) + formatter.highlight(filename, source, linenos=True)) source_lines = len(source.splitlines()) if source_lines < 60: html += '\n
'*(60-source_lines) res = Response(content_type='text/html', charset='utf8') res.unicode_body = html return res source_code.exposed = True def respond(self, environ, start_response): req = Request(environ) if req.environ.get('paste.throw_errors'): return self.application(environ, start_response) base_path = req.application_url + '/_debug' req.environ['paste.throw_errors'] = True started = [] def detect_start_response(status, headers, exc_info=None): try: return start_response(status, headers, exc_info) except: raise else: started.append(True) try: __traceback_supplement__ = errormiddleware.Supplement, self, environ app_iter = self.application(environ, detect_start_response) # Don't create a list from a paste.fileapp object if isinstance(app_iter, fileapp._FileIter): return app_iter try: return_iter = list(app_iter) return return_iter finally: if hasattr(app_iter, 'close'): app_iter.close() except: exc_info = sys.exc_info() # Tell the Registry to save its StackedObjectProxies current state # for later restoration ## FIXME: needs to be more abstract (something in the environ) ## to remove the Paste dependency registry.restorer.save_registry_state(environ) count = get_debug_count(environ) view_uri = self.make_view_url(environ, base_path, count) if not started: headers = [('content-type', 'text/html')] headers.append(('X-Debug-URL', view_uri)) start_response('500 Internal Server Error', headers, exc_info) environ['wsgi.errors'].write('Debug at: %s\n' % view_uri) exc_data = collector.collect_exception(*exc_info) exc_data.view_url = view_uri if self.reporters: for reporter in self.reporters: reporter.report(exc_data) debug_info = DebugInfo(count, exc_info, exc_data, base_path, environ, view_uri, self.error_template, self.templating_formatters, self.head_html, self.footer_html, self.libraries) assert count not in self.debug_infos self.debug_infos[count] = debug_info if self.xmlhttp_key: if self.xmlhttp_key in req.params: exc_data = collector.collect_exception(*exc_info) html, extra_html = formatter.format_html( exc_data, include_hidden_frames=False, include_reusable=False, show_extra_data=False) return [html, extra_html] # @@: it would be nice to deal with bad content types here return debug_info.content() class DebugInfo(object): def __init__(self, counter, exc_info, exc_data, base_path, environ, view_uri, error_template, templating_formatters, head_html, footer_html, libraries): self.counter = counter self.exc_data = exc_data self.base_path = base_path self.environ = environ self.view_uri = view_uri self.error_template = error_template self.created = time.time() self.templating_formatters = templating_formatters self.head_html = head_html self.footer_html = footer_html self.libraries = libraries self.exc_type, self.exc_value, self.tb = exc_info __exception_formatter__ = 1 self.frames = [] n = 0 tb = self.tb while tb is not None and (limit is None or n < limit): if tb.tb_frame.f_locals.get('__exception_formatter__'): # Stop recursion. @@: should make a fake ExceptionFrame break self.frames.append(tb) tb = tb.tb_next n += 1 def json(self): """Return the JSON-able representation of this object""" return { 'uri': self.view_uri, 'created': time.strftime('%c', time.gmtime(self.created)), 'created_timestamp': self.created, 'exception_type': str(self.exc_type), 'exception': str(self.exc_value), } def frame(self, tbid): for frame in self.frames: if id(frame) == tbid: return frame else: raise ValueError, ( "No frame by id %s found from %r" % (tbid, self.frames)) def wsgi_application(self, environ, start_response): start_response('200 OK', [('content-type', 'text/html')]) return self.content() def content(self): traceback_body, extra_data = format_eval_html(self.exc_data, self.base_path, self.counter, self.libraries) repost_button = make_repost_button(self.environ) template_data = '

No Template information available.

' tab = 'traceback_data' for tmpl_formatter in self.templating_formatters: result = tmpl_formatter(self.exc_value) if result: tab = 'template_data' template_data = result break # Decode the exception value itself if needed formatted_exc_value = self.exc_data.exception_value if isinstance(formatted_exc_value, str): last_frame = self.exc_data.frames[-1] formatted_exc_value = formatted_exc_value.decode(last_frame.source_encoding, 'replace') formatted_exc_value = formatted_exc_value.encode('latin1', 'htmlentityreplace') formatted_exc_value = html_quote(formatted_exc_value) template_data = template_data.replace('

', '

') template_data = template_data.replace('

', '') if hasattr(self.exc_data.exception_type, '__name__'): exc_name = self.exc_data.exception_type.__name__ else: exc_name = str(self.exc_data.exception_type) page = self.error_template.substitute( head_html=self.head_html.substitute(prefix=self.base_path), pygments_css=formatter.pygments_css, footer_html=self.footer_html.substitute(prefix=self.base_path), repost_button=repost_button or '', traceback_body=traceback_body, exc_data=self.exc_data, exc_name=exc_name, formatted_exc_value=formatted_exc_value, extra_data=extra_data, template_data=template_data, set_tab=tab, prefix=self.base_path, counter=self.counter, ) return [page] class EvalHTMLFormatter(formatter.HTMLFormatter): def __init__(self, base_path, counter, **kw): super(EvalHTMLFormatter, self).__init__(**kw) self.base_path = base_path self.counter = counter def format_source_line(self, filename, frame): line = formatter.HTMLFormatter.format_source_line( self, filename, frame) location = '%s:%s' % (frame.modname, frame.lineno) return (line + '     ' '     ' 'view' % (frame.tbid, self.base_path, location)) def make_table(items): if hasattr(items, 'items'): items = items.items() items.sort() return table_template.substitute( html_quote=html_quote, items=items, preserve_whitespace=preserve_whitespace, make_wrappable=formatter.make_wrappable, pprint_format=pprint_format) table_template = HTMLTemplate(''' {{py:i = 0}} {{for name, value in items:}} {{py:i += 1}} {{py: value_html = html_quote(pprint_format(value, safe=True)) value_html = make_wrappable(value_html) if len(value_html) > 100: ## FIXME: This can break HTML; truncate before quoting? value_html, expand_html = value_html[:100], value_html[100:] else: expand_html = '' }} {{endfor}}
{{name}} {{preserve_whitespace(value_html, quote=False)|html}}{{if expand_html}} ... {{expand_html|html}} {{endif}}
''', name='table_template') def pprint_format(value, safe=False): out = StringIO() try: pprint.pprint(value, out) except Exception, e: if safe: out.write('Error: %s' % e) else: raise return out.getvalue() def format_eval_html(exc_data, base_path, counter, libraries): short_formatter = EvalHTMLFormatter( base_path=base_path, counter=counter, include_reusable=False) short_er, extra_data = short_formatter.format_collected_data(exc_data) short_text_er, text_extra_data = formatter.format_text(exc_data, show_extra_data=False) long_formatter = EvalHTMLFormatter( base_path=base_path, counter=counter, show_hidden_frames=True, show_extra_data=False, include_reusable=False) long_er, extra_data_none = long_formatter.format_collected_data(exc_data) long_text_er = formatter.format_text(exc_data, show_hidden_frames=True, show_extra_data=False)[0] long_xml_er = formatter.format_xml(exc_data, show_hidden_frames=True, show_extra_data=False, libraries=libraries)[0] short_xml_er = formatter.format_xml(exc_data, show_hidden_frames=False, show_extra_data=False, libraries=libraries)[0] if short_formatter.filter_frames(exc_data.frames) != \ long_formatter.filter_frames(exc_data.frames): # Only display the full traceback when it differs from the # short version long_text_er = cgi.escape(long_text_er) full_traceback_html = """
%s
""" % (long_er, len(long_text_er.splitlines()), long_text_er) else: full_traceback_html = '' short_text_er = cgi.escape(short_text_er) long_xml_leng = len(long_xml_er.splitlines()) if long_xml_leng > 50: long_xml_leng = 50 short_xml_leng = len(short_xml_er.splitlines()) if short_xml_leng > 50: short_xml_leng = 50 return """
%s
%s """ % (short_er, len(short_text_er.splitlines()), short_text_er, long_xml_leng, cgi.escape(long_xml_er), short_xml_leng, cgi.escape(short_xml_er), full_traceback_html), extra_data def make_repost_button(environ): url = request.construct_url(environ) if environ['REQUEST_METHOD'] == 'GET': return ('
' % url) else: # @@: I'd like to reconstruct this, but I can't because # the POST body is probably lost at this point, and # I can't get it back :( return None # @@: Use or lose the following code block """ fields = [] for name, value in request.parse_formvars( environ, include_get_vars=False).items(): if hasattr(value, 'filename'): # @@: Arg, we'll just submit the body, and leave out # the filename :( value = value.value fields.append( '' % (html_quote(name), html_quote(value))) return '''
%s
''' % (url, '\n'.join(fields)) """ input_form = HTMLTemplate('''

''', name='input_form') def make_eval_exception(app, global_conf, xmlhttp_key=None, reporters=None): """ Wraps the application in an interactive debugger. This debugger is a major security hole, and should only be used during development. xmlhttp_key is a string that, if present in QUERY_STRING, indicates that the request is an XMLHttp request, and the Javascript/interactive debugger should not be returned. (If you try to put the debugger somewhere with innerHTML, you will often crash the browser) """ if xmlhttp_key is None: xmlhttp_key = global_conf.get('xmlhttp_key', '_') if reporters is None: reporters = global_conf.get('error_reporters') if reporters and isinstance(reporters, basestring): reporter_strings = reporters.split() reporters = [] for reporter_string in reporter_strings: reporter = import_string.eval_import(reporter_string) if isinstance(reporter, (type, types.ClassType)): reporter = reporter() reporters.append(reporter) return EvalException(app, xmlhttp_key=xmlhttp_key, reporters=reporters) def make_general_exception(app, global_conf, interactive=False, **kw): """ Creates an error-catching middleware. If `interactive` is true then it will be the interactive exception catcher, otherwise it will be the static exception catcher. """ from paste.deploy.converters import asbool interactive = asbool(interactive) if interactive: return make_eval_exception(app, global_conf, **kw) else: from weberror.errormiddleware import make_error_middleware return make_error_middleware(app, global_conf, **kw) WebError-0.10.3/weberror/exceptions/000775 000765 000024 00000000000 11466345335 017255 5ustar00benstaff000000 000000 WebError-0.10.3/weberror/formatter.py000664 000765 000024 00000065151 11335430006 017442 0ustar00benstaff000000 000000 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org) # Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php """ Formatters for the exception data that comes from ExceptionCollector. """ # @@: TODO: # Use this: http://www.zope.org/Members/tino/VisualTraceback/VisualTracebackNews import cgi import re import sys from weberror.util import escaping from xml.dom.minidom import getDOMImplementation from pygments import highlight as pygments_highlight from pygments.lexers import ClassNotFound, PythonLexer, TextLexer, \ get_lexer_for_filename from pygments.formatters import HtmlFormatter try: import pkg_resources except ImportError: pkg_resources = None def html_quote(s): return cgi.escape(str(s), True) pygments_css = HtmlFormatter().get_style_defs('.highlight') def highlight(filename, code, linenos=False, lineanchors=None, cssclass='highlight'): if lineanchors is None and linenos: lineanchors = 'code' lexer = None if filename: if filename.endswith('.py'): # XXX: Pygments gives back NumPyLexer for some reason, which # we don't need lexer = PythonLexer() else: try: lexer = get_lexer_for_filename(filename) except ClassNotFound: pass if not lexer: lexer = TextLexer() formatter = HtmlFormatter(linenos=linenos, lineanchors=lineanchors, cssclass=cssclass) return pygments_highlight(code, lexer, formatter) class AbstractFormatter(object): general_data_order = ['object', 'source_url'] def __init__(self, show_hidden_frames=False, include_reusable=True, show_extra_data=True, trim_source_paths=(), **kwargs): self.show_hidden_frames = show_hidden_frames self.trim_source_paths = trim_source_paths self.include_reusable = include_reusable self.show_extra_data = show_extra_data self.extra_kwargs = kwargs def format_collected_data(self, exc_data): general_data = {} if self.show_extra_data: for name, value_list in exc_data.extra_data.items(): if isinstance(name, tuple): importance, title = name else: importance, title = 'normal', name for value in value_list: general_data[(importance, name)] = self.format_extra_data( importance, title, value) lines = [] frames = self.filter_frames(exc_data.frames) for frame in frames: self.frame = frame res = self.format_frame_start(frame) if res: lines.append(res) sup = frame.supplement if sup: if sup.object: general_data[('important', 'object')] = self.format_sup_object( sup.object) if sup.source_url: general_data[('important', 'source_url')] = self.format_sup_url( sup.source_url) if sup.line: lines.append(self.format_sup_line_pos(sup.line, sup.column)) if sup.expression: lines.append(self.format_sup_expression(sup.expression)) if sup.warnings: for warning in sup.warnings: lines.append(self.format_sup_warning(warning)) if sup.info: lines.extend(self.format_sup_info(sup.info)) if frame.supplement_exception: lines.append('Exception in supplement:') lines.append(self.quote_long(frame.supplement_exception)) if frame.traceback_info: lines.append(self.format_traceback_info(frame.traceback_info)) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break lines.append(self.format_source_line(filename or '?', frame)) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: lines.append(self.format_long_source(filename, source, long_source)) res = self.format_frame_end(frame) if res: lines.append(res) etype = exc_data.exception_type if not isinstance(etype, basestring): etype = etype.__name__ exc_info = self.format_exception_info( etype, exc_data.exception_value) data_by_importance = {'important': [], 'normal': [], 'supplemental': [], 'extra': []} for (importance, name), value in general_data.items(): data_by_importance[importance].append( (name, value)) for value in data_by_importance.values(): value.sort() return self.format_combine(data_by_importance, lines, exc_info) def filter_frames(self, frames): """ Removes any frames that should be hidden, according to the values of traceback_hide, self.show_hidden_frames, and the hidden status of the final frame. """ if self.show_hidden_frames: return frames new_frames = [] hidden = False for frame in frames: hide = frame.traceback_hide # @@: It would be nice to signal a warning if an unknown # hide string was used, but I'm not sure where to put # that warning. if hide == 'before': new_frames = [] hidden = False elif hide == 'before_and_this': new_frames = [] hidden = False continue elif hide == 'reset': hidden = False elif hide == 'reset_and_this': hidden = False continue elif hide == 'after': hidden = True elif hide == 'after_and_this': hidden = True continue elif hide: continue elif hidden: continue new_frames.append(frame) if frames[-1] not in new_frames: # We must include the last frame; that we don't indicates # that the error happened where something was "hidden", # so we just have to show everything return frames return new_frames def format_frame_start(self, frame): """ Called before each frame starts; may return None to output no text. """ return None def format_frame_end(self, frame): """ Called after each frame ends; may return None to output no text. """ return None def pretty_string_repr(self, s): """ Formats the string as a triple-quoted string when it contains newlines. """ if '\n' in s: s = repr(s) s = s[0]*3 + s[1:-1] + s[-1]*3 s = s.replace('\\n', '\n') return s else: return repr(s) def long_item_list(self, lst): """ Returns true if the list contains items that are long, and should be more nicely formatted. """ how_many = 0 for item in lst: if len(repr(item)) > 40: how_many += 1 if how_many >= 3: return True return False class TextFormatter(AbstractFormatter): def quote(self, s): if isinstance(s, str) and hasattr(self, 'frame'): s = s.decode(self.frame.source_encoding, 'replace') return s.encode('latin1', 'htmlentityreplace') def quote_long(self, s): return self.quote(s) def emphasize(self, s): return s def format_sup_object(self, obj): return 'In object: %s' % self.emphasize(self.quote(repr(obj))) def format_sup_url(self, url): return 'URL: %s' % self.quote(url) def format_sup_line_pos(self, line, column): if column: return self.emphasize('Line %i, Column %i' % (line, column)) else: return self.emphasize('Line %i' % line) def format_sup_expression(self, expr): return self.emphasize('In expression: %s' % self.quote(expr)) def format_sup_warning(self, warning): return 'Warning: %s' % self.quote(warning) def format_sup_info(self, info): return [self.quote_long(info)] def format_source_line(self, filename, frame): return 'File %r, line %s in %s' % ( filename, frame.lineno or '?', frame.name or '?') def format_long_source(self, filename, source, long_source): return self.format_source(filename, source) def format_source(self, filename, source_line): return ' ' + self.quote(source_line.strip()) def format_exception_info(self, etype, evalue): return self.emphasize( '%s: %s' % (self.quote(etype), self.quote(evalue))) def format_traceback_info(self, info): return info def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental', 'extra': lines.extend([value for n, value in data_by_importance[name]]) return self.format_combine_lines(lines), '' def format_combine_lines(self, lines): return '\n'.join([convert_to_str(line) for line in lines]) def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:\n%s' % (title, s) else: return '%s: %s' % (title, s) elif isinstance(value, dict): lines = ['\n', title, '-'*len(title)] items = value.items() items.sort() for n, v in items: try: v = repr(v) except Exception, e: v = 'Cannot display: %s' % e v = truncate(v) lines.append(' %s: %s' % (n, v)) return '\n'.join(lines) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): parts = [truncate(repr(v)) for v in value] return '%s: [\n %s]' % ( title, ',\n '.join(parts)) else: return '%s: %s' % (title, truncate(repr(value))) class HTMLFormatter(TextFormatter): def quote(self, s): if isinstance(s, str) and hasattr(self, 'frame'): s = s.decode(self.frame.source_encoding, 'replace') s = s.encode('latin1', 'htmlentityreplace') return html_quote(s) def quote_long(self, s): return '
%s
' % self.quote(s) def emphasize(self, s): return '%s' % s def format_sup_url(self, url): return 'URL: %s' % (url, url) def format_combine_lines(self, lines): ## FIXME: this is horrible: new_lines = [] for line in lines: if not line.startswith(''): line += '
' new_lines.append(convert_to_str(line)) return '\n'.join(new_lines) def format_source_line(self, filename, frame): self.frame = frame name = self.quote(frame.name or '?') return 'Module %s:%s in %s' % ( filename, frame.modname or '?', frame.lineno or '?', name) def format_long_source(self, filename, source, long_source): q_long_source = str2html(long_source, False, 4, True, getattr(self, 'frame', None), filename=filename) q_source = str2html(source, True, 0, False, getattr(self, 'frame', None), filename=filename) return ('' '' % (q_long_source, q_source)) def format_source(self, filename, source_line): return '  %s' % self.quote(source_line.strip()) def format_traceback_info(self, info): return '
%s
' % self.quote(info) def format_frame_start(self, frame): ## FIXME: make it zebra? return '
' def format_frame_end(self, frame): return '
' def format_extra_data(self, importance, title, value): if isinstance(value, str): s = self.pretty_string_repr(value) if '\n' in s: return '%s:
%s
' % (title, self.quote(s)) else: return '%s: %s' % (title, self.quote(s)) elif isinstance(value, dict): return self.zebra_table(title, value) elif (isinstance(value, (list, tuple)) and self.long_item_list(value)): return '%s: [
\n    %s]
' % ( title, ',
    '.join(map(self.quote, map(repr, value)))) else: return '%s: %s' % (title, self.quote(repr(value))) def format_combine(self, data_by_importance, lines, exc_info): lines[:0] = [value for n, value in data_by_importance['important']] lines.append(exc_info) for name in 'normal', 'supplemental': lines.extend([value for n, value in data_by_importance[name]]) extra_data = [] if data_by_importance['extra']: extra_data.extend([value for n, value in data_by_importance['extra']]) text = self.format_combine_lines(lines) ## FIXME: something about this is wrong: if self.include_reusable: return text, extra_data else: # Usually because another error is already on this page, # and so the js & CSS are unneeded return text, extra_data def zebra_table(self, title, rows, table_class="variables"): if isinstance(rows, dict): rows = rows.items() rows.sort() table = ['' % table_class, '' % self.quote(title)] odd = False for name, value in rows: try: value = repr(value) except Exception, e: value = 'Cannot print: %s' % e odd = not odd table.append( '' % (odd and 'odd' or 'even', self.quote(name))) table.append( '' % make_wrappable(self.quote(truncate(value)))) table.append('
%s
%s%s
') return '\n'.join(table) def get_dependencies(circ_check, lib, working_set): libs = {} for proj in working_set.by_key[lib].requires(): if proj.key in circ_check: continue circ_check[proj.key] = True libs[proj.key] = working_set.by_key[proj.key].version libs.update(get_dependencies(circ_check, proj.key, working_set)) return libs def get_libraries(libs=None): """Return a dict of the desired libraries and their version if active in the environment""" if pkg_resources and libs: libraries = {} working_set = pkg_resources.working_set for lib in libs: # Put libs we've either check dependencies on, or are in progress # of checking here, to avoid circular references going forever circ_check = {} if lib in working_set.by_key: if lib in circ_check: continue circ_check[lib] = True libraries[lib] = working_set.by_key[lib].version libraries.update( get_dependencies(circ_check, lib, working_set)) return libraries else: return {} def create_text_node(doc, elem, text): if not isinstance(text, basestring): try: text = escaping.removeIllegalChars(repr(text)) except: text = 'UNABLE TO GET TEXT REPRESENTATION' new_elem = doc.createElement(elem) new_elem.appendChild(doc.createTextNode(text)) return new_elem class XMLFormatter(AbstractFormatter): def format_collected_data(self, exc_data): impl = getDOMImplementation() newdoc = impl.createDocument(None, "traceback", None) top_element = newdoc.documentElement sysinfo = newdoc.createElement('sysinfo') language = create_text_node(newdoc, 'language', 'Python') language.attributes['version'] = sys.version.split(' ')[0] language.attributes['full_version'] = sys.version language.attributes['platform'] = sys.platform sysinfo.appendChild(language) # Pull out pkg_resource libraries for set libraries libs = get_libraries(self.extra_kwargs.get('libraries')) if libs: libraries = newdoc.createElement('libraries') for k, v in libs.iteritems(): lib = newdoc.createElement('library') lib.attributes['version'] = v lib.attributes['name'] = k libraries.appendChild(lib) sysinfo.appendChild(libraries) top_element.appendChild(sysinfo) frames = self.filter_frames(exc_data.frames) stack = newdoc.createElement('stack') top_element.appendChild(stack) for frame in frames: xml_frame = newdoc.createElement('frame') stack.appendChild(xml_frame) filename = frame.filename if filename and self.trim_source_paths: for path, repl in self.trim_source_paths: if filename.startswith(path): filename = repl + filename[len(path):] break self.format_source_line(filename or '?', frame, newdoc, xml_frame) source = frame.get_source_line() long_source = frame.get_source_line(2) if source: self.format_long_source(filename, source.decode(frame.source_encoding, 'replace'), long_source.decode(frame.source_encoding, 'replace'), newdoc, xml_frame) # @@@ TODO: Put in a way to optionally toggle including variables # variables = newdoc.createElement('variables') # xml_frame.appendChild(variables) # for name, value in frame.locals.iteritems(): # if isinstance(value, unicode): # value = value.encode('ascii', 'xmlcharrefreplace') # variable = newdoc.createElement('variable') # variable.appendChild(create_text_node(newdoc, 'name', name)) # variable.appendChild(create_text_node(newdoc, 'value', value)) # variables.appendChild(variable) etype = exc_data.exception_type if not isinstance(etype, basestring): etype = etype.__name__ top_element.appendChild(self.format_exception_info( etype, exc_data.exception_value, newdoc, frame)) return newdoc.toxml(), '' def format_source_line(self, filename, frame, newdoc, xml_frame): name = frame.name or '?' xml_frame.appendChild(create_text_node(newdoc, 'module', frame.modname or '?')) xml_frame.appendChild(create_text_node(newdoc, 'filename', filename)) xml_frame.appendChild(create_text_node(newdoc, 'line', str(frame.lineno) or '?')) xml_frame.appendChild(create_text_node(newdoc, 'function', name)) def format_long_source(self, filename, source, long_source, newdoc, xml_frame): source = source.encode('ascii', 'xmlcharrefreplace') long_source = long_source.encode('ascii', 'xmlcharrefreplace') xml_frame.appendChild(create_text_node(newdoc, 'operation', source.strip())) xml_frame.appendChild(create_text_node(newdoc, 'operation_context', long_source)) def format_exception_info(self, etype, evalue, newdoc, frame): exception = newdoc.createElement('exception') evalue = evalue.decode( frame.source_encoding, 'replace').encode('ascii', 'xmlcharrefreplace') exception.appendChild(create_text_node(newdoc, 'type', etype)) exception.appendChild(create_text_node(newdoc, 'value', evalue)) return exception def format_html(exc_data, include_hidden_frames=False, **ops): if not include_hidden_frames: return HTMLFormatter(**ops).format_collected_data(exc_data) short_er = None if not include_hidden_frames: short_er, head_html = format_html(exc_data, show_hidden_frames=False, **ops) ops['include_reusable'] = False ops['show_extra_data'] = False long_er, head_html = format_html(exc_data, show_hidden_frames=True, **ops) if not include_hidden_frames and short_er == long_er: # Suppress the short error if it is identical to the long one short_er = None text_er, head_text = format_text(exc_data, show_hidden_frames=True, **ops) xml_er, head_xml = format_xml(exc_data, show_hidden_frames=True, **ops) if short_er: short_er = '
%s
\n' % short_er return """ %s %s
%s
""" % ('\n'.join(head_html), short_er or '', long_er, cgi.escape(text_er), cgi.escape(xml_er)) def format_text(exc_data, **ops): return TextFormatter(**ops).format_collected_data(exc_data) def format_xml(exc_data, **ops): return XMLFormatter(**ops).format_collected_data(exc_data) whitespace_re = re.compile(r' +') pre_re = re.compile(r'') error_re = re.compile(r'

ERROR: .*?

') def str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None): """ Convert a string to HTML. Try to be really safe about it, returning a quoted version of the string if nothing else works. """ try: return _str2html(src, strip=strip, indent_subsequent=indent_subsequent, highlight_inner=highlight_inner, frame=frame, filename=filename) except: if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') return src return html_quote(src) def _str2html(src, strip=False, indent_subsequent=0, highlight_inner=False, frame=None, filename=None): if strip: src = src.strip() orig_src = src try: src = highlight(filename, src) src = error_re.sub('', src) src = pre_re.sub('', src) src = re.sub(r'^[\n\r]{0,1}', '', src) src = re.sub(r'[\n\r]{0,1}$', '', src) # This gets rid of the
that Pygments adds: if src.strip().startswith('
') and \ src.strip().endswith('
'): src = src.strip()[len('
'):-len('
')] if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') except: if isinstance(src, str) and frame: src = src.decode(frame.source_encoding, 'replace') src = src.encode('latin1', 'htmlentityreplace') else: src = html_quote(orig_src) lines = src.splitlines() if len(lines) == 1: return lines[0] # XXX: Lame variable width font, I think, requires +3 padding indent_subsequent += 3 indent = ' '*indent_subsequent for i in range(1, len(lines)): lines[i] = indent+lines[i] if highlight_inner and i == len(lines)/2: lines[i] = '%s' % lines[i] src = '
\n'.join(lines) src = whitespace_re.sub( lambda m: ' '*(len(m.group(0))-1) + ' ', src) return src def truncate(string, limit=1000): """ Truncate the string to the limit number of characters """ if len(string) > limit: return string[:limit-20]+'...'+string[-17:] else: return string def make_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): # Currently using , maybe should use ​ # http://www.cs.tut.fi/~jkorpela/html/nobr.html if len(html) <= wrap_limit: return html words = html.split() new_words = [] for word in words: wrapped_word = '' while len(word) > wrap_limit: for char in split_on: if char in word: first, rest = word.split(char, 1) wrapped_word += first+char+'' word = rest break else: for i in range(0, len(word), wrap_limit): wrapped_word += word[i:i+wrap_limit]+'' word = '' wrapped_word += word new_words.append(wrapped_word) return ' '.join(new_words) def make_pre_wrappable(html, wrap_limit=60, split_on=';?&@!$#-/\\"\''): """ Like ``make_wrappable()`` but intended for text that will go in a ``
`` block, so wrap on a line-by-line basis.
    """
    lines = html.splitlines()
    new_lines = []
    for line in lines:
        if len(line) > wrap_limit:
            for char in split_on:
                if char in line:
                    parts = line.split(char)
                    line = ''.join(parts)
                    break
        new_lines.append(line)
    return '\n'.join(lines)

def convert_to_str(s):
    if isinstance(s, unicode):
        return s.encode('utf8')
    return s
WebError-0.10.3/weberror/pdbcapture.py000664 000765 000024 00000011616 11466344257 017606 0ustar00benstaff000000 000000 from webob import Request, Response
import threading
from paste.util import threadedprint
from itertools import count
import tempita
from paste.urlparser import StaticURLParser
from paste.util.filemixin import FileMixin
import os
import sys

try:
    import json
except ImportError: # pragma: no cover
    import simplejson as json

here = os.path.dirname(os.path.abspath(__file__))

#def debug(msg, *args):
#    args = '%s %s' % (msg, ' '.join(map(repr, args)))
#    print >> sys.stderr, args

class PdbCapture(object):

    def __init__(self, app):
        self.app = app
        threadedprint.install(leave_stdout=True)
        threadedprint.install_stdin()
        self.counter = count()
        self.static_app = StaticURLParser(os.path.join(here, 'pdbcapture/static'))
        self.media_app = StaticURLParser(os.path.join(here, 'eval-media'))
        self.states = {}

    def get_template(self, template_name):
        filename = os.path.join(os.path.dirname(__file__), template_name)
        return tempita.HTMLTemplate.from_filename(filename)
        
    def __call__(self, environ, start_response):
        req = Request(environ)
        if req.GET.get('__pdbid__'):
            id = int(req.GET['__pdbid__'])
            response = self.states[id]['response']
            return response(environ, start_response)
        if req.path_info_peek() == '.pdbcapture':
            req.path_info_pop()
            if req.path_info_peek() == 'static':
                req.path_info_pop()
                return self.static_app(environ, start_response)
            if req.path_info_peek() == 'media':
                req.path_info_pop()
                return self.media_app(environ, start_response)
            resp = self.internal_request(req)
            return resp(environ, start_response)
        id = self.counter.next()
        state = dict(id=id,
                     event=threading.Event(),
                     base_url=req.application_url,
                     stdout=[],
                     stdin=[],
                     stdin_event=threading.Event())
        t = threading.Thread(target=self.call_app, args=(req, state))
        t.setDaemon(True)
        t.start()
        state['event'].wait()
        if 'response' in state:
            # Normal request, nothing happened
            resp = state['response']
            return resp(environ, start_response)
        if 'exc_info' in state:
            raise state['exc_info'][0], state['exc_info'][1], state['exc_info'][2]
        self.states[id] = state
        tmpl = self.get_template('pdbcapture_response.html')
        body = tmpl.substitute(req=req, state=state, id=id)
        resp = Response(body)
        return resp(environ, start_response)

    def internal_request(self, req):
        id = int(req.params['id'])
        state = self.states[id]
        if 'response' in state:
            body = {'response': 1}
        else:
            if req.params.get('stdin'):
                state['stdin'].append(req.params['stdin'])
                state['stdin_event'].set()
            stdout = ''.join(state['stdout'])
            state['stdout'][:] = []
            body = {'stdout': stdout}
        if not state['stdin_event'].isSet():
            body['stdinPending'] = 1
        resp = Response(content_type='application/json',
                        body=json.dumps(body))
        return resp

    def call_app(self, req, state):
        event = state['event']
        stream_handler = StreamHandler(stdin=state['stdin'], stdin_event=state['stdin_event'], stdout=state['stdout'],
                                       signal_event=state['event'])
        threadedprint.register(stream_handler)
        threadedprint.register_stdin(stream_handler)
        try:
            resp = req.get_response(self.app)
            state['response'] = resp
        except:
            state['exc_info'] = sys.exc_info()
        event.set()

class StreamHandler(FileMixin):

    def __init__(self, stdin, stdout, stdin_event, signal_event):
        self.stdin = stdin
        self.stdout = stdout
        self.stdin_event = stdin_event
        self.signal_event = signal_event

    def write(self, text):
        self.stdout.append(text)

    def read(self, size=None):
        self.signal_event.set()
        text = ''.join(self.stdin)
        if size is None or size == -1:
            self.stdin[:] = []
            sys.stdout.write(text)
            return text
        while len(text) < size:
            self.stdin_event.clear()
            self.stdin_event.wait()
            text = ''.join(self.stdin)
        pending = text[:size]
        self.stdin[:] = [text[size:]]
        sys.stdout.write(pending)
        return pending

def test_app(environ, start_response):
    import pdb
    message = "Hey, what's up?"
    pdb.set_trace()
    start_response('200 OK', [('Content-type', 'text/plain')])
    return [message]

if __name__ == '__main__':
    from paste import httpserver
    httpserver.serve(PdbCapture(test_app))
    
WebError-0.10.3/weberror/reporter.py000664 000765 000024 00000011531 11335430006 017272 0ustar00benstaff000000 000000 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

from email.MIMEText import MIMEText
from email.MIMEMultipart import MIMEMultipart
import smtplib
import time
from weberror import formatter

class Reporter(object):

    def __init__(self, **conf):
        for name, value in conf.items():
            if not hasattr(self, name):
                raise TypeError(
                    "The keyword argument %s was not expected"
                    % name)
            setattr(self, name, value)
        self.check_params()

    def check_params(self):
        pass

    def format_date(self, exc_data):
        return time.strftime('%c', exc_data.date)

    def format_html(self, exc_data, **kw):
        return formatter.format_html(exc_data, **kw)

    def format_text(self, exc_data, **kw):
        return formatter.format_text(exc_data, **kw)

class EmailReporter(Reporter):

    to_addresses = None
    from_address = None
    smtp_server = 'localhost'
    smtp_username = None
    smtp_password = None
    smtp_use_tls = False
    subject_prefix = ''

    def report(self, exc_data):
        msg = self.assemble_email(exc_data)
        server = smtplib.SMTP(self.smtp_server)
        if self.smtp_use_tls:
            server.ehlo()
            server.starttls()
            server.ehlo()
        if self.smtp_username and self.smtp_password:
            server.login(self.smtp_username, self.smtp_password)
        ## FIXME: this should check the return value from this function:
        result = server.sendmail(self.from_address,
                        self.to_addresses, msg.as_string())
        try:
            server.quit()
        except sslerror:
            # sslerror is raised in tls connections on closing sometimes
            pass

    def check_params(self):
        if not self.to_addresses:
            raise ValueError("You must set to_addresses")
        if not self.from_address:
            raise ValueError("You must set from_address")
        if isinstance(self.to_addresses, (str, unicode)):
            self.to_addresses = [self.to_addresses]

    def assemble_email(self, exc_data):
        short_html_version, short_extra = self.format_html(
            exc_data, show_hidden_frames=False, show_extra_data=True)
        long_html_version, long_extra = self.format_html(
            exc_data, show_hidden_frames=True, show_extra_data=True)
        text_version = self.format_text(
            exc_data, show_hidden_frames=True, show_extra_data=True)[0]
        msg = MIMEMultipart()
        msg.set_type('multipart/alternative')
        msg.preamble = msg.epilogue = ''
        text_msg = MIMEText(as_str(text_version))
        text_msg.set_type('text/plain')
        text_msg.set_param('charset', 'UTF-8')
        msg.attach(text_msg)
        html_msg = MIMEText(as_str(short_html_version) + as_str(''.join(short_extra)))
        html_msg.set_type('text/html')
        html_msg.set_param('charset', 'UTF-8')
        html_long = MIMEText(as_str(long_html_version) + as_str(''.join(long_extra)))
        html_long.set_type('text/html')
        html_long.set_param('charset', 'UTF-8')
        msg.attach(html_msg)
        msg.attach(html_long)
        subject = as_str('%s: %s' % (exc_data.exception_type,
                                     formatter.truncate(str(exc_data.exception_value))))
        msg['Subject'] = as_str(self.subject_prefix) + subject
        msg['From'] = as_str(self.from_address)
        msg['To'] = as_str(', '.join(self.to_addresses))
        return msg

class LogReporter(Reporter):

    filename = None
    show_hidden_frames = True

    def check_params(self):
        assert self.filename is not None, (
            "You must give a filename")

    def report(self, exc_data):
        text, head_text = self.format_text(
            exc_data, show_hidden_frames=self.show_hidden_frames)
        f = open(self.filename, 'a')
        try:
            f.write(text + '\n' + '-'*60 + '\n')
        finally:
            f.close()

class FileReporter(Reporter):

    file = None
    show_hidden_frames = True

    def check_params(self):
        assert self.file is not None, (
            "You must give a file object")

    def report(self, exc_data):
        text = self.format_text(
            exc_data, show_hidden_frames=self.show_hidden_frames)
        self.file.write(text + '\n' + '-'*60 + '\n')

class WSGIAppReporter(Reporter):

    def __init__(self, exc_data):
        self.exc_data = exc_data

    def __call__(self, environ, start_response):
        start_response('500 Server Error', [('Content-type', 'text/html')])
        return [formatter.format_html(self.exc_data)]

def as_str(v):
    if isinstance(v, str):
        return v
    if not isinstance(v, unicode):
        v = unicode(v)
    if isinstance(v, unicode):
        v = v.encode('utf8')
    return v
WebError-0.10.3/weberror/util/000775 000765 000024 00000000000 11466345335 016051 5ustar00benstaff000000 000000 WebError-0.10.3/weberror/util/__init__.py000600 000765 000024 00000000000 10723213331 020117 0ustar00benstaff000000 000000 WebError-0.10.3/weberror/util/errorapp.py000644 000765 000024 00000000462 10727022360 020242 0ustar00benstaff000000 000000 """
This simple application creates errors
"""

def error_app(environ, start_response):
    environ['errorapp.item'] = 1
    raise_error()

def raise_error():
    if 1 == 1:
        raise Exception('This is an exception')
    else:
        do_stuff()

def make_error_app(global_conf):
    return error_app
WebError-0.10.3/weberror/util/escaping.py000664 000765 000024 00000017123 11016722455 020211 0ustar00benstaff000000 000000 # filters.py
# Copyright (C) 2006, 2007, 2008 Geoffrey T. Dairiki  
# and Michael Bayer  and Ben Bangert 
#
# This module heavily based on the one from Mako and is released under
# the MIT License: http://www.opensource.org/licenses/mit-license.php


import re, cgi, urllib, htmlentitydefs, codecs
from StringIO import StringIO

xml_escapes = {
    '&' : '&',
    '>' : '>',
    '<' : '<',
    '"' : '"',   # also " in html-only
    "'" : '''    # also ' in html-only   
}
# XXX: " is valid in HTML and XML
#      ' is not valid HTML, but is valid XML

def html_escape(string):
    return cgi.escape(string, True)

def xml_escape(string):
    return re.sub(r'([&<"\'>])', lambda m: xml_escapes[m.group()], string)

def url_escape(string):
    # convert into a list of octets
    string = string.encode("utf8")
    return urllib.quote_plus(string)

def url_unescape(string):
    text = urllib.unquote_plus(string)
    if not is_ascii_str(text):
        text = text.decode("utf8")
    return text

def trim(string):
    return string.strip()


class Decode(object):
    def __getattr__(self, key):
        def decode(x):
            if isinstance(x, unicode):
                return x
            elif not isinstance(x, str):
                return unicode(str(x), encoding=key)
            else:
                return unicode(x, encoding=key)
        return decode
decode = Decode()
       
           
_ASCII_re = re.compile(r'\A[\x00-\x7f]*\Z')

def is_ascii_str(text):
    return isinstance(text, str) and _ASCII_re.match(text)

################################################################   

class XMLEntityEscaper(object):
    def __init__(self, codepoint2name, name2codepoint):
        self.codepoint2entity = dict([(c, u'&%s;' % n)
                                      for c,n in codepoint2name.iteritems()])
        self.name2codepoint = name2codepoint

    def escape_entities(self, text):
        """Replace characters with their character entity references.

        Only characters corresponding to a named entity are replaced.
        """
        return unicode(text).translate(self.codepoint2entity)

    def __escape(self, m):
        codepoint = ord(m.group())
        try:
            return self.codepoint2entity[codepoint]
        except (KeyError, IndexError):
            return '&#x%X;' % codepoint


    __escapable = re.compile(r'["&<>]|[^\x00-\x7f]')

    def escape(self, text):
        """Replace characters with their character references.

        Replace characters by their named entity references.
        Non-ASCII characters, if they do not have a named entity reference,
        are replaced by numerical character references.

        The return value is guaranteed to be ASCII.
        """
        return self.__escapable.sub(self.__escape, unicode(text)
                                    ).encode('ascii')

    # XXX: This regexp will not match all valid XML entity names__.
    # (It punts on details involving involving CombiningChars and Extenders.)
    #
    # .. __: http://www.w3.org/TR/2000/REC-xml-20001006#NT-EntityRef
    __characterrefs = re.compile(r'''& (?:
                                          \#(\d+)
                                          | \#x([\da-f]+)
                                          | ( (?!\d) [:\w] [-.:\w]+ )
                                          ) ;''',
                                 re.X | re.UNICODE)
   
    def __unescape(self, m):
        dval, hval, name = m.groups()
        if dval:
            codepoint = int(dval)
        elif hval:
            codepoint = int(hval, 16)
        else:
            codepoint = self.name2codepoint.get(name, 0xfffd)
            # U+FFFD = "REPLACEMENT CHARACTER"
        if codepoint < 128:
            return chr(codepoint)
        return unichr(codepoint)
   
    def unescape(self, text):
        """Unescape character references.

        All character references (both entity references and numerical
        character references) are unescaped.
        """
        return self.__characterrefs.sub(self.__unescape, text)


_html_entities_escaper = XMLEntityEscaper(htmlentitydefs.codepoint2name,
                                          htmlentitydefs.name2codepoint)

html_entities_escape = _html_entities_escaper.escape_entities
html_entities_unescape = _html_entities_escaper.unescape


def htmlentityreplace_errors(ex):
    """An encoding error handler.

    This python `codecs`_ error handler replaces unencodable
    characters with HTML entities, or, if no HTML entity exists for
    the character, XML character references.

    >>> u'The cost was \u20ac12.'.encode('latin1', 'htmlentityreplace')
    'The cost was €12.'
    """
    if isinstance(ex, UnicodeEncodeError):
        # Handle encoding errors
        bad_text = ex.object[ex.start:ex.end]
        text = _html_entities_escaper.escape(bad_text)
        return (unicode(text), ex.end)
    raise ex

codecs.register_error('htmlentityreplace', htmlentityreplace_errors)


# TODO: options to make this dynamic per-compilation will be added in a later release
DEFAULT_ESCAPES = {
    'x':'filters.xml_escape',
    'h':'filters.html_escape',
    'u':'filters.url_escape',
    'trim':'filters.trim',
    'entity':'filters.html_entities_escape',
    'unicode':'unicode',
    'decode':'decode',
    'str':'str',
    'n':'n'
}

# regexps used by _translateCdata(),
# made global to compile once.
# see http://www.xml.com/axml/target.html#dt-character
ILLEGAL_LOW_CHARS = '[\x01-\x08\x0B-\x0C\x0E-\x1F]'
ILLEGAL_HIGH_CHARS = '\xEF\xBF[\xBE\xBF]'
# Note: Prolly fuzzy on this, but it looks as if characters from the
# surrogate block are allowed if in scalar form, which is encoded in UTF8 the
# same was as in surrogate block form
XML_ILLEGAL_CHAR_PATTERN = re.compile(
    '%s|%s' % (ILLEGAL_LOW_CHARS, ILLEGAL_HIGH_CHARS))
# the characters that we will want to turn into entrefs
# We must do so for &, <,  and > following ]].
# The xml parser has more leeway, but we're not the parser.
# http://www.xml.com/axml/target.html#dt-chardata
# characters that we must *always* turn to entrefs:
g_cdataCharPatternReq = re.compile('[&<]|]]>')
g_charToEntityReq = {
    '&': '&',
    '<': '<',
    ']]>': ']]>',
    }
# characters that we must turn to entrefs in attr values:
g_cdataCharPattern = re.compile('[&<>"\']|]]>')
g_charToEntity = {
    '&': '&',
    '<': '<',
    '>': '>',
    '"': '"',
    "'": ''',
    ']]>': ']]>',
    }

def removeIllegalChars(characters):
    if XML_ILLEGAL_CHAR_PATTERN.search(characters):
        characters = XML_ILLEGAL_CHAR_PATTERN.subn(
            lambda m: '&#%i;' % ord(m.group()),
            characters)[0]
    return characters

def translateCdata(characters, allEntRefs = None):
    """Translate characters into a legal format."""
    if not characters:
        return ''
    if allEntRefs: # translate all chars to entrefs; for attr value
        if g_cdataCharPattern.search(characters):
            new_string = g_cdataCharPattern.subn(
                lambda m, d=g_charToEntity: d[m.group()],
                characters)[0]
        else:
            new_string = characters
    else: # translate only required chars to entrefs
        if g_cdataCharPatternReq.search(characters):
            new_string = g_cdataCharPatternReq.subn(
                lambda m, d=g_charToEntityReq: d[m.group()],
                characters)[0]
        else:
            new_string = characters
    if XML_ILLEGAL_CHAR_PATTERN.search(new_string):
        new_string = XML_ILLEGAL_CHAR_PATTERN.subn(
            lambda m: '&#%i;' % ord(m.group()),
            new_string)[0]
    return new_string
WebError-0.10.3/weberror/util/serial_number_generator.py000664 000765 000024 00000007620 11070224122 023302 0ustar00benstaff000000 000000 # (c) 2005 Ian Bicking and contributors; written for Paste (http://pythonpaste.org)
# Licensed under the MIT license: http://www.opensource.org/licenses/mit-license.php

"""
Creates a human-readable identifier, using numbers and digits,
avoiding ambiguous numbers and letters.  hash_identifier can be used
to create compact representations that are unique for a certain string
(or concatenation of strings)
"""

try:
    from hashlib import md5
except ImportError:
    from md5 import md5

good_characters = "23456789abcdefghjkmnpqrtuvwxyz"

base = len(good_characters)

def make_identifier(number):
    """
    Encodes a number as an identifier.
    """
    if not isinstance(number, (int, long)):
        raise ValueError(
            "You can only make identifiers out of integers (not %r)"
            % number)
    if number < 0:
        raise ValueError(
            "You cannot make identifiers out of negative numbers: %r"
            % number)
    result = []
    while number:
        next = number % base
        result.append(good_characters[next])
        # Note, this depends on integer rounding of results:
        number = number / base
    return ''.join(result)

def hash_identifier(s, length, pad=True, hasher=md5, prefix='',
                    group=None, upper=False):
    """
    Hashes the string (with the given hashing module), then turns that
    hash into an identifier of the given length (using modulo to
    reduce the length of the identifier).  If ``pad`` is False, then
    the minimum-length identifier will be used; otherwise the
    identifier will be padded with 0's as necessary.

    ``prefix`` will be added last, and does not count towards the
    target length.  ``group`` will group the characters with ``-`` in
    the given lengths, and also does not count towards the target
    length.  E.g., ``group=4`` will cause a identifier like
    ``a5f3-hgk3-asdf``.  Grouping occurs before the prefix.
    """
    if not callable(hasher):
        # Accept sha/md5 modules as well as callables
        hasher = hasher.new
    if length > 26 and hasher is md5:
        raise ValueError, (
            "md5 cannot create hashes longer than 26 characters in "
            "length (you gave %s)" % length)
    if isinstance(s, unicode):
        s = s.encode('utf-8')
    h = hasher(str(s))
    bin_hash = h.digest()
    modulo = base ** length
    number = 0
    for c in list(bin_hash):
        number = (number * 256 + ord(c)) % modulo
    ident = make_identifier(number)
    if pad:
        ident = good_characters[0]*(length-len(ident)) + ident
    if group:
        parts = []
        while ident:
            parts.insert(0, ident[-group:])
            ident = ident[:-group]
        ident = '-'.join(parts)
    if upper:
        ident = ident.upper()
    return prefix + ident

# doctest tests:
__test__ = {
    'make_identifier': """
    >>> make_identifier(0)
    ''
    >>> make_identifier(1000)
    'c53'
    >>> make_identifier(-100)
    Traceback (most recent call last):
        ...
    ValueError: You cannot make identifiers out of negative numbers: -100
    >>> make_identifier('test')
    Traceback (most recent call last):
        ...
    ValueError: You can only make identifiers out of integers (not 'test')
    >>> make_identifier(1000000000000)
    'c53x9rqh3'
    """,
    'hash_identifier': """
    >>> hash_identifier(0, 5)
    'cy2dr'
    >>> hash_identifier(0, 10)
    'cy2dr6rg46'
    >>> hash_identifier('this is a test of a long string', 5)
    'awatu'
    >>> hash_identifier(0, 26)
    'cy2dr6rg46cx8t4w2f3nfexzk4'
    >>> hash_identifier(0, 30)
    Traceback (most recent call last):
        ...
    ValueError: md5 cannot create hashes longer than 26 characters in length (you gave 30)
    >>> hash_identifier(0, 10, group=4)
    'cy-2dr6-rg46'
    >>> hash_identifier(0, 10, group=4, upper=True, prefix='M-')
    'M-CY-2DR6-RG46'
    """}

if __name__ == '__main__':
    import doctest
    doctest.testmod()
    
WebError-0.10.3/weberror/util/source_encoding.py000664 000765 000024 00000003156 11010417022 021550 0ustar00benstaff000000 000000 """Parse a Python source code encoding string"""
import codecs
import re

# Regexp to match python magic encoding line
PYTHON_MAGIC_COMMENT_re = re.compile(
    r'[ \t\f]* \# .* coding[=:][ \t]*([-\w.]+)', re.VERBOSE)
def parse_encoding(lines):
    """Deduce the encoding of a source file from magic comment.

    It does this in the same way as the `Python interpreter`__

    .. __: http://docs.python.org/ref/encodings.html

    The ``lines`` argument should be a list of the first 2 lines of the
    source code.

    (From Jeff Dairiki)
    """
    try:
        line1 = lines[0]
        has_bom = line1.startswith(codecs.BOM_UTF8)
        if has_bom:
            line1 = line1[len(codecs.BOM_UTF8):]

        m = PYTHON_MAGIC_COMMENT_re.match(line1)
        if not m:
            try:
                import parser
                parser.suite(line1)
            except (ImportError, SyntaxError):
                # Either it's a real syntax error, in which case the source is
                # not valid python source, or line2 is a continuation of line1,
                # in which case we don't want to scan line2 for a magic
                # comment.
                pass
            else:
                line2 = lines[1]
                m = PYTHON_MAGIC_COMMENT_re.match(line2)

        if has_bom:
            if m:
                raise SyntaxError(
                    "python refuses to compile code with both a UTF8 "
                    "byte-order-mark and a magic encoding comment")
            return 'utf_8'
        elif m:
            return m.group(1)
        else:
            return None
    except:
        return None
WebError-0.10.3/weberror/exceptions/__init__.py000600 000765 000024 00000000002 10770066101 021330 0ustar00benstaff000000 000000 #
WebError-0.10.3/weberror/exceptions/errormiddleware.py000664 000765 000024 00000001243 11003173153 022776 0ustar00benstaff000000 000000 import warnings

def ErrorMiddleware(*args, **kw):
    warnings.warn(
        'weberror.exceptions.errormiddleware.ErrorMiddleware has been moved '
        'to weberror.errormiddleware.ErrorMiddleware',
        DeprecationWarning, stacklevel=2)
    from weberror.errormiddleware import ErrorMiddleware
    return ErrorMiddleware(*args, **kw)

def handle_exception(*args, **kw):
    warnings.warn(
        'weberror.exceptions.errormiddleware.handle_exception has been moved '
        'to weberror.errormiddleware.handle_exception',
        DeprecationWarning, stacklevel=2)
    from weberror.errormiddleware import handle_exceptions
    return handle_exceptions(*args, **kw)
WebError-0.10.3/weberror/eval-media/debug.js000664 000765 000024 00000025210 11126232531 020506 0ustar00benstaff000000 000000 function showFrame(anchor) {
    var tbid = anchor.getAttribute('tbid');
    var expanded = anchor.expanded;
    if (expanded) {
        hideElement(anchor.expandedElement);
        anchor.expanded = false;
        _swapImage(anchor);
        return false;
    }
    anchor.expanded = true;
    if (anchor.expandedElement) {
        showElement(anchor.expandedElement);
        _swapImage(anchor);
        $('#debug_input_'+tbid).get(0).focus();
        return false;
    }
    var url = debug_base
        + '/show_frame?tbid=' + tbid
        + '&debugcount=' + debug_count;
    callbackXHR(url, null, function (data) {
                    var el = createElement('div');
                    anchor.parentNode.insertBefore(el, anchor.nextSibling);
                    el.innerHTML = data.responseText;
                    anchor.expandedElement = el;
                    _swapImage(anchor);
                    $('#debug_input_'+tbid).focus().keydown(upArrow);
                });
    return false;
}

function _swapImage(anchor) {
    var el = anchor.getElementsByTagName('IMG')[0];
    if (anchor.expanded) {
        var img = 'minus.jpg';
    } else {
        var img = 'plus.jpg';
    }
    el.src = debug_base + '/media/' + img;
}

function showSource(anchor) {
    var location = anchor.getAttribute('location');
    showSourceCode(location);
    return false;
}

function showSourceCode(location) {
    var url = debug_base + '/source_code?location=' + encodeURIComponent(location);
    var source = document.getElementById('source_data');
    source.innerHTML = 'Loading...';
    switch_display('source_data');
    callbackXHR(url, null, function (req) {
                    source.innerHTML = req.responseText;
                    if (location.indexOf(':') > 0) {
                        var lineno = location.substring(location.indexOf(':')+1);
                        lineno = parseInt(lineno) - 10;
                        if (lineno > 1) {
                            document.location.hash = '#code-'+(lineno-10);
                        }
                    }
                });
}

function submitInput(button, tbid) {
    var input = $('#' + button.getAttribute('input-from')).get(0);
    var output = $('#' + button.getAttribute('output-to')).get(0);
    var url = debug_base
        + '/exec_input';
    var history = input.form.history;
    input.historyPosition = 0;
    if (! history) {
        history = input.form.history = [];
    }
    history.push(input.value);
    var vars = {
        tbid: tbid,
        debugcount: debug_count,
        input: input.value
    };
    showElement(output);
    callbackXHR(url, vars, function (data) {
        var result = data.responseText;
        output.innerHTML += result;
        input.value = '';
        input.focus();
    });
    return false;
}

function showError(msg) {
    var el = $('#error-container').get(0);
    if (el.innerHTML) {
        el.innerHTML += '
\n' + msg; } else { el.innerHTML = msg; } showElement($('#error-area').get(0)); } function clearError() { var el = $('#error-container').get(0); el.innerHTML = ''; $('#error-area').hide(); } function upArrow(event) { var key = event.charCode ? event.charCode : event.keyCode; if (key != 38 && key != 40 && key != 63232 && key != 63233) { // not an up- or down-arrow return true; } var dir = ((key == 38) || (key == 63232)) ? 1 : -1; var history = this.form.history; if (! history) { history = this.form.history = []; } var pos = this.historyPosition || 0; if (! pos && dir == -1) { return true; } if (! pos && this.value) { history.push(this.value); pos = 1; } pos += dir; if (history.length-pos < 0) { pos = 1; } if (history.length-pos > history.length-1) { this.value = ''; return true; } this.historyPosition = pos; var line = history[history.length-pos]; if (! line) { return true; } this.value = line; } function expandInput(button) { var input = button.form.elements.input; stdops = { name: 'input', style: 'width: 100%', autocomplete: 'off' }; if (input.tagName == 'INPUT') { var newEl = createElement('textarea', stdops); var text = 'Contract'; } else { stdops['type'] = 'text'; var newEl = createElement('input', stdops); $(newEl).keydown(upArrow); var text = 'Expand'; } newEl.value = input.value; newEl.id = input.id; swapDOM(input, newEl); newEl.focus(); button.value = text; return false; } function expandLong(anchor) { var span = anchor; while (span) { if (span.style && span.style.display == 'none') { break; } span = span.nextSibling; } if (! span) { return false; } showElement(span); hideElement(anchor); return false; } function showElement(el) { el.style.display = ''; } function hideElement(el) { el.style.display = 'none'; } function createElement(tag, attrs /*, sub-elements...*/) { var el = document.createElement(tag); if (attrs) { for (var i in attrs) { el.setAttribute(i, attrs[i]); } } for (var i=2; i' + name + '
'); } function switch_source(el, hide_type) { while (el) { if (el.getAttribute && el.getAttribute('source-type') == hide_type) { break; } el = el.parentNode; } if (! el) { return false; } el.style.display = 'none'; console.log('found current el', el); if (hide_type == 'long') { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'short') { break; } el = el.nextSibling; } console.log('found short el', el); } else { while (el) { if (el.getAttribute && el.getAttribute('source-type') == 'long') { break; } el = el.previousSibling; } console.log('found long el', el); } if (el) { el.style.display = ''; } return false; } $(document).ready(function() { var hide_all = function() { $('#short_text_version, #long_text_version, #short_traceback, #full_traceback, #short_xml_version, #long_xml_version, div.feature-highlight').hide(); $('#view_long_text, #view_short_text, #view_long_html, #view_short_html, #view_short_xml, #view_long_xml').removeClass('active'); }; if ($('#long_text_version').length == 0) { $('#view_long_text').hide(); } if ($('#full_traceback').length == 0) { $('#view_long_html').hide(); } $('#view_short_text').click(function() { hide_all(); $('#short_text_version').show(); $(this).addClass('active'); return false; }); $('#view_long_text').click(function() { hide_all(); $('#long_text_version').show(); $(this).addClass('active'); return false; }); $('#view_short_html').click(function() { hide_all(); $('#short_traceback, div.feature-highlight').show(); $(this).addClass('active'); return false; }); $('#view_long_html').click(function () { hide_all(); $('#full_traceback, div.feature-highlight').show(); $(this).addClass('active'); return false; }); $('#view_short_xml').click(function () { hide_all(); $('#short_xml_version').show(); $(this).addClass('active'); return false; }); $('#view_long_xml').click(function () { hide_all(); $('#long_xml_version').show(); $(this).addClass('active'); return false; }); }); /* Fix case when Firebug isn't present: */ if (typeof console == 'undefined') { var console = {log: function (msg) {}}; } WebError-0.10.3/weberror/eval-media/jquery-1.2.1.min.js000664 000765 000024 00000132545 10770066101 022172 0ustar00benstaff000000 000000 /* * jQuery 1.2.1 - New Wave Javascript * * Copyright (c) 2007 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2007-09-16 23:42:06 -0400 (Sun, 16 Sep 2007) $ * $Rev: 3353 $ */ (function(){if(typeof jQuery!="undefined")var _jQuery=jQuery;var jQuery=window.jQuery=function(selector,context){return this instanceof jQuery?this.init(selector,context):new jQuery(selector,context);};if(typeof $!="undefined")var _$=$;window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(typeof selector=="string"){var m=quickExpr.exec(selector);if(m&&(m[1]||!context)){if(m[1])selector=jQuery.clean([m[1]],context);else{var tmp=document.getElementById(m[3]);if(tmp)if(tmp.id!=m[3])return jQuery().find(selector);else{this[0]=tmp;this.length=1;return this;}else selector=[];}}else return new jQuery(context).find(selector);}else if(jQuery.isFunction(selector))return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.1",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(a){var ret=jQuery(a);ret.prevObject=this;return ret;},setArray:function(a){this.length=0;Array.prototype.push.apply(this,a);return this;},each:function(fn,args){return jQuery.each(this,fn,args);},index:function(obj){var pos=-1;this.each(function(i){if(this==obj)pos=i;});return pos;},attr:function(key,value,type){var obj=key;if(key.constructor==String)if(value==undefined)return this.length&&jQuery[type||"attr"](this[0],key)||undefined;else{obj={};obj[key]=value;}return this.each(function(index){for(var prop in obj)jQuery.attr(type?this.style:this,prop,jQuery.prop(this,obj[prop],type,index,prop));});},css:function(key,value){return this.attr(key,value,"curCSS");},text:function(e){if(typeof e!="object"&&e!=null)return this.empty().append(document.createTextNode(e));var t="";jQuery.each(e||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8)t+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);});});return t;},wrapAll:function(html){if(this[0])jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild)elem=elem.firstChild;return elem;}).append(this);return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,1,function(a){this.appendChild(a);});},prepend:function(){return this.domManip(arguments,true,-1,function(a){this.insertBefore(a,this.firstChild);});},before:function(){return this.domManip(arguments,false,1,function(a){this.parentNode.insertBefore(a,this);});},after:function(){return this.domManip(arguments,false,-1,function(a){this.parentNode.insertBefore(a,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(t){var data=jQuery.map(this,function(a){return jQuery.find(t,a);});return this.pushStack(/[^+>] [^+>]/.test(t)||t.indexOf("..")>-1?jQuery.unique(data):data);},clone:function(events){var ret=this.map(function(){return this.outerHTML?jQuery(this.outerHTML)[0]:this.cloneNode(true);});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined)this[expando]=null;});if(events===true)this.find("*").andSelf().each(function(i){var events=jQuery.data(this,"events");for(var type in events)for(var handler in events[type])jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);});return ret;},filter:function(t){return this.pushStack(jQuery.isFunction(t)&&jQuery.grep(this,function(el,index){return t.apply(el,[index]);})||jQuery.multiFilter(t,this));},not:function(t){return this.pushStack(t.constructor==String&&jQuery.multiFilter(t,this,true)||jQuery.grep(this,function(a){return(t.constructor==Array||t.jquery)?jQuery.inArray(a,t)<0:a!=t;}));},add:function(t){return this.pushStack(jQuery.merge(this.get(),t.constructor==String?jQuery(t).get():t.length!=undefined&&(!t.nodeName||jQuery.nodeName(t,"form"))?t:[t]));},is:function(expr){return expr?jQuery.multiFilter(expr,this).length>0:false;},hasClass:function(expr){return this.is("."+expr);},val:function(val){if(val==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,a=[],options=elem.options,one=elem.type=="select-one";if(index<0)return null;for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,val)>=0);else if(jQuery.nodeName(this,"select")){var tmp=val.constructor==Array?val:[val];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,tmp)>=0||jQuery.inArray(this.text,tmp)>=0);});if(!tmp.length)this.selectedIndex=-1;}else this.value=val;});},html:function(val){return val==undefined?(this.length?this[0].innerHTML:null):this.empty().append(val);},replaceWith:function(val){return this.after(val).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(fn){return this.pushStack(jQuery.map(this,function(elem,i){return fn.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},domManip:function(args,table,dir,fn){var clone=this.length>1,a;return this.each(function(){if(!a){a=jQuery.clean(args,this.ownerDocument);if(dir<0)a.reverse();}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(a[0],"tr"))obj=this.getElementsByTagName("tbody")[0]||this.appendChild(document.createElement("tbody"));jQuery.each(a,function(){var elem=clone?this.cloneNode(true):this;if(!evalScript(0,elem))fn.call(obj,elem);});});}};function evalScript(i,elem){var script=jQuery.nodeName(elem,"script");if(script){if(elem.src)jQuery.ajax({url:elem.src,async:false,dataType:"script"});else jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");if(elem.parentNode)elem.parentNode.removeChild(elem);}else if(elem.nodeType==1)jQuery("script",elem).each(evalScript);return script;}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},a=1,al=arguments.length,deep=false;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};}if(al==1){target=this;a=0;}var prop;for(;a-1;}},swap:function(e,o,f){for(var i in o){e.style["old"+i]=e.style[i];e.style[i]=o[i];}f.apply(e,[]);for(var i in o)e.style[i]=e.style["old"+i];},css:function(e,p){if(p=="height"||p=="width"){var old={},oHeight,oWidth,d=["Top","Bottom","Right","Left"];jQuery.each(d,function(){old["padding"+this]=0;old["border"+this+"Width"]=0;});jQuery.swap(e,old,function(){if(jQuery(e).is(':visible')){oHeight=e.offsetHeight;oWidth=e.offsetWidth;}else{e=jQuery(e.cloneNode(true)).find(":radio").removeAttr("checked").end().css({visibility:"hidden",position:"absolute",display:"block",right:"0",left:"0"}).appendTo(e.parentNode)[0];var parPos=jQuery.css(e.parentNode,"position")||"static";if(parPos=="static")e.parentNode.style.position="relative";oHeight=e.clientHeight;oWidth=e.clientWidth;if(parPos=="static")e.parentNode.style.position="static";e.parentNode.removeChild(e);}});return p=="height"?oHeight:oWidth;}return jQuery.curCSS(e,p);},curCSS:function(elem,prop,force){var ret,stack=[],swap=[];function color(a){if(!jQuery.browser.safari)return false;var ret=document.defaultView.getComputedStyle(a,null);return!ret||ret.getPropertyValue("color")=="";}if(prop=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(prop.match(/float/i))prop=styleFloat;if(!force&&elem.style[prop])ret=elem.style[prop];else if(document.defaultView&&document.defaultView.getComputedStyle){if(prop.match(/float/i))prop="float";prop=prop.replace(/([A-Z])/g,"-$1").toLowerCase();var cur=document.defaultView.getComputedStyle(elem,null);if(cur&&!color(elem))ret=cur.getPropertyValue(prop);else{for(var a=elem;a&&color(a);a=a.parentNode)stack.unshift(a);for(a=0;a]*?)\/>/g,function(m,all,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area)$/i)?m:all+">";});var s=jQuery.trim(arg).toLowerCase(),div=doc.createElement("div"),tb=[];var wrap=!s.indexOf("",""]||!s.indexOf("",""]||s.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!s.indexOf("",""]||(!s.indexOf("",""]||!s.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+arg+wrap[2];while(wrap[0]--)div=div.lastChild;if(jQuery.browser.msie){if(!s.indexOf(""&&s.indexOf("=0;--n)if(jQuery.nodeName(tb[n],"tbody")&&!tb[n].childNodes.length)tb[n].parentNode.removeChild(tb[n]);if(/^\s/.test(arg))div.insertBefore(doc.createTextNode(arg.match(/^\s*/)[0]),div.firstChild);}arg=jQuery.makeArray(div.childNodes);}if(0===arg.length&&(!jQuery.nodeName(arg,"form")&&!jQuery.nodeName(arg,"select")))return;if(arg[0]==undefined||jQuery.nodeName(arg,"form")||arg.options)r.push(arg);else r=jQuery.merge(r,arg);});return r;},attr:function(elem,name,value){var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari)elem.parentNode.selectedIndex;if(fix[name]){if(value!=undefined)elem[fix[name]]=value;return elem[fix[name]];}else if(jQuery.browser.msie&&name=="style")return jQuery.attr(elem.style,"cssText",value);else if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method"))return elem.getAttributeNode(name).nodeValue;else if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode)throw"type property can't be changed";elem.setAttribute(name,value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem))return elem.getAttribute(name,2);return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(z,b){return b.toUpperCase();});if(value!=undefined)elem[name]=value;return elem[name];}},trim:function(t){return(t||"").replace(/^\s+|\s+$/g,"");},makeArray:function(a){var r=[];if(typeof a!="array")for(var i=0,al=a.length;i\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":"m[2]=='*'||jQuery.nodeName(a,m[2])","#":"a.getAttribute('id')==m[2]",":":{lt:"im[3]-0",nth:"m[3]-0==i",eq:"m[3]-0==i",first:"i==0",last:"i==r.length-1",even:"i%2==0",odd:"i%2","first-child":"a.parentNode.getElementsByTagName('*')[0]==a","last-child":"jQuery.nth(a.parentNode.lastChild,1,'previousSibling')==a","only-child":"!jQuery.nth(a.parentNode.lastChild,2,'previousSibling')",parent:"a.firstChild",empty:"!a.firstChild",contains:"(a.textContent||a.innerText||jQuery(a).text()||'').indexOf(m[3])>=0",visible:'"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden"',hidden:'"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden"',enabled:"!a.disabled",disabled:"a.disabled",checked:"a.checked",selected:"a.selected||jQuery.attr(a,'selected')",text:"'text'==a.type",radio:"'radio'==a.type",checkbox:"'checkbox'==a.type",file:"'file'==a.type",password:"'password'==a.type",submit:"'submit'==a.type",image:"'image'==a.type",reset:"'reset'==a.type",button:'"button"==a.type||jQuery.nodeName(a,"button")',input:"/input|select|textarea|button/i.test(a.nodeName)",has:"jQuery.find(m[3],a).length",header:"/h\\d/i.test(a.nodeName)",animated:"jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length"}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string")return[t];if(context&&!context.nodeType)context=null;context=context||document;var ret=[context],done=[],last;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){var nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++)for(var c=ret[i].firstChild;c;c=c.nextSibling)if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName.toUpperCase()))r.push(c);ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0)continue;foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var nodeName=m[2],merge={};m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass)tmp.push(r[i]);}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m)break;if(m[1]==":"&&m[2]=="not")r=jQuery.filter(m[3],r,true).r;else if(m[1]==".")r=jQuery.classFilter(r,m[2],not);else if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not)tmp.push(a);}r=tmp;}else if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(\d*)n\+?(\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"n+"+m[3]||m[3]),first=(test[1]||1)-0,last=test[2]-0;for(var i=0,rl=r.length;i<\/script>");var script=document.getElementById("__ie_init");if(script)script.onreadystatechange=function(){if(this.readyState!="complete")return;jQuery.ready();};script=null;}else if(jQuery.browser.safari)jQuery.safariTimer=setInterval(function(){if(document.readyState=="loaded"||document.readyState=="complete"){clearInterval(jQuery.safariTimer);jQuery.safariTimer=null;jQuery.ready();}},10);jQuery.event.add(window,"load",jQuery.ready);}jQuery.fn.extend({load:function(url,params,callback){if(jQuery.isFunction(url))return this.bind("load",url);var off=url.indexOf(" ");if(off>=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params)if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}var self=this;jQuery.ajax({url:url,type:type,data:params,complete:function(res,status){if(status=="success"||status=="notmodified")self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);setTimeout(function(){self.each(callback,[res.responseText,status,res]);},13);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null},lastModified:{},ajax:function(s){var jsonp,jsre=/=(\?|%3F)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string")s.data=jQuery.param(s.data);if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre))s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}else if(!s.data||!s.data.match(jsre))s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data)s.data=s.data.replace(jsre,"="+jsonp);s.url=s.url.replace(jsre,"="+jsonp);s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}};}if(s.dataType=="script"&&s.cache==null)s.cache=false;if(s.cache===false&&s.type.toLowerCase()=="get")s.url+=(s.url.match(/\?/)?"&":"?")+"_="+(new Date()).getTime();if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++)jQuery.event.trigger("ajaxStart");if(!s.url.indexOf("http")&&s.dataType=="script"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(!jsonp&&(s.success||s.complete)){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async);if(s.data)xml.setRequestHeader("Content-Type",s.contentType);if(s.ifModified)xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");xml.setRequestHeader("X-Requested-With","XMLHttpRequest");if(s.beforeSend)s.beforeSend(xml);if(s.global)jQuery.event.trigger("ajaxSend",[xml,s]);var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes)jQuery.lastModified[s.url]=modRes;if(!jsonp)success();}else jQuery.handleError(s,xml,status);complete();if(s.async)xml=null;}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0)setTimeout(function(){if(xml){xml.abort();if(!requestDone)onreadystatechange("timeout");}},s.timeout);}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async)onreadystatechange();return xml;function success(){if(s.success)s.success(data,status);if(s.global)jQuery.event.trigger("ajaxSuccess",[xml,s]);}function complete(){if(s.complete)s.complete(xml,status);if(s.global)jQuery.event.trigger("ajaxComplete",[xml,s]);if(s.global&&!--jQuery.active)jQuery.event.trigger("ajaxStop");}},handleError:function(s,xml,status,e){if(s.error)s.error(xml,status,e);if(s.global)jQuery.event.trigger("ajaxError",[xml,s,e]);},active:0,httpSuccess:function(r){try{return!r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror")throw"parsererror";if(type=="script")jQuery.globalEval(data);if(type=="json")data=eval("("+data+")");return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery)jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});else for(var j in a)if(a[j]&&a[j].constructor==Array)jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});else s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock?this.oldblock:"";if(jQuery.css(this,"display")=="none")this.style.display="block";}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");if(this.oldblock=="none")this.oldblock="block";this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var opt=jQuery.speed(speed,easing,callback);return this[opt.queue===false?"each":"queue"](function(){opt=jQuery.extend({},opt);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden)return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null)this.style.overflow="hidden";opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val))e[val=="toggle"?hidden?"show":"hide":val](prop);else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1])end=((parts[1]=="-="?-1:1)*end)+start;e.custom(start,end,unit);}else e.custom(start,val,"");}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn))return queue(this[0],type);return this.each(function(){if(fn.constructor==Array)queue(this,type,fn);else{queue(this,type).push(fn);if(queue(this,type).length==1)fn.apply(this);}});},stop:function(){var timers=jQuery.timers;return this.each(function(){for(var i=0;i-10000?r:parseFloat(jQuery.css(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(){return self.step();}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timers.length==1){var timer=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim)if(this.options.curAnim[i]!==true)done=false;if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none")this.elem.style.display="block";}if(this.options.hide)this.elem.style.display="none";if(this.options.hide||this.options.show)for(var p in this.options.curAnim)jQuery.attr(this.elem.style,p,this.options.orig[p]);}if(done&&jQuery.isFunction(this.options.complete))this.options.complete.apply(this.elem);return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem)with(jQuery.browser){var absolute=jQuery.css(elem,"position")=="absolute",parent=elem.parentNode,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522;if(elem.getBoundingClientRect){box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));if(msie){var border=jQuery("html").css("borderWidth");border=(border=="medium"||jQuery.boxModel&&parseInt(version)>=7)&&2||border;add(-border,-border);}}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&/^t[d|h]$/i.test(parent.tagName)||!safari2)border(offsetParent);if(safari2&&!absolute&&jQuery.css(offsetParent,"position")=="absolute")absolute=true;offsetParent=offsetParent.offsetParent;}while(parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table-row.*$/i.test(jQuery.css(parent,"display")))add(-parent.scrollLeft,-parent.scrollTop);if(mozilla&&jQuery.css(parent,"overflow")!="visible")border(parent);parent=parent.parentNode;}if(safari2&&absolute)add(-doc.body.offsetLeft,-doc.body.offsetTop);}results={top:top,left:left};}return results;function border(elem){add(jQuery.css(elem,"borderLeftWidth"),jQuery.css(elem,"borderTopWidth"));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}};})();WebError-0.10.3/weberror/eval-media/jquery-1.2.3.pack.js000644 000765 000024 00000156356 11010422655 022331 0ustar00benstaff000000 000000 /* * jQuery 1.2.3 - New Wave Javascript * * Copyright (c) 2008 John Resig (jquery.com) * Dual licensed under the MIT (MIT-LICENSE.txt) * and GPL (GPL-LICENSE.txt) licenses. * * $Date: 2008-02-06 00:21:25 -0500 (Wed, 06 Feb 2008) $ * $Rev: 4663 $ */ (function(){if(window.jQuery){var _jQuery=window.jQuery;}var jQuery=window.jQuery=function(selector,context){return new jQuery.prototype.init(selector,context);};if(window.$){var _$=window.$;}window.$=jQuery;var quickExpr=/^[^<]*(<(.|\s)+>)[^>]*$|^#(\w+)$/;var isSimple=/^.[^:#\[\.]*$/;jQuery.fn=jQuery.prototype={init:function(selector,context){selector=selector||document;if(selector.nodeType){this[0]=selector;this.length=1;return this;}else{if(typeof selector=="string"){var match=quickExpr.exec(selector);if(match&&(match[1]||!context)){if(match[1]){selector=jQuery.clean([match[1]],context);}else{var elem=document.getElementById(match[3]);if(elem){if(elem.id!=match[3]){return jQuery().find(selector);}else{this[0]=elem;this.length=1;return this;}}else{selector=[];}}}else{return new jQuery(context).find(selector);}}else{if(jQuery.isFunction(selector)){return new jQuery(document)[jQuery.fn.ready?"ready":"load"](selector);}}}return this.setArray(selector.constructor==Array&&selector||(selector.jquery||selector.length&&selector!=window&&!selector.nodeType&&selector[0]!=undefined&&selector[0].nodeType)&&jQuery.makeArray(selector)||[selector]);},jquery:"1.2.3",size:function(){return this.length;},length:0,get:function(num){return num==undefined?jQuery.makeArray(this):this[num];},pushStack:function(elems){var ret=jQuery(elems);ret.prevObject=this;return ret;},setArray:function(elems){this.length=0;Array.prototype.push.apply(this,elems);return this;},each:function(callback,args){return jQuery.each(this,callback,args);},index:function(elem){var ret=-1;this.each(function(i){if(this==elem){ret=i;}});return ret;},attr:function(name,value,type){var options=name;if(name.constructor==String){if(value==undefined){return this.length&&jQuery[type||"attr"](this[0],name)||undefined;}else{options={};options[name]=value;}}return this.each(function(i){for(name in options){jQuery.attr(type?this.style:this,name,jQuery.prop(this,options[name],type,i,name));}});},css:function(key,value){if((key=="width"||key=="height")&&parseFloat(value)<0){value=undefined;}return this.attr(key,value,"curCSS");},text:function(text){if(typeof text!="object"&&text!=null){return this.empty().append((this[0]&&this[0].ownerDocument||document).createTextNode(text));}var ret="";jQuery.each(text||this,function(){jQuery.each(this.childNodes,function(){if(this.nodeType!=8){ret+=this.nodeType!=1?this.nodeValue:jQuery.fn.text([this]);}});});return ret;},wrapAll:function(html){if(this[0]){jQuery(html,this[0].ownerDocument).clone().insertBefore(this[0]).map(function(){var elem=this;while(elem.firstChild){elem=elem.firstChild;}return elem;}).append(this);}return this;},wrapInner:function(html){return this.each(function(){jQuery(this).contents().wrapAll(html);});},wrap:function(html){return this.each(function(){jQuery(this).wrapAll(html);});},append:function(){return this.domManip(arguments,true,false,function(elem){if(this.nodeType==1){this.appendChild(elem);}});},prepend:function(){return this.domManip(arguments,true,true,function(elem){if(this.nodeType==1){this.insertBefore(elem,this.firstChild);}});},before:function(){return this.domManip(arguments,false,false,function(elem){this.parentNode.insertBefore(elem,this);});},after:function(){return this.domManip(arguments,false,true,function(elem){this.parentNode.insertBefore(elem,this.nextSibling);});},end:function(){return this.prevObject||jQuery([]);},find:function(selector){var elems=jQuery.map(this,function(elem){return jQuery.find(selector,elem);});return this.pushStack(/[^+>] [^+>]/.test(selector)||selector.indexOf("..")>-1?jQuery.unique(elems):elems);},clone:function(events){var ret=this.map(function(){if(jQuery.browser.msie&&!jQuery.isXMLDoc(this)){var clone=this.cloneNode(true),container=document.createElement("div");container.appendChild(clone);return jQuery.clean([container.innerHTML])[0];}else{return this.cloneNode(true);}});var clone=ret.find("*").andSelf().each(function(){if(this[expando]!=undefined){this[expando]=null;}});if(events===true){this.find("*").andSelf().each(function(i){if(this.nodeType==3){return ;}var events=jQuery.data(this,"events");for(var type in events){for(var handler in events[type]){jQuery.event.add(clone[i],type,events[type][handler],events[type][handler].data);}}});}return ret;},filter:function(selector){return this.pushStack(jQuery.isFunction(selector)&&jQuery.grep(this,function(elem,i){return selector.call(elem,i);})||jQuery.multiFilter(selector,this));},not:function(selector){if(selector.constructor==String){if(isSimple.test(selector)){return this.pushStack(jQuery.multiFilter(selector,this,true));}else{selector=jQuery.multiFilter(selector,this);}}var isArrayLike=selector.length&&selector[selector.length-1]!==undefined&&!selector.nodeType;return this.filter(function(){return isArrayLike?jQuery.inArray(this,selector)<0:this!=selector;});},add:function(selector){return !selector?this:this.pushStack(jQuery.merge(this.get(),selector.constructor==String?jQuery(selector).get():selector.length!=undefined&&(!selector.nodeName||jQuery.nodeName(selector,"form"))?selector:[selector]));},is:function(selector){return selector?jQuery.multiFilter(selector,this).length>0:false;},hasClass:function(selector){return this.is("."+selector);},val:function(value){if(value==undefined){if(this.length){var elem=this[0];if(jQuery.nodeName(elem,"select")){var index=elem.selectedIndex,values=[],options=elem.options,one=elem.type=="select-one";if(index<0){return null;}for(var i=one?index:0,max=one?index+1:options.length;i=0||jQuery.inArray(this.name,value)>=0);}else{if(jQuery.nodeName(this,"select")){var values=value.constructor==Array?value:[value];jQuery("option",this).each(function(){this.selected=(jQuery.inArray(this.value,values)>=0||jQuery.inArray(this.text,values)>=0);});if(!values.length){this.selectedIndex=-1;}}else{this.value=value;}}});},html:function(value){return value==undefined?(this.length?this[0].innerHTML:null):this.empty().append(value);},replaceWith:function(value){return this.after(value).remove();},eq:function(i){return this.slice(i,i+1);},slice:function(){return this.pushStack(Array.prototype.slice.apply(this,arguments));},map:function(callback){return this.pushStack(jQuery.map(this,function(elem,i){return callback.call(elem,i,elem);}));},andSelf:function(){return this.add(this.prevObject);},data:function(key,value){var parts=key.split(".");parts[1]=parts[1]?"."+parts[1]:"";if(value==null){var data=this.triggerHandler("getData"+parts[1]+"!",[parts[0]]);if(data==undefined&&this.length){data=jQuery.data(this[0],key);}return data==null&&parts[1]?this.data(parts[0]):data;}else{return this.trigger("setData"+parts[1]+"!",[parts[0],value]).each(function(){jQuery.data(this,key,value);});}},removeData:function(key){return this.each(function(){jQuery.removeData(this,key);});},domManip:function(args,table,reverse,callback){var clone=this.length>1,elems;return this.each(function(){if(!elems){elems=jQuery.clean(args,this.ownerDocument);if(reverse){elems.reverse();}}var obj=this;if(table&&jQuery.nodeName(this,"table")&&jQuery.nodeName(elems[0],"tr")){obj=this.getElementsByTagName("tbody")[0]||this.appendChild(this.ownerDocument.createElement("tbody"));}var scripts=jQuery([]);jQuery.each(elems,function(){var elem=clone?jQuery(this).clone(true)[0]:this;if(jQuery.nodeName(elem,"script")){scripts=scripts.add(elem);}else{if(elem.nodeType==1){scripts=scripts.add(jQuery("script",elem).remove());}callback.call(obj,elem);}});scripts.each(evalScript);});}};jQuery.prototype.init.prototype=jQuery.prototype;function evalScript(i,elem){if(elem.src){jQuery.ajax({url:elem.src,async:false,dataType:"script"});}else{jQuery.globalEval(elem.text||elem.textContent||elem.innerHTML||"");}if(elem.parentNode){elem.parentNode.removeChild(elem);}}jQuery.extend=jQuery.fn.extend=function(){var target=arguments[0]||{},i=1,length=arguments.length,deep=false,options;if(target.constructor==Boolean){deep=target;target=arguments[1]||{};i=2;}if(typeof target!="object"&&typeof target!="function"){target={};}if(length==1){target=this;i=0;}for(;i-1;}},swap:function(elem,options,callback){var old={};for(var name in options){old[name]=elem.style[name];elem.style[name]=options[name];}callback.call(elem);for(var name in options){elem.style[name]=old[name];}},css:function(elem,name,force){if(name=="width"||name=="height"){var val,props={position:"absolute",visibility:"hidden",display:"block"},which=name=="width"?["Left","Right"]:["Top","Bottom"];function getWH(){val=name=="width"?elem.offsetWidth:elem.offsetHeight;var padding=0,border=0;jQuery.each(which,function(){padding+=parseFloat(jQuery.curCSS(elem,"padding"+this,true))||0;border+=parseFloat(jQuery.curCSS(elem,"border"+this+"Width",true))||0;});val-=Math.round(padding+border);}if(jQuery(elem).is(":visible")){getWH();}else{jQuery.swap(elem,props,getWH);}return Math.max(0,val);}return jQuery.curCSS(elem,name,force);},curCSS:function(elem,name,force){var ret;function color(elem){if(!jQuery.browser.safari){return false;}var ret=document.defaultView.getComputedStyle(elem,null);return !ret||ret.getPropertyValue("color")=="";}if(name=="opacity"&&jQuery.browser.msie){ret=jQuery.attr(elem.style,"opacity");return ret==""?"1":ret;}if(jQuery.browser.opera&&name=="display"){var save=elem.style.outline;elem.style.outline="0 solid black";elem.style.outline=save;}if(name.match(/float/i)){name=styleFloat;}if(!force&&elem.style&&elem.style[name]){ret=elem.style[name];}else{if(document.defaultView&&document.defaultView.getComputedStyle){if(name.match(/float/i)){name="float";}name=name.replace(/([A-Z])/g,"-$1").toLowerCase();var getComputedStyle=document.defaultView.getComputedStyle(elem,null);if(getComputedStyle&&!color(elem)){ret=getComputedStyle.getPropertyValue(name);}else{var swap=[],stack=[];for(var a=elem;a&&color(a);a=a.parentNode){stack.unshift(a);}for(var i=0;i]*?)\/>/g,function(all,front,tag){return tag.match(/^(abbr|br|col|img|input|link|meta|param|hr|area|embed)$/i)?all:front+">";});var tags=jQuery.trim(elem).toLowerCase(),div=context.createElement("div");var wrap=!tags.indexOf("",""]||!tags.indexOf("",""]||tags.match(/^<(thead|tbody|tfoot|colg|cap)/)&&[1,"","
"]||!tags.indexOf("",""]||(!tags.indexOf("",""]||!tags.indexOf("",""]||jQuery.browser.msie&&[1,"div
","
"]||[0,"",""];div.innerHTML=wrap[1]+elem+wrap[2];while(wrap[0]--){div=div.lastChild;}if(jQuery.browser.msie){var tbody=!tags.indexOf(""&&tags.indexOf("=0;--j){if(jQuery.nodeName(tbody[j],"tbody")&&!tbody[j].childNodes.length){tbody[j].parentNode.removeChild(tbody[j]);}}if(/^\s/.test(elem)){div.insertBefore(context.createTextNode(elem.match(/^\s*/)[0]),div.firstChild);}}elem=jQuery.makeArray(div.childNodes);}if(elem.length===0&&(!jQuery.nodeName(elem,"form")&&!jQuery.nodeName(elem,"select"))){return ;}if(elem[0]==undefined||jQuery.nodeName(elem,"form")||elem.options){ret.push(elem);}else{ret=jQuery.merge(ret,elem);}});return ret;},attr:function(elem,name,value){if(!elem||elem.nodeType==3||elem.nodeType==8){return undefined;}var fix=jQuery.isXMLDoc(elem)?{}:jQuery.props;if(name=="selected"&&jQuery.browser.safari){elem.parentNode.selectedIndex;}if(fix[name]){if(value!=undefined){elem[fix[name]]=value;}return elem[fix[name]];}else{if(jQuery.browser.msie&&name=="style"){return jQuery.attr(elem.style,"cssText",value);}else{if(value==undefined&&jQuery.browser.msie&&jQuery.nodeName(elem,"form")&&(name=="action"||name=="method")){return elem.getAttributeNode(name).nodeValue;}else{if(elem.tagName){if(value!=undefined){if(name=="type"&&jQuery.nodeName(elem,"input")&&elem.parentNode){throw"type property can't be changed";}elem.setAttribute(name,""+value);}if(jQuery.browser.msie&&/href|src/.test(name)&&!jQuery.isXMLDoc(elem)){return elem.getAttribute(name,2);}return elem.getAttribute(name);}else{if(name=="opacity"&&jQuery.browser.msie){if(value!=undefined){elem.zoom=1;elem.filter=(elem.filter||"").replace(/alpha\([^)]*\)/,"")+(parseFloat(value).toString()=="NaN"?"":"alpha(opacity="+value*100+")");}return elem.filter&&elem.filter.indexOf("opacity=")>=0?(parseFloat(elem.filter.match(/opacity=([^)]*)/)[1])/100).toString():"";}name=name.replace(/-([a-z])/ig,function(all,letter){return letter.toUpperCase();});if(value!=undefined){elem[name]=value;}return elem[name];}}}}},trim:function(text){return(text||"").replace(/^\s+|\s+$/g,"");},makeArray:function(array){var ret=[];if(typeof array!="array"){for(var i=0,length=array.length;i*",this).remove();while(this.firstChild){this.removeChild(this.firstChild);}}},function(name,fn){jQuery.fn[name]=function(){return this.each(fn,arguments);};});jQuery.each(["Height","Width"],function(i,name){var type=name.toLowerCase();jQuery.fn[type]=function(size){return this[0]==window?jQuery.browser.opera&&document.body["client"+name]||jQuery.browser.safari&&window["inner"+name]||document.compatMode=="CSS1Compat"&&document.documentElement["client"+name]||document.body["client"+name]:this[0]==document?Math.max(Math.max(document.body["scroll"+name],document.documentElement["scroll"+name]),Math.max(document.body["offset"+name],document.documentElement["offset"+name])):size==undefined?(this.length?jQuery.css(this[0],type):null):this.css(type,size.constructor==String?size:size+"px");};});var chars=jQuery.browser.safari&&parseInt(jQuery.browser.version)<417?"(?:[\\w*_-]|\\\\.)":"(?:[\\w\u0128-\uFFFF*_-]|\\\\.)",quickChild=new RegExp("^>\\s*("+chars+"+)"),quickID=new RegExp("^("+chars+"+)(#)("+chars+"+)"),quickClass=new RegExp("^([#.]?)("+chars+"*)");jQuery.extend({expr:{"":function(a,i,m){return m[2]=="*"||jQuery.nodeName(a,m[2]);},"#":function(a,i,m){return a.getAttribute("id")==m[2];},":":{lt:function(a,i,m){return im[3]-0;},nth:function(a,i,m){return m[3]-0==i;},eq:function(a,i,m){return m[3]-0==i;},first:function(a,i){return i==0;},last:function(a,i,m,r){return i==r.length-1;},even:function(a,i){return i%2==0;},odd:function(a,i){return i%2;},"first-child":function(a){return a.parentNode.getElementsByTagName("*")[0]==a;},"last-child":function(a){return jQuery.nth(a.parentNode.lastChild,1,"previousSibling")==a;},"only-child":function(a){return !jQuery.nth(a.parentNode.lastChild,2,"previousSibling");},parent:function(a){return a.firstChild;},empty:function(a){return !a.firstChild;},contains:function(a,i,m){return(a.textContent||a.innerText||jQuery(a).text()||"").indexOf(m[3])>=0;},visible:function(a){return"hidden"!=a.type&&jQuery.css(a,"display")!="none"&&jQuery.css(a,"visibility")!="hidden";},hidden:function(a){return"hidden"==a.type||jQuery.css(a,"display")=="none"||jQuery.css(a,"visibility")=="hidden";},enabled:function(a){return !a.disabled;},disabled:function(a){return a.disabled;},checked:function(a){return a.checked;},selected:function(a){return a.selected||jQuery.attr(a,"selected");},text:function(a){return"text"==a.type;},radio:function(a){return"radio"==a.type;},checkbox:function(a){return"checkbox"==a.type;},file:function(a){return"file"==a.type;},password:function(a){return"password"==a.type;},submit:function(a){return"submit"==a.type;},image:function(a){return"image"==a.type;},reset:function(a){return"reset"==a.type;},button:function(a){return"button"==a.type||jQuery.nodeName(a,"button");},input:function(a){return/input|select|textarea|button/i.test(a.nodeName);},has:function(a,i,m){return jQuery.find(m[3],a).length;},header:function(a){return/h\d/i.test(a.nodeName);},animated:function(a){return jQuery.grep(jQuery.timers,function(fn){return a==fn.elem;}).length;}}},parse:[/^(\[) *@?([\w-]+) *([!*$^~=]*) *('?"?)(.*?)\4 *\]/,/^(:)([\w-]+)\("?'?(.*?(\(.*?\))?[^(]*?)"?'?\)/,new RegExp("^([:.#]*)("+chars+"+)")],multiFilter:function(expr,elems,not){var old,cur=[];while(expr&&expr!=old){old=expr;var f=jQuery.filter(expr,elems,not);expr=f.t.replace(/^\s*,\s*/,"");cur=not?elems=f.r:jQuery.merge(cur,f.r);}return cur;},find:function(t,context){if(typeof t!="string"){return[t];}if(context&&context.nodeType!=1&&context.nodeType!=9){return[];}context=context||document;var ret=[context],done=[],last,nodeName;while(t&&last!=t){var r=[];last=t;t=jQuery.trim(t);var foundToken=false;var re=quickChild;var m=re.exec(t);if(m){nodeName=m[1].toUpperCase();for(var i=0;ret[i];i++){for(var c=ret[i].firstChild;c;c=c.nextSibling){if(c.nodeType==1&&(nodeName=="*"||c.nodeName.toUpperCase()==nodeName)){r.push(c);}}}ret=r;t=t.replace(re,"");if(t.indexOf(" ")==0){continue;}foundToken=true;}else{re=/^([>+~])\s*(\w*)/i;if((m=re.exec(t))!=null){r=[];var merge={};nodeName=m[2].toUpperCase();m=m[1];for(var j=0,rl=ret.length;j=0;if(!not&&pass||not&&!pass){tmp.push(r[i]);}}return tmp;},filter:function(t,r,not){var last;while(t&&t!=last){last=t;var p=jQuery.parse,m;for(var i=0;p[i];i++){m=p[i].exec(t);if(m){t=t.substring(m[0].length);m[2]=m[2].replace(/\\/g,"");break;}}if(!m){break;}if(m[1]==":"&&m[2]=="not"){r=isSimple.test(m[3])?jQuery.filter(m[3],r,true).r:jQuery(r).not(m[3]);}else{if(m[1]=="."){r=jQuery.classFilter(r,m[2],not);}else{if(m[1]=="["){var tmp=[],type=m[3];for(var i=0,rl=r.length;i=0)^not){tmp.push(a);}}r=tmp;}else{if(m[1]==":"&&m[2]=="nth-child"){var merge={},tmp=[],test=/(-?)(\d*)n((?:\+|-)?\d*)/.exec(m[3]=="even"&&"2n"||m[3]=="odd"&&"2n+1"||!/\D/.test(m[3])&&"0n+"+m[3]||m[3]),first=(test[1]+(test[2]||1))-0,last=test[3]-0;for(var i=0,rl=r.length;i=0){add=true;}}if(add^not){tmp.push(node);}}r=tmp;}else{var fn=jQuery.expr[m[1]];if(typeof fn=="object"){fn=fn[m[2]];}if(typeof fn=="string"){fn=eval("false||function(a,i){return "+fn+";}");}r=jQuery.grep(r,function(elem,i){return fn(elem,i,m,r);},not);}}}}}return{r:r,t:t};},dir:function(elem,dir){var matched=[];var cur=elem[dir];while(cur&&cur!=document){if(cur.nodeType==1){matched.push(cur);}cur=cur[dir];}return matched;},nth:function(cur,result,dir,elem){result=result||1;var num=0;for(;cur;cur=cur[dir]){if(cur.nodeType==1&&++num==result){break;}}return cur;},sibling:function(n,elem){var r=[];for(;n;n=n.nextSibling){if(n.nodeType==1&&(!elem||n!=elem)){r.push(n);}}return r;}});jQuery.event={add:function(elem,types,handler,data){if(elem.nodeType==3||elem.nodeType==8){return ;}if(jQuery.browser.msie&&elem.setInterval!=undefined){elem=window;}if(!handler.guid){handler.guid=this.guid++;}if(data!=undefined){var fn=handler;handler=function(){return fn.apply(this,arguments);};handler.data=data;handler.guid=fn.guid;}var events=jQuery.data(elem,"events")||jQuery.data(elem,"events",{}),handle=jQuery.data(elem,"handle")||jQuery.data(elem,"handle",function(){var val;if(typeof jQuery=="undefined"||jQuery.event.triggered){return val;}val=jQuery.event.handle.apply(arguments.callee.elem,arguments);return val;});handle.elem=elem;jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];handler.type=parts[1];var handlers=events[type];if(!handlers){handlers=events[type]={};if(!jQuery.event.special[type]||jQuery.event.special[type].setup.call(elem)===false){if(elem.addEventListener){elem.addEventListener(type,handle,false);}else{if(elem.attachEvent){elem.attachEvent("on"+type,handle);}}}}handlers[handler.guid]=handler;jQuery.event.global[type]=true;});elem=null;},guid:1,global:{},remove:function(elem,types,handler){if(elem.nodeType==3||elem.nodeType==8){return ;}var events=jQuery.data(elem,"events"),ret,index;if(events){if(types==undefined||(typeof types=="string"&&types.charAt(0)==".")){for(var type in events){this.remove(elem,type+(types||""));}}else{if(types.type){handler=types.handler;types=types.type;}jQuery.each(types.split(/\s+/),function(index,type){var parts=type.split(".");type=parts[0];if(events[type]){if(handler){delete events[type][handler.guid];}else{for(handler in events[type]){if(!parts[1]||events[type][handler].type==parts[1]){delete events[type][handler];}}}for(ret in events[type]){break;}if(!ret){if(!jQuery.event.special[type]||jQuery.event.special[type].teardown.call(elem)===false){if(elem.removeEventListener){elem.removeEventListener(type,jQuery.data(elem,"handle"),false);}else{if(elem.detachEvent){elem.detachEvent("on"+type,jQuery.data(elem,"handle"));}}}ret=null;delete events[type];}}});}for(ret in events){break;}if(!ret){var handle=jQuery.data(elem,"handle");if(handle){handle.elem=null;}jQuery.removeData(elem,"events");jQuery.removeData(elem,"handle");}}},trigger:function(type,data,elem,donative,extra){data=jQuery.makeArray(data||[]);if(type.indexOf("!")>=0){type=type.slice(0,-1);var exclusive=true;}if(!elem){if(this.global[type]){jQuery("*").add([window,document]).trigger(type,data);}}else{if(elem.nodeType==3||elem.nodeType==8){return undefined;}var val,ret,fn=jQuery.isFunction(elem[type]||null),event=!data[0]||!data[0].preventDefault;if(event){data.unshift(this.fix({type:type,target:elem}));}data[0].type=type;if(exclusive){data[0].exclusive=true;}if(jQuery.isFunction(jQuery.data(elem,"handle"))){val=jQuery.data(elem,"handle").apply(elem,data);}if(!fn&&elem["on"+type]&&elem["on"+type].apply(elem,data)===false){val=false;}if(event){data.shift();}if(extra&&jQuery.isFunction(extra)){ret=extra.apply(elem,val==null?data:data.concat(val));if(ret!==undefined){val=ret;}}if(fn&&donative!==false&&val!==false&&!(jQuery.nodeName(elem,"a")&&type=="click")){this.triggered=true;try{elem[type]();}catch(e){}}this.triggered=false;}return val;},handle:function(event){var val;event=jQuery.event.fix(event||window.event||{});var parts=event.type.split(".");event.type=parts[0];var handlers=jQuery.data(this,"events")&&jQuery.data(this,"events")[event.type],args=Array.prototype.slice.call(arguments,1);args.unshift(event);for(var j in handlers){var handler=handlers[j];args[0].handler=handler;args[0].data=handler.data;if(!parts[1]&&!event.exclusive||handler.type==parts[1]){var ret=handler.apply(this,args);if(val!==false){val=ret;}if(ret===false){event.preventDefault();event.stopPropagation();}}}if(jQuery.browser.msie){event.target=event.preventDefault=event.stopPropagation=event.handler=event.data=null;}return val;},fix:function(event){var originalEvent=event;event=jQuery.extend({},originalEvent);event.preventDefault=function(){if(originalEvent.preventDefault){originalEvent.preventDefault();}originalEvent.returnValue=false;};event.stopPropagation=function(){if(originalEvent.stopPropagation){originalEvent.stopPropagation();}originalEvent.cancelBubble=true;};if(!event.target){event.target=event.srcElement||document;}if(event.target.nodeType==3){event.target=originalEvent.target.parentNode;}if(!event.relatedTarget&&event.fromElement){event.relatedTarget=event.fromElement==event.target?event.toElement:event.fromElement;}if(event.pageX==null&&event.clientX!=null){var doc=document.documentElement,body=document.body;event.pageX=event.clientX+(doc&&doc.scrollLeft||body&&body.scrollLeft||0)-(doc.clientLeft||0);event.pageY=event.clientY+(doc&&doc.scrollTop||body&&body.scrollTop||0)-(doc.clientTop||0);}if(!event.which&&((event.charCode||event.charCode===0)?event.charCode:event.keyCode)){event.which=event.charCode||event.keyCode;}if(!event.metaKey&&event.ctrlKey){event.metaKey=event.ctrlKey;}if(!event.which&&event.button){event.which=(event.button&1?1:(event.button&2?3:(event.button&4?2:0)));}return event;},special:{ready:{setup:function(){bindReady();return ;},teardown:function(){return ;}},mouseenter:{setup:function(){if(jQuery.browser.msie){return false;}jQuery(this).bind("mouseover",jQuery.event.special.mouseenter.handler);return true;},teardown:function(){if(jQuery.browser.msie){return false;}jQuery(this).unbind("mouseover",jQuery.event.special.mouseenter.handler);return true;},handler:function(event){if(withinElement(event,this)){return true;}arguments[0].type="mouseenter";return jQuery.event.handle.apply(this,arguments);}},mouseleave:{setup:function(){if(jQuery.browser.msie){return false;}jQuery(this).bind("mouseout",jQuery.event.special.mouseleave.handler);return true;},teardown:function(){if(jQuery.browser.msie){return false;}jQuery(this).unbind("mouseout",jQuery.event.special.mouseleave.handler);return true;},handler:function(event){if(withinElement(event,this)){return true;}arguments[0].type="mouseleave";return jQuery.event.handle.apply(this,arguments);}}}};jQuery.fn.extend({bind:function(type,data,fn){return type=="unload"?this.one(type,data,fn):this.each(function(){jQuery.event.add(this,type,fn||data,fn&&data);});},one:function(type,data,fn){return this.each(function(){jQuery.event.add(this,type,function(event){jQuery(this).unbind(event);return(fn||data).apply(this,arguments);},fn&&data);});},unbind:function(type,fn){return this.each(function(){jQuery.event.remove(this,type,fn);});},trigger:function(type,data,fn){return this.each(function(){jQuery.event.trigger(type,data,this,true,fn);});},triggerHandler:function(type,data,fn){if(this[0]){return jQuery.event.trigger(type,data,this[0],false,fn);}return undefined;},toggle:function(){var args=arguments;return this.click(function(event){this.lastToggle=0==this.lastToggle?1:0;event.preventDefault();return args[this.lastToggle].apply(this,arguments)||false;});},hover:function(fnOver,fnOut){return this.bind("mouseenter",fnOver).bind("mouseleave",fnOut);},ready:function(fn){bindReady();if(jQuery.isReady){fn.call(document,jQuery);}else{jQuery.readyList.push(function(){return fn.call(this,jQuery);});}return this;}});jQuery.extend({isReady:false,readyList:[],ready:function(){if(!jQuery.isReady){jQuery.isReady=true;if(jQuery.readyList){jQuery.each(jQuery.readyList,function(){this.apply(document);});jQuery.readyList=null;}jQuery(document).triggerHandler("ready");}}});var readyBound=false;function bindReady(){if(readyBound){return ;}readyBound=true;if(document.addEventListener&&!jQuery.browser.opera){document.addEventListener("DOMContentLoaded",jQuery.ready,false);}if(jQuery.browser.msie&&window==top){(function(){if(jQuery.isReady){return ;}try{document.documentElement.doScroll("left");}catch(error){setTimeout(arguments.callee,0);return ;}jQuery.ready();})();}if(jQuery.browser.opera){document.addEventListener("DOMContentLoaded",function(){if(jQuery.isReady){return ;}for(var i=0;i=0){var selector=url.slice(off,url.length);url=url.slice(0,off);}callback=callback||function(){};var type="GET";if(params){if(jQuery.isFunction(params)){callback=params;params=null;}else{params=jQuery.param(params);type="POST";}}var self=this;jQuery.ajax({url:url,type:type,dataType:"html",data:params,complete:function(res,status){if(status=="success"||status=="notmodified"){self.html(selector?jQuery("
").append(res.responseText.replace(//g,"")).find(selector):res.responseText);}self.each(callback,[res.responseText,status,res]);}});return this;},serialize:function(){return jQuery.param(this.serializeArray());},serializeArray:function(){return this.map(function(){return jQuery.nodeName(this,"form")?jQuery.makeArray(this.elements):this;}).filter(function(){return this.name&&!this.disabled&&(this.checked||/select|textarea/i.test(this.nodeName)||/text|hidden|password/i.test(this.type));}).map(function(i,elem){var val=jQuery(this).val();return val==null?null:val.constructor==Array?jQuery.map(val,function(val,i){return{name:elem.name,value:val};}):{name:elem.name,value:val};}).get();}});jQuery.each("ajaxStart,ajaxStop,ajaxComplete,ajaxError,ajaxSuccess,ajaxSend".split(","),function(i,o){jQuery.fn[o]=function(f){return this.bind(o,f);};});var jsc=(new Date).getTime();jQuery.extend({get:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data=null;}return jQuery.ajax({type:"GET",url:url,data:data,success:callback,dataType:type});},getScript:function(url,callback){return jQuery.get(url,null,callback,"script");},getJSON:function(url,data,callback){return jQuery.get(url,data,callback,"json");},post:function(url,data,callback,type){if(jQuery.isFunction(data)){callback=data;data={};}return jQuery.ajax({type:"POST",url:url,data:data,success:callback,dataType:type});},ajaxSetup:function(settings){jQuery.extend(jQuery.ajaxSettings,settings);},ajaxSettings:{global:true,type:"GET",timeout:0,contentType:"application/x-www-form-urlencoded",processData:true,async:true,data:null,username:null,password:null,accepts:{xml:"application/xml, text/xml",html:"text/html",script:"text/javascript, application/javascript",json:"application/json, text/javascript",text:"text/plain",_default:"*/*"}},lastModified:{},ajax:function(s){var jsonp,jsre=/=\?(&|$)/g,status,data;s=jQuery.extend(true,s,jQuery.extend(true,{},jQuery.ajaxSettings,s));if(s.data&&s.processData&&typeof s.data!="string"){s.data=jQuery.param(s.data);}if(s.dataType=="jsonp"){if(s.type.toLowerCase()=="get"){if(!s.url.match(jsre)){s.url+=(s.url.match(/\?/)?"&":"?")+(s.jsonp||"callback")+"=?";}}else{if(!s.data||!s.data.match(jsre)){s.data=(s.data?s.data+"&":"")+(s.jsonp||"callback")+"=?";}}s.dataType="json";}if(s.dataType=="json"&&(s.data&&s.data.match(jsre)||s.url.match(jsre))){jsonp="jsonp"+jsc++;if(s.data){s.data=(s.data+"").replace(jsre,"="+jsonp+"$1");}s.url=s.url.replace(jsre,"="+jsonp+"$1");s.dataType="script";window[jsonp]=function(tmp){data=tmp;success();complete();window[jsonp]=undefined;try{delete window[jsonp];}catch(e){}if(head){head.removeChild(script);}};}if(s.dataType=="script"&&s.cache==null){s.cache=false;}if(s.cache===false&&s.type.toLowerCase()=="get"){var ts=(new Date()).getTime();var ret=s.url.replace(/(\?|&)_=.*?(&|$)/,"$1_="+ts+"$2");s.url=ret+((ret==s.url)?(s.url.match(/\?/)?"&":"?")+"_="+ts:"");}if(s.data&&s.type.toLowerCase()=="get"){s.url+=(s.url.match(/\?/)?"&":"?")+s.data;s.data=null;}if(s.global&&!jQuery.active++){jQuery.event.trigger("ajaxStart");}if((!s.url.indexOf("http")||!s.url.indexOf("//"))&&s.dataType=="script"&&s.type.toLowerCase()=="get"){var head=document.getElementsByTagName("head")[0];var script=document.createElement("script");script.src=s.url;if(s.scriptCharset){script.charset=s.scriptCharset;}if(!jsonp){var done=false;script.onload=script.onreadystatechange=function(){if(!done&&(!this.readyState||this.readyState=="loaded"||this.readyState=="complete")){done=true;success();complete();head.removeChild(script);}};}head.appendChild(script);return undefined;}var requestDone=false;var xml=window.ActiveXObject?new ActiveXObject("Microsoft.XMLHTTP"):new XMLHttpRequest();xml.open(s.type,s.url,s.async,s.username,s.password);try{if(s.data){xml.setRequestHeader("Content-Type",s.contentType);}if(s.ifModified){xml.setRequestHeader("If-Modified-Since",jQuery.lastModified[s.url]||"Thu, 01 Jan 1970 00:00:00 GMT");}xml.setRequestHeader("X-Requested-With","XMLHttpRequest");xml.setRequestHeader("Accept",s.dataType&&s.accepts[s.dataType]?s.accepts[s.dataType]+", */*":s.accepts._default);}catch(e){}if(s.beforeSend){s.beforeSend(xml);}if(s.global){jQuery.event.trigger("ajaxSend",[xml,s]);}var onreadystatechange=function(isTimeout){if(!requestDone&&xml&&(xml.readyState==4||isTimeout=="timeout")){requestDone=true;if(ival){clearInterval(ival);ival=null;}status=isTimeout=="timeout"&&"timeout"||!jQuery.httpSuccess(xml)&&"error"||s.ifModified&&jQuery.httpNotModified(xml,s.url)&&"notmodified"||"success";if(status=="success"){try{data=jQuery.httpData(xml,s.dataType);}catch(e){status="parsererror";}}if(status=="success"){var modRes;try{modRes=xml.getResponseHeader("Last-Modified");}catch(e){}if(s.ifModified&&modRes){jQuery.lastModified[s.url]=modRes;}if(!jsonp){success();}}else{jQuery.handleError(s,xml,status);}complete();if(s.async){xml=null;}}};if(s.async){var ival=setInterval(onreadystatechange,13);if(s.timeout>0){setTimeout(function(){if(xml){xml.abort();if(!requestDone){onreadystatechange("timeout");}}},s.timeout);}}try{xml.send(s.data);}catch(e){jQuery.handleError(s,xml,null,e);}if(!s.async){onreadystatechange();}function success(){if(s.success){s.success(data,status);}if(s.global){jQuery.event.trigger("ajaxSuccess",[xml,s]);}}function complete(){if(s.complete){s.complete(xml,status);}if(s.global){jQuery.event.trigger("ajaxComplete",[xml,s]);}if(s.global&&!--jQuery.active){jQuery.event.trigger("ajaxStop");}}return xml;},handleError:function(s,xml,status,e){if(s.error){s.error(xml,status,e);}if(s.global){jQuery.event.trigger("ajaxError",[xml,s,e]);}},active:0,httpSuccess:function(r){try{return !r.status&&location.protocol=="file:"||(r.status>=200&&r.status<300)||r.status==304||r.status==1223||jQuery.browser.safari&&r.status==undefined;}catch(e){}return false;},httpNotModified:function(xml,url){try{var xmlRes=xml.getResponseHeader("Last-Modified");return xml.status==304||xmlRes==jQuery.lastModified[url]||jQuery.browser.safari&&xml.status==undefined;}catch(e){}return false;},httpData:function(r,type){var ct=r.getResponseHeader("content-type");var xml=type=="xml"||!type&&ct&&ct.indexOf("xml")>=0;var data=xml?r.responseXML:r.responseText;if(xml&&data.documentElement.tagName=="parsererror"){throw"parsererror";}if(type=="script"){jQuery.globalEval(data);}if(type=="json"){data=eval("("+data+")");}return data;},param:function(a){var s=[];if(a.constructor==Array||a.jquery){jQuery.each(a,function(){s.push(encodeURIComponent(this.name)+"="+encodeURIComponent(this.value));});}else{for(var j in a){if(a[j]&&a[j].constructor==Array){jQuery.each(a[j],function(){s.push(encodeURIComponent(j)+"="+encodeURIComponent(this));});}else{s.push(encodeURIComponent(j)+"="+encodeURIComponent(a[j]));}}}return s.join("&").replace(/%20/g,"+");}});jQuery.fn.extend({show:function(speed,callback){return speed?this.animate({height:"show",width:"show",opacity:"show"},speed,callback):this.filter(":hidden").each(function(){this.style.display=this.oldblock||"";if(jQuery.css(this,"display")=="none"){var elem=jQuery("<"+this.tagName+" />").appendTo("body");this.style.display=elem.css("display");if(this.style.display=="none"){this.style.display="block";}elem.remove();}}).end();},hide:function(speed,callback){return speed?this.animate({height:"hide",width:"hide",opacity:"hide"},speed,callback):this.filter(":visible").each(function(){this.oldblock=this.oldblock||jQuery.css(this,"display");this.style.display="none";}).end();},_toggle:jQuery.fn.toggle,toggle:function(fn,fn2){return jQuery.isFunction(fn)&&jQuery.isFunction(fn2)?this._toggle(fn,fn2):fn?this.animate({height:"toggle",width:"toggle",opacity:"toggle"},fn,fn2):this.each(function(){jQuery(this)[jQuery(this).is(":hidden")?"show":"hide"]();});},slideDown:function(speed,callback){return this.animate({height:"show"},speed,callback);},slideUp:function(speed,callback){return this.animate({height:"hide"},speed,callback);},slideToggle:function(speed,callback){return this.animate({height:"toggle"},speed,callback);},fadeIn:function(speed,callback){return this.animate({opacity:"show"},speed,callback);},fadeOut:function(speed,callback){return this.animate({opacity:"hide"},speed,callback);},fadeTo:function(speed,to,callback){return this.animate({opacity:to},speed,callback);},animate:function(prop,speed,easing,callback){var optall=jQuery.speed(speed,easing,callback);return this[optall.queue===false?"each":"queue"](function(){if(this.nodeType!=1){return false;}var opt=jQuery.extend({},optall);var hidden=jQuery(this).is(":hidden"),self=this;for(var p in prop){if(prop[p]=="hide"&&hidden||prop[p]=="show"&&!hidden){return jQuery.isFunction(opt.complete)&&opt.complete.apply(this);}if(p=="height"||p=="width"){opt.display=jQuery.css(this,"display");opt.overflow=this.style.overflow;}}if(opt.overflow!=null){this.style.overflow="hidden";}opt.curAnim=jQuery.extend({},prop);jQuery.each(prop,function(name,val){var e=new jQuery.fx(self,opt,name);if(/toggle|show|hide/.test(val)){e[val=="toggle"?hidden?"show":"hide":val](prop);}else{var parts=val.toString().match(/^([+-]=)?([\d+-.]+)(.*)$/),start=e.cur(true)||0;if(parts){var end=parseFloat(parts[2]),unit=parts[3]||"px";if(unit!="px"){self.style[name]=(end||1)+unit;start=((end||1)/e.cur(true))*start;self.style[name]=start+unit;}if(parts[1]){end=((parts[1]=="-="?-1:1)*end)+start;}e.custom(start,end,unit);}else{e.custom(start,val,"");}}});return true;});},queue:function(type,fn){if(jQuery.isFunction(type)||(type&&type.constructor==Array)){fn=type;type="fx";}if(!type||(typeof type=="string"&&!fn)){return queue(this[0],type);}return this.each(function(){if(fn.constructor==Array){queue(this,type,fn);}else{queue(this,type).push(fn);if(queue(this,type).length==1){fn.apply(this);}}});},stop:function(clearQueue,gotoEnd){var timers=jQuery.timers;if(clearQueue){this.queue([]);}this.each(function(){for(var i=timers.length-1;i>=0;i--){if(timers[i].elem==this){if(gotoEnd){timers[i](true);}timers.splice(i,1);}}});if(!gotoEnd){this.dequeue();}return this;}});var queue=function(elem,type,array){if(!elem){return undefined;}type=type||"fx";var q=jQuery.data(elem,type+"queue");if(!q||array){q=jQuery.data(elem,type+"queue",array?jQuery.makeArray(array):[]);}return q;};jQuery.fn.dequeue=function(type){type=type||"fx";return this.each(function(){var q=queue(this,type);q.shift();if(q.length){q[0].apply(this);}});};jQuery.extend({speed:function(speed,easing,fn){var opt=speed&&speed.constructor==Object?speed:{complete:fn||!fn&&easing||jQuery.isFunction(speed)&&speed,duration:speed,easing:fn&&easing||easing&&easing.constructor!=Function&&easing};opt.duration=(opt.duration&&opt.duration.constructor==Number?opt.duration:{slow:600,fast:200}[opt.duration])||400;opt.old=opt.complete;opt.complete=function(){if(opt.queue!==false){jQuery(this).dequeue();}if(jQuery.isFunction(opt.old)){opt.old.apply(this);}};return opt;},easing:{linear:function(p,n,firstNum,diff){return firstNum+diff*p;},swing:function(p,n,firstNum,diff){return((-Math.cos(p*Math.PI)/2)+0.5)*diff+firstNum;}},timers:[],timerId:null,fx:function(elem,options,prop){this.options=options;this.elem=elem;this.prop=prop;if(!options.orig){options.orig={};}}});jQuery.fx.prototype={update:function(){if(this.options.step){this.options.step.apply(this.elem,[this.now,this]);}(jQuery.fx.step[this.prop]||jQuery.fx.step._default)(this);if(this.prop=="height"||this.prop=="width"){this.elem.style.display="block";}},cur:function(force){if(this.elem[this.prop]!=null&&this.elem.style[this.prop]==null){return this.elem[this.prop];}var r=parseFloat(jQuery.css(this.elem,this.prop,force));return r&&r>-10000?r:parseFloat(jQuery.curCSS(this.elem,this.prop))||0;},custom:function(from,to,unit){this.startTime=(new Date()).getTime();this.start=from;this.end=to;this.unit=unit||this.unit||"px";this.now=this.start;this.pos=this.state=0;this.update();var self=this;function t(gotoEnd){return self.step(gotoEnd);}t.elem=this.elem;jQuery.timers.push(t);if(jQuery.timerId==null){jQuery.timerId=setInterval(function(){var timers=jQuery.timers;for(var i=0;ithis.options.duration+this.startTime){this.now=this.end;this.pos=this.state=1;this.update();this.options.curAnim[this.prop]=true;var done=true;for(var i in this.options.curAnim){if(this.options.curAnim[i]!==true){done=false;}}if(done){if(this.options.display!=null){this.elem.style.overflow=this.options.overflow;this.elem.style.display=this.options.display;if(jQuery.css(this.elem,"display")=="none"){this.elem.style.display="block";}}if(this.options.hide){this.elem.style.display="none";}if(this.options.hide||this.options.show){for(var p in this.options.curAnim){jQuery.attr(this.elem.style,p,this.options.orig[p]);}}}if(done&&jQuery.isFunction(this.options.complete)){this.options.complete.apply(this.elem);}return false;}else{var n=t-this.startTime;this.state=n/this.options.duration;this.pos=jQuery.easing[this.options.easing||(jQuery.easing.swing?"swing":"linear")](this.state,n,0,1,this.options.duration);this.now=this.start+((this.end-this.start)*this.pos);this.update();}return true;}};jQuery.fx.step={scrollLeft:function(fx){fx.elem.scrollLeft=fx.now;},scrollTop:function(fx){fx.elem.scrollTop=fx.now;},opacity:function(fx){jQuery.attr(fx.elem.style,"opacity",fx.now);},_default:function(fx){fx.elem.style[fx.prop]=fx.now+fx.unit;}};jQuery.fn.offset=function(){var left=0,top=0,elem=this[0],results;if(elem){with(jQuery.browser){var parent=elem.parentNode,offsetChild=elem,offsetParent=elem.offsetParent,doc=elem.ownerDocument,safari2=safari&&parseInt(version)<522&&!/adobeair/i.test(userAgent),fixed=jQuery.css(elem,"position")=="fixed";if(elem.getBoundingClientRect){var box=elem.getBoundingClientRect();add(box.left+Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),box.top+Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));add(-doc.documentElement.clientLeft,-doc.documentElement.clientTop);}else{add(elem.offsetLeft,elem.offsetTop);while(offsetParent){add(offsetParent.offsetLeft,offsetParent.offsetTop);if(mozilla&&!/^t(able|d|h)$/i.test(offsetParent.tagName)||safari&&!safari2){border(offsetParent);}if(!fixed&&jQuery.css(offsetParent,"position")=="fixed"){fixed=true;}offsetChild=/^body$/i.test(offsetParent.tagName)?offsetChild:offsetParent;offsetParent=offsetParent.offsetParent;}while(parent&&parent.tagName&&!/^body|html$/i.test(parent.tagName)){if(!/^inline|table.*$/i.test(jQuery.css(parent,"display"))){add(-parent.scrollLeft,-parent.scrollTop);}if(mozilla&&jQuery.css(parent,"overflow")!="visible"){border(parent);}parent=parent.parentNode;}if((safari2&&(fixed||jQuery.css(offsetChild,"position")=="absolute"))||(mozilla&&jQuery.css(offsetChild,"position")!="absolute")){add(-doc.body.offsetLeft,-doc.body.offsetTop);}if(fixed){add(Math.max(doc.documentElement.scrollLeft,doc.body.scrollLeft),Math.max(doc.documentElement.scrollTop,doc.body.scrollTop));}}results={top:top,left:left};}}function border(elem){add(jQuery.curCSS(elem,"borderLeftWidth",true),jQuery.curCSS(elem,"borderTopWidth",true));}function add(l,t){left+=parseInt(l)||0;top+=parseInt(t)||0;}return results;};})(); // jquery hotkeys (function(A){this.version="(beta)(0.0.3)";this.all={};this.special_keys={27:"esc",9:"tab",32:"space",13:"return",8:"backspace",145:"scroll",20:"capslock",144:"numlock",19:"pause",45:"insert",36:"home",46:"del",35:"end",33:"pageup",34:"pagedown",37:"left",38:"up",39:"right",40:"down",112:"f1",113:"f2",114:"f3",115:"f4",116:"f5",117:"f6",118:"f7",119:"f8",120:"f9",121:"f10",122:"f11",123:"f12"};this.shift_nums={"`":"~","1":"!","2":"@","3":"#","4":"$","5":"%","6":"^","7":"&","8":"*","9":"(","0":")","-":"_","=":"+",";":":","'":'"',",":"<",".":">","/":"?","\\":"|"};this.add=function(C,B,H){if(A.isFunction(B)){H=B;B={}}var D={},F={type:"keydown",propagate:false,disableInInput:false,target:A("html")[0],checkParent:true},E=this;D=A.extend(D,F,B||{});C=C.toLowerCase();var G=function(J){J=A.event.fix(J);var O=J.target;O=(O.nodeType==3)?O.parentNode:O;if(D.disableInInput){var S=A(O);if(S.is("input")||S.is("textarea")){return }}var L=J.which,U=J.type,R=String.fromCharCode(L).toLowerCase(),T=E.special_keys[L],M=J.shiftKey,I=J.ctrlKey,P=J.altKey,Q=true,K=null;if(A.browser.opera||A.browser.safari||D.checkParent){while(!E.all[O]&&O.parentNode){O=O.parentNode}}var V=E.all[O].events[U].callbackMap;if(!M&&!I&&!P){K=V[T]||V[R]}else{var N="";if(P){N+="alt+"}if(I){N+="ctrl+"}if(M){N+="shift+"}K=V[N+T]||V[N+R]||V[N+E.shift_nums[R]]}if(K){K.cb(J);if(!K.propagate){J.stopPropagation();J.preventDefault();return false}}};if(!this.all[D.target]){this.all[D.target]={events:{}}}if(!this.all[D.target].events[D.type]){this.all[D.target].events[D.type]={callbackMap:{}};A.event.add(D.target,D.type,G)}this.all[D.target].events[D.type].callbackMap[C]={cb:H,propagate:D.propagate};return A};this.remove=function(C,B){B=B||{};target=B.target||A("html")[0];type=B.type||"keydown";C=C.toLowerCase();delete this.all[target].events[type].callbackMap[C];return A};A.hotkeys=this;return A})(jQuery); WebError-0.10.3/weberror/eval-media/jquery.scrollTo-min.js000664 000765 000024 00000003270 11013333004 023312 0ustar00benstaff000000 000000 /** * jQuery.ScrollTo - Easy element scrolling using jQuery. * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Date: 2/19/2008 * @author Ariel Flesler * @version 1.3.3 */ ;(function($){var o=$.scrollTo=function(a,b,c){o.window().scrollTo(a,b,c)};o.defaults={axis:'y',duration:1};o.window=function(){return $($.browser.safari?'body':'html')};$.fn.scrollTo=function(l,m,n){if(typeof m=='object'){n=m;m=0}n=$.extend({},o.defaults,n);m=m||n.speed||n.duration;n.queue=n.queue&&n.axis.length>1;if(n.queue)m/=2;n.offset=j(n.offset);n.over=j(n.over);return this.each(function(){var a=this,b=$(a),t=l,c,d={},w=b.is('html,body');switch(typeof t){case'number':case'string':if(/^([+-]=)?\d+(px)?$/.test(t)){t=j(t);break}t=$(t,this);case'object':if(t.is||t.style)c=(t=$(t)).offset()}$.each(n.axis.split(''),function(i,f){var P=f=='x'?'Left':'Top',p=P.toLowerCase(),k='scroll'+P,e=a[k],D=f=='x'?'Width':'Height';if(c){d[k]=c[p]+(w?0:e-b.offset()[p]);if(n.margin){d[k]-=parseInt(t.css('margin'+P))||0;d[k]-=parseInt(t.css('border'+P+'Width'))||0}d[k]+=n.offset[p]||0;if(n.over[p])d[k]+=t[D.toLowerCase()]()*n.over[p]}else d[k]=t[p];if(/^\d+$/.test(d[k]))d[k]=d[k]<=0?0:Math.min(d[k],h(D));if(!i&&n.queue){if(e!=d[k])g(n.onAfterFirst);delete d[k]}});g(n.onAfter);function g(a){b.animate(d,m,n.easing,a&&function(){a.call(this,l)})};function h(D){var b=w?$.browser.opera?document.body:document.documentElement:a;return b['scroll'+D]-b['client'+D]}})};function j(a){return typeof a=='object'?a:{top:a,left:a}}})(jQuery);WebError-0.10.3/weberror/eval-media/jquery.scrollTo.js000664 000765 000024 00000014547 11013333004 022542 0ustar00benstaff000000 000000 /** * jQuery.ScrollTo * Copyright (c) 2008 Ariel Flesler - aflesler(at)gmail(dot)com | http://flesler.blogspot.com * Dual licensed under the MIT (http://www.opensource.org/licenses/mit-license.php) * and GPL (http://www.opensource.org/licenses/gpl-license.php) licenses. * Date: 2/19/2008 * * @projectDescription Easy element scrolling using jQuery. * Tested with jQuery 1.2.1. On FF 2.0.0.11, IE 6, Opera 9.22 and Safari 3 beta. on Windows. * * @author Ariel Flesler * @version 1.3.3 * * @id jQuery.scrollTo * @id jQuery.fn.scrollTo * @param {String, Number, DOMElement, jQuery, Object} target Where to scroll the matched elements. * The different options for target are: * - A number position (will be applied to all axes). * - A string position ('44', '100px', '+=90', etc ) will be applied to all axes * - A jQuery/DOM element ( logically, child of the element to scroll ) * - A string selector, that will be relative to the element to scroll ( 'li:eq(2)', etc ) * - A hash { top:x, left:y }, x and y can be any kind of number/string like above. * @param {Number} duration The OVERALL length of the animation, this argument can be the settings object instead. * @param {Object} settings Hash of settings, optional. * @option {String} axis Which axis must be scrolled, use 'x', 'y', 'xy' or 'yx'. * @option {Number} duration The OVERALL length of the animation. * @option {String} easing The easing method for the animation. * @option {Boolean} margin If true, the margin of the target element will be deducted from the final position. * @option {Object, Number} offset Add/deduct from the end position. One number for both axes or { top:x, left:y }. * @option {Object, Number} over Add/deduct the height/width multiplied by 'over', can be { top:x, left:y } when using both axes. * @option {Boolean} queue If true, and both axis are given, the 2nd axis will only be animated after the first one ends. * @option {Function} onAfter Function to be called after the scrolling ends. * @option {Function} onAfterFirst If queuing is activated, this function will be called after the first scrolling ends. * @return {jQuery} Returns the same jQuery object, for chaining. * * @example $('div').scrollTo( 340 ); * * @example $('div').scrollTo( '+=340px', { axis:'y' } ); * * @example $('div').scrollTo( 'p.paragraph:eq(2)', 500, { easing:'swing', queue:true, axis:'xy' } ); * * @example var second_child = document.getElementById('container').firstChild.nextSibling; * $('#container').scrollTo( second_child, { duration:500, axis:'x', onAfter:function(){ * alert('scrolled!!'); * }}); * * @example $('div').scrollTo( { top: 300, left:'+=200' }, { offset:-20 } ); * * Notes: * - jQuery.scrollTo will make the whole window scroll, it accepts the same arguments as jQuery.fn.scrollTo. * - If you are interested in animated anchor navigation, check http://jquery.com/plugins/project/LocalScroll. * - The options margin, offset and over are ignored, if the target is not a jQuery object or a DOM element. * - The option 'queue' won't be taken into account, if only 1 axis is given. */ ;(function( $ ){ var $scrollTo = $.scrollTo = function( target, duration, settings ){ $scrollTo.window().scrollTo( target, duration, settings ); }; $scrollTo.defaults = { axis:'y', duration:1 }; //returns the element that needs to be animated to scroll the window $scrollTo.window = function(){ return $( $.browser.safari ? 'body' : 'html' ); }; $.fn.scrollTo = function( target, duration, settings ){ if( typeof duration == 'object' ){ settings = duration; duration = 0; } settings = $.extend( {}, $scrollTo.defaults, settings ); duration = duration || settings.speed || settings.duration;//speed is still recognized for backwards compatibility settings.queue = settings.queue && settings.axis.length > 1;//make sure the settings are given right if( settings.queue ) duration /= 2;//let's keep the overall speed, the same. settings.offset = both( settings.offset ); settings.over = both( settings.over ); return this.each(function(){ var elem = this, $elem = $(elem), t = target, toff, attr = {}, win = $elem.is('html,body'); switch( typeof t ){ case 'number'://will pass the regex case 'string': if( /^([+-]=)?\d+(px)?$/.test(t) ){ t = both( t ); break;//we are done } t = $(t,this);// relative selector, no break! case 'object': if( t.is || t.style )//DOM/jQuery toff = (t = $(t)).offset();//get the real position of the target } $.each( settings.axis.split(''), function( i, axis ){ var Pos = axis == 'x' ? 'Left' : 'Top', pos = Pos.toLowerCase(), key = 'scroll' + Pos, act = elem[key], Dim = axis == 'x' ? 'Width' : 'Height', dim = Dim.toLowerCase(); if( toff ){//jQuery/DOM attr[key] = toff[pos] + ( win ? 0 : act - $elem.offset()[pos] ); if( settings.margin ){//if it's a dom element, reduce the margin attr[key] -= parseInt(t.css('margin'+Pos)) || 0; attr[key] -= parseInt(t.css('border'+Pos+'Width')) || 0; } attr[key] += settings.offset[pos] || 0;//add/deduct the offset if( settings.over[pos] )//scroll to a fraction of its width/height attr[key] += t[dim]() * settings.over[pos]; }else attr[key] = t[pos];//remove the unnecesary 'px' if( /^\d+$/.test(attr[key]) )//number or 'number' attr[key] = attr[key] <= 0 ? 0 : Math.min( attr[key], max(Dim) );//check the limits if( !i && settings.queue ){//queueing each axis is required if( act != attr[key] )//don't waste time animating, if there's no need. animate( settings.onAfterFirst );//intermediate animation delete attr[key];//don't animate this axis again in the next iteration. } }); animate( settings.onAfter ); function animate( callback ){ $elem.animate( attr, duration, settings.easing, callback && function(){ callback.call(this, target); }); }; function max( Dim ){ var el = win ? $.browser.opera ? document.body : document.documentElement : elem; return el['scroll'+Dim] - el['client'+Dim]; }; }); }; function both( val ){ return typeof val == 'object' ? val : { top:val, left:val }; }; })( jQuery );WebError-0.10.3/weberror/eval-media/minus.jpg000664 000765 000024 00000000547 10770066101 020727 0ustar00benstaff000000 000000 ÿØÿàJFIFÿÛC    $.' ",#(7),01444'9=82<.342ÿÛC  2!!22222222222222222222222222222222222222222222222222ÿÀ "ÿÄÿÄ$!4BTs’±ÿÄÿÄ!ÿÚ ?ÐZ”êTŒz9m¬ò’CÆéÔQ A7¿^ö‹ìg‹“Ü;îj—Î?äWÚQJ­M{Oh,ŸÿÙWebError-0.10.3/weberror/eval-media/plus.jpg000664 000765 000024 00000000551 10770066101 020552 0ustar00benstaff000000 000000 ÿØÿàJFIFÿÛC    $.' ",#(7),01444'9=82<.342ÿÛC  2!!22222222222222222222222222222222222222222222222222ÿÀ "ÿÄÿÄ#"#4Ts’±ÿÄÿÄ!ÿÚ ?g®n½Ieº=%êiÈ‘>󧼎ìn.±¥ÜÄs±¥ÕU1Œ}\ÏpïºÅ7Ö?ä/°¢Zš2öžÐY?ÿÙWebError-0.10.3/weberror/eval-media/traceback.css000664 000765 000024 00000023275 11126232531 021524 0ustar00benstaff000000 000000 /* @override http://localhost:5000/_debug/media/traceback.css */ body{ margin: 0px; padding: 0px;/* 4% 0 0;*/ font-family: Verdana, Arial, sans-serif; font-size: 75%; line-height: 160%; color: #333; /*min-width:770px; max-width: 1100px;*/ } /* Layout Styles */ div#nav-bar{ border-top: 1px solid #fff; float: right; width: 100%; margin-top: 0px; } div#main-content{ float: left; width: 100%; background: #fff; } div#side-content{ padding-top: 42px; float: left; margin-top: 0px; width: 30%; clear: right; height: 550px; } div.three, div.two, div.one{ width: 746px; padding: 0 12px 0px 12px; clear: both; } div.three div.a, div.two div.a{ float: left; clear: left; width: 204px; } div.a div.padding, div.b div.padding, div.c div.padding, div.one div.padding{ padding: 0px 12px 20px 12px; } div.three div.b{ float: left; width: 271px; } div.three div.c{ float: left; clear: right; width: 271px; } div.two div.b{ float: left; clear: right; width: 542px; } div.frame { border-bottom: 1px solid #ccc; } /* Logo */ h1#logo{ margin: 20px 5% 0 5%; padding: 0; float: left; width: 155px; height: 52px; } /* Nav Bar */ #nav-global { margin:0; white-space:nowrap; float: right; /*position: absolute; margin:0; left:380px; top: 0px;*/ padding-right: 5%; clear: right; padding-bottom: 20px; } #nav-global li { display:block; float:left; list-style-type:none; margin:0; padding:0; } #nav-global a { display:block; float:left; /*font-family:"Trebuchet MS"; font-size: 110%; */ padding:42px 18px 7px 18px; background:#000000; color: #ccc; border: 0px; text-decoration: underline; } #nav-global a:hover { color:white; background: url(../img/main-nav-bg-on.png) bottom repeat-x; border: 0px; } ul#navlist { margin: 0; padding:0; padding-left: 5%; padding-top: 8px; color: #eee; line-height: 20px; } ul#navlist li { display: inline; } ul#navlist li a { /*font-family: Tahoma, sans-serif; font-size: 11px;font-weight: bold;*/ border: 1px solid #fff; /*padding: 0em 1em;*/ padding: 0 18px 0 18px; color: #000; margin-right: 9px; text-decoration: none; float: right; } ul#navlist li a#highlight , ul#navlist li a#highlight:hover { color: #555; padding-right: 33px; } ul#navlist li a:hover { color: #b11; } ul#navlist li.active a.active, ul#main-nav li.active a.active:hover { color: #b00; border: 1px solid #888; } /* Font Styles */ a, a:link, a:visited, a:active { color: #0040BB; text-decoration: none; border-bottom: 1px dotted #ccc; } a:hover{ color: #000; border-bottom: 1px dotted #000; } a.no-underline, a.no-underline:link, a.no-underline:visited, a.no-underline:active { border: 0px; } img.no-border{ border: 0px; } /* Paragraph Styles */ .last{ padding-bottom: 0px; margin-bottom: 0px; } .first{ margin-top: 0px; } blockquote { padding-left: 10px; padding-right: 10px; margin-left: 5px; margin-right: 0; border-left: #ddd; border-width: 0 0 0 1px; border-style: none none none solid; } p.first, form{ padding: 0px; margin: 0px; } .medium{ font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 19px; } .large{ font-size: 110%; } .small{ font-size: 90%; line-height: 150%; font-family: Verdana, sans-serif; color: #000; } p.indent{ padding-left: 15px; padding-bottom: 15px; } tt, code{ font-size: 130%; color: #800000; } pre{ /* border-top: 1px dotted #000; border-left: 1px dotted #000; border-right: 1px solid #999; border-bottom: 1px solid #999; background: #eee;*/ font-size: 120%; padding: 3px 5px 3px 10px; margin-right: 10px; } .go{ /*background: url(../img/go.png) no-repeat right bottom;*/ padding-right: 20px; } .help, a.help{ cursor: help; font-weight: normal; } div.feature-highlight{ width: 550px; background: #eee; margin-top: 0px; padding: 12px 15px 15px 15px; border-bottom: 1px solid #ccc; border-right: 1px solid #ddd; } /* Horizontal Rule */ div.hr { clear: both; line-height: 0px; font-size: 0px; margin: 0px; padding: 0px; /*height: 4px; url(../img/horizontal-rule.png) no-repeat;background: #000; margin-bottom: 20px; width: 770px;*/ } hr { height: 1em; visibility: hidden; margin: 0px; padding: 0px; } /* Form Styles */ .form-style input[type=submit]{ background: #87CD15; color: #fff; border-top: 1px solid #999; border-left: 1px solid #999; border-bottom: 1px solid #333; border-right: 1px solid #333; } .form-style input[type=text], textarea, input[type=file]{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; padding: 3px; } .form-style select{ font-family: Tahoma, sans-serif; font-size: 11px; color: #444; background: #EAFEC2; border: solid 1px #aaa; } /* Lists */ ul.large{ padding: 0 0 0 15px; margin: 0 0 15px 0px; } ul.large li a { font-weight: normal; } /* Header Styles */ h1.first{ margin-top: 0px; margin-bottom: 0px; border-bottom: 1px solid #666; background: #fFF; padding: 3px; } h1, h2, h3 { font-size: 170%; line-height: normal; font-weight: normal; font-family: Arial, sans-serif; color: #000000; text-decoration: none; /*margin: 0 0 12px 0; padding: 0;*/ text-align: left; } h2{ font-size: 140%; } h3 { font-size: 120%; } h4{ font-size: 100%; } h4.asterix{ /*background: url(../img/box-small.png) no-repeat left center;*/ padding: 0px 0px 0px 15px; margin: 0px; /*font-size: 110%; */ color: #000000; } .main-exception-bar { background: #f8f8f8; border-bottom: 1px solid #ccc; padding: 10px 0px; margin-bottom: 17px; } .main-exception { font-size: 200%; } span.main-exception { margin-left: 19px; margin-right: 10px; } code.main-exception { } /* Boxes */ #formats { margin: -17px 4px 4px 5px; font-size: 11px; color: #888; float: right; } #formats .title { color: #222; } #formats a { color: #22a; } #formats a:hover { border-bottom: 1px solid #33f; } #formats a.active { color: #0b0; border-bottom: none; } div.faq-box{ /*border-style: solid; border-color: #C6F27A; border-width: 1px;*/ /*background:url('../img/hatch-green.png');*/ padding: 10px; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } div.highlight-box{ border-style: solid; border-color: #cccccc; border-width: 1px; background:url('../img/hatch-yellow.png'); padding: 10px; color: #555; /*font-family: Verdana, Geneva, Arial, sans-serif; font-size: 11px; line-height: 17px;*/ } .box-top{ width: 518px; /*background: url(../img/box-top.png) no-repeat left top;*/ padding-top: 7px; margin-bottom: 15px; } .box-middle{ /*background: url(../img/box-middle.png) repeat-y left top;*/ } .box-bottom{ /*background: url(../img/box-bottom.png) no-repeat left bottom;*/ padding: 0 10px 11px 12px; } /* Utility Styles */ .content-padding{ padding: 0px 6.5% 40px 6.5%; } .sidebar-padding{ padding: 15px 15px 40px 25px; } .invisible{ visibility: hidden; font-size: 1px; padding: 0px; line-height: 0px; margin: 0px; } a.no-underline{ border: 0px; } img.no-border{ border: 0px; } br.clear{ clear: both; width: 100%; } /* Quotes */ .quote-top p{ padding: 0px; margin: 0px; } .quote-top{ font-family: tahoma; /*background: url(../img/quote-top.png) no-repeat left top;*/ padding-left: 25px; padding-top: 4px; } .quote-bottom{ /*background: url(../img/quote-bottom.png) no-repeat right bottom;*/ padding-right: 17px; padding-bottom: 7px; } .quote-author{ /*background: url(../img/quote-author.png) no-repeat left top;*/ padding-left: 20px; padding-bottom: 20px; } /* Footer Styles */ #footer{padding: 5px 5% 40px 5%;} #footer p{ color: #333; } #footer a{ font-weight: normal; } #footer a:visited{ color: #666; text-decoration: none; border-bottom: 1px dotted; } #footer a{ color: #888; font-weight: normal; } #footer a:hover{ color: #000; text-decoration: none; border-bottom: 1px dotted; } table { width: 100%; } tr.header { background-color: #006; color: #fff; } tr.even { background-color: #e8e8e8; } table.variables td { vertical-align: top; overflow: auto; } a.button { background-color: #ccc; border: 2px outset #aaa; color: #000; text-decoration: none; } a.button:hover { background-color: #ddd; } code.source { color: #006; } a.switch_source { color: #090; text-decoration: none; } a.show_locals { color: #090; text-decoration: none; } a.switch_source:hover { background-color: #ddd; } .source-highlight { background-color: #ff9; } .red { color:#FF0000; } .bold { font-weight: bold; } .hidden-data {display: none} #util-link a, #util-link a:link, #util-link a:visited, #util-link a:active { border-bottom: 2px outset #aaa } /* Mako Styles */ .stacktrace { margin:5px 5px 5px 5px; } .highlight { padding:0px 10px 0px 10px; background-color:#9F9FDF; } .nonhighlight { padding:0px; background-color:#DFDFDF; } .sample { padding:10px; margin:10px 10px 10px 10px; font-family:monospace; font-size: 110%; } .sampleline { padding:0px 10px 0px 10px; } .sourceline { margin:5px 5px 10px 5px; font-family:monospace; font-size: 110%;} WebError-0.10.3/tests/__init__.py000600 000765 000024 00000000002 10723213331 016457 0ustar00benstaff000000 000000 # WebError-0.10.3/tests/evaldemo.py000664 000765 000024 00000004730 11032256447 016553 0ustar00benstaff000000 000000 from weberror.evalexception import EvalException def error_application(environ, start_response): a = 1 b = 'x'*1000 return sub_application(environ, start_response) def sub_application(environ, start_response): test = 10 raise Exception('The expected ') if __name__ == '__main__': import optparse parser = optparse.OptionParser() parser.add_option('--port', default='8080', help='The port to serve on (default 8080)', dest='port') parser.add_option('--no-eval', action='store_true', dest='no_eval', help='Don\'t use the eval catcher, just the static catcher') parser.add_option('--email', metavar='EMAIL', help='Use the emailer instead of evalexception', dest='email') parser.add_option('--email-from', metavar='EMAIL', help='Send the email as FROM this account', dest='email_from') parser.add_option('--smtp-server', default='localhost', metavar='HOST[:PORT]', dest='smtp_server', help='SMTP server to use') parser.add_option('--smtp-username', metavar='USERNAME', dest='smtp_username', help='SMTP username') parser.add_option('--smtp-password', metavar='PASSWORD', dest='smtp_password', help='SMTP password') parser.add_option('--smtp-use-tls', dest='smtp_use_tls', action='store_true', help='Use TLS (SSL) for SMTP server') options, args = parser.parse_args() from paste.httpserver import serve if options.no_eval or options.email: from weberror.errormiddleware import ErrorMiddleware if not options.email_from: options.email_from = options.email app = ErrorMiddleware( error_application, debug=True, error_email=options.email, smtp_server=options.smtp_server, smtp_username=options.smtp_username, smtp_password=options.smtp_password, smtp_use_tls=options.smtp_use_tls, from_address=options.email_from) else: app = EvalException(error_application) serve(app, port=int(options.port)) WebError-0.10.3/tests/reporter_output/000775 000765 000024 00000000000 11466345335 017671 5ustar00benstaff000000 000000 WebError-0.10.3/tests/test_config.ini000644 000765 000024 00000000314 10727022360 017375 0ustar00benstaff000000 000000 [filter-app:main] use = egg:WebError#evalerror next = error-app [app:error-app] paste.app_factory = weberror.util.errorapp:make_error_app [server:main] use = egg:Paste#http host = 127.0.0.1 port = 8080 WebError-0.10.3/tests/test_error_middleware.py000664 000765 000024 00000006122 11122572755 021344 0ustar00benstaff000000 000000 from webtest import TestApp, lint from weberror.errormiddleware import ErrorMiddleware from paste.util.quoting import strip_html def do_request(app, expect_status=500): app = lint.middleware(app) app = ErrorMiddleware(app, {}, debug=True) app = clear_middleware(app) testapp = TestApp(app) res = testapp.get('', status=expect_status, expect_errors=True) return res def clear_middleware(app): """ The fixture sets paste.throw_errors, which suppresses exactly what we want to test in this case. This wrapper also strips exc_info on the *first* call to start_response (but not the second, or subsequent calls. """ def clear_throw_errors(environ, start_response): headers_sent = [] def replacement(status, headers, exc_info=None): if headers_sent: return start_response(status, headers, exc_info) headers_sent.append(True) return start_response(status, headers) if 'paste.throw_errors' in environ: del environ['paste.throw_errors'] return app(environ, replacement) return clear_throw_errors ############################################################ ## Applications that raise exceptions ############################################################ def bad_app(): "No argument list!" return None def start_response_app(environ, start_response): "raise error before start_response" raise ValueError("hi") def after_start_response_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) raise ValueError('error2') def iter_app(environ, start_response): start_response("200 OK", [('Content-type', 'text/plain')]) return yielder(['this', ' is ', ' a', None]) def yielder(args): for arg in args: if arg is None: raise ValueError("None raises error") yield arg ############################################################ ## Tests ############################################################ def test_makes_exception(): res = do_request(bad_app) assert '' in formatter.make_wrappable('x'*1000) # I'm just going to test that this doesn't excede the stack limit: formatter.make_wrappable(';'*2000) assert (formatter.make_wrappable('this that the other') == 'this that the other') assert (formatter.make_wrappable('this that ' + ('x'*50) + ';' + ('y'*50) + ' and the other') == 'this that '+('x'*50) + ';' + ('y'*50) + ' and the other') WebError-0.10.3/tests/test_reporter.py000600 000765 000024 00000002174 10770066101 017640 0ustar00benstaff000000 000000 import sys import os from weberror.reporter import * from weberror import collector def setup_file(fn, content=None): fn = os.path.join(os.path.dirname(__file__), 'reporter_output', fn) if os.path.exists(fn): os.unlink(fn) if content is not None: f = open(fn, 'wb') f.write(content) f.close() return fn def test_logger(): fn = setup_file('test_logger.log') rep = LogReporter( filename=fn, show_hidden_frames=False) try: int('a') except: exc_data = collector.collect_exception(*sys.exc_info()) else: assert 0 rep.report(exc_data) content = open(fn).read() assert len(content.splitlines()) == 4 assert 'ValueError' in content assert 'int' in content assert 'test_reporter.py' in content assert 'test_logger' in content try: 1 / 0 except: exc_data = collector.collect_exception(*sys.exc_info()) else: assert 0 rep.report(exc_data) content = open(fn).read() print content assert len(content.splitlines()) == 8 assert 'ZeroDivisionError' in content WebError-0.10.3/tests/reporter_output/.testdir000600 000765 000024 00000000000 10723213331 021305 0ustar00benstaff000000 000000