text
stringlengths
0
1.05M
meta
dict
__all__ = ["get_centroids"] import numpy as np from .label_clusters import label_clusters from .label_stats import label_stats def get_centroids(image, clustparam=0): """ Reduces a variate/statistical/network image to a set of centroids describing the center of each stand-alone non-zero component in the image ANTsR function: `getCentroids` Arguments --------- image : ANTsImage image from which centroids will be calculated clustparam : integer look at regions greater than or equal to this size Returns ------- ndarray Example ------- >>> import ants >>> image = ants.image_read( ants.get_ants_data( "r16" ) ) >>> image = ants.threshold_image( image, 90, 120 ) >>> image = ants.label_clusters( image, 10 ) >>> cents = ants.get_centroids( image ) """ imagedim = image.dimension if clustparam > 0: mypoints = label_clusters(image, clustparam, max_thresh=1e15) if clustparam == 0: mypoints = image.clone() mypoints = label_stats(mypoints, mypoints) nonzero = mypoints[["LabelValue"]] > 0 mypoints = mypoints[nonzero["LabelValue"]] mypoints = mypoints.iloc[:, :] x = mypoints.x y = mypoints.y if imagedim == 3: z = mypoints.z else: z = np.zeros(mypoints.shape[0]) if imagedim == 4: t = mypoints.t else: t = np.zeros(mypoints.shape[0]) centroids = np.stack([x, y, z, t]).T return centroids
{ "repo_name": "ANTsX/ANTsPy", "path": "ants/utils/get_centroids.py", "copies": "1", "size": "1500", "license": "apache-2.0", "hash": -5582113283343429000, "line_mean": 24.4237288136, "line_max": 77, "alpha_frac": 0.614, "autogenerated": false, "ratio": 3.51288056206089, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.962688056206089, "avg_score": 0, "num_lines": 59 }
__all__ = ["get_config", "get_defaults", "dump_defaults", "get_imagecrawler", "parse_yaml_file", "ImageCrawlerSetupError"] from os.path import dirname, join as path_join, realpath from typing import Any, Dict, Optional from nichtparasoup.core.imagecrawler import BaseImageCrawler _SCHEMA_FILE = realpath(path_join(dirname(__file__), "schema.yaml")) _schema = None # type: Optional[Any] _DEFAULTS_FILE = realpath(path_join(dirname(__file__), "defaults.yaml")) _defaults = None # type: Optional[Dict[str, Any]] class ImageCrawlerSetupError(Exception): def __init__(self, ic_name: str, ic_class: type, ic_config: Dict[Any, Any]) -> None: # pragma: no cover self._name = ic_name self._class = ic_class self._config = ic_config def __str__(self) -> str: # pragma: no cover return 'Failed setup crawler {!r} of type {!r} with config {!r}'.format(self._name, self._class, self._config) def get_imagecrawler(config_crawler: Dict[str, Any]) -> BaseImageCrawler: from nichtparasoup.imagecrawler import get_imagecrawlers imagecrawler_name = config_crawler['name'] imagecrawler_class = get_imagecrawlers().get_class(imagecrawler_name) if not imagecrawler_class: raise ValueError('unknown crawler name {!r}'.format(imagecrawler_name)) imagecrawler_config = config_crawler['config'] try: return imagecrawler_class(**imagecrawler_config) except Exception as e: raise ImageCrawlerSetupError(imagecrawler_name, imagecrawler_class, imagecrawler_config) from e def parse_yaml_file(file_path: str) -> Dict[str, Any]: import yamale # type: ignore global _schema if not _schema: _schema = yamale.make_schema(_SCHEMA_FILE, parser='ruamel') _data = yamale.make_data(file_path, parser='ruamel') yamale.validate(_schema, _data, strict=True) config = _data[0][0] # type: Dict[str, Any] config.setdefault('logging', dict()) config['logging'].setdefault('level', 'INFO') for config_crawler in config['crawlers']: config_crawler.setdefault("weight", 1) config_crawler.setdefault('config', dict()) return config def dump_defaults(file_path: str) -> None: from shutil import copyfile copyfile(_DEFAULTS_FILE, file_path) def get_defaults() -> Dict[str, Any]: global _defaults if not _defaults: _defaults = parse_yaml_file(_DEFAULTS_FILE) from copy import deepcopy return deepcopy(_defaults) def get_config(config_file: Optional[str] = None) -> Dict[str, Any]: if not config_file: return get_defaults() try: return parse_yaml_file(config_file) except Exception as e: raise ValueError('invalid config file {!r}'.format(config_file)) from e
{ "repo_name": "k4cg/nichtparasoup", "path": "nichtparasoup/config/__init__.py", "copies": "1", "size": "2764", "license": "mit", "hash": -1896548258880934700, "line_mean": 35.8533333333, "line_max": 118, "alpha_frac": 0.6751085384, "autogenerated": false, "ratio": 3.530012771392082, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9702621154042945, "avg_score": 0.0005000311498272453, "num_lines": 75 }
__all__ = ['get_config_vars', 'get_path'] try: # Python 2.7 or >=3.2 from sysconfig import get_config_vars, get_path except ImportError: from distutils.sysconfig import get_config_vars, get_python_lib def get_path(name): if name not in ('platlib', 'purelib'): raise ValueError("Name must be purelib or platlib") return get_python_lib(name=='platlib') try: # Python >=3.2 from tempfile import TemporaryDirectory except ImportError: import shutil import tempfile class TemporaryDirectory(object): """" Very simple temporary directory context manager. Will try to delete afterward, but will also ignore OS and similar errors on deletion. """ def __init__(self): self.name = None # Handle mkdtemp raising an exception self.name = tempfile.mkdtemp() def __enter__(self): return self.name def __exit__(self, exctype, excvalue, exctrace): try: shutil.rmtree(self.name, True) except OSError: #removal errors are not the only possible pass self.name = None
{ "repo_name": "SurfasJones/djcmsrc3", "path": "venv/lib/python2.7/site-packages/setuptools/py31compat.py", "copies": "10", "size": "1184", "license": "mit", "hash": -6427629324895659000, "line_mean": 31, "line_max": 73, "alpha_frac": 0.6021959459, "autogenerated": false, "ratio": 4.369003690036901, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0035879960429942887, "num_lines": 37 }
__all__ = ['get_current_request'] import logging import sys from typing import Optional, Union from starlette.requests import Request from starlette.types import Receive, Scope log = logging.getLogger(__name__) if sys.version_info[:2] == (3, 6): # Backport PEP 567 try: import aiocontextvars except ImportError: # Do not raise an exception as the module is exported to package API # but is still optional log.error( 'Python 3.6 requires `aiocontextvars` package to be installed' ' to support global access to request objects' ) try: from contextvars import ContextVar except ImportError: ContextVar = None if ContextVar: _current_request: ContextVar[Optional[Request]] = ContextVar( 'rollbar-request-object', default=None ) def get_current_request() -> Optional[Request]: """ Return current request. Do NOT modify the returned request object. """ if ContextVar is None: log.error( 'Python 3.7+ (or aiocontextvars package)' ' is required to receive current request.' ) return None request = _current_request.get() if request is None: log.error('Request is not available in the present context.') return None return request def store_current_request( request_or_scope: Union[Request, Scope], receive: Optional[Receive] = None ) -> Optional[Request]: if ContextVar is None: return None if receive is None: request = request_or_scope else: request = Request(request_or_scope, receive) _current_request.set(request) return request def hasuser(request: Request) -> bool: try: return hasattr(request, 'user') except AssertionError: return False
{ "repo_name": "rollbar/pyrollbar", "path": "rollbar/contrib/starlette/requests.py", "copies": "1", "size": "1825", "license": "mit", "hash": 7898874865958705000, "line_mean": 22.7012987013, "line_max": 78, "alpha_frac": 0.6471232877, "autogenerated": false, "ratio": 4.176201372997712, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5323324660697711, "avg_score": null, "num_lines": null }
__all__ = ["get_day_boxoffice"] import tushare as ts from flask import json TRANS = {"AvgPrice": "平均票价", "AvpPeoPle": "场均人次", "BoxOffice": "单日票房(万)", "BoxOffice_Up": "环比变化 (%)", "IRank": "排名", "MovieDay": "上映天数", "MovieName": "影片名", "SumBoxOffice": "累计票房(万)", "WomIndex": "口碑指数" } def get_day_boxoffice(day=None): if day == None: total = ts.day_boxoffice().to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} else: try: total = ts.day_boxoffice(day).to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} except Exception as e: result = {"error": True, "message": "can not get the data, format date as YYYY-M-D"} return result
{ "repo_name": "FinaceInfo/Chinese-box-office-info", "path": "app/boxoffice/day_boxoffice.py", "copies": "1", "size": "1109", "license": "mit", "hash": -2256031181057465900, "line_mean": 31.21875, "line_max": 96, "alpha_frac": 0.5053346266, "autogenerated": false, "ratio": 2.801630434782609, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.3806965061382609, "avg_score": null, "num_lines": null }
__all__ = ["get_day_cinema"] import tushare as ts from flask import json TRANS = {"Attendance": "上座率", "AvgPeople": "场均人次", "CinemaName": "影院名称", "RowNum": "排名", "TodayAudienceCount": "当日观众人数", "TodayBox": "当日票房", "TodayShowCount": "当日场次", "price": "场均票价(元)" } def get_day_cinema(day=None): print(day) if day == None: try: total = ts.day_cinema().to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} except Exception as e: result = {"error": "true", "message": str(e)} else: try: total = ts.day_cinema(day).to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} except Exception as e: result = {"error": "true", "message": "can not get the data, format date as YYYY-M-D"} print("result") print(result) return result
{ "repo_name": "FinaceInfo/Chinese-box-office-info", "path": "app/boxoffice/day_cinema.py", "copies": "1", "size": "1257", "license": "mit", "hash": -1355990365481550600, "line_mean": 29.4871794872, "line_max": 81, "alpha_frac": 0.4911690496, "autogenerated": false, "ratio": 3.056555269922879, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.903975058593939, "avg_score": 0.0015947467166979362, "num_lines": 39 }
__all__ = ['getDpi', 'getContext', 'getPreset', 'getScreenContext'] import matplotlib as mpl from math import sqrt def getDpi(): return 72.27 _screenDpi = 96 _screenFontSize = 12 _goldenRatio = (1 + sqrt(5)) / 2 _presets = { 'revtex12-single': (468, 10.95, None), # Single-column revtex; 12pt. 'mnras': (240, 8, _goldenRatio), # Double-column MNRAS; default font size. 'mnras-2': (504, 8, _goldenRatio * 1.2), # Single-column MNRAS; default font size. 'thesis': (300, 8, _goldenRatio), 'thesis-wide': (426, 8, _goldenRatio) } def getPreset(preset): return _presets[preset] def getContext(returnParams=False, *args, **kwargs): width, height, dpi, fontSize, tickFontSize = _getParams(*args, **kwargs) rc = {} rc['text.latex.unicode'] = True rc['text.usetex'] = True rc['font.family'] = 'serif' rc['font.serif'] = ['Computer Modern'] rc['font.size'] = fontSize rc['axes.labelsize'] = fontSize rc['legend.fontsize']= fontSize rc['xtick.labelsize'] = tickFontSize rc['ytick.labelsize'] = tickFontSize rc['axes.labelcolor'] = 'black' rc['xtick.color'] = 'black' rc['ytick.color'] = 'black' rc['figure.figsize'] = width, height rc['figure.dpi'] = dpi if returnParams: return rc else: return mpl.rc_context(rc) def getScreenContext(pixelWidth=None, fontSize=None, aspectRatio=None, returnParams=False): if aspectRatio is None: aspectRatio = _goldenRatio if fontSize is None: fontSize = _screenFontSize params = { 'figure.dpi': _screenDpi, 'text.usetex': False, 'mathtext.fontset': 'stixsans', 'font.family': 'Bitstream Vera Sans', 'font.size': fontSize, 'axes.labelsize': fontSize, 'legend.fontsize': fontSize, 'xtick.labelsize': fontSize * 0.8, 'ytick.labelsize': fontSize * 0.8, } if pixelWidth is not None: pixelHeight = pixelWidth / aspectRatio params['figure.figsize'] = (pixelWidth / _screenDpi, pixelHeight / _screenDpi) if returnParams: return params else: return mpl.rc_context(params) def _getParams(preset=None, width=None, fontSize=None, aspectRatio=None, height=None): if preset is not None: assert preset in _presets, \ 'Preset not found.' width0, fontSize0, aspectRatio0 = _presets[preset] else: width0, fontSize0, aspectRatio0 = None, None, None if width is not None: if width <= 1: assert width0 is not None width *= width0 else: width = width0 width = width if width is not None else width0 fontSize = fontSize if fontSize is not None else fontSize0 aspectRatio = aspectRatio if aspectRatio is not None else aspectRatio0 assert width is not None and fontSize is not None, \ 'Column width or font size missing.' dpi = getDpi() # One inch in points (according to TeX). if height is None: if aspectRatio is None: aspectRatio = _goldenRatio height = width / aspectRatio width /= dpi height /= dpi return width, height, dpi, fontSize, fontSize * 0.8
{ "repo_name": "willvousden/mpltex", "path": "mpltex/mpltex.py", "copies": "1", "size": "3207", "license": "mit", "hash": 8623044847310524000, "line_mean": 28.9719626168, "line_max": 91, "alpha_frac": 0.6239476146, "autogenerated": false, "ratio": 3.4483870967741934, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.45723347113741936, "avg_score": null, "num_lines": null }
__all__ = ["GET_FIRST_CLIENT_RECT", \ "GET_LOCATION_IN_VIEW", \ "GET_PAGE_ZOOM", \ "IS_ELEMENT_CLICKABLE", \ "TOUCH_SINGLE_TAP", \ "CLEAR", \ "CLEAR_LOCAL_STORAGE", \ "CLEAR_SESSION_STORAGE", \ "CLICK", \ "EXECUTE_ASYNC_SCRIPT", \ "EXECUTE_SCRIPT", \ "EXECUTE_SQL", \ "FIND_ELEMENT", \ "FIND_ELEMENTS", \ "GET_APPCACHE_STATUS", \ "GET_ATTRIBUTE", \ "GET_EFFECTIVE_STYLE", \ "GET_IN_VIEW_LOCATION", \ "GET_LOCAL_STORAGE_ITEM", \ "GET_LOCAL_STORAGE_KEY", \ "GET_LOCAL_STORAGE_KEYS", \ "GET_LOCAL_STORAGE_SIZE", \ "GET_SESSION_STORAGE_ITEM", \ "GET_SESSION_STORAGE_KEY", \ "GET_SESSION_STORAGE_KEYS", \ "GET_SESSION_STORAGE_SIZE", \ "GET_LOCATION", \ "GET_SIZE", \ "GET_TEXT", \ "IS_DISPLAYED", \ "IS_ENABLED", \ "IS_ONLINE", \ "IS_SELECTED", \ "REMOVE_LOCAL_STORAGE_ITEM", \ "REMOVE_SESSION_STORAGE_ITEM", \ "SET_LOCAL_STORAGE_ITEM", \ "SET_SESSION_STORAGE_ITEM", \ "SUBMIT"] GET_FIRST_CLIENT_RECT = \ "function(){return function(){var g=this;\nfunction h(a){var b=typeof a;"\ "if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a insta"\ "nceof Object)return b;var e=Object.prototype.toString.call(a);if(\"[obj"\ "ect Window]\"==e)return\"object\";if(\"[object Array]\"==e||\"number\"="\ "=typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof"\ " a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"ar"\ "ray\";if(\"[object Function]\"==e||\"undefined\"!=typeof a.call&&\"unde"\ "fined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call"\ "\"))return\"function\"}else return\"null\";else if(\"function\"==\nb&&"\ "\"undefined\"==typeof a.call)return\"object\";return b};var k;function "\ "l(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}l.prototype.toString"\ "=function(){return\"(\"+this.x+\", \"+this.y+\")\"};function m(a){retur"\ "n 9==a.nodeType?a:a.ownerDocument||a.document}function n(a){this.b=a||g"\ ".document||document}function p(a){var b=a.b;a=b.body;b=b.parentWindow||"\ "b.defaultView;return new l(b.pageXOffset||a.scrollLeft,b.pageYOffset||a"\ ".scrollTop)};function q(a,b,e,d){this.left=a;this.top=b;this.width=e;th"\ "is.height=d}q.prototype.toString=function(){return\"(\"+this.left+\", "\ "\"+this.top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};function s("\ "a){var b;a:{b=m(a);if(b.defaultView&&b.defaultView.getComputedStyle&&(b"\ "=b.defaultView.getComputedStyle(a,null))){b=b.position||b.getPropertyVa"\ "lue(\"position\")||\"\";break a}b=\"\"}return b||(a.currentStyle?a.curr"\ "entStyle.position:null)||a.style&&a.style.position}function t(a){var b;"\ "try{b=a.getBoundingClientRect()}catch(e){return{left:0,top:0,right:0,bo"\ "ttom:0}}return b}\nfunction u(a){var b=m(a),e=s(a),d=\"fixed\"==e||\"ab"\ "solute\"==e;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(e=s(a),d=d&&\""\ "static\"==e&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clien"\ "tWidth||a.scrollHeight>a.clientHeight||\"fixed\"==e||\"absolute\"==e||"\ "\"relative\"==e))return a;return null};function v(a){var b=a.getClientR"\ "ects();if(0==b.length)throw Error(\"Element does not have any client re"\ "cts\");b=b[0];if(1==a.nodeType)if(a.getBoundingClientRect)a=t(a),a=new "\ "l(a.left,a.top);else{var e=p(a?new n(m(a)):k||(k=new n));var d=m(a),z=s"\ "(a),c=new l(0,0),r=(d?m(d):document).documentElement;if(a!=r)if(a.getBo"\ "undingClientRect)a=t(a),d=p(d?new n(m(d)):k||(k=new n)),c.x=a.left+d.x,"\ "c.y=a.top+d.y;else if(d.getBoxObjectFor)a=d.getBoxObjectFor(a),d=d.getB"\ "oxObjectFor(r),c.x=a.screenX-d.screenX,c.y=a.screenY-\nd.screenY;else{v"\ "ar f=a;do{c.x+=f.offsetLeft;c.y+=f.offsetTop;f!=a&&(c.x+=f.clientLeft||"\ "0,c.y+=f.clientTop||0);if(\"fixed\"==s(f)){c.x+=d.body.scrollLeft;c.y+="\ "d.body.scrollTop;break}f=f.offsetParent}while(f&&f!=a);\"absolute\"==z&"\ "&(c.y-=d.body.offsetTop);for(f=a;(f=u(f))&&f!=d.body&&f!=r;)c.x-=f.scro"\ "llLeft,c.y-=f.scrollTop}a=new l(c.x-e.x,c.y-e.y)}else e=\"function\"==h"\ "(a.a),c=a,a.targetTouches?c=a.targetTouches[0]:e&&a.a().targetTouches&&"\ "(c=a.a().targetTouches[0]),a=new l(c.clientX,c.clientY);return new q(b."\ "left-\na.x,b.top-a.y,b.right-b.left,b.bottom-b.top)}var w=[\"_\"],x=g;w"\ "[0]in x||!x.execScript||x.execScript(\"var \"+w[0]);for(var y;w.length&"\ "&(y=w.shift());)w.length||void 0===v?x=x[y]?x[y]:x[y]={}:x[y]=v;; retur"\ "n this._.apply(null,arguments);}.apply({navigator:typeof window!=undefi"\ "ned?window.navigator:null,document:typeof window!=undefined?window.docu"\ "ment:null}, arguments);}" GET_LOCATION_IN_VIEW = \ "function(){return function(){var k=this;\nfunction l(a){var b=typeof a;"\ "if(\"object\"==b)if(a){if(a instanceof Array)return\"array\";if(a insta"\ "nceof Object)return b;var c=Object.prototype.toString.call(a);if(\"[obj"\ "ect Window]\"==c)return\"object\";if(\"[object Array]\"==c||\"number\"="\ "=typeof a.length&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof"\ " a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"splice\"))return\"ar"\ "ray\";if(\"[object Function]\"==c||\"undefined\"!=typeof a.call&&\"unde"\ "fined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call"\ "\"))return\"function\"}else return\"null\";else if(\"function\"==\nb&&"\ "\"undefined\"==typeof a.call)return\"object\";return b};var m;function "\ "n(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}n.prototype.toString"\ "=function(){return\"(\"+this.x+\", \"+this.y+\")\"};function p(a,b){thi"\ "s.width=a;this.height=b}p.prototype.toString=function(){return\"(\"+thi"\ "s.width+\" x \"+this.height+\")\"};function q(a){return a?new r(s(a)):m"\ "||(m=new r)}function s(a){return 9==a.nodeType?a:a.ownerDocument||a.doc"\ "ument}function r(a){this.a=a||k.document||document}function t(a){a=(a.a"\ ".parentWindow||a.a.defaultView||window).document;a=\"CSS1Compat\"==a.co"\ "mpatMode?a.documentElement:a.body;return new p(a.clientWidth,a.clientHe"\ "ight)}function u(a){var b=a.a;a=b.body;b=b.parentWindow||b.defaultView;"\ "return new n(b.pageXOffset||a.scrollLeft,b.pageYOffset||a.scrollTop)};f"\ "unction v(a,b,c,d){this.top=a;this.right=b;this.bottom=c;this.left=d}v."\ "prototype.toString=function(){return\"(\"+this.top+\"t, \"+this.right+"\ "\"r, \"+this.bottom+\"b, \"+this.left+\"l)\"};function w(a,b,c,d){this."\ "left=a;this.top=b;this.width=c;this.height=d}w.prototype.toString=funct"\ "ion(){return\"(\"+this.left+\", \"+this.top+\" - \"+this.width+\"w x \""\ "+this.height+\"h)\"};function x(a,b){var c=s(a);return c.defaultView&&c"\ ".defaultView.getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null"\ "))?c[b]||c.getPropertyValue(b)||\"\":\"\"}function y(a){return x(a,\"po"\ "sition\")||(a.currentStyle?a.currentStyle.position:null)||a.style&&a.st"\ "yle.position}function z(a){var b;try{b=a.getBoundingClientRect()}catch("\ "c){return{left:0,top:0,right:0,bottom:0}}return b}\nfunction A(a){var b"\ "=s(a),c=y(a),d=\"fixed\"==c||\"absolute\"==c;for(a=a.parentNode;a&&a!=b"\ ";a=a.parentNode)if(c=y(a),d=d&&\"static\"==c&&a!=b.documentElement&&a!="\ "b.body,!d&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight|"\ "|\"fixed\"==c||\"absolute\"==c||\"relative\"==c))return a;return null}"\ "\nfunction B(a){var b=s(a),c=y(a),d=new n(0,0),f=(b?s(b):document).docu"\ "mentElement;if(a==f)return d;if(a.getBoundingClientRect)a=z(a),b=u(q(b)"\ "),d.x=a.left+b.x,d.y=a.top+b.y;else if(b.getBoxObjectFor)a=b.getBoxObje"\ "ctFor(a),b=b.getBoxObjectFor(f),d.x=a.screenX-b.screenX,d.y=a.screenY-b"\ ".screenY;else{var e=a;do{d.x+=e.offsetLeft;d.y+=e.offsetTop;e!=a&&(d.x+"\ "=e.clientLeft||0,d.y+=e.clientTop||0);if(\"fixed\"==y(e)){d.x+=b.body.s"\ "crollLeft;d.y+=b.body.scrollTop;break}e=e.offsetParent}while(e&&e!=a);"\ "\"absolute\"==\nc&&(d.y-=b.body.offsetTop);for(e=a;(e=A(e))&&e!=b.body&"\ "&e!=f;)d.x-=e.scrollLeft,d.y-=e.scrollTop}return d}function C(a){if(1=="\ "a.nodeType){if(a.getBoundingClientRect)a=z(a),a=new n(a.left,a.top);els"\ "e{var b=u(q(a));a=B(a);a=new n(a.x-b.x,a.y-b.y)}return a}var b=\"functi"\ "on\"==l(a.b),c=a;a.targetTouches?c=a.targetTouches[0]:b&&a.b().targetTo"\ "uches&&(c=a.b().targetTouches[0]);return new n(c.clientX,c.clientY)};fu"\ "nction D(a,b){var c;c=B(b);var d=B(a);c=new n(c.x-d.x,c.y-d.y);var f,e,"\ "h;h=x(a,\"borderLeftWidth\");e=x(a,\"borderRightWidth\");f=x(a,\"border"\ "TopWidth\");d=x(a,\"borderBottomWidth\");d=new v(parseFloat(f),parseFlo"\ "at(e),parseFloat(d),parseFloat(h));c.x-=d.left;c.y-=d.top;return c}\nfu"\ "nction E(a,b,c){function d(a,b,c,d,e){d=new w(c.x+d.left,c.y+d.top,d.wi"\ "dth,d.height);c=[0,0];b=[b.width,b.height];var f=[d.left,d.top];d=[d.wi"\ "dth,d.height];for(var g=0;2>g;g++)if(d[g]>b[g])c[g]=e?f[g]+d[g]/2-b[g]/"\ "2:f[g];else{var h=f[g]-b[g]+d[g];0<h?c[g]=h:0>f[g]&&(c[g]=f[g])}e=new n"\ "(c[0],c[1]);a.scrollLeft+=e.x;a.scrollTop+=e.y}for(var f=s(a),e=a.paren"\ "tNode,h;e&&e!=f.documentElement&&e!=f.body;)h=D(e,a),d(e,new p(e.client"\ "Width,e.clientHeight),h,b,c),e=e.parentNode;h=C(a);a=t(q(a));d(f.body,a"\ ",h,\nb,c)};function F(a,b,c){c||(c=new w(0,0,a.offsetWidth,a.offsetHeig"\ "ht));E(a,c,b);a=C(a);return new n(a.x+c.left,a.y+c.top)}var G=[\"_\"],H"\ "=k;G[0]in H||!H.execScript||H.execScript(\"var \"+G[0]);for(var I;G.len"\ "gth&&(I=G.shift());)G.length||void 0===F?H=H[I]?H[I]:H[I]={}:H[I]=F;; r"\ "eturn this._.apply(null,arguments);}.apply({navigator:typeof window!=un"\ "defined?window.navigator:null,document:typeof window!=undefined?window."\ "document:null}, arguments);}" GET_PAGE_ZOOM = \ "function(){return function(){function a(b){b=9==b.nodeType?b:b.ownerDoc"\ "ument||b.document;var c=b.documentElement,c=Math.max(c.clientWidth,c.of"\ "fsetWidth,c.scrollWidth);return b.width/c}var d=[\"_\"],e=this;d[0]in e"\ "||!e.execScript||e.execScript(\"var \"+d[0]);for(var f;d.length&&(f=d.s"\ "hift());)d.length||void 0===a?e=e[f]?e[f]:e[f]={}:e[f]=a;; return this."\ "_.apply(null,arguments);}.apply({navigator:typeof window!=undefined?win"\ "dow.navigator:null,document:typeof window!=undefined?window.document:nu"\ "ll}, arguments);}" IS_ELEMENT_CLICKABLE = \ "function(){return function(){function c(h,d){function g(a,b){var d={cli"\ "ckable:a};b&&(d.message=b);return d}var a=h.ownerDocument.elementFromPo"\ "int(d.x,d.y);if(a==h)return g(!0);var l=\"(\"+d.x+\", \"+d.y+\")\";if(n"\ "ull==a)return g(!1,\"Element is not clickable at point \"+l);var b=a.ou"\ "terHTML;if(a.hasChildNodes())var m=a.innerHTML,n=b.length-m.length-(\"<"\ "/\"+a.tagName+\">\").length,b=b.substring(0,n)+\"...\"+b.substring(n+m."\ "length);for(a=a.parentNode;a;){if(a==h)return g(!0,\"Element's descenda"\ "nt would receive the click. Consider clicking the descendant instead. D"\ "escendant: \"+\nb);a=a.parentNode}return g(!1,\"Element is not clickabl"\ "e at point \"+l+\". Other element would receive the click: \"+b)}var e="\ "[\"_\"],f=this;e[0]in f||!f.execScript||f.execScript(\"var \"+e[0]);for"\ "(var k;e.length&&(k=e.shift());)e.length||void 0===c?f=f[k]?f[k]:f[k]={"\ "}:f[k]=c;; return this._.apply(null,arguments);}.apply({navigator:typeo"\ "f window!=undefined?window.navigator:null,document:typeof window!=undef"\ "ined?window.document:null}, arguments);}" TOUCH_SINGLE_TAP = \ "function(){return function(){function aa(a){return function(){return th"\ "is[a]}}function ba(a){return function(){return a}}var g,k=this;\nfuncti"\ "on ca(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)re"\ "turn\"array\";if(a instanceof Object)return b;var c=Object.prototype.to"\ "String.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object "\ "Array]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splic"\ "e&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerabl"\ "e(\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined"\ "\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.pro"\ "pertyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nel"\ "se if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";re"\ "turn b}function l(a){return void 0!==a}function m(a){return\"string\"=="\ "typeof a}function da(a){return\"number\"==typeof a}function p(a){return"\ "\"function\"==ca(a)}function r(a,b){function c(){}c.prototype=b.prototy"\ "pe;a.ha=b.prototype;a.prototype=new c};var ea=window;function fa(a){ret"\ "urn String(a).replace(/\\-([a-z])/g,function(a,c){return c.toUpperCase("\ ")})};var ga=Array.prototype;function s(a,b){for(var c=a.length,d=m(a)?a"\ ".split(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function ha("\ "a,b){for(var c=a.length,d=Array(c),e=m(a)?a.split(\"\"):a,f=0;f<c;f++)f"\ " in e&&(d[f]=b.call(void 0,e[f],f,a));return d}function ia(a,b){if(a.re"\ "duce)return a.reduce(b,\"\");var c=\"\";s(a,function(d,e){c=b.call(void"\ " 0,c,d,e,a)});return c}function ja(a,b){for(var c=a.length,d=m(a)?a.spl"\ "it(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return!0;retu"\ "rn!1}\nfunction ka(a,b){var c;a:if(m(a))c=m(b)&&1==b.length?a.indexOf(b"\ ",0):-1;else{for(c=0;c<a.length;c++)if(c in a&&a[c]===b)break a;c=-1}ret"\ "urn 0<=c}function la(a,b,c){return 2>=arguments.length?ga.slice.call(a,"\ "b):ga.slice.call(a,b,c)};var ma={aliceblue:\"#f0f8ff\",antiquewhite:\"#"\ "faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",azure:\"#f0ffff\",beig"\ "e:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\",blanchedalmond:\"#ff"\ "ebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brown:\"#a52a2a\",burlyw"\ "ood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:"\ "\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6495ed\",cornsilk:\"#ff"\ "f8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcy"\ "an:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:\"#a9a9a9\",darkgreen"\ ":\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki:\"#bdb76b\",darkmagenta:"\ "\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:\"#ff8c00\",darkorchi"\ "d:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9967a\",darkseagreen:"\ "\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray:\"#2f4f4f\",darksla"\ "tegrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkviolet:\"#9400d3\",dee"\ "ppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:\"#696969\",dimgrey:"\ "\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22222\",floralwhite:\""\ "#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff\",gainsboro:\"#dcdc"\ "dc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\",goldenrod:\"#daa520\",gr"\ "ay:\"#808080\",green:\"#008000\",greenyellow:\"#adff2f\",grey:\"#808080"\ "\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianred:\"#cd5c5c\",indig"\ "o:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",lavender:\"#e6e6fa\","\ "lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lemonchiffon:\"#fffacd"\ "\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",lightcyan:\"#e0ffff\",l"\ "ightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3\",lightgreen:\"#90e"\ "e90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1\",lightsalmon:\"#ffa07a"\ "\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#87cefa\",lightslategray:"\ "\"#778899\",lightslategrey:\"#778899\",lightsteelblue:\"#b0c4de\",light"\ "yellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32cd32\",linen:\"#faf0"\ "e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediumaquamarine:\"#66cdaa"\ "\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",mediumpurple:\"#9370"\ "db\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7b68ee\",mediumsprin"\ "ggreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediumvioletred:\"#c7158"\ "5\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",mistyrose:\"#ffe4e1"\ "\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",navy:\"#000080\",oldl"\ "ace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23\",orange:\"#ffa50"\ "0\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegoldenrod:\"#eee8aa\","\ "palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palevioletred:\"#db7093"\ "\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:\"#cd853f\",pink:"\ "\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",purple:\"#800080\","\ "red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#4169e1\",saddlebrown"\ ":\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\",seagreen:\"#2e8b"\ "57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",silver:\"#c0c0c0\",skybl"\ "ue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#708090\",slategrey:\""\ "#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",steelblue:\"#4682b4"\ "\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\",tomato:\"#ff634"\ "7\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f5deb3\",white:\""\ "#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yellowgreen:\"#9acd"\ "32\"};var na=\"background-color border-top-color border-right-color bor"\ "der-bottom-color border-left-color color outline-color\".split(\" \"),o"\ "a=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;function pa(a){if(!qa.test"\ "(a))throw Error(\"'\"+a+\"' is not a valid hex color\");4==a.length&&(a"\ "=a.replace(oa,\"#$1$1$2$2$3$3\"));return a.toLowerCase()}var qa=/^#(?:["\ "0-9a-f]{3}){1,2}$/i,ra=/^(?:rgba)?\\((\\d{1,3}),\\s?(\\d{1,3}),\\s?(\\d"\ "{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction sa(a){var b=a.match(ra);if(b"\ "){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b=Number(b[4]);if(0<"\ "=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)return[a,c,d,b]}retu"\ "rn[]}var ta=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2}),\\s?(0"\ "|[1-9]\\d{0,2})\\)$/i;function ua(a){var b=a.match(ta);if(b){a=Number(b"\ "[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>=a&&0<=c&&255>=c&&0"\ "<=b&&255>=b)return[a,c,b]}return[]};function t(a,b){this.code=a;this.st"\ "ate=va[a]||xa;this.message=b||\"\";var c=this.state.replace(/((?:^|\\s+"\ ")[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/g,\""\ "\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";this."\ "name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||\"\"}"\ "r(t,Error);\nvar xa=\"unknown error\",va={15:\"element not selectable\""\ ",11:\"element not visible\",31:\"ime engine activation failed\",30:\"im"\ "e not available\",24:\"invalid cookie domain\",29:\"invalid element coo"\ "rdinates\",12:\"invalid element state\",32:\"invalid selector\",51:\"in"\ "valid selector\",52:\"invalid selector\",17:\"javascript error\",405:\""\ "unsupported operation\",34:\"move target out of bounds\",27:\"no such a"\ "lert\",7:\"no such element\",8:\"no such frame\",23:\"no such window\","\ "28:\"script timeout\",33:\"session not created\",10:\"stale element ref"\ "erence\",\n0:\"success\",21:\"timeout\",25:\"unable to set cookie\",26:"\ "\"unexpected alert open\"};va[13]=xa;va[9]=\"unknown command\";t.protot"\ "ype.toString=function(){return this.name+\": \"+this.message};var ya,za"\ ",Aa,Ba=k.navigator;Aa=Ba&&Ba.platform||\"\";ya=-1!=Aa.indexOf(\"Mac\");"\ "za=-1!=Aa.indexOf(\"Win\");var u=-1!=Aa.indexOf(\"Linux\");var Ca;funct"\ "ion v(a,b){this.x=l(a)?a:0;this.y=l(b)?b:0}g=v.prototype;g.toString=fun"\ "ction(){return\"(\"+this.x+\", \"+this.y+\")\"};g.ceil=function(){this."\ "x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this};g.floor=funct"\ "ion(){this.x=Math.floor(this.x);this.y=Math.floor(this.y);return this};"\ "g.round=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);"\ "return this};g.scale=function(a,b){var c=da(b)?b:a;this.x*=a;this.y*=c;"\ "return this};function Da(a,b){this.width=a;this.height=b}g=Da.prototype"\ ";g.toString=function(){return\"(\"+this.width+\" x \"+this.height+\")\""\ "};g.ceil=function(){this.width=Math.ceil(this.width);this.height=Math.c"\ "eil(this.height);return this};g.floor=function(){this.width=Math.floor("\ "this.width);this.height=Math.floor(this.height);return this};g.round=fu"\ "nction(){this.width=Math.round(this.width);this.height=Math.round(this."\ "height);return this};g.scale=function(a,b){var c=da(b)?b:a;this.width*="\ "a;this.height*=c;return this};var Ea=3;function Fa(a){for(;a&&1!=a.node"\ "Type;)a=a.previousSibling;return a}function Ga(a,b){if(a.contains&&1==b"\ ".nodeType)return a==b||a.contains(b);if(\"undefined\"!=typeof a.compare"\ "DocumentPosition)return a==b||Boolean(a.compareDocumentPosition(b)&16);"\ "for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction Ha(a,b){if(a==b)ret"\ "urn 0;if(a.compareDocumentPosition)return a.compareDocumentPosition(b)&"\ "2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"sourceIndex\"in a.parent"\ "Node){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return a.sourceIndex-"\ "b.sourceIndex;var e=a.parentNode,f=b.parentNode;return e==f?Ia(a,b):!c&"\ "&Ga(e,b)?-1*Ja(a,b):!d&&Ga(f,a)?Ja(b,a):(c?a.sourceIndex:e.sourceIndex)"\ "-(d?b.sourceIndex:f.sourceIndex)}d=w(a);c=d.createRange();c.selectNode("\ "a);c.collapse(!0);d=d.createRange();d.selectNode(b);\nd.collapse(!0);re"\ "turn c.compareBoundaryPoints(k.Range.START_TO_END,d)}function Ja(a,b){v"\ "ar c=a.parentNode;if(c==b)return-1;for(var d=b;d.parentNode!=c;)d=d.par"\ "entNode;return Ia(d,a)}function Ia(a,b){for(var c=b;c=c.previousSibling"\ ";)if(c==a)return-1;return 1}function w(a){return 9==a.nodeType?a:a.owne"\ "rDocument||a.document}function Ka(a,b,c){c||(a=a.parentNode);for(c=0;a;"\ "){if(b(a))return a;a=a.parentNode;c++}return null}function La(a){try{re"\ "turn a&&a.activeElement}catch(b){}return null}\nfunction x(a){this.P=a|"\ "|k.document||document}function Ma(a){var b=a.P;a=b.body;b=b.parentWindo"\ "w||b.defaultView;return new v(b.pageXOffset||a.scrollLeft,b.pageYOffset"\ "||a.scrollTop)}x.prototype.contains=Ga;function y(a){var b=null,c=a.nod"\ "eType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerText:b,b=void "\ "0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c){a=9==c?a.d"\ "ocumentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do 1!=a.nodeTyp"\ "e&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&&!(a=d[--c].n"\ "extSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction z(a,b,c){if("\ "null===b)return!0;try{if(!a.getAttribute)return!1}catch(d){return!1}ret"\ "urn null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}function Na(a,b,"\ "c,d,e){return Oa.call(null,a,b,m(c)?c:null,m(d)?d:null,e||new B)}\nfunc"\ "tion Oa(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b.getElements"\ "ByName(d),s(b,function(b){a.matches(b)&&e.add(b)})):b.getElementsByClas"\ "sName&&d&&\"class\"==c?(b=b.getElementsByClassName(d),s(b,function(b){b"\ ".className==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagName&&(b=b.g"\ "etElementsByTagName(a.getName()),s(b,function(a){z(a,c,d)&&e.add(a)}));"\ "return e}function Pa(a,b,c,d,e){for(b=b.firstChild;b;b=b.nextSibling)z("\ "b,c,d)&&a.matches(b)&&e.add(b);return e}\nfunction Qa(a,b,c,d,e){for(b="\ "b.firstChild;b;b=b.nextSibling)z(b,c,d)&&a.matches(b)&&e.add(b),Qa(a,b,"\ "c,d,e)};function B(){this.h=this.g=null;this.p=0}function Ra(a){this.J="\ "a;this.next=this.B=null}B.prototype.unshift=function(a){a=new Ra(a);a.n"\ "ext=this.g;this.h?this.g.B=a:this.g=this.h=a;this.g=a;this.p++};B.proto"\ "type.add=function(a){a=new Ra(a);a.B=this.h;this.g?this.h.next=a:this.g"\ "=this.h=a;this.h=a;this.p++};function Sa(a){return(a=a.g)?a.J:null}func"\ "tion Ta(a){return(a=Sa(a))?y(a):\"\"}function C(a,b){this.ca=a;this.F=("\ "this.K=b)?a.h:a.g;this.Q=null}\nC.prototype.next=function(){var a=this."\ "F;if(null==a)return null;var b=this.Q=a;this.F=this.K?a.B:a.next;return"\ " b.J};function D(a,b){var c=a.evaluate(b);return c instanceof B?+Ta(c):"\ "+c}function E(a,b){var c=a.evaluate(b);return c instanceof B?Ta(c):\"\""\ "+c}function H(a,b){var c=a.evaluate(b);return c instanceof B?!!c.p:!!c}"\ ";function I(a,b,c,d,e){b=b.evaluate(d);c=c.evaluate(d);var f;if(b insta"\ "nceof B&&c instanceof B){e=new C(b,!1);for(d=e.next();d;d=e.next())for("\ "b=new C(c,!1),f=b.next();f;f=b.next())if(a(y(d),y(f)))return!0;return!1"\ "}if(b instanceof B||c instanceof B){b instanceof B?e=b:(e=c,c=b);e=new "\ "C(e,!1);b=typeof c;for(d=e.next();d;d=e.next()){switch(b){case \"number"\ "\":d=+y(d);break;case \"boolean\":d=!!y(d);break;case \"string\":d=y(d)"\ ";break;default:throw Error(\"Illegal primitive type for comparison.\");"\ "}if(a(d,c))return!0}return!1}return e?\n\"boolean\"==typeof b||\"boolea"\ "n\"==typeof c?a(!!b,!!c):\"number\"==typeof b||\"number\"==typeof c?a(+"\ "b,+c):a(b,c):a(+b,+c)}function Ua(a,b,c,d){this.R=a;this.fa=b;this.O=c;"\ "this.o=d}Ua.prototype.toString=aa(\"R\");var Va={};function J(a,b,c,d){"\ "if(a in Va)throw Error(\"Binary operator already created: \"+a);a=new U"\ "a(a,b,c,d);Va[a.toString()]=a}J(\"div\",6,1,function(a,b,c){return D(a,"\ "c)/D(b,c)});J(\"mod\",6,1,function(a,b,c){return D(a,c)%D(b,c)});J(\"*"\ "\",6,1,function(a,b,c){return D(a,c)*D(b,c)});\nJ(\"+\",5,1,function(a,"\ "b,c){return D(a,c)+D(b,c)});J(\"-\",5,1,function(a,b,c){return D(a,c)-D"\ "(b,c)});J(\"<\",4,2,function(a,b,c){return I(function(a,b){return a<b},"\ "a,b,c)});J(\">\",4,2,function(a,b,c){return I(function(a,b){return a>b}"\ ",a,b,c)});J(\"<=\",4,2,function(a,b,c){return I(function(a,b){return a<"\ "=b},a,b,c)});J(\">=\",4,2,function(a,b,c){return I(function(a,b){return"\ " a>=b},a,b,c)});J(\"=\",3,2,function(a,b,c){return I(function(a,b){retu"\ "rn a==b},a,b,c,!0)});\nJ(\"!=\",3,2,function(a,b,c){return I(function(a"\ ",b){return a!=b},a,b,c,!0)});J(\"and\",2,2,function(a,b,c){return H(a,c"\ ")&&H(b,c)});J(\"or\",1,2,function(a,b,c){return H(a,c)||H(b,c)});functi"\ "on Wa(a,b,c,d,e,f,h,q,n){this.A=a;this.O=b;this.ba=c;this.aa=d;this.$=e"\ ";this.o=f;this.Z=h;this.Y=l(q)?q:h;this.da=!!n}Wa.prototype.toString=aa"\ "(\"A\");var Xa={};function K(a,b,c,d,e,f,h,q){if(a in Xa)throw Error(\""\ "Function already created: \"+a+\".\");Xa[a]=new Wa(a,b,c,d,!1,e,f,h,q)}"\ "K(\"boolean\",2,!1,!1,function(a,b){return H(b,a)},1);K(\"ceiling\",1,!"\ "1,!1,function(a,b){return Math.ceil(D(b,a))},1);\nK(\"concat\",3,!1,!1,"\ "function(a,b){var c=la(arguments,1);return ia(c,function(b,c){return b+"\ "E(c,a)})},2,null);K(\"contains\",2,!1,!1,function(a,b,c){b=E(b,a);a=E(c"\ ",a);return-1!=b.indexOf(a)},2);K(\"count\",1,!1,!1,function(a,b){return"\ " b.evaluate(a).p},1,1,!0);K(\"false\",2,!1,!1,ba(!1),0);K(\"floor\",1,!"\ "1,!1,function(a,b){return Math.floor(D(b,a))},1);\nK(\"id\",4,!1,!1,fun"\ "ction(a,b){var c=a.m,d=9==c.nodeType?c:c.ownerDocument,c=E(b,a).split(/"\ "\\s+/),e=[];s(c,function(a){(a=d.getElementById(a))&&!ka(e,a)&&e.push(a"\ ")});e.sort(Ha);var f=new B;s(e,function(a){f.add(a)});return f},1);K(\""\ "lang\",2,!1,!1,ba(!1),1);K(\"last\",1,!0,!1,function(a){if(1!=arguments"\ ".length)throw Error(\"Function last expects ()\");return a.h},0);K(\"lo"\ "cal-name\",3,!1,!0,function(a,b){var c=b?Sa(b.evaluate(a)):a.m;return c"\ "?c.nodeName.toLowerCase():\"\"},0,1,!0);\nK(\"name\",3,!1,!0,function(a"\ ",b){var c=b?Sa(b.evaluate(a)):a.m;return c?c.nodeName.toLowerCase():\""\ "\"},0,1,!0);K(\"namespace-uri\",3,!0,!1,ba(\"\"),0,1,!0);K(\"normalize-"\ "space\",3,!1,!0,function(a,b){return(b?E(b,a):y(a.m)).replace(/[\\s\\xa"\ "0]+/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,1);K(\"not\",2,!1,!1,funct"\ "ion(a,b){return!H(b,a)},1);K(\"number\",1,!1,!0,function(a,b){return b?"\ "D(b,a):+y(a.m)},0,1);K(\"position\",1,!0,!1,function(a){return a.ea},0)"\ ";K(\"round\",1,!1,!1,function(a,b){return Math.round(D(b,a))},1);\nK(\""\ "starts-with\",2,!1,!1,function(a,b,c){b=E(b,a);a=E(c,a);return 0==b.las"\ "tIndexOf(a,0)},2);K(\"string\",3,!1,!0,function(a,b){return b?E(b,a):y("\ "a.m)},0,1);K(\"string-length\",1,!1,!0,function(a,b){return(b?E(b,a):y("\ "a.m)).length},0,1);\nK(\"substring\",3,!1,!1,function(a,b,c,d){c=D(c,a)"\ ";if(isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?D(d,a):Infinity;"\ "if(isNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max("\ "c,0);a=E(b,a);if(Infinity==d)return a.substring(e);b=Math.round(d);retu"\ "rn a.substring(e,c+b)},2,3);K(\"substring-after\",3,!1,!1,function(a,b,"\ "c){b=E(b,a);a=E(c,a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.le"\ "ngth)},2);\nK(\"substring-before\",3,!1,!1,function(a,b,c){b=E(b,a);a=E"\ "(c,a);a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);K(\"sum\",1,"\ "!1,!1,function(a,b){var c;c=b.evaluate(a);c=new C(c,!1);for(var d=0,e=c"\ ".next();e;e=c.next())d+=+y(e);return d},1,1,!0);K(\"translate\",3,!1,!1"\ ",function(a,b,c,d){b=E(b,a);c=E(c,a);var e=E(d,a);a=[];for(d=0;d<c.leng"\ "th;d++){var f=c.charAt(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b"\ ".length;d++)f=b.charAt(d),c+=f in a?a[f]:f;return c},3);K(\"true\",2,!1"\ ",!1,ba(!0),0);function Ya(a,b,c,d){this.A=a;this.W=b;this.K=c;this.ia=d"\ "}Ya.prototype.toString=aa(\"A\");var Za={};function L(a,b,c,d){if(a in "\ "Za)throw Error(\"Axis already created: \"+a);Za[a]=new Ya(a,b,c,!!d)}L("\ "\"ancestor\",function(a,b){for(var c=new B,d=b;d=d.parentNode;)a.matche"\ "s(d)&&c.unshift(d);return c},!0);L(\"ancestor-or-self\",function(a,b){v"\ "ar c=new B,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);retu"\ "rn c},!0);\nL(\"attribute\",function(a,b){var c=new B,d=a.getName(),e=b"\ ".attributes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e"\ ".getNamedItem(d))&&c.add(f);return c},!1);L(\"child\",function(a,b,c,d,"\ "e){return Pa.call(null,a,b,m(c)?c:null,m(d)?d:null,e||new B)},!1,!0);L("\ "\"descendant\",Na,!1,!0);L(\"descendant-or-self\",function(a,b,c,d){var"\ " e=new B;z(b,c,d)&&a.matches(b)&&e.add(b);return Na(a,b,c,d,e)},!1,!0);"\ "\nL(\"following\",function(a,b,c,d){var e=new B;do for(var f=b;f=f.next"\ "Sibling;)z(f,c,d)&&a.matches(f)&&e.add(f),e=Na(a,f,c,d,e);while(b=b.par"\ "entNode);return e},!1,!0);L(\"following-sibling\",function(a,b){for(var"\ " c=new B,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);L(\""\ "namespace\",function(){return new B},!1);L(\"parent\",function(a,b){var"\ " c=new B;if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.owne"\ "rElement),c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nL"\ "(\"preceding\",function(a,b,c,d){var e=new B,f=[];do f.unshift(b);while"\ "(b=b.parentNode);for(var h=1,q=f.length;h<q;h++){var n=[];for(b=f[h];b="\ "b.previousSibling;)n.unshift(b);for(var A=0,wa=n.length;A<wa;A++)b=n[A]"\ ",z(b,c,d)&&a.matches(b)&&e.add(b),e=Na(a,b,c,d,e)}return e},!0,!0);L(\""\ "preceding-sibling\",function(a,b){for(var c=new B,d=b;d=d.previousSibli"\ "ng;)a.matches(d)&&c.unshift(d);return c},!0);L(\"self\",function(a,b){v"\ "ar c=new B;a.matches(b)&&c.add(b);return c},!1);var M={};M.L=function()"\ "{var a={ja:\"http://www.w3.org/2000/svg\"};return function(b){return a["\ "b]||null}}();M.o=function(a,b,c){var d=w(a);try{var e=d.createNSResolve"\ "r?d.createNSResolver(d.documentElement):M.L;return d.evaluate(b,a,e,c,n"\ "ull)}catch(f){throw new t(32,\"Unable to locate an element with the xpa"\ "th expression \"+b+\" because of the following error:\\n\"+f);}};\nM.D="\ "function(a,b){if(!a||1!=a.nodeType)throw new t(32,'The result of the xp"\ "ath expression \"'+b+'\" is: '+a+\". It should be an element.\");};M.T="\ "function(a,b){var c=function(){var c=M.o(b,a,9);return c?c.singleNodeVa"\ "lue||null:b.selectSingleNode?(c=w(b),c.setProperty&&c.setProperty(\"Sel"\ "ectionLanguage\",\"XPath\"),b.selectSingleNode(a)):null}();null===c||M."\ "D(c,a);return c};\nM.X=function(a,b){var c=function(){var c=M.o(b,a,7);"\ "if(c){for(var e=c.snapshotLength,f=[],h=0;h<e;++h)f.push(c.snapshotItem"\ "(h));return f}return b.selectNodes?(c=w(b),c.setProperty&&c.setProperty"\ "(\"SelectionLanguage\",\"XPath\"),b.selectNodes(a)):[]}();s(c,function("\ "b){M.D(b,a)});return c};var $a,ab=/Chrome\\/([0-9.]+)/.exec(k.navigator"\ "?k.navigator.userAgent:null);$a=ab?ab[1]:\"\";function bb(a,b,c,d){this"\ ".top=a;this.right=b;this.bottom=c;this.left=d}g=bb.prototype;g.toString"\ "=function(){return\"(\"+this.top+\"t, \"+this.right+\"r, \"+this.bottom"\ "+\"b, \"+this.left+\"l)\"};g.contains=function(a){return this&&a?a inst"\ "anceof bb?a.left>=this.left&&a.right<=this.right&&a.top>=this.top&&a.bo"\ "ttom<=this.bottom:a.x>=this.left&&a.x<=this.right&&a.y>=this.top&&a.y<="\ "this.bottom:!1};\ng.ceil=function(){this.top=Math.ceil(this.top);this.r"\ "ight=Math.ceil(this.right);this.bottom=Math.ceil(this.bottom);this.left"\ "=Math.ceil(this.left);return this};g.floor=function(){this.top=Math.flo"\ "or(this.top);this.right=Math.floor(this.right);this.bottom=Math.floor(t"\ "his.bottom);this.left=Math.floor(this.left);return this};g.round=functi"\ "on(){this.top=Math.round(this.top);this.right=Math.round(this.right);th"\ "is.bottom=Math.round(this.bottom);this.left=Math.round(this.left);retur"\ "n this};\ng.scale=function(a,b){var c=da(b)?b:a;this.left*=a;this.right"\ "*=a;this.top*=c;this.bottom*=c;return this};function N(a,b,c,d){this.le"\ "ft=a;this.top=b;this.width=c;this.height=d}g=N.prototype;g.toString=fun"\ "ction(){return\"(\"+this.left+\", \"+this.top+\" - \"+this.width+\"w x "\ "\"+this.height+\"h)\"};g.contains=function(a){return a instanceof N?thi"\ "s.left<=a.left&&this.left+this.width>=a.left+a.width&&this.top<=a.top&&"\ "this.top+this.height>=a.top+a.height:a.x>=this.left&&a.x<=this.left+thi"\ "s.width&&a.y>=this.top&&a.y<=this.top+this.height};\ng.ceil=function(){"\ "this.left=Math.ceil(this.left);this.top=Math.ceil(this.top);this.width="\ "Math.ceil(this.width);this.height=Math.ceil(this.height);return this};g"\ ".floor=function(){this.left=Math.floor(this.left);this.top=Math.floor(t"\ "his.top);this.width=Math.floor(this.width);this.height=Math.floor(this."\ "height);return this};g.round=function(){this.left=Math.round(this.left)"\ ";this.top=Math.round(this.top);this.width=Math.round(this.width);this.h"\ "eight=Math.round(this.height);return this};\ng.scale=function(a,b){var "\ "c=da(b)?b:a;this.left*=a;this.width*=a;this.top*=c;this.height*=c;retur"\ "n this};function O(a,b){var c=w(a);return c.defaultView&&c.defaultView."\ "getComputedStyle&&(c=c.defaultView.getComputedStyle(a,null))?c[b]||c.ge"\ "tPropertyValue(b)||\"\":\"\"}function P(a,b){return O(a,b)||(a.currentS"\ "tyle?a.currentStyle[b]:null)||a.style&&a.style[b]}function cb(a){var b;"\ "try{b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bo"\ "ttom:0}}return b}\nfunction db(a){var b=w(a),c=P(a,\"position\"),d=\"fi"\ "xed\"==c||\"absolute\"==c;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if("\ "c=P(a,\"position\"),d=d&&\"static\"==c&&a!=b.documentElement&&a!=b.body"\ ",!d&&(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight||\"fix"\ "ed\"==c||\"absolute\"==c||\"relative\"==c))return a;return null}\nfunct"\ "ion eb(a){var b=w(a),c=P(a,\"position\"),d=new v(0,0),e=(b?w(b):documen"\ "t).documentElement;if(a==e)return d;if(a.getBoundingClientRect)a=cb(a),"\ "b=Ma(b?new x(w(b)):Ca||(Ca=new x)),d.x=a.left+b.x,d.y=a.top+b.y;else if"\ "(b.getBoxObjectFor)a=b.getBoxObjectFor(a),b=b.getBoxObjectFor(e),d.x=a."\ "screenX-b.screenX,d.y=a.screenY-b.screenY;else{var f=a;do{d.x+=f.offset"\ "Left;d.y+=f.offsetTop;f!=a&&(d.x+=f.clientLeft||0,d.y+=f.clientTop||0);"\ "if(\"fixed\"==P(f,\"position\")){d.x+=b.body.scrollLeft;d.y+=b.body.scr"\ "ollTop;\nbreak}f=f.offsetParent}while(f&&f!=a);\"absolute\"==c&&(d.y-=b"\ ".body.offsetTop);for(f=a;(f=db(f))&&f!=b.body&&f!=e;)d.x-=f.scrollLeft,"\ "d.y-=f.scrollTop}return d}function fb(a){if(1==a.nodeType){if(a.getBoun"\ "dingClientRect)a=cb(a),a=new v(a.left,a.top);else{var b=Ma(a?new x(w(a)"\ "):Ca||(Ca=new x));a=eb(a);a=new v(a.x-b.x,a.y-b.y)}return a}var b=p(a.H"\ "),c=a;a.targetTouches?c=a.targetTouches[0]:b&&a.H().targetTouches&&(c=a"\ ".H().targetTouches[0]);return new v(c.clientX,c.clientY)}\nfunction gb("\ "a){var b=a.offsetWidth,c=a.offsetHeight;return l(b)&&(b||c)||!a.getBoun"\ "dingClientRect?new Da(b,c):(a=cb(a),new Da(a.right-a.left,a.bottom-a.to"\ "p))};function Q(a,b){return!!a&&1==a.nodeType&&(!b||a.tagName.toUpperCa"\ "se()==b)}function hb(a){return ib(a,!0)&&jb(a)&&\"none\"!=R(a,\"pointer"\ "-events\")}function kb(a){return Q(a,\"OPTION\")?!0:Q(a,\"INPUT\")?(a=a"\ ".type.toLowerCase(),\"checkbox\"==a||\"radio\"==a):!1}function lb(a){if"\ "(!kb(a))throw new t(15,\"Element is not selectable\");var b=\"selected"\ "\",c=a.type&&a.type.toLowerCase();if(\"checkbox\"==c||\"radio\"==c)b=\""\ "checked\";return!!a[b]}var mb=\"BUTTON INPUT OPTGROUP OPTION SELECT TEX"\ "TAREA\".split(\" \");\nfunction jb(a){var b=a.tagName.toUpperCase();ret"\ "urn ka(mb,b)?a.disabled?!1:a.parentNode&&1==a.parentNode.nodeType&&\"OP"\ "TGROUP\"==b||\"OPTION\"==b?jb(a.parentNode):!Ka(a,function(a){var b=a.p"\ "arentNode;if(b&&Q(b,\"FIELDSET\")&&b.disabled){if(!Q(a,\"LEGEND\"))retu"\ "rn!0;for(;a=void 0!=a.previousElementSibling?a.previousElementSibling:F"\ "a(a.previousSibling);)if(Q(a,\"LEGEND\"))return!0}return!1},!0):!0}\nfu"\ "nction S(a){for(a=a.parentNode;a&&1!=a.nodeType&&9!=a.nodeType&&11!=a.n"\ "odeType;)a=a.parentNode;return Q(a)?a:null}\nfunction R(a,b){var c=fa(b"\ ");if(\"float\"==c||\"cssFloat\"==c||\"styleFloat\"==c)c=\"cssFloat\";c="\ "O(a,c)||nb(a,c);if(null===c)c=null;else if(ka(na,b)&&(qa.test(\"#\"==c."\ "charAt(0)?c:\"#\"+c)||ua(c).length||ma&&ma[c.toLowerCase()]||sa(c).leng"\ "th)){var d=sa(c);if(!d.length){a:if(d=ua(c),!d.length){d=(d=ma[c.toLowe"\ "rCase()])?d:\"#\"==c.charAt(0)?c:\"#\"+c;if(qa.test(d)&&(d=pa(d),d=pa(d"\ "),d=[parseInt(d.substr(1,2),16),parseInt(d.substr(3,2),16),parseInt(d.s"\ "ubstr(5,2),16)],d.length))break a;d=[]}3==d.length&&d.push(1)}c=4!=\nd."\ "length?c:\"rgba(\"+d.join(\", \")+\")\"}return c}function nb(a,b){var c"\ "=a.currentStyle||a.style,d=c[b];!l(d)&&p(c.getPropertyValue)&&(d=c.getP"\ "ropertyValue(b));return\"inherit\"!=d?l(d)?d:null:(c=S(a))?nb(c,b):null"\ "}\nfunction ib(a,b){function c(a){if(\"none\"==R(a,\"display\"))return!"\ "1;a=S(a);return!a||c(a)}function d(a){var b=T(a);return 0<b.height&&0<b"\ ".width?!0:Q(a,\"PATH\")&&(0<b.height||0<b.width)?(a=R(a,\"stroke-width"\ "\"),!!a&&0<parseInt(a,10)):\"hidden\"!=R(a,\"overflow\")&&ja(a.childNod"\ "es,function(a){return a.nodeType==Ea||Q(a)&&d(a)})}function e(a){var b="\ "R(a,\"-o-transform\")||R(a,\"-webkit-transform\")||R(a,\"-ms-transform"\ "\")||R(a,\"-moz-transform\")||R(a,\"transform\");if(b&&\"none\"!==b)ret"\ "urn b=fb(a),a=T(a),0<=b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=S(a);retur"\ "n!a||e(a)}if(!Q(a))throw Error(\"Argument to isShown must be of type El"\ "ement\");if(Q(a,\"OPTION\")||Q(a,\"OPTGROUP\")){var f=Ka(a,function(a){"\ "return Q(a,\"SELECT\")});return!!f&&ib(f,!0)}return(f=ob(a))?!!f.I&&0<f"\ ".rect.width&&0<f.rect.height&&ib(f.I,b):Q(a,\"INPUT\")&&\"hidden\"==a.t"\ "ype.toLowerCase()||Q(a,\"NOSCRIPT\")||\"hidden\"==R(a,\"visibility\")||"\ "!c(a)||!b&&0==pb(a)||!d(a)||qb(a)==rb?!1:e(a)}var rb=\"hidden\";\nfunct"\ "ion qb(a){function b(a){var b=a;if(\"visible\"==q)if(a==f)b=h;else if(a"\ "==h)return{x:\"visible\",y:\"visible\"};b={x:R(b,\"overflow-x\"),y:R(b,"\ "\"overflow-y\")};a==f&&(b.x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"h"\ "idden\"==b.y?\"hidden\":\"auto\");return b}function c(a){var b=R(a,\"po"\ "sition\");if(\"fixed\"==b)return f;for(a=S(a);a&&a!=f&&(0==R(a,\"displa"\ "y\").lastIndexOf(\"inline\",0)||\"absolute\"==b&&\"static\"==R(a,\"posi"\ "tion\"));)a=S(a);return a}var d=T(a),e=w(a),f=e.documentElement,h=e.bod"\ "y,q=R(f,\"overflow\");for(a=c(a);a;a=\nc(a)){var n=T(a),e=b(a),A=d.left"\ ">=n.left+n.width,n=d.top>=n.top+n.height;if(A&&\"hidden\"==e.x||n&&\"hi"\ "dden\"==e.y)return rb;if(A&&\"visible\"!=e.x||n&&\"visible\"!=e.y)retur"\ "n qb(a)==rb?rb:\"scroll\"}return\"none\"}\nfunction T(a){var b=ob(a);if"\ "(b)return b.rect;if(p(a.getBBox))try{var c=a.getBBox();return new N(c.x"\ ",c.y,c.width,c.height)}catch(d){throw d;}else{if(Q(a,\"HTML\"))return a"\ "=((w(a)?w(a).parentWindow||w(a).defaultView:window)||window).document,a"\ "=\"CSS1Compat\"==a.compatMode?a.documentElement:a.body,a=new Da(a.clien"\ "tWidth,a.clientHeight),new N(0,0,a.width,a.height);var b=fb(a),c=a.offs"\ "etWidth,e=a.offsetHeight;c||(e||!a.getBoundingClientRect)||(a=a.getBoun"\ "dingClientRect(),c=a.right-a.left,e=a.bottom-a.top);\nreturn new N(b.x,"\ "b.y,c,e)}}function ob(a){var b=Q(a,\"MAP\");if(!b&&!Q(a,\"AREA\"))retur"\ "n null;var c=b?a:Q(a.parentNode,\"MAP\")?a.parentNode:null,d=null,e=nul"\ "l;if(c&&c.name&&(d=M.T('/descendant::*[@usemap = \"#'+c.name+'\"]',w(c)"\ "))&&(e=T(d),!b&&\"default\"!=a.shape.toLowerCase())){var f=sb(a);a=Math"\ ".min(Math.max(f.left,0),e.width);b=Math.min(Math.max(f.top,0),e.height)"\ ";c=Math.min(f.width,e.width-a);f=Math.min(f.height,e.height-b);e=new N("\ "a+e.left,b+e.top,c,f)}return{I:d,rect:e||new N(0,0,0,0)}}\nfunction sb("\ "a){var b=a.shape.toLowerCase();a=a.coords.split(\",\");if(\"rect\"==b&&"\ "4==a.length){var b=a[0],c=a[1];return new N(b,c,a[2]-b,a[3]-c)}if(\"cir"\ "cle\"==b&&3==a.length)return b=a[2],new N(a[0]-b,a[1]-b,2*b,2*b);if(\"p"\ "oly\"==b&&2<a.length){for(var b=a[0],c=a[1],d=b,e=c,f=2;f+1<a.length;f+"\ "=2)b=Math.min(b,a[f]),d=Math.max(d,a[f]),c=Math.min(c,a[f+1]),e=Math.ma"\ "x(e,a[f+1]);return new N(b,c,d-b,e-c)}return new N(0,0,0,0)}\nfunction "\ "pb(a){var b=1,c=R(a,\"opacity\");c&&(b=Number(c));(a=S(a))&&(b*=pb(a));"\ "return b};function tb(a,b){this.c=ea.document.documentElement;this.f=nu"\ "ll;var c=La(w(this.c));c&&ub(this,c);this.i=a||new vb;this.G=b||new wb}"\ "function ub(a,b){a.c=b;a.f=Q(b,\"OPTION\")?Ka(b,function(a){return Q(a,"\ "\"SELECT\")}):null}\ntb.prototype.k=function(a,b,c,d,e,f,h){if(!f&&!hb("\ "this.c))return!1;if(d&&xb!=a&&yb!=a)throw new t(12,\"Event type does no"\ "t allow related target: \"+a);b={clientX:b.x,clientY:b.y,button:c,altKe"\ "y:this.i.d(4),ctrlKey:this.i.d(2),shiftKey:this.i.d(1),metaKey:this.i.d"\ "(8),wheelDelta:e||0,relatedTarget:d||null};h=h||1;c=this.c;if(a!=zb&&a!"\ "=Ab&&h in Bb)c=Bb[h];else if(this.f)a:switch(a){case zb:case Cb:c=this."\ "f.multiple?this.c:this.f;break a;default:c=this.f.multiple?this.c:null}"\ "return c?this.G.k(c,a,b):!0};\ntb.prototype.v=function(a,b,c,d,e){funct"\ "ion f(b,c){var d={identifier:b,screenX:c.x,screenY:c.y,clientX:c.x,clie"\ "ntY:c.y,pageX:c.x,pageY:c.y};h.changedTouches.push(d);if(a==Db||a==Eb)h"\ ".touches.push(d),h.targetTouches.push(d)}var h={touches:[],targetTouche"\ "s:[],changedTouches:[],altKey:this.i.d(4),ctrlKey:this.i.d(2),shiftKey:"\ "this.i.d(1),metaKey:this.i.d(8),relatedTarget:null,scale:0,rotation:0};"\ "f(b,c);l(d)&&f(d,e);return this.G.v(this.c,a,h)};function vb(){this.S=0"\ "}\nvb.prototype.d=function(a){return 0!=(this.S&a)};var Bb={};function "\ "wb(){}wb.prototype.k=function(a,b,c){return Fb(a,b,c)};wb.prototype.v=f"\ "unction(a,b,c){return Fb(a,b,c)};function U(a,b,c){this.n=a;this.r=b;th"\ "is.s=c}U.prototype.create=function(a){a=w(a).createEvent(\"HTMLEvents\""\ ");a.initEvent(this.n,this.r,this.s);return a};U.prototype.toString=aa("\ "\"n\");function V(a,b,c){U.call(this,a,b,c)}r(V,U);\nV.prototype.create"\ "=function(a,b){if(this==Gb)throw new t(9,\"Browser does not support a m"\ "ouse pixel scroll event.\");var c=w(a),d=c?c.parentWindow||c.defaultVie"\ "w:window,c=c.createEvent(\"MouseEvents\");this==Hb&&(c.wheelDelta=b.whe"\ "elDelta);c.initMouseEvent(this.n,this.r,this.s,d,1,0,0,b.clientX,b.clie"\ "ntY,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,b.button,b.relatedTarget);r"\ "eturn c};function W(a,b,c){U.call(this,a,b,c)}r(W,U);\nW.prototype.crea"\ "te=function(a,b){function c(b){var c=ha(b,function(b){return{identifier"\ ":b.identifier,screenX:b.screenX,screenY:b.screenY,clientX:b.clientX,cli"\ "entY:b.clientY,pageX:b.pageX,pageY:b.pageY,target:a}});c.item=function("\ "a){return c[a]};return c}var d=w(a),e=d?d.parentWindow||d.defaultView:w"\ "indow,f=c(b.changedTouches),h=b.touches==b.changedTouches?f:c(b.touches"\ "),q=b.targetTouches==b.changedTouches?f:c(b.targetTouches),d=d.createEv"\ "ent(\"MouseEvents\");d.initMouseEvent(this.n,this.r,this.s,e,\n1,0,0,b."\ "clientX,b.clientY,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,0,b.relatedTa"\ "rget);d.touches=h;d.targetTouches=q;d.changedTouches=f;d.scale=b.scale;"\ "d.rotation=b.rotation;return d};\nvar Ib=new U(\"change\",!0,!1),zb=new"\ " V(\"click\",!0,!0),Ab=new V(\"mousedown\",!0,!0),Jb=new V(\"mousemove"\ "\",!0,!1),yb=new V(\"mouseout\",!0,!0),xb=new V(\"mouseover\",!0,!0),Cb"\ "=new V(\"mouseup\",!0,!0),Hb=new V(\"mousewheel\",!0,!0),Gb=new V(\"Moz"\ "MousePixelScroll\",!0,!0),Kb=new W(\"touchend\",!0,!0),Eb=new W(\"touch"\ "move\",!0,!0),Db=new W(\"touchstart\",!0,!0);function Fb(a,b,c){b=b.cre"\ "ate(a,c);\"isTrusted\"in b||(b.isTrusted=!1);return a.dispatchEvent(b)}"\ ";function X(a,b){this.l={};this.e=[];var c=arguments.length;if(1<c){if("\ "c%2)throw Error(\"Uneven number of arguments\");for(var d=0;d<c;d+=2)th"\ "is.set(arguments[d],arguments[d+1])}else if(a){var e;if(a instanceof X)"\ "for(d=Lb(a),Mb(a),e=[],c=0;c<a.e.length;c++)e.push(a.l[a.e[c]]);else{va"\ "r c=[],f=0;for(d in a)c[f++]=d;d=c;c=[];f=0;for(e in a)c[f++]=a[e];e=c}"\ "for(c=0;c<d.length;c++)this.set(d[c],e[c])}}X.prototype.u=0;X.prototype"\ ".V=0;function Lb(a){Mb(a);return a.e.concat()}\nfunction Mb(a){if(a.u!="\ "a.e.length){for(var b=0,c=0;b<a.e.length;){var d=a.e[b];Object.prototyp"\ "e.hasOwnProperty.call(a.l,d)&&(a.e[c++]=d);b++}a.e.length=c}if(a.u!=a.e"\ ".length){for(var e={},c=b=0;b<a.e.length;)d=a.e[b],Object.prototype.has"\ "OwnProperty.call(e,d)||(a.e[c++]=d,e[d]=1),b++;a.e.length=c}}X.prototyp"\ "e.get=function(a,b){return Object.prototype.hasOwnProperty.call(this.l,"\ "a)?this.l[a]:b};\nX.prototype.set=function(a,b){Object.prototype.hasOwn"\ "Property.call(this.l,a)||(this.u++,this.e.push(a),this.V++);this.l[a]=b"\ "};var Ob={};function Y(a,b,c){var d=typeof a;(\"object\"==d&&null!=a||"\ "\"function\"==d)&&(a=a.a);a=new Pb(a,b,c);!b||b in Ob&&!c||(Ob[b]={key:"\ "a,shift:!1},c&&(Ob[c]={key:a,shift:!0}));return a}function Pb(a,b,c){th"\ "is.code=a;this.N=b||null;this.ga=c||this.N}Y(8);Y(9);Y(13);var Qb=Y(16)"\ ",Rb=Y(17),Sb=Y(18);Y(19);Y(20);Y(27);Y(32,\" \");Y(33);Y(34);Y(35);Y(36"\ ");Y(37);Y(38);Y(39);Y(40);Y(44);Y(45);Y(46);Y(48,\"0\",\")\");Y(49,\"1"\ "\",\"!\");Y(50,\"2\",\"@\");Y(51,\"3\",\"#\");Y(52,\"4\",\"$\");Y(53,\""\ "5\",\"%\");Y(54,\"6\",\"^\");Y(55,\"7\",\"&\");\nY(56,\"8\",\"*\");Y(57"\ ",\"9\",\"(\");Y(65,\"a\",\"A\");Y(66,\"b\",\"B\");Y(67,\"c\",\"C\");Y(6"\ "8,\"d\",\"D\");Y(69,\"e\",\"E\");Y(70,\"f\",\"F\");Y(71,\"g\",\"G\");Y("\ "72,\"h\",\"H\");Y(73,\"i\",\"I\");Y(74,\"j\",\"J\");Y(75,\"k\",\"K\");Y"\ "(76,\"l\",\"L\");Y(77,\"m\",\"M\");Y(78,\"n\",\"N\");Y(79,\"o\",\"O\");"\ "Y(80,\"p\",\"P\");Y(81,\"q\",\"Q\");Y(82,\"r\",\"R\");Y(83,\"s\",\"S\")"\ ";Y(84,\"t\",\"T\");Y(85,\"u\",\"U\");Y(86,\"v\",\"V\");Y(87,\"w\",\"W\""\ ");Y(88,\"x\",\"X\");Y(89,\"y\",\"Y\");Y(90,\"z\",\"Z\");var Tb=Y(za?{b:"\ "91,a:91,opera:219}:ya?{b:224,a:91,opera:17}:{b:0,a:91,opera:null});\nY("\ "za?{b:92,a:92,opera:220}:ya?{b:224,a:93,opera:17}:{b:0,a:92,opera:null}"\ ");Y(za?{b:93,a:93,opera:0}:ya?{b:0,a:0,opera:16}:{b:93,a:null,opera:0})"\ ";Y({b:96,a:96,opera:48},\"0\");Y({b:97,a:97,opera:49},\"1\");Y({b:98,a:"\ "98,opera:50},\"2\");Y({b:99,a:99,opera:51},\"3\");Y({b:100,a:100,opera:"\ "52},\"4\");Y({b:101,a:101,opera:53},\"5\");Y({b:102,a:102,opera:54},\"6"\ "\");Y({b:103,a:103,opera:55},\"7\");Y({b:104,a:104,opera:56},\"8\");Y({"\ "b:105,a:105,opera:57},\"9\");Y({b:106,a:106,opera:u?56:42},\"*\");\nY({"\ "b:107,a:107,opera:u?61:43},\"+\");Y({b:109,a:109,opera:u?109:45},\"-\")"\ ";Y({b:110,a:110,opera:u?190:78},\".\");Y({b:111,a:111,opera:u?191:47},"\ "\"/\");Y(144);Y(112);Y(113);Y(114);Y(115);Y(116);Y(117);Y(118);Y(119);Y"\ "(120);Y(121);Y(122);Y(123);Y({b:107,a:187,opera:61},\"=\",\"+\");Y(108,"\ "\",\");Y({b:109,a:189,opera:109},\"-\",\"_\");Y(188,\",\",\"<\");Y(190,"\ "\".\",\">\");Y(191,\"/\",\"?\");Y(192,\"`\",\"~\");Y(219,\"[\",\"{\");Y"\ "(220,\"\\\\\",\"|\");Y(221,\"]\",\"}\");Y({b:59,a:186,opera:59},\";\","\ "\":\");Y(222,\"'\",'\"');var Z=new X;Z.set(1,Qb);Z.set(2,Rb);\nZ.set(4,"\ "Sb);Z.set(8,Tb);(function(a){var b=new X;s(Lb(a),function(c){b.set(a.ge"\ "t(c).code,c)});return b})(Z);function Ub(){tb.call(this);this.j=new v(0"\ ",0);this.t=new v(0,0)}r(Ub,tb);g=Ub.prototype;g.w=!1;g.M=!1;g.q=0;g.C=0"\ ";g.U=2;g.move=function(a,b,c){this.d()||ub(this,a);a=T(a);this.j.x=b.x+"\ "a.left;this.j.y=b.y+a.top;l(c)&&(this.t.x=c.x+a.left,this.t.y=c.y+a.top"\ ");this.d()&&(this.w=!0,Vb(this,Eb))};g.d=function(){return!!this.q};fun"\ "ction Vb(a,b){if(!a.d())throw new t(13,\"Should never fire event when t"\ "ouchscreen is not pressed.\");var c,d;a.C&&(c=a.C,d=a.t);a.v(b,a.q,a.j,"\ "c,d)};function Wb(a,b){this.x=a;this.y=b}r(Wb,v);Wb.prototype.scale=v.p"\ "rototype.scale;Wb.prototype.add=function(a){this.x+=a.x;this.y+=a.y;ret"\ "urn this};function Xb(a){var b;if(\"none\"!=P(a,\"display\"))b=gb(a);el"\ "se{b=a.style;var c=b.display,d=b.visibility,e=b.position;b.visibility="\ "\"hidden\";b.position=\"absolute\";b.display=\"inline\";var f=gb(a);b.d"\ "isplay=c;b.position=e;b.visibility=d;b=f}return 0<b.width&&0<b.height||"\ "!a.offsetParent?b:Xb(a.offsetParent)};function Yb(a,b,c){if(!ib(a,!0))t"\ "hrow new t(11,\"Element is not currently visible and may not be manipul"\ "ated\");var d=w(a).body,e;e=eb(a);var f=eb(d),h,q,n,A;A=O(d,\"borderLef"\ "tWidth\");n=O(d,\"borderRightWidth\");h=O(d,\"borderTopWidth\");q=O(d,"\ "\"borderBottomWidth\");h=new bb(parseFloat(h),parseFloat(n),parseFloat("\ "q),parseFloat(A));q=e.x-f.x-h.left;e=e.y-f.y-h.top;f=d.clientHeight-a.o"\ "ffsetHeight;h=d.scrollLeft;n=d.scrollTop;h+=Math.min(q,Math.max(q-(d.cl"\ "ientWidth-a.offsetWidth),0));n+=Math.min(e,Math.max(e-\nf,0));e=new v(h"\ ",n);d.scrollLeft=e.x;d.scrollTop=e.y;b?b=new Wb(b.x,b.y):(b=Xb(a),b=new"\ " Wb(b.width/2,b.height/2));c=c||new Ub;c.move(a,b);if(c.d())throw new t"\ "(13,\"Cannot press touchscreen when already pressed.\");c.w=!1;c.q=c.U+"\ "+;Vb(c,Db);if(!c.d())throw new t(13,\"Cannot release touchscreen when n"\ "ot already pressed.\");Vb(c,Kb);if(!c.w){c.k(Jb,c.j,0);if(c.k(Ab,c.j,0)"\ "&&(a=c.f||c.c,b=La(w(a)),a!=b)){if(b&&p(b.blur)&&!Q(b,\"BODY\"))try{b.b"\ "lur()}catch(wa){throw wa;}p(a.focus)&&a.focus()}if(c.f&&hb(c.c)&&(a=\nc"\ ".f,b=lb(c.c),!b||a.multiple)){c.c.selected=!b;if(b=a.multiple){b=0;d=St"\ "ring($a).replace(/^[\\s\\xa0]+|[\\s\\xa0]+$/g,\"\").split(\".\");e=\"28"\ "\".replace(/^[\\s\\xa0]+|[\\s\\xa0]+$/g,\"\").split(\".\");f=Math.max(d"\ ".length,e.length);for(q=0;0==b&&q<f;q++){h=d[q]||\"\";n=e[q]||\"\";A=Re"\ "gExp(\"(\\\\d*)(\\\\D*)\",\"g\");var Nb=RegExp(\"(\\\\d*)(\\\\D*)\",\"g"\ "\");do{var F=A.exec(h)||[\"\",\"\",\"\"],G=Nb.exec(n)||[\"\",\"\",\"\"]"\ ";if(0==F[0].length&&0==G[0].length)break;b=((0==F[1].length?0:parseInt("\ "F[1],10))<(0==G[1].length?0:parseInt(G[1],10))?-1:(0==\nF[1].length?0:p"\ "arseInt(F[1],10))>(0==G[1].length?0:parseInt(G[1],10))?1:0)||((0==F[2]."\ "length)<(0==G[2].length)?-1:(0==F[2].length)>(0==G[2].length)?1:0)||(F["\ "2]<G[2]?-1:F[2]>G[2]?1:0)}while(0==b)}b=!(0<=b)}b||Fb(a,Ib)}c.k(Cb,c.j,"\ "0);a=c.j;hb(c.c)&&(!c.f&&kb(c.c)&&lb(c.c),c.k(zb,a,0,null,0,!1,void 0))"\ "}Bb={};c.q=0;c.C=0;c.M=!1}var Zb=[\"_\"],$=k;Zb[0]in $||!$.execScript||"\ "$.execScript(\"var \"+Zb[0]);for(var $b;Zb.length&&($b=Zb.shift());)Zb."\ "length||void 0===Yb?$=$[$b]?$[$b]:$[$b]={}:$[$b]=Yb;; return this._.app"\ "ly(null,arguments);}.apply({navigator:typeof window!=undefined?window.n"\ "avigator:null,document:typeof window!=undefined?window.document:null}, "\ "arguments);}" CLEAR = \ "function(){return function(){function f(a){return function(){return thi"\ "s[a]}}function k(a){return function(){return a}}var l=this;\nfunction a"\ "a(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)return"\ "\"array\";if(a instanceof Object)return b;var c=Object.prototype.toStri"\ "ng.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Arra"\ "y]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&"\ "\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("\ "\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!"\ "=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.proper"\ "tyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse "\ "if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";retur"\ "n b}function m(a){return\"string\"==typeof a}function n(a){return\"func"\ "tion\"==aa(a)}function ba(a,b){function c(){}c.prototype=b.prototype;a."\ "da=b.prototype;a.prototype=new c};var ca=window;function da(a){return S"\ "tring(a).replace(/\\-([a-z])/g,function(a,c){return c.toUpperCase()})};"\ "var ea=Array.prototype;function p(a,b){for(var c=a.length,d=m(a)?a.spli"\ "t(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function fa(a,b){"\ "if(a.reduce)return a.reduce(b,\"\");var c=\"\";p(a,function(d,e){c=b.ca"\ "ll(void 0,c,d,e,a)});return c}function ga(a,b){for(var c=a.length,d=m(a"\ ")?a.split(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return"\ "!0;return!1}\nfunction q(a,b){var c;a:if(m(a))c=m(b)&&1==b.length?a.ind"\ "exOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c in a&&a[c]===b)break a;c="\ "-1}return 0<=c}function ha(a,b,c){return 2>=arguments.length?ea.slice.c"\ "all(a,b):ea.slice.call(a,b,c)};var ia={aliceblue:\"#f0f8ff\",antiquewhi"\ "te:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",azure:\"#f0ffff"\ "\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\",blanchedalmon"\ "d:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brown:\"#a52a2a\""\ ",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",cho"\ "colate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6495ed\",cornsil"\ "k:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\""\ ",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:\"#a9a9a9\",da"\ "rkgreen:\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki:\"#bdb76b\",darkma"\ "genta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:\"#ff8c00\",dar"\ "korchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9967a\",darkseag"\ "reen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray:\"#2f4f4f\",da"\ "rkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkviolet:\"#9400d3"\ "\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:\"#696969\",dim"\ "grey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22222\",floralwhi"\ "te:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff\",gainsboro:\""\ "#dcdcdc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\",goldenrod:\"#daa520"\ "\",gray:\"#808080\",green:\"#008000\",greenyellow:\"#adff2f\",grey:\"#8"\ "08080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianred:\"#cd5c5c\","\ "indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",lavender:\"#e6e6"\ "fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lemonchiffon:\"#ff"\ "facd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",lightcyan:\"#e0ffff"\ "\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3\",lightgreen:\""\ "#90ee90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1\",lightsalmon:\"#ff"\ "a07a\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#87cefa\",lightslateg"\ "ray:\"#778899\",lightslategrey:\"#778899\",lightsteelblue:\"#b0c4de\",l"\ "ightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32cd32\",linen:\"#"\ "faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediumaquamarine:\"#66c"\ "daa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",mediumpurple:\"#9"\ "370db\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7b68ee\",mediumsp"\ "ringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediumvioletred:\"#c7"\ "1585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",mistyrose:\"#ffe4"\ "e1\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",navy:\"#000080\",ol"\ "dlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23\",orange:\"#ffa"\ "500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegoldenrod:\"#eee8aa"\ "\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palevioletred:\"#db7"\ "093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:\"#cd853f\",pin"\ "k:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",purple:\"#800080"\ "\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#4169e1\",saddlebr"\ "own:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\",seagreen:\"#2"\ "e8b57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",silver:\"#c0c0c0\",sk"\ "yblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#708090\",slategrey"\ ":\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",steelblue:\"#4682"\ "b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\",tomato:\"#ff6"\ "347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f5deb3\",white:"\ "\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yellowgreen:\"#9a"\ "cd32\"};var ja=\"background-color border-top-color border-right-color b"\ "order-bottom-color border-left-color color outline-color\".split(\" \")"\ ",ka=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;function la(a){if(!ma.te"\ "st(a))throw Error(\"'\"+a+\"' is not a valid hex color\");4==a.length&&"\ "(a=a.replace(ka,\"#$1$1$2$2$3$3\"));return a.toLowerCase()}var ma=/^#(?"\ ":[0-9a-f]{3}){1,2}$/i,na=/^(?:rgba)?\\((\\d{1,3}),\\s?(\\d{1,3}),\\s?("\ "\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction oa(a){var b=a.match(na);i"\ "f(b){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b=Number(b[4]);if"\ "(0<=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)return[a,c,d,b]}r"\ "eturn[]}var pa=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2}),\\s"\ "?(0|[1-9]\\d{0,2})\\)$/i;function qa(a){var b=a.match(pa);if(b){a=Numbe"\ "r(b[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>=a&&0<=c&&255>=c"\ "&&0<=b&&255>=b)return[a,c,b]}return[]};function r(a,b){this.code=a;this"\ ".state=ra[a]||sa;this.message=b||\"\";var c=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";t"\ "his.name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||"\ "\"\"}ba(r,Error);\nvar sa=\"unknown error\",ra={15:\"element not select"\ "able\",11:\"element not visible\",31:\"ime engine activation failed\",3"\ "0:\"ime not available\",24:\"invalid cookie domain\",29:\"invalid eleme"\ "nt coordinates\",12:\"invalid element state\",32:\"invalid selector\",5"\ "1:\"invalid selector\",52:\"invalid selector\",17:\"javascript error\","\ "405:\"unsupported operation\",34:\"move target out of bounds\",27:\"no "\ "such alert\",7:\"no such element\",8:\"no such frame\",23:\"no such win"\ "dow\",28:\"script timeout\",33:\"session not created\",10:\"stale eleme"\ "nt reference\",\n0:\"success\",21:\"timeout\",25:\"unable to set cookie"\ "\",26:\"unexpected alert open\"};ra[13]=sa;ra[9]=\"unknown command\";r."\ "prototype.toString=function(){return this.name+\": \"+this.message};var"\ " t,u,v,ta=l.navigator;v=ta&&ta.platform||\"\";t=-1!=v.indexOf(\"Mac\");"\ "u=-1!=v.indexOf(\"Win\");var w=-1!=v.indexOf(\"Linux\");var x;function "\ "y(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}y.prototype.toString"\ "=function(){return\"(\"+this.x+\", \"+this.y+\")\"};y.prototype.ceil=fu"\ "nction(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this}"\ ";y.prototype.floor=function(){this.x=Math.floor(this.x);this.y=Math.flo"\ "or(this.y);return this};y.prototype.round=function(){this.x=Math.round("\ "this.x);this.y=Math.round(this.y);return this};function A(a,b){this.wid"\ "th=a;this.height=b}A.prototype.toString=function(){return\"(\"+this.wid"\ "th+\" x \"+this.height+\")\"};A.prototype.ceil=function(){this.width=Ma"\ "th.ceil(this.width);this.height=Math.ceil(this.height);return this};A.p"\ "rototype.floor=function(){this.width=Math.floor(this.width);this.height"\ "=Math.floor(this.height);return this};A.prototype.round=function(){this"\ ".width=Math.round(this.width);this.height=Math.round(this.height);retur"\ "n this};var ua=3;function va(a){for(;a&&1!=a.nodeType;)a=a.previousSibl"\ "ing;return a}function wa(a,b){if(a.contains&&1==b.nodeType)return a==b|"\ "|a.contains(b);if(\"undefined\"!=typeof a.compareDocumentPosition)retur"\ "n a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.pare"\ "ntNode;return b==a}\nfunction xa(a,b){if(a==b)return 0;if(a.compareDocu"\ "mentPosition)return a.compareDocumentPosition(b)&2?1:-1;if(\"sourceInde"\ "x\"in a||a.parentNode&&\"sourceIndex\"in a.parentNode){var c=1==a.nodeT"\ "ype,d=1==b.nodeType;if(c&&d)return a.sourceIndex-b.sourceIndex;var e=a."\ "parentNode,g=b.parentNode;return e==g?ya(a,b):!c&&wa(e,b)?-1*za(a,b):!d"\ "&&wa(g,a)?za(b,a):(c?a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:g.so"\ "urceIndex)}d=B(a);c=d.createRange();c.selectNode(a);c.collapse(!0);d=d."\ "createRange();d.selectNode(b);\nd.collapse(!0);return c.compareBoundary"\ "Points(l.Range.START_TO_END,d)}function za(a,b){var c=a.parentNode;if(c"\ "==b)return-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return ya(d,a)"\ "}function ya(a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;ret"\ "urn 1}function B(a){return 9==a.nodeType?a:a.ownerDocument||a.document}"\ "function Aa(a,b,c){c||(a=a.parentNode);for(c=0;a;){if(b(a))return a;a=a"\ ".parentNode;c++}return null}function Ba(a){try{return a&&a.activeElemen"\ "t}catch(b){}return null}\nfunction C(a){this.I=a||l.document||document}"\ "function Ca(a){var b=a.I;a=b.body;b=b.parentWindow||b.defaultView;retur"\ "n new y(b.pageXOffset||a.scrollLeft,b.pageYOffset||a.scrollTop)}C.proto"\ "type.contains=wa;function D(a){var b=null,c=a.nodeType;1==c&&(b=a.textC"\ "ontent,b=void 0==b||null==b?a.innerText:b,b=void 0==b||null==b?\"\":b);"\ "if(\"string\"!=typeof b)if(9==c||1==c){a=9==c?a.documentElement:a.first"\ "Child;for(var c=0,d=[],b=\"\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d["\ "c++]=a;while(a=a.firstChild);for(;c&&!(a=d[--c].nextSibling););}}else b"\ "=a.nodeValue;return\"\"+b}\nfunction E(a,b,c){if(null===b)return!0;try{"\ "if(!a.getAttribute)return!1}catch(d){return!1}return null==c?!!a.getAtt"\ "ribute(b):a.getAttribute(b,2)==c}function F(a,b,c,d,e){return Da.call(n"\ "ull,a,b,m(c)?c:null,m(d)?d:null,e||new H)}\nfunction Da(a,b,c,d,e){b.ge"\ "tElementsByName&&d&&\"name\"==c?(b=b.getElementsByName(d),p(b,function("\ "b){a.matches(b)&&e.add(b)})):b.getElementsByClassName&&d&&\"class\"==c?"\ "(b=b.getElementsByClassName(d),p(b,function(b){b.className==d&&a.matche"\ "s(b)&&e.add(b)})):b.getElementsByTagName&&(b=b.getElementsByTagName(a.g"\ "etName()),p(b,function(a){E(a,c,d)&&e.add(a)}));return e}function Ea(a,"\ "b,c,d,e){for(b=b.firstChild;b;b=b.nextSibling)E(b,c,d)&&a.matches(b)&&e"\ ".add(b);return e};function H(){this.g=this.f=null;this.n=0}function Fa("\ "a){this.v=a;this.next=this.p=null}H.prototype.unshift=function(a){a=new"\ " Fa(a);a.next=this.f;this.g?this.f.p=a:this.f=this.g=a;this.f=a;this.n+"\ "+};H.prototype.add=function(a){a=new Fa(a);a.p=this.g;this.f?this.g.nex"\ "t=a:this.f=this.g=a;this.g=a;this.n++};function Ga(a){return(a=a.f)?a.v"\ ":null}function I(a){return new Ha(a,!1)}function Ha(a,b){this.Z=a;this."\ "r=(this.w=b)?a.g:a.f;this.K=null}\nHa.prototype.next=function(){var a=t"\ "his.r;if(null==a)return null;var b=this.K=a;this.r=this.w?a.p:a.next;re"\ "turn b.v};function J(a,b,c,d,e){b=b.evaluate(d);c=c.evaluate(d);var g;i"\ "f(b instanceof H&&c instanceof H){e=I(b);for(d=e.next();d;d=e.next())fo"\ "r(b=I(c),g=b.next();g;g=b.next())if(a(D(d),D(g)))return!0;return!1}if(b"\ " instanceof H||c instanceof H){b instanceof H?e=b:(e=c,c=b);e=I(e);b=ty"\ "peof c;for(d=e.next();d;d=e.next()){switch(b){case \"number\":d=+D(d);b"\ "reak;case \"boolean\":d=!!D(d);break;case \"string\":d=D(d);break;defau"\ "lt:throw Error(\"Illegal primitive type for comparison.\");}if(a(d,c))r"\ "eturn!0}return!1}return e?\n\"boolean\"==typeof b||\"boolean\"==typeof "\ "c?a(!!b,!!c):\"number\"==typeof b||\"number\"==typeof c?a(+b,+c):a(b,c)"\ ":a(+b,+c)}function Ia(a,b,c,d){this.L=a;this.aa=b;this.H=c;this.k=d}Ia."\ "prototype.toString=f(\"L\");var Ja={};function K(a,b,c,d){if(a in Ja)th"\ "row Error(\"Binary operator already created: \"+a);a=new Ia(a,b,c,d);Ja"\ "[a.toString()]=a}K(\"div\",6,1,function(a,b,c){return a.d(c)/b.d(c)});K"\ "(\"mod\",6,1,function(a,b,c){return a.d(c)%b.d(c)});K(\"*\",6,1,functio"\ "n(a,b,c){return a.d(c)*b.d(c)});\nK(\"+\",5,1,function(a,b,c){return a."\ "d(c)+b.d(c)});K(\"-\",5,1,function(a,b,c){return a.d(c)-b.d(c)});K(\"<"\ "\",4,2,function(a,b,c){return J(function(a,b){return a<b},a,b,c)});K(\""\ ">\",4,2,function(a,b,c){return J(function(a,b){return a>b},a,b,c)});K("\ "\"<=\",4,2,function(a,b,c){return J(function(a,b){return a<=b},a,b,c)})"\ ";K(\">=\",4,2,function(a,b,c){return J(function(a,b){return a>=b},a,b,c"\ ")});K(\"=\",3,2,function(a,b,c){return J(function(a,b){return a==b},a,b"\ ",c,!0)});\nK(\"!=\",3,2,function(a,b,c){return J(function(a,b){return a"\ "!=b},a,b,c,!0)});K(\"and\",2,2,function(a,b,c){return a.j(c)&&b.j(c)});"\ "K(\"or\",1,2,function(a,b,c){return a.j(c)||b.j(c)});function Ka(a,b,c,"\ "d,e,g,h,z,s){this.o=a;this.H=b;this.Y=c;this.X=d;this.W=e;this.k=g;this"\ ".U=h;this.T=void 0!==z?z:h;this.$=!!s}Ka.prototype.toString=f(\"o\");va"\ "r La={};function L(a,b,c,d,e,g,h,z){if(a in La)throw Error(\"Function a"\ "lready created: \"+a+\".\");La[a]=new Ka(a,b,c,d,!1,e,g,h,z)}L(\"boolea"\ "n\",2,!1,!1,function(a,b){return b.j(a)},1);L(\"ceiling\",1,!1,!1,funct"\ "ion(a,b){return Math.ceil(b.d(a))},1);\nL(\"concat\",3,!1,!1,function(a"\ ",b){var c=ha(arguments,1);return fa(c,function(b,c){return b+c.c(a)})},"\ "2,null);L(\"contains\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return"\ "-1!=b.indexOf(a)},2);L(\"count\",1,!1,!1,function(a,b){return b.evaluat"\ "e(a).n},1,1,!0);L(\"false\",2,!1,!1,k(!1),0);L(\"floor\",1,!1,!1,functi"\ "on(a,b){return Math.floor(b.d(a))},1);\nL(\"id\",4,!1,!1,function(a,b){"\ "var c=a.h(),d=9==c.nodeType?c:c.ownerDocument,c=b.c(a).split(/\\s+/),e="\ "[];p(c,function(a){(a=d.getElementById(a))&&!q(e,a)&&e.push(a)});e.sort"\ "(xa);var g=new H;p(e,function(a){g.add(a)});return g},1);L(\"lang\",2,!"\ "1,!1,k(!1),1);L(\"last\",1,!0,!1,function(a){if(1!=arguments.length)thr"\ "ow Error(\"Function last expects ()\");return a.Q()},0);L(\"local-name"\ "\",3,!1,!0,function(a,b){var c=b?Ga(b.evaluate(a)):a.h();return c?c.nod"\ "eName.toLowerCase():\"\"},0,1,!0);\nL(\"name\",3,!1,!0,function(a,b){va"\ "r c=b?Ga(b.evaluate(a)):a.h();return c?c.nodeName.toLowerCase():\"\"},0"\ ",1,!0);L(\"namespace-uri\",3,!0,!1,k(\"\"),0,1,!0);L(\"normalize-space"\ "\",3,!1,!0,function(a,b){return(b?b.c(a):D(a.h())).replace(/[\\s\\xa0]+"\ "/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,1);L(\"not\",2,!1,!1,function"\ "(a,b){return!b.j(a)},1);L(\"number\",1,!1,!0,function(a,b){return b?b.d"\ "(a):+D(a.h())},0,1);L(\"position\",1,!0,!1,function(a){return a.R()},0)"\ ";L(\"round\",1,!1,!1,function(a,b){return Math.round(b.d(a))},1);\nL(\""\ "starts-with\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return 0==b.las"\ "tIndexOf(a,0)},2);L(\"string\",3,!1,!0,function(a,b){return b?b.c(a):D("\ "a.h())},0,1);L(\"string-length\",1,!1,!0,function(a,b){return(b?b.c(a):"\ "D(a.h())).length},0,1);\nL(\"substring\",3,!1,!1,function(a,b,c,d){c=c."\ "d(a);if(isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.d(a):Infin"\ "ity;if(isNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math."\ "max(c,0);a=b.c(a);if(Infinity==d)return a.substring(e);b=Math.round(d);"\ "return a.substring(e,c+b)},2,3);L(\"substring-after\",3,!1,!1,function("\ "a,b,c){b=b.c(a);a=c.c(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+"\ "a.length)},2);\nL(\"substring-before\",3,!1,!1,function(a,b,c){b=b.c(a)"\ ";a=c.c(a);a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);L(\"sum"\ "\",1,!1,!1,function(a,b){for(var c=I(b.evaluate(a)),d=0,e=c.next();e;e="\ "c.next())d+=+D(e);return d},1,1,!0);L(\"translate\",3,!1,!1,function(a,"\ "b,c,d){b=b.c(a);c=c.c(a);var e=d.c(a);a=[];for(d=0;d<c.length;d++){var "\ "g=c.charAt(d);g in a||(a[g]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d++)"\ "g=b.charAt(d),c+=g in a?a[g]:g;return c},3);L(\"true\",2,!1,!1,k(!0),0)"\ ";function Ma(a,b,c,d){this.o=a;this.P=b;this.w=c;this.ea=d}Ma.prototype"\ ".toString=f(\"o\");var Na={};function M(a,b,c,d){if(a in Na)throw Error"\ "(\"Axis already created: \"+a);Na[a]=new Ma(a,b,c,!!d)}M(\"ancestor\",f"\ "unction(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matches(d)&&c.unshif"\ "t(d);return c},!0);M(\"ancestor-or-self\",function(a,b){var c=new H,d=b"\ ";do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c},!0);\nM("\ "\"attribute\",function(a,b){var c=new H,d=a.getName(),e=b.attributes;if"\ "(e)if(\"*\"==d)for(var d=0,g;g=e[d];d++)c.add(g);else(g=e.getNamedItem("\ "d))&&c.add(g);return c},!1);M(\"child\",function(a,b,c,d,e){return Ea.c"\ "all(null,a,b,m(c)?c:null,m(d)?d:null,e||new H)},!1,!0);M(\"descendant\""\ ",F,!1,!0);M(\"descendant-or-self\",function(a,b,c,d){var e=new H;E(b,c,"\ "d)&&a.matches(b)&&e.add(b);return F(a,b,c,d,e)},!1,!0);\nM(\"following"\ "\",function(a,b,c,d){var e=new H;do for(var g=b;g=g.nextSibling;)E(g,c,"\ "d)&&a.matches(g)&&e.add(g),e=F(a,g,c,d,e);while(b=b.parentNode);return "\ "e},!1,!0);M(\"following-sibling\",function(a,b){for(var c=new H,d=b;d=d"\ ".nextSibling;)a.matches(d)&&c.add(d);return c},!1);M(\"namespace\",func"\ "tion(){return new H},!1);M(\"parent\",function(a,b){var c=new H;if(9==b"\ ".nodeType)return c;if(2==b.nodeType)return c.add(b.ownerElement),c;var "\ "d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nM(\"preceding\",f"\ "unction(a,b,c,d){var e=new H,g=[];do g.unshift(b);while(b=b.parentNode)"\ ";for(var h=1,z=g.length;h<z;h++){var s=[];for(b=g[h];b=b.previousSiblin"\ "g;)s.unshift(b);for(var G=0,fb=s.length;G<fb;G++)b=s[G],E(b,c,d)&&a.mat"\ "ches(b)&&e.add(b),e=F(a,b,c,d,e)}return e},!0,!0);M(\"preceding-sibling"\ "\",function(a,b){for(var c=new H,d=b;d=d.previousSibling;)a.matches(d)&"\ "&c.unshift(d);return c},!0);M(\"self\",function(a,b){var c=new H;a.matc"\ "hes(b)&&c.add(b);return c},!1);var N={};N.C=function(){var a={fa:\"http"\ "://www.w3.org/2000/svg\"};return function(b){return a[b]||null}}();N.k="\ "function(a,b,c){var d=B(a);try{var e=d.createNSResolver?d.createNSResol"\ "ver(d.documentElement):N.C;return d.evaluate(b,a,e,c,null)}catch(g){thr"\ "ow new r(32,\"Unable to locate an element with the xpath expression \"+"\ "b+\" because of the following error:\\n\"+g);}};\nN.q=function(a,b){if("\ "!a||1!=a.nodeType)throw new r(32,'The result of the xpath expression \""\ "'+b+'\" is: '+a+\". It should be an element.\");};N.M=function(a,b){var"\ " c=function(){var c=N.k(b,a,9);return c?c.singleNodeValue||null:b.selec"\ "tSingleNode?(c=B(b),c.setProperty&&c.setProperty(\"SelectionLanguage\","\ "\"XPath\"),b.selectSingleNode(a)):null}();null===c||N.q(c,a);return c};"\ "\nN.S=function(a,b){var c=function(){var c=N.k(b,a,7);if(c){for(var e=c"\ ".snapshotLength,g=[],h=0;h<e;++h)g.push(c.snapshotItem(h));return g}ret"\ "urn b.selectNodes?(c=B(b),c.setProperty&&c.setProperty(\"SelectionLangu"\ "age\",\"XPath\"),b.selectNodes(a)):[]}();p(c,function(b){N.q(b,a)});ret"\ "urn c};function O(a,b,c,d){this.left=a;this.top=b;this.width=c;this.hei"\ "ght=d}O.prototype.toString=function(){return\"(\"+this.left+\", \"+this"\ ".top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};O.prototype.contai"\ "ns=function(a){return a instanceof O?this.left<=a.left&&this.left+this."\ "width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a.top+a.h"\ "eight:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&a.y<=th"\ "is.top+this.height};\nO.prototype.ceil=function(){this.left=Math.ceil(t"\ "his.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.width)"\ ";this.height=Math.ceil(this.height);return this};O.prototype.floor=func"\ "tion(){this.left=Math.floor(this.left);this.top=Math.floor(this.top);th"\ "is.width=Math.floor(this.width);this.height=Math.floor(this.height);ret"\ "urn this};\nO.prototype.round=function(){this.left=Math.round(this.left"\ ");this.top=Math.round(this.top);this.width=Math.round(this.width);this."\ "height=Math.round(this.height);return this};function Oa(a,b){var c=B(a)"\ ";return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView"\ ".getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||\"\":\"\"}funct"\ "ion P(a){return Oa(a,\"position\")||(a.currentStyle?a.currentStyle.posi"\ "tion:null)||a.style&&a.style.position}function Pa(a){var b;try{b=a.getB"\ "oundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}retu"\ "rn b}\nfunction Qa(a){var b=B(a),c=P(a),d=\"fixed\"==c||\"absolute\"==c"\ ";for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=P(a),d=d&&\"static\"==c"\ "&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clientWidth||a.s"\ "crollHeight>a.clientHeight||\"fixed\"==c||\"absolute\"==c||\"relative\""\ "==c))return a;return null}\nfunction Ra(a){if(1==a.nodeType){var b;if(a"\ ".getBoundingClientRect)b=Pa(a),b=new y(b.left,b.top);else{b=Ca(a?new C("\ "B(a)):x||(x=new C));var c=B(a),d=P(a),e=new y(0,0),g=(c?B(c):document)."\ "documentElement;if(a!=g)if(a.getBoundingClientRect)a=Pa(a),c=Ca(c?new C"\ "(B(c)):x||(x=new C)),e.x=a.left+c.x,e.y=a.top+c.y;else if(c.getBoxObjec"\ "tFor)a=c.getBoxObjectFor(a),c=c.getBoxObjectFor(g),e.x=a.screenX-c.scre"\ "enX,e.y=a.screenY-c.screenY;else{var h=a;do{e.x+=h.offsetLeft;e.y+=h.of"\ "fsetTop;h!=a&&(e.x+=h.clientLeft||\n0,e.y+=h.clientTop||0);if(\"fixed\""\ "==P(h)){e.x+=c.body.scrollLeft;e.y+=c.body.scrollTop;break}h=h.offsetPa"\ "rent}while(h&&h!=a);\"absolute\"==d&&(e.y-=c.body.offsetTop);for(h=a;(h"\ "=Qa(h))&&h!=c.body&&h!=g;)e.x-=h.scrollLeft,e.y-=h.scrollTop}b=new y(e."\ "x-b.x,e.y-b.y)}return b}b=n(a.s);e=a;a.targetTouches?e=a.targetTouches["\ "0]:b&&a.s().targetTouches&&(e=a.s().targetTouches[0]);return new y(e.cl"\ "ientX,e.clientY)};function Q(a,b){return!!a&&1==a.nodeType&&(!b||a.tagN"\ "ame.toUpperCase()==b)}var Sa=\"BUTTON INPUT OPTGROUP OPTION SELECT TEXT"\ "AREA\".split(\" \");\nfunction Ta(a){var b=a.tagName.toUpperCase();retu"\ "rn q(Sa,b)?a.disabled?!1:a.parentNode&&1==a.parentNode.nodeType&&\"OPTG"\ "ROUP\"==b||\"OPTION\"==b?Ta(a.parentNode):!Aa(a,function(a){var b=a.par"\ "entNode;if(b&&Q(b,\"FIELDSET\")&&b.disabled){if(!Q(a,\"LEGEND\"))return"\ "!0;for(;a=void 0!=a.previousElementSibling?a.previousElementSibling:va("\ "a.previousSibling);)if(Q(a,\"LEGEND\"))return!0}return!1},!0):!0}var Ua"\ "=\"text search tel url email password number\".split(\" \");\nfunction "\ "Va(a){function b(a){return\"inherit\"==a.contentEditable?(a=R(a))?b(a):"\ "!1:\"true\"==a.contentEditable}return void 0!==a.contentEditable?void 0"\ "!==a.isContentEditable?a.isContentEditable:b(a):!1}function R(a){for(a="\ "a.parentNode;a&&1!=a.nodeType&&9!=a.nodeType&&11!=a.nodeType;)a=a.paren"\ "tNode;return Q(a)?a:null}\nfunction S(a,b){var c=da(b);if(\"float\"==c|"\ "|\"cssFloat\"==c||\"styleFloat\"==c)c=\"cssFloat\";c=Oa(a,c)||Wa(a,c);i"\ "f(null===c)c=null;else if(q(ja,b)&&(ma.test(\"#\"==c.charAt(0)?c:\"#\"+"\ "c)||qa(c).length||ia&&ia[c.toLowerCase()]||oa(c).length)){var d=oa(c);i"\ "f(!d.length){a:if(d=qa(c),!d.length){d=(d=ia[c.toLowerCase()])?d:\"#\"="\ "=c.charAt(0)?c:\"#\"+c;if(ma.test(d)&&(d=la(d),d=la(d),d=[parseInt(d.su"\ "bstr(1,2),16),parseInt(d.substr(3,2),16),parseInt(d.substr(5,2),16)],d."\ "length))break a;d=[]}3==d.length&&d.push(1)}c=4!=\nd.length?c:\"rgba(\""\ "+d.join(\", \")+\")\"}return c}function Wa(a,b){var c=a.currentStyle||a"\ ".style,d=c[b];void 0===d&&n(c.getPropertyValue)&&(d=c.getPropertyValue("\ "b));return\"inherit\"!=d?void 0!==d?d:null:(c=R(a))?Wa(c,b):null}\nfunc"\ "tion Xa(a,b){function c(a){if(\"none\"==S(a,\"display\"))return!1;a=R(a"\ ");return!a||c(a)}function d(a){var b=T(a);return 0<b.height&&0<b.width?"\ "!0:Q(a,\"PATH\")&&(0<b.height||0<b.width)?(a=S(a,\"stroke-width\"),!!a&"\ "&0<parseInt(a,10)):\"hidden\"!=S(a,\"overflow\")&&ga(a.childNodes,funct"\ "ion(a){return a.nodeType==ua||Q(a)&&d(a)})}function e(a){var b=S(a,\"-o"\ "-transform\")||S(a,\"-webkit-transform\")||S(a,\"-ms-transform\")||S(a,"\ "\"-moz-transform\")||S(a,\"transform\");if(b&&\"none\"!==b)return b=Ra("\ "a),a=T(a),0<=b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=R(a);return!a||e(a)"\ "}if(!Q(a))throw Error(\"Argument to isShown must be of type Element\");"\ "if(Q(a,\"OPTION\")||Q(a,\"OPTGROUP\")){var g=Aa(a,function(a){return Q("\ "a,\"SELECT\")});return!!g&&Xa(g,!0)}return(g=Ya(a))?!!g.t&&0<g.rect.wid"\ "th&&0<g.rect.height&&Xa(g.t,b):Q(a,\"INPUT\")&&\"hidden\"==a.type.toLow"\ "erCase()||Q(a,\"NOSCRIPT\")||\"hidden\"==S(a,\"visibility\")||!c(a)||!b"\ "&&0==Za(a)||!d(a)||$a(a)==ab?!1:e(a)}var ab=\"hidden\";\nfunction $a(a)"\ "{function b(a){var b=a;if(\"visible\"==z)if(a==g)b=h;else if(a==h)retur"\ "n{x:\"visible\",y:\"visible\"};b={x:S(b,\"overflow-x\"),y:S(b,\"overflo"\ "w-y\")};a==g&&(b.x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"hidden\"=="\ "b.y?\"hidden\":\"auto\");return b}function c(a){var b=S(a,\"position\")"\ ";if(\"fixed\"==b)return g;for(a=R(a);a&&a!=g&&(0==S(a,\"display\").last"\ "IndexOf(\"inline\",0)||\"absolute\"==b&&\"static\"==S(a,\"position\"));"\ ")a=R(a);return a}var d=T(a),e=B(a),g=e.documentElement,h=e.body,z=S(g,"\ "\"overflow\");for(a=c(a);a;a=\nc(a)){var s=T(a),e=b(a),G=d.left>=s.left"\ "+s.width,s=d.top>=s.top+s.height;if(G&&\"hidden\"==e.x||s&&\"hidden\"=="\ "e.y)return ab;if(G&&\"visible\"!=e.x||s&&\"visible\"!=e.y)return $a(a)="\ "=ab?ab:\"scroll\"}return\"none\"}\nfunction T(a){var b=Ya(a);if(b)retur"\ "n b.rect;if(n(a.getBBox))try{var c=a.getBBox();return new O(c.x,c.y,c.w"\ "idth,c.height)}catch(d){throw d;}else{if(Q(a,\"HTML\"))return a=((B(a)?"\ "B(a).parentWindow||B(a).defaultView:window)||window).document,a=\"CSS1C"\ "ompat\"==a.compatMode?a.documentElement:a.body,a=new A(a.clientWidth,a."\ "clientHeight),new O(0,0,a.width,a.height);var b=Ra(a),c=a.offsetWidth,e"\ "=a.offsetHeight;c||(e||!a.getBoundingClientRect)||(a=a.getBoundingClien"\ "tRect(),c=a.right-a.left,e=a.bottom-a.top);\nreturn new O(b.x,b.y,c,e)}"\ "}function Ya(a){var b=Q(a,\"MAP\");if(!b&&!Q(a,\"AREA\"))return null;va"\ "r c=b?a:Q(a.parentNode,\"MAP\")?a.parentNode:null,d=null,e=null;if(c&&c"\ ".name&&(d=N.M('/descendant::*[@usemap = \"#'+c.name+'\"]',B(c)))&&(e=T("\ "d),!b&&\"default\"!=a.shape.toLowerCase())){var g=bb(a);a=Math.min(Math"\ ".max(g.left,0),e.width);b=Math.min(Math.max(g.top,0),e.height);c=Math.m"\ "in(g.width,e.width-a);g=Math.min(g.height,e.height-b);e=new O(a+e.left,"\ "b+e.top,c,g)}return{t:d,rect:e||new O(0,0,0,0)}}\nfunction bb(a){var b="\ "a.shape.toLowerCase();a=a.coords.split(\",\");if(\"rect\"==b&&4==a.leng"\ "th){var b=a[0],c=a[1];return new O(b,c,a[2]-b,a[3]-c)}if(\"circle\"==b&"\ "&3==a.length)return b=a[2],new O(a[0]-b,a[1]-b,2*b,2*b);if(\"poly\"==b&"\ "&2<a.length){for(var b=a[0],c=a[1],d=b,e=c,g=2;g+1<a.length;g+=2)b=Math"\ ".min(b,a[g]),d=Math.max(d,a[g]),c=Math.min(c,a[g+1]),e=Math.max(e,a[g+1"\ "]);return new O(b,c,d-b,e-c)}return new O(0,0,0,0)}\nfunction Za(a){var"\ " b=1,c=S(a,\"opacity\");c&&(b=Number(c));(a=R(a))&&(b*=Za(a));return b}"\ ";function cb(a,b){this.m=ca.document.documentElement;this.A=null;var c="\ "Ba(B(this.m));c&&db(this,c);this.V=a||new eb;this.O=b||new gb}function "\ "db(a,b){a.m=b;a.A=Q(b,\"OPTION\")?Aa(b,function(a){return Q(a,\"SELECT"\ "\")}):null}function eb(){this.ba=0}function gb(){};function hb(a,b,c){t"\ "his.B=a;this.D=b;this.F=c}hb.prototype.create=function(a){a=B(a).create"\ "Event(\"HTMLEvents\");a.initEvent(this.B,this.D,this.F);return a};hb.pr"\ "ototype.toString=f(\"B\");var ib=new hb(\"change\",!0,!1);function U(a,"\ "b){this.i={};this.e=[];var c=arguments.length;if(1<c){if(c%2)throw Erro"\ "r(\"Uneven number of arguments\");for(var d=0;d<c;d+=2)this.set(argumen"\ "ts[d],arguments[d+1])}else if(a){var e;if(a instanceof U)for(d=jb(a),kb"\ "(a),e=[],c=0;c<a.e.length;c++)e.push(a.i[a.e[c]]);else{var c=[],g=0;for"\ "(d in a)c[g++]=d;d=c;c=[];g=0;for(e in a)c[g++]=a[e];e=c}for(c=0;c<d.le"\ "ngth;c++)this.set(d[c],e[c])}}U.prototype.l=0;U.prototype.N=0;function "\ "jb(a){kb(a);return a.e.concat()}\nfunction kb(a){if(a.l!=a.e.length){fo"\ "r(var b=0,c=0;b<a.e.length;){var d=a.e[b];Object.prototype.hasOwnProper"\ "ty.call(a.i,d)&&(a.e[c++]=d);b++}a.e.length=c}if(a.l!=a.e.length){for(v"\ "ar e={},c=b=0;b<a.e.length;)d=a.e[b],Object.prototype.hasOwnProperty.ca"\ "ll(e,d)||(a.e[c++]=d,e[d]=1),b++;a.e.length=c}}U.prototype.get=function"\ "(a,b){return Object.prototype.hasOwnProperty.call(this.i,a)?this.i[a]:b"\ "};\nU.prototype.set=function(a,b){Object.prototype.hasOwnProperty.call("\ "this.i,a)||(this.l++,this.e.push(a),this.N++);this.i[a]=b};var lb={};fu"\ "nction V(a,b,c){var d=typeof a;(\"object\"==d&&null!=a||\"function\"==d"\ ")&&(a=a.a);a=new mb(a,b,c);!b||b in lb&&!c||(lb[b]={key:a,shift:!1},c&&"\ "(lb[c]={key:a,shift:!0}));return a}function mb(a,b,c){this.code=a;this."\ "G=b||null;this.ca=c||this.G}V(8);V(9);V(13);var nb=V(16),ob=V(17),pb=V("\ "18);V(19);V(20);V(27);V(32,\" \");V(33);V(34);V(35);V(36);V(37);V(38);V"\ "(39);V(40);V(44);V(45);V(46);V(48,\"0\",\")\");V(49,\"1\",\"!\");V(50,"\ "\"2\",\"@\");V(51,\"3\",\"#\");V(52,\"4\",\"$\");V(53,\"5\",\"%\");V(54"\ ",\"6\",\"^\");V(55,\"7\",\"&\");\nV(56,\"8\",\"*\");V(57,\"9\",\"(\");V"\ "(65,\"a\",\"A\");V(66,\"b\",\"B\");V(67,\"c\",\"C\");V(68,\"d\",\"D\");"\ "V(69,\"e\",\"E\");V(70,\"f\",\"F\");V(71,\"g\",\"G\");V(72,\"h\",\"H\")"\ ";V(73,\"i\",\"I\");V(74,\"j\",\"J\");V(75,\"k\",\"K\");V(76,\"l\",\"L\""\ ");V(77,\"m\",\"M\");V(78,\"n\",\"N\");V(79,\"o\",\"O\");V(80,\"p\",\"P"\ "\");V(81,\"q\",\"Q\");V(82,\"r\",\"R\");V(83,\"s\",\"S\");V(84,\"t\",\""\ "T\");V(85,\"u\",\"U\");V(86,\"v\",\"V\");V(87,\"w\",\"W\");V(88,\"x\","\ "\"X\");V(89,\"y\",\"Y\");V(90,\"z\",\"Z\");var qb=V(u?{b:91,a:91,opera:"\ "219}:t?{b:224,a:91,opera:17}:{b:0,a:91,opera:null});\nV(u?{b:92,a:92,op"\ "era:220}:t?{b:224,a:93,opera:17}:{b:0,a:92,opera:null});V(u?{b:93,a:93,"\ "opera:0}:t?{b:0,a:0,opera:16}:{b:93,a:null,opera:0});V({b:96,a:96,opera"\ ":48},\"0\");V({b:97,a:97,opera:49},\"1\");V({b:98,a:98,opera:50},\"2\")"\ ";V({b:99,a:99,opera:51},\"3\");V({b:100,a:100,opera:52},\"4\");V({b:101"\ ",a:101,opera:53},\"5\");V({b:102,a:102,opera:54},\"6\");V({b:103,a:103,"\ "opera:55},\"7\");V({b:104,a:104,opera:56},\"8\");V({b:105,a:105,opera:5"\ "7},\"9\");V({b:106,a:106,opera:w?56:42},\"*\");V({b:107,a:107,opera:w?6"\ "1:43},\"+\");\nV({b:109,a:109,opera:w?109:45},\"-\");V({b:110,a:110,ope"\ "ra:w?190:78},\".\");V({b:111,a:111,opera:w?191:47},\"/\");V(144);V(112)"\ ";V(113);V(114);V(115);V(116);V(117);V(118);V(119);V(120);V(121);V(122);"\ "V(123);V({b:107,a:187,opera:61},\"=\",\"+\");V(108,\",\");V({b:109,a:18"\ "9,opera:109},\"-\",\"_\");V(188,\",\",\"<\");V(190,\".\",\">\");V(191,"\ "\"/\",\"?\");V(192,\"`\",\"~\");V(219,\"[\",\"{\");V(220,\"\\\\\",\"|\""\ ");V(221,\"]\",\"}\");V({b:59,a:186,opera:59},\";\",\":\");V(222,\"'\",'"\ "\"');var W=new U;W.set(1,nb);W.set(2,ob);W.set(4,pb);W.set(8,qb);\n(fun"\ "ction(a){var b=new U;p(jb(a),function(c){b.set(a.get(c).code,c)});retur"\ "n b})(W);function X(){cb.call(this)}ba(X,cb);X.J=function(){return X.u?"\ "X.u:X.u=new X};function rb(a){if(!Xa(a,!0)||!Ta(a)||\"none\"==S(a,\"poi"\ "nter-events\"))throw new r(12,\"Element is not currently interactable a"\ "nd may not be manipulated\");var b;(b=!(Q(a,\"TEXTAREA\")||(Q(a,\"INPUT"\ "\")?q(Ua,a.type.toLowerCase()):Va(a))))||(b=a.readOnly);if(b)throw new "\ "r(12,\"Element must be user-editable in order to clear it.\");b=X.J();d"\ "b(b,a);b=b.A||b.m;var c=Ba(B(b));if(b!=c){if(c&&n(c.blur)&&!Q(c,\"BODY"\ "\"))try{c.blur()}catch(d){throw d;}n(b.focus)&&b.focus()}a.value&&(a.va"\ "lue=\"\",b=ib.create(a,void 0),\"isTrusted\"in\nb||(b.isTrusted=!1),a.d"\ "ispatchEvent(b));Va(a)&&(a.innerHTML=\" \")}var Y=[\"_\"],Z=l;Y[0]in Z|"\ "|!Z.execScript||Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.sh"\ "ift());)Y.length||void 0===rb?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=rb;; return this"\ "._.apply(null,arguments);}.apply({navigator:typeof window!=undefined?wi"\ "ndow.navigator:null,document:typeof window!=undefined?window.document:n"\ "ull}, arguments);}" CLEAR_LOCAL_STORAGE = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};function p(){if(!m())throw new d"\ "(13,\"Local storage undefined\");(new n(c.localStorage)).clear()}var q="\ "[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);for"\ "(var s;q.length&&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]={"\ "}:r[s]=p;; return this._.apply(null,arguments);}.apply({navigator:typeo"\ "f window!=undefined?window.navigator:null,document:typeof window!=undef"\ "ined?window.document:null}, arguments);}" CLEAR_SESSION_STORAGE = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};function p(){var a;if(m())a=new "\ "n(c.sessionStorage);else throw new d(13,\"Session storage undefined\");"\ "a.clear()}var q=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript(\""\ "var \"+q[0]);for(var s;q.length&&(s=q.shift());)q.length||void 0===p?r="\ "r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,arguments);}.apply("\ "{navigator:typeof window!=undefined?window.navigator:null,document:type"\ "of window!=undefined?window.document:null}, arguments);}" CLICK = \ "function(){return function(){function g(a){return function(){return thi"\ "s[a]}}function aa(a){return function(){return a}}var k=this;\nfunction "\ "ba(a){var b=typeof a;if(\"object\"==b)if(a){if(a instanceof Array)retur"\ "n\"array\";if(a instanceof Object)return b;var c=Object.prototype.toStr"\ "ing.call(a);if(\"[object Window]\"==c)return\"object\";if(\"[object Arr"\ "ay]\"==c||\"number\"==typeof a.length&&\"undefined\"!=typeof a.splice&&"\ "\"undefined\"!=typeof a.propertyIsEnumerable&&!a.propertyIsEnumerable("\ "\"splice\"))return\"array\";if(\"[object Function]\"==c||\"undefined\"!"\ "=typeof a.call&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.proper"\ "tyIsEnumerable(\"call\"))return\"function\"}else return\"null\";\nelse "\ "if(\"function\"==b&&\"undefined\"==typeof a.call)return\"object\";retur"\ "n b}function l(a){return\"string\"==typeof a}function m(a){return\"func"\ "tion\"==ba(a)}function ca(a,b){function c(){}c.prototype=b.prototype;a."\ "ja=b.prototype;a.prototype=new c};var da=window;function ea(a){return S"\ "tring(a).replace(/\\-([a-z])/g,function(a,c){return c.toUpperCase()})};"\ "var fa=Array.prototype;function n(a,b){for(var c=a.length,d=l(a)?a.spli"\ "t(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function ga(a,b){"\ "if(a.reduce)return a.reduce(b,\"\");var c=\"\";n(a,function(d,e){c=b.ca"\ "ll(void 0,c,d,e,a)});return c}function ha(a,b){for(var c=a.length,d=l(a"\ ")?a.split(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return"\ "!0;return!1}\nfunction ia(a,b){var c;a:if(l(a))c=l(b)&&1==b.length?a.in"\ "dexOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c in a&&a[c]===b)break a;c"\ "=-1}return 0<=c}function ja(a,b,c){return 2>=arguments.length?fa.slice."\ "call(a,b):fa.slice.call(a,b,c)};var ka={aliceblue:\"#f0f8ff\",antiquewh"\ "ite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",azure:\"#f0ffff"\ "\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\",blanchedalmon"\ "d:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brown:\"#a52a2a\""\ ",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\"#7fff00\",cho"\ "colate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6495ed\",cornsil"\ "k:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblue:\"#00008b\""\ ",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:\"#a9a9a9\",da"\ "rkgreen:\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki:\"#bdb76b\",darkma"\ "genta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:\"#ff8c00\",dar"\ "korchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9967a\",darkseag"\ "reen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray:\"#2f4f4f\",da"\ "rkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkviolet:\"#9400d3"\ "\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:\"#696969\",dim"\ "grey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22222\",floralwhi"\ "te:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff\",gainsboro:\""\ "#dcdcdc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\",goldenrod:\"#daa520"\ "\",gray:\"#808080\",green:\"#008000\",greenyellow:\"#adff2f\",grey:\"#8"\ "08080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianred:\"#cd5c5c\","\ "indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",lavender:\"#e6e6"\ "fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lemonchiffon:\"#ff"\ "facd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",lightcyan:\"#e0ffff"\ "\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3\",lightgreen:\""\ "#90ee90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1\",lightsalmon:\"#ff"\ "a07a\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#87cefa\",lightslateg"\ "ray:\"#778899\",lightslategrey:\"#778899\",lightsteelblue:\"#b0c4de\",l"\ "ightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32cd32\",linen:\"#"\ "faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediumaquamarine:\"#66c"\ "daa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",mediumpurple:\"#9"\ "370db\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7b68ee\",mediumsp"\ "ringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediumvioletred:\"#c7"\ "1585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",mistyrose:\"#ffe4"\ "e1\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",navy:\"#000080\",ol"\ "dlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23\",orange:\"#ffa"\ "500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegoldenrod:\"#eee8aa"\ "\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palevioletred:\"#db7"\ "093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:\"#cd853f\",pin"\ "k:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",purple:\"#800080"\ "\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#4169e1\",saddlebr"\ "own:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\",seagreen:\"#2"\ "e8b57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",silver:\"#c0c0c0\",sk"\ "yblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#708090\",slategrey"\ ":\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",steelblue:\"#4682"\ "b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\",tomato:\"#ff6"\ "347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f5deb3\",white:"\ "\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yellowgreen:\"#9a"\ "cd32\"};var la=\"background-color border-top-color border-right-color b"\ "order-bottom-color border-left-color color outline-color\".split(\" \")"\ ",ma=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;function na(a){if(!oa.te"\ "st(a))throw Error(\"'\"+a+\"' is not a valid hex color\");4==a.length&&"\ "(a=a.replace(ma,\"#$1$1$2$2$3$3\"));return a.toLowerCase()}var oa=/^#(?"\ ":[0-9a-f]{3}){1,2}$/i,pa=/^(?:rgba)?\\((\\d{1,3}),\\s?(\\d{1,3}),\\s?("\ "\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction qa(a){var b=a.match(pa);i"\ "f(b){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b=Number(b[4]);if"\ "(0<=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)return[a,c,d,b]}r"\ "eturn[]}var ra=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2}),\\s"\ "?(0|[1-9]\\d{0,2})\\)$/i;function sa(a){var b=a.match(ra);if(b){a=Numbe"\ "r(b[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>=a&&0<=c&&255>=c"\ "&&0<=b&&255>=b)return[a,c,b]}return[]};function r(a,b){this.code=a;this"\ ".state=ta[a]||ua;this.message=b||\"\";var c=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";t"\ "his.name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||"\ "\"\"}ca(r,Error);\nvar ua=\"unknown error\",ta={15:\"element not select"\ "able\",11:\"element not visible\",31:\"ime engine activation failed\",3"\ "0:\"ime not available\",24:\"invalid cookie domain\",29:\"invalid eleme"\ "nt coordinates\",12:\"invalid element state\",32:\"invalid selector\",5"\ "1:\"invalid selector\",52:\"invalid selector\",17:\"javascript error\","\ "405:\"unsupported operation\",34:\"move target out of bounds\",27:\"no "\ "such alert\",7:\"no such element\",8:\"no such frame\",23:\"no such win"\ "dow\",28:\"script timeout\",33:\"session not created\",10:\"stale eleme"\ "nt reference\",\n0:\"success\",21:\"timeout\",25:\"unable to set cookie"\ "\",26:\"unexpected alert open\"};ta[13]=ua;ta[9]=\"unknown command\";r."\ "prototype.toString=function(){return this.name+\": \"+this.message};var"\ " va,wa,xa,ya=k.navigator;xa=ya&&ya.platform||\"\";va=-1!=xa.indexOf(\"M"\ "ac\");wa=-1!=xa.indexOf(\"Win\");var s=-1!=xa.indexOf(\"Linux\");var za"\ ";function t(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}t.prototyp"\ "e.toString=function(){return\"(\"+this.x+\", \"+this.y+\")\"};t.prototy"\ "pe.ceil=function(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);re"\ "turn this};t.prototype.floor=function(){this.x=Math.floor(this.x);this."\ "y=Math.floor(this.y);return this};t.prototype.round=function(){this.x=M"\ "ath.round(this.x);this.y=Math.round(this.y);return this};function u(a,b"\ "){this.width=a;this.height=b}u.prototype.toString=function(){return\"("\ "\"+this.width+\" x \"+this.height+\")\"};u.prototype.ceil=function(){th"\ "is.width=Math.ceil(this.width);this.height=Math.ceil(this.height);retur"\ "n this};u.prototype.floor=function(){this.width=Math.floor(this.width);"\ "this.height=Math.floor(this.height);return this};u.prototype.round=func"\ "tion(){this.width=Math.round(this.width);this.height=Math.round(this.he"\ "ight);return this};var Ba=3;function Ca(a){for(;a&&1!=a.nodeType;)a=a.p"\ "reviousSibling;return a}function Da(a,b){if(a.contains&&1==b.nodeType)r"\ "eturn a==b||a.contains(b);if(\"undefined\"!=typeof a.compareDocumentPos"\ "ition)return a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!="\ "b;)b=b.parentNode;return b==a}\nfunction Ea(a,b){if(a==b)return 0;if(a."\ "compareDocumentPosition)return a.compareDocumentPosition(b)&2?1:-1;if("\ "\"sourceIndex\"in a||a.parentNode&&\"sourceIndex\"in a.parentNode){var "\ "c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return a.sourceIndex-b.sourceIn"\ "dex;var e=a.parentNode,f=b.parentNode;return e==f?Fa(a,b):!c&&Da(e,b)?-"\ "1*Ga(a,b):!d&&Da(f,a)?Ga(b,a):(c?a.sourceIndex:e.sourceIndex)-(d?b.sour"\ "ceIndex:f.sourceIndex)}d=v(a);c=d.createRange();c.selectNode(a);c.colla"\ "pse(!0);d=d.createRange();d.selectNode(b);\nd.collapse(!0);return c.com"\ "pareBoundaryPoints(k.Range.START_TO_END,d)}function Ga(a,b){var c=a.par"\ "entNode;if(c==b)return-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;re"\ "turn Fa(d,a)}function Fa(a,b){for(var c=b;c=c.previousSibling;)if(c==a)"\ "return-1;return 1}function v(a){return 9==a.nodeType?a:a.ownerDocument|"\ "|a.document}function Ha(a,b,c){c||(a=a.parentNode);for(c=0;a;){if(b(a))"\ "return a;a=a.parentNode;c++}return null}function w(a){this.G=a||k.docum"\ "ent||document}\nw.prototype.i=function(a){return l(a)?this.G.getElement"\ "ById(a):a};function Ia(a){var b=a.G;a=b.body;b=b.parentWindow||b.defaul"\ "tView;return new t(b.pageXOffset||a.scrollLeft,b.pageYOffset||a.scrollT"\ "op)}w.prototype.contains=Da;function x(a){var b=null,c=a.nodeType;1==c&"\ "&(b=a.textContent,b=void 0==b||null==b?a.innerText:b,b=void 0==b||null="\ "=b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c){a=9==c?a.documentElem"\ "ent:a.firstChild;for(var c=0,d=[],b=\"\";a;){do 1!=a.nodeType&&(b+=a.no"\ "deValue),d[c++]=a;while(a=a.firstChild);for(;c&&!(a=d[--c].nextSibling)"\ ";);}}else b=a.nodeValue;return\"\"+b}\nfunction y(a,b,c){if(null===b)re"\ "turn!0;try{if(!a.getAttribute)return!1}catch(d){return!1}return null==c"\ "?!!a.getAttribute(b):a.getAttribute(b,2)==c}function Ja(a,b,c,d,e){retu"\ "rn Ka.call(null,a,b,l(c)?c:null,l(d)?d:null,e||new z)}\nfunction Ka(a,b"\ ",c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b.getElementsByName(d),n"\ "(b,function(b){a.matches(b)&&e.add(b)})):b.getElementsByClassName&&d&&"\ "\"class\"==c?(b=b.getElementsByClassName(d),n(b,function(b){b.className"\ "==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagName&&(b=b.getElements"\ "ByTagName(a.getName()),n(b,function(a){y(a,c,d)&&e.add(a)}));return e}f"\ "unction La(a,b,c,d,e){for(b=b.firstChild;b;b=b.nextSibling)y(b,c,d)&&a."\ "matches(b)&&e.add(b);return e}\nfunction Ma(a,b,c,d,e){for(b=b.firstChi"\ "ld;b;b=b.nextSibling)y(b,c,d)&&a.matches(b)&&e.add(b),Ma(a,b,c,d,e)};fu"\ "nction z(){this.h=this.g=null;this.q=0}function Na(a){this.J=a;this.nex"\ "t=this.A=null}z.prototype.unshift=function(a){a=new Na(a);a.next=this.g"\ ";this.h?this.g.A=a:this.g=this.h=a;this.g=a;this.q++};z.prototype.add=f"\ "unction(a){a=new Na(a);a.A=this.h;this.g?this.h.next=a:this.g=this.h=a;"\ "this.h=a;this.q++};function Oa(a){return(a=a.g)?a.J:null}function Pa(a)"\ "{return(a=Oa(a))?x(a):\"\"}function A(a,b){this.ea=a;this.F=(this.K=b)?"\ "a.h:a.g;this.Q=null}\nA.prototype.next=function(){var a=this.F;if(null="\ "=a)return null;var b=this.Q=a;this.F=this.K?a.A:a.next;return b.J};func"\ "tion B(a,b){var c=a.evaluate(b);return c instanceof z?+Pa(c):+c}functio"\ "n D(a,b){var c=a.evaluate(b);return c instanceof z?Pa(c):\"\"+c}functio"\ "n E(a,b){var c=a.evaluate(b);return c instanceof z?!!c.q:!!c};function "\ "H(a,b,c,d,e){b=b.evaluate(d);c=c.evaluate(d);var f;if(b instanceof z&&c"\ " instanceof z){e=new A(b,!1);for(d=e.next();d;d=e.next())for(b=new A(c,"\ "!1),f=b.next();f;f=b.next())if(a(x(d),x(f)))return!0;return!1}if(b inst"\ "anceof z||c instanceof z){b instanceof z?e=b:(e=c,c=b);e=new A(e,!1);b="\ "typeof c;for(d=e.next();d;d=e.next()){switch(b){case \"number\":d=+x(d)"\ ";break;case \"boolean\":d=!!x(d);break;case \"string\":d=x(d);break;def"\ "ault:throw Error(\"Illegal primitive type for comparison.\");}if(a(d,c)"\ ")return!0}return!1}return e?\n\"boolean\"==typeof b||\"boolean\"==typeo"\ "f c?a(!!b,!!c):\"number\"==typeof b||\"number\"==typeof c?a(+b,+c):a(b,"\ "c):a(+b,+c)}function Qa(a,b,c,d){this.R=a;this.ha=b;this.N=c;this.o=d}Q"\ "a.prototype.toString=g(\"R\");var Ra={};function I(a,b,c,d){if(a in Ra)"\ "throw Error(\"Binary operator already created: \"+a);a=new Qa(a,b,c,d);"\ "Ra[a.toString()]=a}I(\"div\",6,1,function(a,b,c){return B(a,c)/B(b,c)})"\ ";I(\"mod\",6,1,function(a,b,c){return B(a,c)%B(b,c)});I(\"*\",6,1,funct"\ "ion(a,b,c){return B(a,c)*B(b,c)});\nI(\"+\",5,1,function(a,b,c){return "\ "B(a,c)+B(b,c)});I(\"-\",5,1,function(a,b,c){return B(a,c)-B(b,c)});I(\""\ "<\",4,2,function(a,b,c){return H(function(a,b){return a<b},a,b,c)});I("\ "\">\",4,2,function(a,b,c){return H(function(a,b){return a>b},a,b,c)});I"\ "(\"<=\",4,2,function(a,b,c){return H(function(a,b){return a<=b},a,b,c)}"\ ");I(\">=\",4,2,function(a,b,c){return H(function(a,b){return a>=b},a,b,"\ "c)});I(\"=\",3,2,function(a,b,c){return H(function(a,b){return a==b},a,"\ "b,c,!0)});\nI(\"!=\",3,2,function(a,b,c){return H(function(a,b){return "\ "a!=b},a,b,c,!0)});I(\"and\",2,2,function(a,b,c){return E(a,c)&&E(b,c)})"\ ";I(\"or\",1,2,function(a,b,c){return E(a,c)||E(b,c)});function Sa(a,b,c"\ ",d,e,f,h,q,p){this.w=a;this.N=b;this.ca=c;this.ba=d;this.aa=e;this.o=f;"\ "this.$=h;this.Z=void 0!==q?q:h;this.fa=!!p}Sa.prototype.toString=g(\"w"\ "\");var Ta={};function J(a,b,c,d,e,f,h,q){if(a in Ta)throw Error(\"Func"\ "tion already created: \"+a+\".\");Ta[a]=new Sa(a,b,c,d,!1,e,f,h,q)}J(\""\ "boolean\",2,!1,!1,function(a,b){return E(b,a)},1);J(\"ceiling\",1,!1,!1"\ ",function(a,b){return Math.ceil(B(b,a))},1);\nJ(\"concat\",3,!1,!1,func"\ "tion(a,b){var c=ja(arguments,1);return ga(c,function(b,c){return b+D(c,"\ "a)})},2,null);J(\"contains\",2,!1,!1,function(a,b,c){b=D(b,a);a=D(c,a);"\ "return-1!=b.indexOf(a)},2);J(\"count\",1,!1,!1,function(a,b){return b.e"\ "valuate(a).q},1,1,!0);J(\"false\",2,!1,!1,aa(!1),0);J(\"floor\",1,!1,!1"\ ",function(a,b){return Math.floor(B(b,a))},1);\nJ(\"id\",4,!1,!1,functio"\ "n(a,b){var c=a.k,d=9==c.nodeType?c:c.ownerDocument,c=D(b,a).split(/\\s+"\ "/),e=[];n(c,function(a){(a=d.getElementById(a))&&!ia(e,a)&&e.push(a)});"\ "e.sort(Ea);var f=new z;n(e,function(a){f.add(a)});return f},1);J(\"lang"\ "\",2,!1,!1,aa(!1),1);J(\"last\",1,!0,!1,function(a){if(1!=arguments.len"\ "gth)throw Error(\"Function last expects ()\");return a.h},0);J(\"local-"\ "name\",3,!1,!0,function(a,b){var c=b?Oa(b.evaluate(a)):a.k;return c?c.n"\ "odeName.toLowerCase():\"\"},0,1,!0);\nJ(\"name\",3,!1,!0,function(a,b){"\ "var c=b?Oa(b.evaluate(a)):a.k;return c?c.nodeName.toLowerCase():\"\"},0"\ ",1,!0);J(\"namespace-uri\",3,!0,!1,aa(\"\"),0,1,!0);J(\"normalize-space"\ "\",3,!1,!0,function(a,b){return(b?D(b,a):x(a.k)).replace(/[\\s\\xa0]+/g"\ ",\" \").replace(/^\\s+|\\s+$/g,\"\")},0,1);J(\"not\",2,!1,!1,function(a"\ ",b){return!E(b,a)},1);J(\"number\",1,!1,!0,function(a,b){return b?B(b,a"\ "):+x(a.k)},0,1);J(\"position\",1,!0,!1,function(a){return a.ga},0);J(\""\ "round\",1,!1,!1,function(a,b){return Math.round(B(b,a))},1);\nJ(\"start"\ "s-with\",2,!1,!1,function(a,b,c){b=D(b,a);a=D(c,a);return 0==b.lastInde"\ "xOf(a,0)},2);J(\"string\",3,!1,!0,function(a,b){return b?D(b,a):x(a.k)}"\ ",0,1);J(\"string-length\",1,!1,!0,function(a,b){return(b?D(b,a):x(a.k))"\ ".length},0,1);\nJ(\"substring\",3,!1,!1,function(a,b,c,d){c=B(c,a);if(i"\ "sNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?B(d,a):Infinity;if(is"\ "NaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max(c,0);"\ "a=D(b,a);if(Infinity==d)return a.substring(e);b=Math.round(d);return a."\ "substring(e,c+b)},2,3);J(\"substring-after\",3,!1,!1,function(a,b,c){b="\ "D(b,a);a=D(c,a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.length)"\ "},2);\nJ(\"substring-before\",3,!1,!1,function(a,b,c){b=D(b,a);a=D(c,a)"\ ";a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);J(\"sum\",1,!1,!1"\ ",function(a,b){var c;c=b.evaluate(a);c=new A(c,!1);for(var d=0,e=c.next"\ "();e;e=c.next())d+=+x(e);return d},1,1,!0);J(\"translate\",3,!1,!1,func"\ "tion(a,b,c,d){b=D(b,a);c=D(c,a);var e=D(d,a);a=[];for(d=0;d<c.length;d+"\ "+){var f=c.charAt(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b.leng"\ "th;d++)f=b.charAt(d),c+=f in a?a[f]:f;return c},3);J(\"true\",2,!1,!1,a"\ "a(!0),0);function Ua(a,b,c,d){this.w=a;this.W=b;this.K=c;this.ka=d}Ua.p"\ "rototype.toString=g(\"w\");var Va={};function K(a,b,c,d){if(a in Va)thr"\ "ow Error(\"Axis already created: \"+a);Va[a]=new Ua(a,b,c,!!d)}K(\"ance"\ "stor\",function(a,b){for(var c=new z,d=b;d=d.parentNode;)a.matches(d)&&"\ "c.unshift(d);return c},!0);K(\"ancestor-or-self\",function(a,b){var c=n"\ "ew z,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c},"\ "!0);\nK(\"attribute\",function(a,b){var c=new z,d=a.getName(),e=b.attri"\ "butes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e.getNa"\ "medItem(d))&&c.add(f);return c},!1);K(\"child\",function(a,b,c,d,e){ret"\ "urn La.call(null,a,b,l(c)?c:null,l(d)?d:null,e||new z)},!1,!0);K(\"desc"\ "endant\",Ja,!1,!0);K(\"descendant-or-self\",function(a,b,c,d){var e=new"\ " z;y(b,c,d)&&a.matches(b)&&e.add(b);return Ja(a,b,c,d,e)},!1,!0);\nK(\""\ "following\",function(a,b,c,d){var e=new z;do for(var f=b;f=f.nextSiblin"\ "g;)y(f,c,d)&&a.matches(f)&&e.add(f),e=Ja(a,f,c,d,e);while(b=b.parentNod"\ "e);return e},!1,!0);K(\"following-sibling\",function(a,b){for(var c=new"\ " z,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);K(\"namesp"\ "ace\",function(){return new z},!1);K(\"parent\",function(a,b){var c=new"\ " z;if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerEleme"\ "nt),c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nK(\"pre"\ "ceding\",function(a,b,c,d){var e=new z,f=[];do f.unshift(b);while(b=b.p"\ "arentNode);for(var h=1,q=f.length;h<q;h++){var p=[];for(b=f[h];b=b.prev"\ "iousSibling;)p.unshift(b);for(var C=0,Aa=p.length;C<Aa;C++)b=p[C],y(b,c"\ ",d)&&a.matches(b)&&e.add(b),e=Ja(a,b,c,d,e)}return e},!0,!0);K(\"preced"\ "ing-sibling\",function(a,b){for(var c=new z,d=b;d=d.previousSibling;)a."\ "matches(d)&&c.unshift(d);return c},!0);K(\"self\",function(a,b){var c=n"\ "ew z;a.matches(b)&&c.add(b);return c},!1);var L={};L.L=function(){var a"\ "={la:\"http://www.w3.org/2000/svg\"};return function(b){return a[b]||nu"\ "ll}}();L.o=function(a,b,c){var d=v(a);try{var e=d.createNSResolver?d.cr"\ "eateNSResolver(d.documentElement):L.L;return d.evaluate(b,a,e,c,null)}c"\ "atch(f){throw new r(32,\"Unable to locate an element with the xpath exp"\ "ression \"+b+\" because of the following error:\\n\"+f);}};\nL.D=functi"\ "on(a,b){if(!a||1!=a.nodeType)throw new r(32,'The result of the xpath ex"\ "pression \"'+b+'\" is: '+a+\". It should be an element.\");};L.S=functi"\ "on(a,b){var c=function(){var c=L.o(b,a,9);return c?c.singleNodeValue||n"\ "ull:b.selectSingleNode?(c=v(b),c.setProperty&&c.setProperty(\"Selection"\ "Language\",\"XPath\"),b.selectSingleNode(a)):null}();null===c||L.D(c,a)"\ ";return c};\nL.Y=function(a,b){var c=function(){var c=L.o(b,a,7);if(c){"\ "for(var e=c.snapshotLength,f=[],h=0;h<e;++h)f.push(c.snapshotItem(h));r"\ "eturn f}return b.selectNodes?(c=v(b),c.setProperty&&c.setProperty(\"Sel"\ "ectionLanguage\",\"XPath\"),b.selectNodes(a)):[]}();n(c,function(b){L.D"\ "(b,a)});return c};var Wa,Xa=/Chrome\\/([0-9.]+)/.exec(k.navigator?k.nav"\ "igator.userAgent:null);Wa=Xa?Xa[1]:\"\";function M(a,b,c,d){this.top=a;"\ "this.right=b;this.bottom=c;this.left=d}M.prototype.toString=function(){"\ "return\"(\"+this.top+\"t, \"+this.right+\"r, \"+this.bottom+\"b, \"+thi"\ "s.left+\"l)\"};M.prototype.contains=function(a){return this&&a?a instan"\ "ceof M?a.left>=this.left&&a.right<=this.right&&a.top>=this.top&&a.botto"\ "m<=this.bottom:a.x>=this.left&&a.x<=this.right&&a.y>=this.top&&a.y<=thi"\ "s.bottom:!1};\nM.prototype.ceil=function(){this.top=Math.ceil(this.top)"\ ";this.right=Math.ceil(this.right);this.bottom=Math.ceil(this.bottom);th"\ "is.left=Math.ceil(this.left);return this};M.prototype.floor=function(){"\ "this.top=Math.floor(this.top);this.right=Math.floor(this.right);this.bo"\ "ttom=Math.floor(this.bottom);this.left=Math.floor(this.left);return thi"\ "s};\nM.prototype.round=function(){this.top=Math.round(this.top);this.ri"\ "ght=Math.round(this.right);this.bottom=Math.round(this.bottom);this.lef"\ "t=Math.round(this.left);return this};function N(a,b,c,d){this.left=a;th"\ "is.top=b;this.width=c;this.height=d}N.prototype.toString=function(){ret"\ "urn\"(\"+this.left+\", \"+this.top+\" - \"+this.width+\"w x \"+this.hei"\ "ght+\"h)\"};N.prototype.contains=function(a){return a instanceof N?this"\ ".left<=a.left&&this.left+this.width>=a.left+a.width&&this.top<=a.top&&t"\ "his.top+this.height>=a.top+a.height:a.x>=this.left&&a.x<=this.left+this"\ ".width&&a.y>=this.top&&a.y<=this.top+this.height};\nN.prototype.ceil=fu"\ "nction(){this.left=Math.ceil(this.left);this.top=Math.ceil(this.top);th"\ "is.width=Math.ceil(this.width);this.height=Math.ceil(this.height);retur"\ "n this};N.prototype.floor=function(){this.left=Math.floor(this.left);th"\ "is.top=Math.floor(this.top);this.width=Math.floor(this.width);this.heig"\ "ht=Math.floor(this.height);return this};\nN.prototype.round=function(){"\ "this.left=Math.round(this.left);this.top=Math.round(this.top);this.widt"\ "h=Math.round(this.width);this.height=Math.round(this.height);return thi"\ "s};function O(a,b){var c=v(a);return c.defaultView&&c.defaultView.getCo"\ "mputedStyle&&(c=c.defaultView.getComputedStyle(a,null))?c[b]||c.getProp"\ "ertyValue(b)||\"\":\"\"}function P(a,b){return O(a,b)||(a.currentStyle?"\ "a.currentStyle[b]:null)||a.style&&a.style[b]}function Ya(a){var b;try{b"\ "=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:"\ "0}}return b}\nfunction Za(a){var b=v(a),c=P(a,\"position\"),d=\"fixed\""\ "==c||\"absolute\"==c;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=P(a"\ ",\"position\"),d=d&&\"static\"==c&&a!=b.documentElement&&a!=b.body,!d&&"\ "(a.scrollWidth>a.clientWidth||a.scrollHeight>a.clientHeight||\"fixed\"="\ "=c||\"absolute\"==c||\"relative\"==c))return a;return null}\nfunction $"\ "a(a){var b=v(a),c=P(a,\"position\"),d=new t(0,0),e=(b?v(b):document).do"\ "cumentElement;if(a==e)return d;if(a.getBoundingClientRect)a=Ya(a),b=Ia("\ "b?new w(v(b)):za||(za=new w)),d.x=a.left+b.x,d.y=a.top+b.y;else if(b.ge"\ "tBoxObjectFor)a=b.getBoxObjectFor(a),b=b.getBoxObjectFor(e),d.x=a.scree"\ "nX-b.screenX,d.y=a.screenY-b.screenY;else{var f=a;do{d.x+=f.offsetLeft;"\ "d.y+=f.offsetTop;f!=a&&(d.x+=f.clientLeft||0,d.y+=f.clientTop||0);if(\""\ "fixed\"==P(f,\"position\")){d.x+=b.body.scrollLeft;d.y+=b.body.scrollTo"\ "p;\nbreak}f=f.offsetParent}while(f&&f!=a);\"absolute\"==c&&(d.y-=b.body"\ ".offsetTop);for(f=a;(f=Za(f))&&f!=b.body&&f!=e;)d.x-=f.scrollLeft,d.y-="\ "f.scrollTop}return d}function ab(a){if(1==a.nodeType){if(a.getBoundingC"\ "lientRect)a=Ya(a),a=new t(a.left,a.top);else{var b=Ia(a?new w(v(a)):za|"\ "|(za=new w));a=$a(a);a=new t(a.x-b.x,a.y-b.y)}return a}var b=m(a.H),c=a"\ ";a.targetTouches?c=a.targetTouches[0]:b&&a.H().targetTouches&&(c=a.H()."\ "targetTouches[0]);return new t(c.clientX,c.clientY)}\nfunction bb(a){va"\ "r b=a.offsetWidth,c=a.offsetHeight;return void 0!==b&&(b||c)||!a.getBou"\ "ndingClientRect?new u(b,c):(a=Ya(a),new u(a.right-a.left,a.bottom-a.top"\ "))};function cb(a){var b;a:{a=v(a);try{b=a&&a.activeElement;break a}cat"\ "ch(c){}b=null}return b}function Q(a,b){return!!a&&1==a.nodeType&&(!b||a"\ ".tagName.toUpperCase()==b)}function db(a){return eb(a,!0)&&fb(a)&&\"non"\ "e\"!=R(a,\"pointer-events\")}function gb(a){return Q(a,\"OPTION\")?!0:Q"\ "(a,\"INPUT\")?(a=a.type.toLowerCase(),\"checkbox\"==a||\"radio\"==a):!1"\ "}\nfunction hb(a){if(!gb(a))throw new r(15,\"Element is not selectable"\ "\");var b=\"selected\",c=a.type&&a.type.toLowerCase();if(\"checkbox\"=="\ "c||\"radio\"==c)b=\"checked\";return!!a[b]}var ib=\"BUTTON INPUT OPTGRO"\ "UP OPTION SELECT TEXTAREA\".split(\" \");\nfunction fb(a){var b=a.tagNa"\ "me.toUpperCase();return ia(ib,b)?a.disabled?!1:a.parentNode&&1==a.paren"\ "tNode.nodeType&&\"OPTGROUP\"==b||\"OPTION\"==b?fb(a.parentNode):!Ha(a,f"\ "unction(a){var b=a.parentNode;if(b&&Q(b,\"FIELDSET\")&&b.disabled){if(!"\ "Q(a,\"LEGEND\"))return!0;for(;a=void 0!=a.previousElementSibling?a.prev"\ "iousElementSibling:Ca(a.previousSibling);)if(Q(a,\"LEGEND\"))return!0}r"\ "eturn!1},!0):!0}\nfunction S(a){for(a=a.parentNode;a&&1!=a.nodeType&&9!"\ "=a.nodeType&&11!=a.nodeType;)a=a.parentNode;return Q(a)?a:null}\nfuncti"\ "on R(a,b){var c=ea(b);if(\"float\"==c||\"cssFloat\"==c||\"styleFloat\"="\ "=c)c=\"cssFloat\";c=O(a,c)||jb(a,c);if(null===c)c=null;else if(ia(la,b)"\ "&&(oa.test(\"#\"==c.charAt(0)?c:\"#\"+c)||sa(c).length||ka&&ka[c.toLowe"\ "rCase()]||qa(c).length)){var d=qa(c);if(!d.length){a:if(d=sa(c),!d.leng"\ "th){d=(d=ka[c.toLowerCase()])?d:\"#\"==c.charAt(0)?c:\"#\"+c;if(oa.test"\ "(d)&&(d=na(d),d=na(d),d=[parseInt(d.substr(1,2),16),parseInt(d.substr(3"\ ",2),16),parseInt(d.substr(5,2),16)],d.length))break a;d=[]}3==d.length&"\ "&d.push(1)}c=4!=\nd.length?c:\"rgba(\"+d.join(\", \")+\")\"}return c}fu"\ "nction jb(a,b){var c=a.currentStyle||a.style,d=c[b];void 0===d&&m(c.get"\ "PropertyValue)&&(d=c.getPropertyValue(b));return\"inherit\"!=d?void 0!="\ "=d?d:null:(c=S(a))?jb(c,b):null}\nfunction eb(a,b){function c(a){if(\"n"\ "one\"==R(a,\"display\"))return!1;a=S(a);return!a||c(a)}function d(a){va"\ "r b=T(a);return 0<b.height&&0<b.width?!0:Q(a,\"PATH\")&&(0<b.height||0<"\ "b.width)?(a=R(a,\"stroke-width\"),!!a&&0<parseInt(a,10)):\"hidden\"!=R("\ "a,\"overflow\")&&ha(a.childNodes,function(a){return a.nodeType==Ba||Q(a"\ ")&&d(a)})}function e(a){var b=R(a,\"-o-transform\")||R(a,\"-webkit-tran"\ "sform\")||R(a,\"-ms-transform\")||R(a,\"-moz-transform\")||R(a,\"transf"\ "orm\");if(b&&\"none\"!==b)return b=ab(a),a=T(a),0<=b.x+a.width&&\n0<=b."\ "y+a.height?!0:!1;a=S(a);return!a||e(a)}if(!Q(a))throw Error(\"Argument "\ "to isShown must be of type Element\");if(Q(a,\"OPTION\")||Q(a,\"OPTGROU"\ "P\")){var f=Ha(a,function(a){return Q(a,\"SELECT\")});return!!f&&eb(f,!"\ "0)}return(f=kb(a))?!!f.I&&0<f.rect.width&&0<f.rect.height&&eb(f.I,b):Q("\ "a,\"INPUT\")&&\"hidden\"==a.type.toLowerCase()||Q(a,\"NOSCRIPT\")||\"hi"\ "dden\"==R(a,\"visibility\")||!c(a)||!b&&0==lb(a)||!d(a)||mb(a)==nb?!1:e"\ "(a)}var nb=\"hidden\";\nfunction mb(a){function b(a){var b=a;if(\"visib"\ "le\"==q)if(a==f)b=h;else if(a==h)return{x:\"visible\",y:\"visible\"};b="\ "{x:R(b,\"overflow-x\"),y:R(b,\"overflow-y\")};a==f&&(b.x=\"hidden\"==b."\ "x?\"hidden\":\"auto\",b.y=\"hidden\"==b.y?\"hidden\":\"auto\");return b"\ "}function c(a){var b=R(a,\"position\");if(\"fixed\"==b)return f;for(a=S"\ "(a);a&&a!=f&&(0==R(a,\"display\").lastIndexOf(\"inline\",0)||\"absolute"\ "\"==b&&\"static\"==R(a,\"position\"));)a=S(a);return a}var d=T(a),e=v(a"\ "),f=e.documentElement,h=e.body,q=R(f,\"overflow\");for(a=c(a);a;a=\nc(a"\ ")){var p=T(a),e=b(a),C=d.left>=p.left+p.width,p=d.top>=p.top+p.height;i"\ "f(C&&\"hidden\"==e.x||p&&\"hidden\"==e.y)return nb;if(C&&\"visible\"!=e"\ ".x||p&&\"visible\"!=e.y)return mb(a)==nb?nb:\"scroll\"}return\"none\"}"\ "\nfunction T(a){var b=kb(a);if(b)return b.rect;if(m(a.getBBox))try{var "\ "c=a.getBBox();return new N(c.x,c.y,c.width,c.height)}catch(d){throw d;}"\ "else{if(Q(a,\"HTML\"))return a=((v(a)?v(a).parentWindow||v(a).defaultVi"\ "ew:window)||window).document,a=\"CSS1Compat\"==a.compatMode?a.documentE"\ "lement:a.body,a=new u(a.clientWidth,a.clientHeight),new N(0,0,a.width,a"\ ".height);var b=ab(a),c=a.offsetWidth,e=a.offsetHeight;c||(e||!a.getBoun"\ "dingClientRect)||(a=a.getBoundingClientRect(),c=a.right-a.left,e=a.bott"\ "om-a.top);\nreturn new N(b.x,b.y,c,e)}}function kb(a){var b=Q(a,\"MAP\""\ ");if(!b&&!Q(a,\"AREA\"))return null;var c=b?a:Q(a.parentNode,\"MAP\")?a"\ ".parentNode:null,d=null,e=null;if(c&&c.name&&(d=L.S('/descendant::*[@us"\ "emap = \"#'+c.name+'\"]',v(c)))&&(e=T(d),!b&&\"default\"!=a.shape.toLow"\ "erCase())){var f=ob(a);a=Math.min(Math.max(f.left,0),e.width);b=Math.mi"\ "n(Math.max(f.top,0),e.height);c=Math.min(f.width,e.width-a);f=Math.min("\ "f.height,e.height-b);e=new N(a+e.left,b+e.top,c,f)}return{I:d,rect:e||n"\ "ew N(0,0,0,0)}}\nfunction ob(a){var b=a.shape.toLowerCase();a=a.coords."\ "split(\",\");if(\"rect\"==b&&4==a.length){var b=a[0],c=a[1];return new "\ "N(b,c,a[2]-b,a[3]-c)}if(\"circle\"==b&&3==a.length)return b=a[2],new N("\ "a[0]-b,a[1]-b,2*b,2*b);if(\"poly\"==b&&2<a.length){for(var b=a[0],c=a[1"\ "],d=b,e=c,f=2;f+1<a.length;f+=2)b=Math.min(b,a[f]),d=Math.max(d,a[f]),c"\ "=Math.min(c,a[f+1]),e=Math.max(e,a[f+1]);return new N(b,c,d-b,e-c)}retu"\ "rn new N(0,0,0,0)}\nfunction lb(a){var b=1,c=R(a,\"opacity\");c&&(b=Num"\ "ber(c));(a=S(a))&&(b*=lb(a));return b};function pb(a,b){this.c=da.docum"\ "ent.documentElement;this.f=null;var c=cb(this.c);c&&qb(this,c);this.r=a"\ "||new rb;this.P=b||new sb}pb.prototype.i=g(\"c\");function qb(a,b){a.c="\ "b;a.f=Q(b,\"OPTION\")?Ha(b,function(a){return Q(a,\"SELECT\")}):null}\n"\ "pb.prototype.p=function(a,b,c,d,e,f,h){if(!f&&!db(this.c))return!1;if(d"\ "&&tb!=a&&ub!=a)throw new r(12,\"Event type does not allow related targe"\ "t: \"+a);b={clientX:b.x,clientY:b.y,button:c,altKey:0!=(this.r.s&4),ctr"\ "lKey:0!=(this.r.s&2),shiftKey:0!=(this.r.s&1),metaKey:0!=(this.r.s&8),w"\ "heelDelta:e||0,relatedTarget:d||null};h=h||1;c=this.c;if(a!=U&&a!=vb&&h"\ " in wb)c=wb[h];else if(this.f)a:switch(a){case U:case xb:c=this.f.multi"\ "ple?this.c:this.f;break a;default:c=this.f.multiple?this.c:null}return "\ "c?this.P.p(c,\na,b):!0};function rb(){this.s=0}var wb={};function sb(){"\ "}sb.prototype.p=function(a,b,c){return yb(a,b,c)};function zb(a,b,c){th"\ "is.t=a;this.B=b;this.C=c}zb.prototype.create=function(a){a=v(a).createE"\ "vent(\"HTMLEvents\");a.initEvent(this.t,this.B,this.C);return a};zb.pro"\ "totype.toString=g(\"t\");function V(a,b,c){zb.call(this,a,b,c)}ca(V,zb)"\ ";\nV.prototype.create=function(a,b){if(this==Ab)throw new r(9,\"Browser"\ " does not support a mouse pixel scroll event.\");var c=v(a),d=c?c.paren"\ "tWindow||c.defaultView:window,c=c.createEvent(\"MouseEvents\");this==Bb"\ "&&(c.wheelDelta=b.wheelDelta);c.initMouseEvent(this.t,this.B,this.C,d,1"\ ",0,0,b.clientX,b.clientY,b.ctrlKey,b.altKey,b.shiftKey,b.metaKey,b.butt"\ "on,b.relatedTarget);return c};\nvar Cb=new zb(\"change\",!0,!1),U=new V"\ "(\"click\",!0,!0),Db=new V(\"contextmenu\",!0,!0),Eb=new V(\"dblclick\""\ ",!0,!0),vb=new V(\"mousedown\",!0,!0),Fb=new V(\"mousemove\",!0,!1),ub="\ "new V(\"mouseout\",!0,!0),tb=new V(\"mouseover\",!0,!0),xb=new V(\"mous"\ "eup\",!0,!0),Bb=new V(\"mousewheel\",!0,!0),Ab=new V(\"MozMousePixelScr"\ "oll\",!0,!0);function yb(a,b,c){b=b.create(a,c);\"isTrusted\"in b||(b.i"\ "sTrusted=!1);return a.dispatchEvent(b)};function W(a,b){this.j={};this."\ "d=[];var c=arguments.length;if(1<c){if(c%2)throw Error(\"Uneven number "\ "of arguments\");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+"\ "1])}else if(a){var e;if(a instanceof W)for(d=Gb(a),Hb(a),e=[],c=0;c<a.d"\ ".length;c++)e.push(a.j[a.d[c]]);else{var c=[],f=0;for(d in a)c[f++]=d;d"\ "=c;c=[];f=0;for(e in a)c[f++]=a[e];e=c}for(c=0;c<d.length;c++)this.set("\ "d[c],e[c])}}W.prototype.u=0;W.prototype.T=0;function Gb(a){Hb(a);return"\ " a.d.concat()}\nfunction Hb(a){if(a.u!=a.d.length){for(var b=0,c=0;b<a."\ "d.length;){var d=a.d[b];Object.prototype.hasOwnProperty.call(a.j,d)&&(a"\ ".d[c++]=d);b++}a.d.length=c}if(a.u!=a.d.length){for(var e={},c=b=0;b<a."\ "d.length;)d=a.d[b],Object.prototype.hasOwnProperty.call(e,d)||(a.d[c++]"\ "=d,e[d]=1),b++;a.d.length=c}}W.prototype.get=function(a,b){return Objec"\ "t.prototype.hasOwnProperty.call(this.j,a)?this.j[a]:b};\nW.prototype.se"\ "t=function(a,b){Object.prototype.hasOwnProperty.call(this.j,a)||(this.u"\ "++,this.d.push(a),this.T++);this.j[a]=b};var Ib={};function X(a,b,c){va"\ "r d=typeof a;(\"object\"==d&&null!=a||\"function\"==d)&&(a=a.a);a=new J"\ "b(a,b,c);!b||b in Ib&&!c||(Ib[b]={key:a,shift:!1},c&&(Ib[c]={key:a,shif"\ "t:!0}));return a}function Jb(a,b,c){this.code=a;this.M=b||null;this.ia="\ "c||this.M}X(8);X(9);X(13);var Kb=X(16),Lb=X(17),Nb=X(18);X(19);X(20);X("\ "27);X(32,\" \");X(33);X(34);X(35);X(36);X(37);X(38);X(39);X(40);X(44);X"\ "(45);X(46);X(48,\"0\",\")\");X(49,\"1\",\"!\");X(50,\"2\",\"@\");X(51,"\ "\"3\",\"#\");X(52,\"4\",\"$\");X(53,\"5\",\"%\");X(54,\"6\",\"^\");X(55"\ ",\"7\",\"&\");\nX(56,\"8\",\"*\");X(57,\"9\",\"(\");X(65,\"a\",\"A\");X"\ "(66,\"b\",\"B\");X(67,\"c\",\"C\");X(68,\"d\",\"D\");X(69,\"e\",\"E\");"\ "X(70,\"f\",\"F\");X(71,\"g\",\"G\");X(72,\"h\",\"H\");X(73,\"i\",\"I\")"\ ";X(74,\"j\",\"J\");X(75,\"k\",\"K\");X(76,\"l\",\"L\");X(77,\"m\",\"M\""\ ");X(78,\"n\",\"N\");X(79,\"o\",\"O\");X(80,\"p\",\"P\");X(81,\"q\",\"Q"\ "\");X(82,\"r\",\"R\");X(83,\"s\",\"S\");X(84,\"t\",\"T\");X(85,\"u\",\""\ "U\");X(86,\"v\",\"V\");X(87,\"w\",\"W\");X(88,\"x\",\"X\");X(89,\"y\","\ "\"Y\");X(90,\"z\",\"Z\");var Ob=X(wa?{b:91,a:91,opera:219}:va?{b:224,a:"\ "91,opera:17}:{b:0,a:91,opera:null});\nX(wa?{b:92,a:92,opera:220}:va?{b:"\ "224,a:93,opera:17}:{b:0,a:92,opera:null});X(wa?{b:93,a:93,opera:0}:va?{"\ "b:0,a:0,opera:16}:{b:93,a:null,opera:0});X({b:96,a:96,opera:48},\"0\");"\ "X({b:97,a:97,opera:49},\"1\");X({b:98,a:98,opera:50},\"2\");X({b:99,a:9"\ "9,opera:51},\"3\");X({b:100,a:100,opera:52},\"4\");X({b:101,a:101,opera"\ ":53},\"5\");X({b:102,a:102,opera:54},\"6\");X({b:103,a:103,opera:55},\""\ "7\");X({b:104,a:104,opera:56},\"8\");X({b:105,a:105,opera:57},\"9\");X("\ "{b:106,a:106,opera:s?56:42},\"*\");\nX({b:107,a:107,opera:s?61:43},\"+"\ "\");X({b:109,a:109,opera:s?109:45},\"-\");X({b:110,a:110,opera:s?190:78"\ "},\".\");X({b:111,a:111,opera:s?191:47},\"/\");X(144);X(112);X(113);X(1"\ "14);X(115);X(116);X(117);X(118);X(119);X(120);X(121);X(122);X(123);X({b"\ ":107,a:187,opera:61},\"=\",\"+\");X(108,\",\");X({b:109,a:189,opera:109"\ "},\"-\",\"_\");X(188,\",\",\"<\");X(190,\".\",\">\");X(191,\"/\",\"?\")"\ ";X(192,\"`\",\"~\");X(219,\"[\",\"{\");X(220,\"\\\\\",\"|\");X(221,\"]"\ "\",\"}\");X({b:59,a:186,opera:59},\";\",\":\");X(222,\"'\",'\"');var Pb"\ "=new W;Pb.set(1,Kb);\nPb.set(2,Lb);Pb.set(4,Nb);Pb.set(8,Ob);(function("\ "a){var b=new W;n(Gb(a),function(c){b.set(a.get(c).code,c)});return b})("\ "Pb);function Qb(a,b,c){pb.call(this,b,c);this.n=this.e=null;this.l=new "\ "t(0,0);this.v=this.m=!1;if(a){this.e=a.U;try{Q(a.O)&&(this.n=a.O)}catch"\ "(d){this.e=null}this.l=a.V;this.m=a.da;this.v=a.X;try{Q(a.element)&&qb("\ "this,a.element)}catch(e){this.e=null}}}ca(Qb,pb);var Y={};Y[U]=[0,1,2,n"\ "ull];Y[Db]=[null,null,2,null];Y[xb]=[0,1,2,null];Y[ub]=[0,1,2,0];Y[Fb]="\ "[0,1,2,0];Y[Eb]=Y[U];Y[vb]=Y[xb];Y[tb]=Y[ub];\nQb.prototype.move=functi"\ "on(a,b){var c=db(a),d=T(a);this.l.x=b.x+d.left;this.l.y=b.y+d.top;d=thi"\ "s.i();if(a!=d){try{(v(d)?v(d).parentWindow||v(d).defaultView:window).cl"\ "osed&&(d=null)}catch(e){d=null}if(d){var f=d===da.document.documentElem"\ "ent||d===da.document.body,d=!this.v&&f?null:d;Z(this,ub,a)}qb(this,a);Z"\ "(this,tb,d,null,c)}Z(this,Fb,null,null,c);this.m=!1};function Z(a,b,c,d"\ ",e){a.v=!0;return a.p(b,a.l,Rb(a,b),c,d,e)}\nfunction Rb(a,b){if(!(b in"\ " Y))return 0;var c=Y[b][null===a.e?3:a.e];if(null===c)throw new r(13,\""\ "Event does not permit the specified mouse button.\");return c};function"\ " Sb(a,b){this.x=a;this.y=b}ca(Sb,t);Sb.prototype.add=function(a){this.x"\ "+=a.x;this.y+=a.y;return this};function Tb(a){var b;if(\"none\"!=P(a,\""\ "display\"))b=bb(a);else{b=a.style;var c=b.display,d=b.visibility,e=b.po"\ "sition;b.visibility=\"hidden\";b.position=\"absolute\";b.display=\"inli"\ "ne\";var f=bb(a);b.display=c;b.position=e;b.visibility=d;b=f}return 0<b"\ ".width&&0<b.height||!a.offsetParent?b:Tb(a.offsetParent)};function Ub(a"\ ",b,c){if(!eb(a,!0))throw new r(11,\"Element is not currently visible an"\ "d may not be manipulated\");var d=v(a).body,e;e=$a(a);var f=$a(d),h,q,p"\ ",C;C=O(d,\"borderLeftWidth\");p=O(d,\"borderRightWidth\");h=O(d,\"borde"\ "rTopWidth\");q=O(d,\"borderBottomWidth\");h=new M(parseFloat(h),parseFl"\ "oat(p),parseFloat(q),parseFloat(C));q=e.x-f.x-h.left;e=e.y-f.y-h.top;f="\ "d.clientHeight-a.offsetHeight;h=d.scrollLeft;p=d.scrollTop;h+=Math.min("\ "q,Math.max(q-(d.clientWidth-a.offsetWidth),0));p+=Math.min(e,Math.max(e"\ "-\nf,0));e=new t(h,p);d.scrollLeft=e.x;d.scrollTop=e.y;b?b=new Sb(b.x,b"\ ".y):(b=Tb(a),b=new Sb(b.width/2,b.height/2));c=c||new Qb;c.move(a,b);if"\ "(null!==c.e)throw new r(13,\"Cannot press more then one button or an al"\ "ready pressed button.\");c.e=0;c.n=c.i();if(Q(c.i(),\"OPTION\")||Q(c.i("\ "),\"SELECT\")||Z(c,vb))if(a=c.f||c.c,b=cb(a),a!=b){if(b&&m(b.blur)&&!Q("\ "b,\"BODY\"))try{b.blur()}catch(Aa){throw Aa;}m(a.focus)&&a.focus()}if(n"\ "ull===c.e)throw new r(13,\"Cannot release a button when no button is pr"\ "essed.\");if(c.f&&\ndb(c.c)&&(a=c.f,b=hb(c.c),!b||a.multiple)){c.c.sele"\ "cted=!b;if(b=a.multiple){b=0;d=String(Wa).replace(/^[\\s\\xa0]+|[\\s\\x"\ "a0]+$/g,\"\").split(\".\");e=\"28\".replace(/^[\\s\\xa0]+|[\\s\\xa0]+$/"\ "g,\"\").split(\".\");f=Math.max(d.length,e.length);for(q=0;0==b&&q<f;q+"\ "+){h=d[q]||\"\";p=e[q]||\"\";C=RegExp(\"(\\\\d*)(\\\\D*)\",\"g\");var M"\ "b=RegExp(\"(\\\\d*)(\\\\D*)\",\"g\");do{var F=C.exec(h)||[\"\",\"\",\""\ "\"],G=Mb.exec(p)||[\"\",\"\",\"\"];if(0==F[0].length&&0==G[0].length)br"\ "eak;b=((0==F[1].length?0:parseInt(F[1],10))<(0==G[1].length?0:parseInt("\ "G[1],\n10))?-1:(0==F[1].length?0:parseInt(F[1],10))>(0==G[1].length?0:p"\ "arseInt(G[1],10))?1:0)||((0==F[2].length)<(0==G[2].length)?-1:(0==F[2]."\ "length)>(0==G[2].length)?1:0)||(F[2]<G[2]?-1:F[2]>G[2]?1:0)}while(0==b)"\ "}b=!(0<=b)}b||yb(a,Cb)}Z(c,xb);0==c.e&&c.i()==c.n?(a=c.l,b=Rb(c,U),db(c"\ ".c)&&(!c.f&&gb(c.c)&&hb(c.c),c.p(U,a,b,null,0,!1,void 0)),c.m&&Z(c,Eb),"\ "c.m=!c.m):2==c.e&&Z(c,Db);wb={};c.e=null;c.n=null}var Vb=[\"_\"],$=k;Vb"\ "[0]in $||!$.execScript||$.execScript(\"var \"+Vb[0]);\nfor(var Wb;Vb.le"\ "ngth&&(Wb=Vb.shift());)Vb.length||void 0===Ub?$=$[Wb]?$[Wb]:$[Wb]={}:$["\ "Wb]=Ub;; return this._.apply(null,arguments);}.apply({navigator:typeof "\ "window!=undefined?window.navigator:null,document:typeof window!=undefin"\ "ed?window.document:null}, arguments);}" EXECUTE_ASYNC_SCRIPT = \ "function(){return function(){function h(a){var b=typeof a;if(\"object\""\ "==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)"\ "return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\""\ "==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.len"\ "gth&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[o"\ "bject Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=type"\ "of a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"fu"\ "nction\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"=="\ "typeof a.call)return\"object\";return b}function k(a){var b=h(a);return"\ "\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function l(a){"\ "var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}function m"\ "(a,b){var c=Array.prototype.slice.call(arguments,1);return function(){v"\ "ar b=Array.prototype.slice.call(arguments);b.unshift.apply(b,c);return "\ "a.apply(this,b)}}var p=Date.now||function(){return+new Date};var q=0,r="\ "13;function s(a,b){this.code=a;this.state=t[a]||u;this.message=b||\"\";"\ "var c=this.state.replace(/((?:^|\\s+)[a-z])/g,function(a){return a.toUp"\ "perCase().replace(/^[\\s\\xa0]+/g,\"\")}),e=c.length-5;if(0>e||c.indexO"\ "f(\"Error\",e)!=e)c+=\"Error\";this.name=c;c=Error(this.message);c.name"\ "=this.name;this.stack=c.stack||\"\"}(function(){var a=s,b=Error;functio"\ "n c(){}c.prototype=b.prototype;a.c=b.prototype;a.prototype=new c})();\n"\ "var u=\"unknown error\",t={15:\"element not selectable\",11:\"element n"\ "ot visible\",31:\"ime engine activation failed\",30:\"ime not available"\ "\",24:\"invalid cookie domain\",29:\"invalid element coordinates\",12:"\ "\"invalid element state\",32:\"invalid selector\",51:\"invalid selector"\ "\",52:\"invalid selector\",17:\"javascript error\",405:\"unsupported op"\ "eration\",34:\"move target out of bounds\",27:\"no such alert\",7:\"no "\ "such element\",8:\"no such frame\",23:\"no such window\",28:\"script ti"\ "meout\",33:\"session not created\",10:\"stale element reference\"};\nt["\ "q]=\"success\";t[21]=\"timeout\";t[25]=\"unable to set cookie\";t[26]="\ "\"unexpected alert open\";t[r]=u;t[9]=\"unknown command\";s.prototype.t"\ "oString=function(){return this.name+\": \"+this.message};function w(){t"\ "his.a=void 0}\nfunction x(a,b,c){switch(typeof b){case \"string\":y(b,c"\ ");break;case \"number\":c.push(isFinite(b)&&!isNaN(b)?b:\"null\");break"\ ";case \"boolean\":c.push(b);break;case \"undefined\":c.push(\"null\");b"\ "reak;case \"object\":if(null==b){c.push(\"null\");break}if(\"array\"==h"\ "(b)){var e=b.length;c.push(\"[\");for(var f=\"\",d=0;d<e;d++)c.push(f),"\ "f=b[d],x(a,a.a?a.a.call(b,String(d),f):f,c),f=\",\";c.push(\"]\");break"\ "}c.push(\"{\");e=\"\";for(d in b)Object.prototype.hasOwnProperty.call(b"\ ",d)&&(f=b[d],\"function\"!=typeof f&&(c.push(e),y(d,\nc),c.push(\":\"),"\ "x(a,a.a?a.a.call(b,d,f):f,c),e=\",\"));c.push(\"}\");break;case \"funct"\ "ion\":break;default:throw Error(\"Unknown type: \"+typeof b);}}var z={'"\ "\"':'\\\\\"',\"\\\\\":\"\\\\\\\\\",\"/\":\"\\\\/\",\"\\b\":\"\\\\b\",\""\ "\\f\":\"\\\\f\",\"\\n\":\"\\\\n\",\"\\r\":\"\\\\r\",\"\\t\":\"\\\\t\","\ "\"\\x0B\":\"\\\\u000b\"},A=/\\uffff/.test(\"\\uffff\")?/[\\\\\\\"\\x00-"\ "\\x1f\\x7f-\\uffff]/g:/[\\\\\\\"\\x00-\\x1f\\x7f-\\xff]/g;\nfunction y("\ "a,b){b.push('\"',a.replace(A,function(a){if(a in z)return z[a];var b=a."\ "charCodeAt(0),f=\"\\\\u\";16>b?f+=\"000\":256>b?f+=\"00\":4096>b&&(f+="\ "\"0\");return z[a]=f+b.toString(16)}),'\"')};function B(a,b){for(var c="\ "a.length,e=Array(c),f=\"string\"==typeof a?a.split(\"\"):a,d=0;d<c;d++)"\ "d in f&&(e[d]=b.call(void 0,f[d],d,a));return e};function C(a,b){var c="\ "{},e;for(e in a)b.call(void 0,a[e],e,a)&&(c[e]=a[e]);return c}function "\ "D(a,b){var c={},e;for(e in a)c[e]=b.call(void 0,a[e],e,a);return c}func"\ "tion E(a,b){for(var c in a)if(b.call(void 0,a[c],c,a))return c};functio"\ "n F(a){switch(h(a)){case \"string\":case \"number\":case \"boolean\":re"\ "turn a;case \"function\":return a.toString();case \"array\":return B(a,"\ "F);case \"object\":if(\"nodeType\"in a&&(1==a.nodeType||9==a.nodeType))"\ "{var b={};b.ELEMENT=G(a);return b}if(\"document\"in a)return b={},b.WIN"\ "DOW=G(a),b;if(k(a))return B(a,F);a=C(a,function(a,b){return\"number\"=="\ "typeof b||\"string\"==typeof b});return D(a,F);default:return null}}\nf"\ "unction H(a,b){return\"array\"==h(a)?B(a,function(a){return H(a,b)}):l("\ "a)?\"function\"==typeof a?a:\"ELEMENT\"in a?L(a.ELEMENT,b):\"WINDOW\"in"\ " a?L(a.WINDOW,b):D(a,function(a){return H(a,b)}):a}function M(a){a=a||d"\ "ocument;var b=a.$wdc_;b||(b=a.$wdc_={},b.b=p());b.b||(b.b=p());return b"\ "}function G(a){var b=M(a.ownerDocument),c=E(b,function(b){return b==a})"\ ";c||(c=\":wdc:\"+b.b++,b[c]=a);return c}\nfunction L(a,b){a=decodeURICo"\ "mponent(a);var c=b||document,e=M(c);if(!(a in e))throw new s(10,\"Eleme"\ "nt does not exist in cache\");var f=e[a];if(\"setInterval\"in f){if(f.c"\ "losed)throw delete e[a],new s(23,\"Window has been closed.\");return f}"\ "for(var d=f;d;){if(d==c.documentElement)return f;d=d.parentNode}delete "\ "e[a];throw new s(10,\"Element is no longer attached to the DOM\");};fun"\ "ction N(a,b,c,e,f,d){function n(a,b){if(!I){g.removeEventListener?g.rem"\ "oveEventListener(\"unload\",v,!0):g.detachEvent(\"onunload\",v);g.clear"\ "Timeout(J);if(a!=q){var c=new s(a,b.message||b+\"\");c.stack=b.stack;b="\ "{status:\"code\"in c?c.code:r,value:{message:c.message}}}else b={status"\ ":q,value:F(b)};var c=e,d;f?(d=[],x(new w,b,d),d=d.join(\"\")):d=b;c(d);"\ "I=!0}}function v(){n(r,Error(\"Detected a page unload event; asynchrono"\ "us script execution does not work across page loads.\"))}var g=d||windo"\ "w,J,I=!1;d=m(n,\nr);if(g.closed)d(\"Unable to execute script; the targe"\ "t window is closed.\");else{a=\"string\"==typeof a?new g.Function(a):g="\ "=window?a:new g.Function(\"return (\"+a+\").apply(null,arguments);\");b"\ "=H(b,g.document);b.push(m(n,q));g.addEventListener?g.addEventListener("\ "\"unload\",v,!0):g.attachEvent(\"onunload\",v);var R=p();try{a.apply(g,"\ "b),J=g.setTimeout(function(){n(28,Error(\"Timed out waiting for asyncrh"\ "onous script result after \"+(p()-R)+\" ms\"))},Math.max(0,c))}catch(K)"\ "{n(K.code||r,K)}}}var O=[\"_\"],P=this;\nO[0]in P||!P.execScript||P.exe"\ "cScript(\"var \"+O[0]);for(var Q;O.length&&(Q=O.shift());)O.length||voi"\ "d 0===N?P=P[Q]?P[Q]:P[Q]={}:P[Q]=N;; return this._.apply(null,arguments"\ ");}.apply({navigator:typeof window!=undefined?window.navigator:null,doc"\ "ument:typeof window!=undefined?window.document:null}, arguments);}" EXECUTE_SCRIPT = \ "function(){return function(){function g(a){var b=typeof a;if(\"object\""\ "==b)if(a){if(a instanceof Array)return\"array\";if(a instanceof Object)"\ "return b;var c=Object.prototype.toString.call(a);if(\"[object Window]\""\ "==c)return\"object\";if(\"[object Array]\"==c||\"number\"==typeof a.len"\ "gth&&\"undefined\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"splice\"))return\"array\";if(\"[o"\ "bject Function]\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=type"\ "of a.propertyIsEnumerable&&!a.propertyIsEnumerable(\"call\"))return\"fu"\ "nction\"}else return\"null\";\nelse if(\"function\"==b&&\"undefined\"=="\ "typeof a.call)return\"object\";return b}function h(a){var b=g(a);return"\ "\"array\"==b||\"object\"==b&&\"number\"==typeof a.length}function k(a){"\ "var b=typeof a;return\"object\"==b&&null!=a||\"function\"==b}var l=Date"\ ".now||function(){return+new Date};var m=window;function n(a,b){this.cod"\ "e=a;this.state=p[a]||q;this.message=b||\"\";var c=this.state.replace(/("\ "(?:^|\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\x"\ "a0]+/g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Erro"\ "r\";this.name=c;c=Error(this.message);c.name=this.name;this.stack=c.sta"\ "ck||\"\"}(function(){var a=Error;function b(){}b.prototype=a.prototype;"\ "n.c=a.prototype;n.prototype=new b})();\nvar q=\"unknown error\",p={15:"\ "\"element not selectable\",11:\"element not visible\",31:\"ime engine a"\ "ctivation failed\",30:\"ime not available\",24:\"invalid cookie domain"\ "\",29:\"invalid element coordinates\",12:\"invalid element state\",32:"\ "\"invalid selector\",51:\"invalid selector\",52:\"invalid selector\",17"\ ":\"javascript error\",405:\"unsupported operation\",34:\"move target ou"\ "t of bounds\",27:\"no such alert\",7:\"no such element\",8:\"no such fr"\ "ame\",23:\"no such window\",28:\"script timeout\",33:\"session not crea"\ "ted\",10:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:"\ "\"unable to set cookie\",26:\"unexpected alert open\"};p[13]=q;p[9]=\"u"\ "nknown command\";n.prototype.toString=function(){return this.name+\": "\ "\"+this.message};function r(){this.a=void 0}\nfunction s(a,b,c){switch("\ "typeof b){case \"string\":t(b,c);break;case \"number\":c.push(isFinite("\ "b)&&!isNaN(b)?b:\"null\");break;case \"boolean\":c.push(b);break;case "\ "\"undefined\":c.push(\"null\");break;case \"object\":if(null==b){c.push"\ "(\"null\");break}if(\"array\"==g(b)){var d=b.length;c.push(\"[\");for(v"\ "ar e=\"\",f=0;f<d;f++)c.push(e),e=b[f],s(a,a.a?a.a.call(b,String(f),e):"\ "e,c),e=\",\";c.push(\"]\");break}c.push(\"{\");d=\"\";for(f in b)Object"\ ".prototype.hasOwnProperty.call(b,f)&&(e=b[f],\"function\"!=typeof e&&(c"\ ".push(d),t(f,\nc),c.push(\":\"),s(a,a.a?a.a.call(b,f,e):e,c),d=\",\"));"\ "c.push(\"}\");break;case \"function\":break;default:throw Error(\"Unkno"\ "wn type: \"+typeof b);}}var v={'\"':'\\\\\"',\"\\\\\":\"\\\\\\\\\",\"/"\ "\":\"\\\\/\",\"\\b\":\"\\\\b\",\"\\f\":\"\\\\f\",\"\\n\":\"\\\\n\",\""\ "\\r\":\"\\\\r\",\"\\t\":\"\\\\t\",\"\\x0B\":\"\\\\u000b\"},w=/\\uffff/."\ "test(\"\\uffff\")?/[\\\\\\\"\\x00-\\x1f\\x7f-\\uffff]/g:/[\\\\\\\"\\x00"\ "-\\x1f\\x7f-\\xff]/g;\nfunction t(a,b){b.push('\"',a.replace(w,function"\ "(a){if(a in v)return v[a];var b=a.charCodeAt(0),e=\"\\\\u\";16>b?e+=\"0"\ "00\":256>b?e+=\"00\":4096>b&&(e+=\"0\");return v[a]=e+b.toString(16)}),"\ "'\"')};function x(a,b){for(var c=a.length,d=Array(c),e=\"string\"==type"\ "of a?a.split(\"\"):a,f=0;f<c;f++)f in e&&(d[f]=b.call(void 0,e[f],f,a))"\ ";return d};function y(a,b){var c={},d;for(d in a)b.call(void 0,a[d],d,a"\ ")&&(c[d]=a[d]);return c}function z(a,b){var c={},d;for(d in a)c[d]=b.ca"\ "ll(void 0,a[d],d,a);return c}function A(a,b){for(var c in a)if(b.call(v"\ "oid 0,a[c],c,a))return c};function B(a){switch(g(a)){case \"string\":ca"\ "se \"number\":case \"boolean\":return a;case \"function\":return a.toSt"\ "ring();case \"array\":return x(a,B);case \"object\":if(\"nodeType\"in a"\ "&&(1==a.nodeType||9==a.nodeType)){var b={};b.ELEMENT=C(a);return b}if("\ "\"document\"in a)return b={},b.WINDOW=C(a),b;if(h(a))return x(a,B);a=y("\ "a,function(a,b){return\"number\"==typeof b||\"string\"==typeof b});retu"\ "rn z(a,B);default:return null}}\nfunction D(a,b){return\"array\"==g(a)?"\ "x(a,function(a){return D(a,b)}):k(a)?\"function\"==typeof a?a:\"ELEMENT"\ "\"in a?E(a.ELEMENT,b):\"WINDOW\"in a?E(a.WINDOW,b):z(a,function(a){retu"\ "rn D(a,b)}):a}function F(a){a=a||document;var b=a.$wdc_;b||(b=a.$wdc_={"\ "},b.b=l());b.b||(b.b=l());return b}function C(a){var b=F(a.ownerDocumen"\ "t),c=A(b,function(b){return b==a});c||(c=\":wdc:\"+b.b++,b[c]=a);return"\ " c}\nfunction E(a,b){a=decodeURIComponent(a);var c=b||document,d=F(c);i"\ "f(!(a in d))throw new n(10,\"Element does not exist in cache\");var e=d"\ "[a];if(\"setInterval\"in e){if(e.closed)throw delete d[a],new n(23,\"Wi"\ "ndow has been closed.\");return e}for(var f=e;f;){if(f==c.documentEleme"\ "nt)return e;f=f.parentNode}delete d[a];throw new n(10,\"Element is no l"\ "onger attached to the DOM\");};function G(a,b,c,d){d=d||m;var e;try{a="\ "\"string\"==typeof a?new d.Function(a):d==window?a:new d.Function(\"ret"\ "urn (\"+a+\").apply(null,arguments);\");var f=D(b,d.document),K=a.apply"\ "(null,f);e={status:0,value:B(K)}}catch(u){e={status:\"code\"in u?u.code"\ ":13,value:{message:u.message}}}c&&(a=[],s(new r,e,a),e=a.join(\"\"));re"\ "turn e}var H=[\"_\"],I=this;H[0]in I||!I.execScript||I.execScript(\"var"\ " \"+H[0]);for(var J;H.length&&(J=H.shift());)H.length||void 0===G?I=I[J"\ "]?I[J]:I[J]={}:I[J]=G;; return this._.apply(null,arguments);}.apply({na"\ "vigator:typeof window!=undefined?window.navigator:null,document:typeof "\ "window!=undefined?window.document:null}, arguments);}" EXECUTE_SQL = \ "function(){return function(){var d=window;function f(a,b){this.code=a;t"\ "his.state=g[a]||h;this.message=b||\"\";var c=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),e=c.length-5;if(0>e||c.indexOf(\"Error\",e)!=e)c+=\"Error\";t"\ "his.name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||"\ "\"\"}(function(){var a=Error;function b(){}b.prototype=a.prototype;f.a="\ "a.prototype;f.prototype=new b})();\nvar h=\"unknown error\",g={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};g[13]=h;g[9]=\"unknown "\ "command\";f.prototype.toString=function(){return this.name+\": \"+this."\ "message};function k(a){this.rows=[];for(var b=0;b<a.rows.length;b++)thi"\ "s.rows[b]=a.rows.item(b);this.rowsAffected=a.rowsAffected;this.insertId"\ "=-1;try{this.insertId=a.insertId}catch(c){}};function l(a,b,c,e,q,s,t){"\ "function u(a,b){var c=new k(b);e(a,c)}var n;try{n=d.openDatabase(a,\"\""\ ",a+\"name\",5242880)}catch(v){throw new f(13,v.message);}n.transaction("\ "function(a){a.executeSql(b,c,u,t)},q,s)}var m=[\"_\"],p=this;m[0]in p||"\ "!p.execScript||p.execScript(\"var \"+m[0]);for(var r;m.length&&(r=m.shi"\ "ft());)m.length||void 0===l?p=p[r]?p[r]:p[r]={}:p[r]=l;; return this._."\ "apply(null,arguments);}.apply({navigator:typeof window!=undefined?windo"\ "w.navigator:null,document:typeof window!=undefined?window.document:null"\ "}, arguments);}" FIND_ELEMENT = \ "function(){return function(){function h(a){return function(){return a}}"\ "var k=this;\nfunction aa(a){var b=typeof a;if(\"object\"==b)if(a){if(a "\ "instanceof Array)return\"array\";if(a instanceof Object)return b;var c="\ "Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"obj"\ "ect\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefine"\ "d\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a."\ "propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]"\ "\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else r"\ "eturn\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)r"\ "eturn\"object\";return b}function l(a){return\"string\"==typeof a}funct"\ "ion n(a){return\"function\"==aa(a)};var ba=window;function ca(a){var b="\ "a.length-1;return 0<=b&&a.indexOf(\" \",b)==b}function p(a){return a.re"\ "place(/^[\\s\\xa0]+|[\\s\\xa0]+$/g,\"\")}function da(a){return String(a"\ ").replace(/\\-([a-z])/g,function(a,c){return c.toUpperCase()})};var ea="\ "Array.prototype;function r(a,b){for(var c=a.length,d=l(a)?a.split(\"\")"\ ":a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function s(a,b){for(var "\ "c=a.length,d=[],e=0,f=l(a)?a.split(\"\"):a,g=0;g<c;g++)if(g in f){var q"\ "=f[g];b.call(void 0,q,g,a)&&(d[e++]=q)}return d}function fa(a,b){if(a.r"\ "educe)return a.reduce(b,\"\");var c=\"\";r(a,function(d,e){c=b.call(voi"\ "d 0,c,d,e,a)});return c}function ga(a,b){for(var c=a.length,d=l(a)?a.sp"\ "lit(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return!0;ret"\ "urn!1}\nfunction ha(a,b){var c;a:{c=a.length;for(var d=l(a)?a.split(\""\ "\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a)){c=e;break a}c=-1}"\ "return 0>c?null:l(a)?a.charAt(c):a[c]}function t(a,b){var c;a:if(l(a))c"\ "=l(b)&&1==b.length?a.indexOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c i"\ "n a&&a[c]===b)break a;c=-1}return 0<=c}function ia(a,b,c){return 2>=arg"\ "uments.length?ea.slice.call(a,b):ea.slice.call(a,b,c)};var ja;function "\ "u(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}u.prototype.toString"\ "=function(){return\"(\"+this.x+\", \"+this.y+\")\"};u.prototype.ceil=fu"\ "nction(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this}"\ ";u.prototype.floor=function(){this.x=Math.floor(this.x);this.y=Math.flo"\ "or(this.y);return this};u.prototype.round=function(){this.x=Math.round("\ "this.x);this.y=Math.round(this.y);return this};function v(a,b){this.wid"\ "th=a;this.height=b}v.prototype.toString=function(){return\"(\"+this.wid"\ "th+\" x \"+this.height+\")\"};v.prototype.ceil=function(){this.width=Ma"\ "th.ceil(this.width);this.height=Math.ceil(this.height);return this};v.p"\ "rototype.floor=function(){this.width=Math.floor(this.width);this.height"\ "=Math.floor(this.height);return this};v.prototype.round=function(){this"\ ".width=Math.round(this.width);this.height=Math.round(this.height);retur"\ "n this};var ka=3;function w(a){return a?new la(x(a)):ja||(ja=new la)}fu"\ "nction ma(a){for(;a&&1!=a.nodeType;)a=a.previousSibling;return a}functi"\ "on y(a,b){if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if(\""\ "undefined\"!=typeof a.compareDocumentPosition)return a==b||Boolean(a.co"\ "mpareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}"\ "\nfunction na(a,b){if(a==b)return 0;if(a.compareDocumentPosition)return"\ " a.compareDocumentPosition(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNo"\ "de&&\"sourceIndex\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType"\ ";if(c&&d)return a.sourceIndex-b.sourceIndex;var e=a.parentNode,f=b.pare"\ "ntNode;return e==f?oa(a,b):!c&&y(e,b)?-1*pa(a,b):!d&&y(f,a)?pa(b,a):(c?"\ "a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}d=x(a);c=d"\ ".createRange();c.selectNode(a);c.collapse(!0);d=d.createRange();d.selec"\ "tNode(b);d.collapse(!0);\nreturn c.compareBoundaryPoints(k.Range.START_"\ "TO_END,d)}function pa(a,b){var c=a.parentNode;if(c==b)return-1;for(var "\ "d=b;d.parentNode!=c;)d=d.parentNode;return oa(d,a)}function oa(a,b){for"\ "(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1}function x(a){r"\ "eturn 9==a.nodeType?a:a.ownerDocument||a.document}function qa(a,b){a=a."\ "parentNode;for(var c=0;a;){if(b(a))return a;a=a.parentNode;c++}return n"\ "ull}function la(a){this.j=a||k.document||document}\nfunction z(a,b,c,d)"\ "{a=d||a.j;b=b&&\"*\"!=b?b.toUpperCase():\"\";if(a.querySelectorAll&&a.q"\ "uerySelector&&(b||c))c=a.querySelectorAll(b+(c?\".\"+c:\"\"));else if(c"\ "&&a.getElementsByClassName)if(a=a.getElementsByClassName(c),b){d={};for"\ "(var e=0,f=0,g;g=a[f];f++)b==g.nodeName&&(d[e++]=g);d.length=e;c=d}else"\ " c=a;else if(a=a.getElementsByTagName(b||\"*\"),c){d={};for(f=e=0;g=a[f"\ "];f++)b=g.className,\"function\"==typeof b.split&&t(b.split(/\\s+/),c)&"\ "&(d[e++]=g);d.length=e;c=d}else c=a;return c}\nfunction ra(a){var b=a.j"\ ";a=b.body;b=b.parentWindow||b.defaultView;return new u(b.pageXOffset||a"\ ".scrollLeft,b.pageYOffset||a.scrollTop)}la.prototype.contains=y;var A={"\ "n:function(a){return!(!a.querySelectorAll||!a.querySelector)},c:functio"\ "n(a,b){if(!a)throw Error(\"No class name specified\");a=p(a);if(1<a.spl"\ "it(/\\s+/).length)throw Error(\"Compound class names not permitted\");i"\ "f(A.n(b))return b.querySelector(\".\"+a.replace(/\\./g,\"\\\\.\"))||nul"\ "l;var c=z(w(b),\"*\",a,b);return c.length?c[0]:null},d:function(a,b){if"\ "(!a)throw Error(\"No class name specified\");a=p(a);if(1<a.split(/\\s+/"\ ").length)throw Error(\"Compound class names not permitted\");return A.n"\ "(b)?b.querySelectorAll(\".\"+\na.replace(/\\./g,\"\\\\.\")):z(w(b),\"*"\ "\",a,b)}};var C={c:function(a,b){n(b.querySelector);if(!a)throw Error("\ "\"No selector specified\");a=p(a);var c=b.querySelector(a);return c&&1="\ "=c.nodeType?c:null},d:function(a,b){n(b.querySelectorAll);if(!a)throw E"\ "rror(\"No selector specified\");a=p(a);return b.querySelectorAll(a)}};v"\ "ar sa={aliceblue:\"#f0f8ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\","\ "aquamarine:\"#7fffd4\",azure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ff"\ "e4c4\",black:\"#000000\",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",bl"\ "ueviolet:\"#8a2be2\",brown:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:"\ "\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f5"\ "0\",cornflowerblue:\"#6495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\""\ ",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenr"\ "od:\"#b8860b\",darkgray:\"#a9a9a9\",darkgreen:\"#006400\",\ndarkgrey:\""\ "#a9a9a9\",darkkhaki:\"#bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:"\ "\"#556b2f\",darkorange:\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b"\ "0000\",darksalmon:\"#e9967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\""\ "#483d8b\",darkslategray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturqu"\ "oise:\"#00ced1\",darkviolet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblu"\ "e:\"#00bfff\",dimgray:\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e9"\ "0ff\",firebrick:\"#b22222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b"\ "22\",fuchsia:\"#ff00ff\",gainsboro:\"#dcdcdc\",\nghostwhite:\"#f8f8ff\""\ ",gold:\"#ffd700\",goldenrod:\"#daa520\",gray:\"#808080\",green:\"#00800"\ "0\",greenyellow:\"#adff2f\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpi"\ "nk:\"#ff69b4\",indianred:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0"\ "\",khaki:\"#f0e68c\",lavender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",law"\ "ngreen:\"#7cfc00\",lemonchiffon:\"#fffacd\",lightblue:\"#add8e6\",light"\ "coral:\"#f08080\",lightcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2"\ "\",lightgray:\"#d3d3d3\",lightgreen:\"#90ee90\",lightgrey:\"#d3d3d3\",l"\ "ightpink:\"#ffb6c1\",lightsalmon:\"#ffa07a\",\nlightseagreen:\"#20b2aa"\ "\",lightskyblue:\"#87cefa\",lightslategray:\"#778899\",lightslategrey:"\ "\"#778899\",lightsteelblue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#"\ "00ff00\",limegreen:\"#32cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",ma"\ "roon:\"#800000\",mediumaquamarine:\"#66cdaa\",mediumblue:\"#0000cd\",me"\ "diumorchid:\"#ba55d3\",mediumpurple:\"#9370db\",mediumseagreen:\"#3cb37"\ "1\",mediumslateblue:\"#7b68ee\",mediumspringgreen:\"#00fa9a\",mediumtur"\ "quoise:\"#48d1cc\",mediumvioletred:\"#c71585\",midnightblue:\"#191970\""\ ",mintcream:\"#f5fffa\",mistyrose:\"#ffe4e1\",\nmoccasin:\"#ffe4b5\",nav"\ "ajowhite:\"#ffdead\",navy:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#8080"\ "00\",olivedrab:\"#6b8e23\",orange:\"#ffa500\",orangered:\"#ff4500\",orc"\ "hid:\"#da70d6\",palegoldenrod:\"#eee8aa\",palegreen:\"#98fb98\",paletur"\ "quoise:\"#afeeee\",palevioletred:\"#db7093\",papayawhip:\"#ffefd5\",pea"\ "chpuff:\"#ffdab9\",peru:\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",p"\ "owderblue:\"#b0e0e6\",purple:\"#800080\",red:\"#ff0000\",rosybrown:\"#b"\ "c8f8f\",royalblue:\"#4169e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072"\ "\",sandybrown:\"#f4a460\",seagreen:\"#2e8b57\",\nseashell:\"#fff5ee\",s"\ "ienna:\"#a0522d\",silver:\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6"\ "a5acd\",slategray:\"#708090\",slategrey:\"#708090\",snow:\"#fffafa\",sp"\ "ringgreen:\"#00ff7f\",steelblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008"\ "080\",thistle:\"#d8bfd8\",tomato:\"#ff6347\",turquoise:\"#40e0d0\",viol"\ "et:\"#ee82ee\",wheat:\"#f5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5"\ "\",yellow:\"#ffff00\",yellowgreen:\"#9acd32\"};var ta=\"background-colo"\ "r border-top-color border-right-color border-bottom-color border-left-c"\ "olor color outline-color\".split(\" \"),ua=/#([0-9a-fA-F])([0-9a-fA-F])"\ "([0-9a-fA-F])/;function va(a){if(!wa.test(a))throw Error(\"'\"+a+\"' is"\ " not a valid hex color\");4==a.length&&(a=a.replace(ua,\"#$1$1$2$2$3$3"\ "\"));return a.toLowerCase()}var wa=/^#(?:[0-9a-f]{3}){1,2}$/i,xa=/^(?:r"\ "gba)?\\((\\d{1,3}),\\s?(\\d{1,3}),\\s?(\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$"\ "/i;\nfunction ya(a){var b=a.match(xa);if(b){a=Number(b[1]);var c=Number"\ "(b[2]),d=Number(b[3]),b=Number(b[4]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<="\ "d&&255>=d&&0<=b&&1>=b)return[a,c,d,b]}return[]}var za=/^(?:rgb)?\\((0|["\ "1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2})\\)$/i;functio"\ "n Aa(a){var b=a.match(za);if(b){a=Number(b[1]);var c=Number(b[2]),b=Num"\ "ber(b[3]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<=b&&255>=b)return[a,c,b]}ret"\ "urn[]};function D(a,b){this.code=a;this.state=Ba[a]||Ca;this.message=b|"\ "|\"\";var c=this.state.replace(/((?:^|\\s+)[a-z])/g,function(a){return "\ "a.toUpperCase().replace(/^[\\s\\xa0]+/g,\"\")}),d=c.length-5;if(0>d||c."\ "indexOf(\"Error\",d)!=d)c+=\"Error\";this.name=c;c=Error(this.message);"\ "c.name=this.name;this.stack=c.stack||\"\"}(function(){var a=Error;funct"\ "ion b(){}b.prototype=a.prototype;D.P=a.prototype;D.prototype=new b})();"\ "\nvar Ca=\"unknown error\",Ba={15:\"element not selectable\",11:\"eleme"\ "nt not visible\",31:\"ime engine activation failed\",30:\"ime not avail"\ "able\",24:\"invalid cookie domain\",29:\"invalid element coordinates\","\ "12:\"invalid element state\",32:\"invalid selector\",51:\"invalid selec"\ "tor\",52:\"invalid selector\",17:\"javascript error\",405:\"unsupported"\ " operation\",34:\"move target out of bounds\",27:\"no such alert\",7:\""\ "no such element\",8:\"no such frame\",23:\"no such window\",28:\"script"\ " timeout\",33:\"session not created\",10:\"stale element reference\",\n"\ "0:\"success\",21:\"timeout\",25:\"unable to set cookie\",26:\"unexpecte"\ "d alert open\"};Ba[13]=Ca;Ba[9]=\"unknown command\";D.prototype.toStrin"\ "g=function(){return this.name+\": \"+this.message};function E(a){var b="\ "null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerTe"\ "xt:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c"\ "){a=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do "\ "1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&&"\ "!(a=d[--c].nextSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction "\ "F(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)return!1}catch(d){"\ "return!1}return null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}func"\ "tion G(a,b,c,d,e){return Da.call(null,a,b,l(c)?c:null,l(d)?d:null,e||ne"\ "w H)}\nfunction Da(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b."\ "getElementsByName(d),r(b,function(b){a.matches(b)&&e.add(b)})):b.getEle"\ "mentsByClassName&&d&&\"class\"==c?(b=b.getElementsByClassName(d),r(b,fu"\ "nction(b){b.className==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagN"\ "ame&&(b=b.getElementsByTagName(a.getName()),r(b,function(a){F(a,c,d)&&e"\ ".add(a)}));return e}function Ea(a,b,c,d,e){for(b=b.firstChild;b;b=b.nex"\ "tSibling)F(b,c,d)&&a.matches(b)&&e.add(b);return e};function H(){this.f"\ "=this.e=null;this.k=0}function Fa(a){this.t=a;this.next=this.m=null}H.p"\ "rototype.unshift=function(a){a=new Fa(a);a.next=this.e;this.f?this.e.m="\ "a:this.e=this.f=a;this.e=a;this.k++};H.prototype.add=function(a){a=new "\ "Fa(a);a.m=this.f;this.e?this.f.next=a:this.e=this.f=a;this.f=a;this.k++"\ "};function Ga(a){return(a=a.e)?a.t:null}function I(a){return new Ha(a,!"\ "1)}function Ha(a,b){this.M=a;this.p=(this.u=b)?a.f:a.e;this.B=null}\nHa"\ ".prototype.next=function(){var a=this.p;if(null==a)return null;var b=th"\ "is.B=a;this.p=this.u?a.m:a.next;return b.t};function J(a,b,c,d,e){b=b.e"\ "valuate(d);c=c.evaluate(d);var f;if(b instanceof H&&c instanceof H){e=I"\ "(b);for(d=e.next();d;d=e.next())for(b=I(c),f=b.next();f;f=b.next())if(a"\ "(E(d),E(f)))return!0;return!1}if(b instanceof H||c instanceof H){b inst"\ "anceof H?e=b:(e=c,c=b);e=I(e);b=typeof c;for(d=e.next();d;d=e.next()){s"\ "witch(b){case \"number\":d=+E(d);break;case \"boolean\":d=!!E(d);break;"\ "case \"string\":d=E(d);break;default:throw Error(\"Illegal primitive ty"\ "pe for comparison.\");}if(a(d,c))return!0}return!1}return e?\n\"boolean"\ "\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeof b||\""\ "number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function Ia(a,b,c,d){this.C"\ "=a;this.O=b;this.A=c;this.i=d}Ia.prototype.toString=function(){return t"\ "his.C};var Ja={};function K(a,b,c,d){if(a in Ja)throw Error(\"Binary op"\ "erator already created: \"+a);a=new Ia(a,b,c,d);Ja[a.toString()]=a}K(\""\ "div\",6,1,function(a,b,c){return a.b(c)/b.b(c)});K(\"mod\",6,1,function"\ "(a,b,c){return a.b(c)%b.b(c)});K(\"*\",6,1,function(a,b,c){return a.b(c"\ ")*b.b(c)});\nK(\"+\",5,1,function(a,b,c){return a.b(c)+b.b(c)});K(\"-\""\ ",5,1,function(a,b,c){return a.b(c)-b.b(c)});K(\"<\",4,2,function(a,b,c)"\ "{return J(function(a,b){return a<b},a,b,c)});K(\">\",4,2,function(a,b,c"\ "){return J(function(a,b){return a>b},a,b,c)});K(\"<=\",4,2,function(a,b"\ ",c){return J(function(a,b){return a<=b},a,b,c)});K(\">=\",4,2,function("\ "a,b,c){return J(function(a,b){return a>=b},a,b,c)});K(\"=\",3,2,functio"\ "n(a,b,c){return J(function(a,b){return a==b},a,b,c,!0)});\nK(\"!=\",3,2"\ ",function(a,b,c){return J(function(a,b){return a!=b},a,b,c,!0)});K(\"an"\ "d\",2,2,function(a,b,c){return a.h(c)&&b.h(c)});K(\"or\",1,2,function(a"\ ",b,c){return a.h(c)||b.h(c)});function Ka(a,b,c,d,e,f,g,q,m){this.l=a;t"\ "his.A=b;this.L=c;this.K=d;this.J=e;this.i=f;this.I=g;this.H=void 0!==q?"\ "q:g;this.N=!!m}Ka.prototype.toString=function(){return this.l};var La={"\ "};function L(a,b,c,d,e,f,g,q){if(a in La)throw Error(\"Function already"\ " created: \"+a+\".\");La[a]=new Ka(a,b,c,d,!1,e,f,g,q)}L(\"boolean\",2,"\ "!1,!1,function(a,b){return b.h(a)},1);L(\"ceiling\",1,!1,!1,function(a,"\ "b){return Math.ceil(b.b(a))},1);\nL(\"concat\",3,!1,!1,function(a,b){va"\ "r c=ia(arguments,1);return fa(c,function(b,c){return b+c.a(a)})},2,null"\ ");L(\"contains\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return-1!=b."\ "indexOf(a)},2);L(\"count\",1,!1,!1,function(a,b){return b.evaluate(a).k"\ "},1,1,!0);L(\"false\",2,!1,!1,h(!1),0);L(\"floor\",1,!1,!1,function(a,b"\ "){return Math.floor(b.b(a))},1);\nL(\"id\",4,!1,!1,function(a,b){var c="\ "a.g(),d=9==c.nodeType?c:c.ownerDocument,c=b.a(a).split(/\\s+/),e=[];r(c"\ ",function(a){(a=d.getElementById(a))&&!t(e,a)&&e.push(a)});e.sort(na);v"\ "ar f=new H;r(e,function(a){f.add(a)});return f},1);L(\"lang\",2,!1,!1,h"\ "(!1),1);L(\"last\",1,!0,!1,function(a){if(1!=arguments.length)throw Err"\ "or(\"Function last expects ()\");return a.F()},0);L(\"local-name\",3,!1"\ ",!0,function(a,b){var c=b?Ga(b.evaluate(a)):a.g();return c?c.nodeName.t"\ "oLowerCase():\"\"},0,1,!0);\nL(\"name\",3,!1,!0,function(a,b){var c=b?G"\ "a(b.evaluate(a)):a.g();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);"\ "L(\"namespace-uri\",3,!0,!1,h(\"\"),0,1,!0);L(\"normalize-space\",3,!1,"\ "!0,function(a,b){return(b?b.a(a):E(a.g())).replace(/[\\s\\xa0]+/g,\" \""\ ").replace(/^\\s+|\\s+$/g,\"\")},0,1);L(\"not\",2,!1,!1,function(a,b){re"\ "turn!b.h(a)},1);L(\"number\",1,!1,!0,function(a,b){return b?b.b(a):+E(a"\ ".g())},0,1);L(\"position\",1,!0,!1,function(a){return a.G()},0);L(\"rou"\ "nd\",1,!1,!1,function(a,b){return Math.round(b.b(a))},1);\nL(\"starts-w"\ "ith\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return 0==b.lastIndexOf"\ "(a,0)},2);L(\"string\",3,!1,!0,function(a,b){return b?b.a(a):E(a.g())},"\ "0,1);L(\"string-length\",1,!1,!0,function(a,b){return(b?b.a(a):E(a.g())"\ ").length},0,1);\nL(\"substring\",3,!1,!1,function(a,b,c,d){c=c.b(a);if("\ "isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.b(a):Infinity;if(i"\ "sNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max(c,0)"\ ";a=b.a(a);if(Infinity==d)return a.substring(e);b=Math.round(d);return a"\ ".substring(e,c+b)},2,3);L(\"substring-after\",3,!1,!1,function(a,b,c){b"\ "=b.a(a);a=c.a(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.length"\ ")},2);\nL(\"substring-before\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a"\ ");a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);L(\"sum\",1,!1,!"\ "1,function(a,b){for(var c=I(b.evaluate(a)),d=0,e=c.next();e;e=c.next())"\ "d+=+E(e);return d},1,1,!0);L(\"translate\",3,!1,!1,function(a,b,c,d){b="\ "b.a(a);c=c.a(a);var e=d.a(a);a=[];for(d=0;d<c.length;d++){var f=c.charA"\ "t(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d++)f=b.charA"\ "t(d),c+=f in a?a[f]:f;return c},3);L(\"true\",2,!1,!1,h(!0),0);function"\ " Ma(a,b,c,d){this.l=a;this.D=b;this.u=c;this.Q=d}Ma.prototype.toString="\ "function(){return this.l};var Na={};function M(a,b,c,d){if(a in Na)thro"\ "w Error(\"Axis already created: \"+a);Na[a]=new Ma(a,b,c,!!d)}M(\"ances"\ "tor\",function(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matches(d)&&c"\ ".unshift(d);return c},!0);M(\"ancestor-or-self\",function(a,b){var c=ne"\ "w H,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c},!"\ "0);\nM(\"attribute\",function(a,b){var c=new H,d=a.getName(),e=b.attrib"\ "utes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e.getNam"\ "edItem(d))&&c.add(f);return c},!1);M(\"child\",function(a,b,c,d,e){retu"\ "rn Ea.call(null,a,b,l(c)?c:null,l(d)?d:null,e||new H)},!1,!0);M(\"desce"\ "ndant\",G,!1,!0);M(\"descendant-or-self\",function(a,b,c,d){var e=new H"\ ";F(b,c,d)&&a.matches(b)&&e.add(b);return G(a,b,c,d,e)},!1,!0);\nM(\"fol"\ "lowing\",function(a,b,c,d){var e=new H;do for(var f=b;f=f.nextSibling;)"\ "F(f,c,d)&&a.matches(f)&&e.add(f),e=G(a,f,c,d,e);while(b=b.parentNode);r"\ "eturn e},!1,!0);M(\"following-sibling\",function(a,b){for(var c=new H,d"\ "=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);M(\"namespace"\ "\",function(){return new H},!1);M(\"parent\",function(a,b){var c=new H;"\ "if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerElement)"\ ",c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nM(\"preced"\ "ing\",function(a,b,c,d){var e=new H,f=[];do f.unshift(b);while(b=b.pare"\ "ntNode);for(var g=1,q=f.length;g<q;g++){var m=[];for(b=f[g];b=b.previou"\ "sSibling;)m.unshift(b);for(var B=0,ab=m.length;B<ab;B++)b=m[B],F(b,c,d)"\ "&&a.matches(b)&&e.add(b),e=G(a,b,c,d,e)}return e},!0,!0);M(\"preceding-"\ "sibling\",function(a,b){for(var c=new H,d=b;d=d.previousSibling;)a.matc"\ "hes(d)&&c.unshift(d);return c},!0);M(\"self\",function(a,b){var c=new H"\ ";a.matches(b)&&c.add(b);return c},!1);var N={};N.w=function(){var a={R:"\ "\"http://www.w3.org/2000/svg\"};return function(b){return a[b]||null}}("\ ");N.i=function(a,b,c){var d=x(a);try{var e=d.createNSResolver?d.createN"\ "SResolver(d.documentElement):N.w;return d.evaluate(b,a,e,c,null)}catch("\ "f){throw new D(32,\"Unable to locate an element with the xpath expressi"\ "on \"+b+\" because of the following error:\\n\"+f);}};N.o=function(a,b)"\ "{if(!a||1!=a.nodeType)throw new D(32,'The result of the xpath expressio"\ "n \"'+b+'\" is: '+a+\". It should be an element.\");};\nN.c=function(a,"\ "b){var c=function(){var c=N.i(b,a,9);return c?c.singleNodeValue||null:b"\ ".selectSingleNode?(c=x(b),c.setProperty&&c.setProperty(\"SelectionLangu"\ "age\",\"XPath\"),b.selectSingleNode(a)):null}();null===c||N.o(c,a);retu"\ "rn c};\nN.d=function(a,b){var c=function(){var c=N.i(b,a,7);if(c){for(v"\ "ar e=c.snapshotLength,f=[],g=0;g<e;++g)f.push(c.snapshotItem(g));return"\ " f}return b.selectNodes?(c=x(b),c.setProperty&&c.setProperty(\"Selectio"\ "nLanguage\",\"XPath\"),b.selectNodes(a)):[]}();r(c,function(b){N.o(b,a)"\ "});return c};function O(a,b,c,d){this.left=a;this.top=b;this.width=c;th"\ "is.height=d}O.prototype.toString=function(){return\"(\"+this.left+\", "\ "\"+this.top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};O.prototype"\ ".contains=function(a){return a instanceof O?this.left<=a.left&&this.lef"\ "t+this.width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a."\ "top+a.height:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&"\ "a.y<=this.top+this.height};\nO.prototype.ceil=function(){this.left=Math"\ ".ceil(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this"\ ".width);this.height=Math.ceil(this.height);return this};O.prototype.flo"\ "or=function(){this.left=Math.floor(this.left);this.top=Math.floor(this."\ "top);this.width=Math.floor(this.width);this.height=Math.floor(this.heig"\ "ht);return this};\nO.prototype.round=function(){this.left=Math.round(th"\ "is.left);this.top=Math.round(this.top);this.width=Math.round(this.width"\ ");this.height=Math.round(this.height);return this};function Oa(a,b){var"\ " c=x(a);return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defa"\ "ultView.getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||\"\":\""\ "\"}function P(a){return Oa(a,\"position\")||(a.currentStyle?a.currentSt"\ "yle.position:null)||a.style&&a.style.position}function Pa(a){var b;try{"\ "b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom"\ ":0}}return b}\nfunction Qa(a){var b=x(a),c=P(a),d=\"fixed\"==c||\"absol"\ "ute\"==c;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=P(a),d=d&&\"sta"\ "tic\"==c&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clientWi"\ "dth||a.scrollHeight>a.clientHeight||\"fixed\"==c||\"absolute\"==c||\"re"\ "lative\"==c))return a;return null}\nfunction Ra(a){if(1==a.nodeType){va"\ "r b;if(a.getBoundingClientRect)b=Pa(a),b=new u(b.left,b.top);else{b=ra("\ "w(a));var c=x(a),d=P(a),e=new u(0,0),f=(c?x(c):document).documentElemen"\ "t;if(a!=f)if(a.getBoundingClientRect)a=Pa(a),c=ra(w(c)),e.x=a.left+c.x,"\ "e.y=a.top+c.y;else if(c.getBoxObjectFor)a=c.getBoxObjectFor(a),c=c.getB"\ "oxObjectFor(f),e.x=a.screenX-c.screenX,e.y=a.screenY-c.screenY;else{var"\ " g=a;do{e.x+=g.offsetLeft;e.y+=g.offsetTop;g!=a&&(e.x+=g.clientLeft||0,"\ "e.y+=g.clientTop||0);if(\"fixed\"==P(g)){e.x+=\nc.body.scrollLeft;e.y+="\ "c.body.scrollTop;break}g=g.offsetParent}while(g&&g!=a);\"absolute\"==d&"\ "&(e.y-=c.body.offsetTop);for(g=a;(g=Qa(g))&&g!=c.body&&g!=f;)e.x-=g.scr"\ "ollLeft,e.y-=g.scrollTop}b=new u(e.x-b.x,e.y-b.y)}return b}b=n(a.q);e=a"\ ";a.targetTouches?e=a.targetTouches[0]:b&&a.q().targetTouches&&(e=a.q()."\ "targetTouches[0]);return new u(e.clientX,e.clientY)};function Q(a,b){re"\ "turn!!a&&1==a.nodeType&&(!b||a.tagName.toUpperCase()==b)}var Sa=/[;]+(?"\ "=(?:(?:[^\"]*\"){2})*[^\"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:[^()]*"\ "\\([^()]*\\))*[^()]*$)/;function Ta(a){var b=[];r(a.split(Sa),function("\ "a){var d=a.indexOf(\":\");0<d&&(a=[a.slice(0,d),a.slice(d+1)],2==a.leng"\ "th&&b.push(a[0].toLowerCase(),\":\",a[1],\";\"))});b=b.join(\"\");retur"\ "n b=\";\"==b.charAt(b.length-1)?b:b+\";\"}\nfunction R(a,b){b=b.toLower"\ "Case();if(\"style\"==b)return Ta(a.style.cssText);var c=a.getAttributeN"\ "ode(b);return c&&c.specified?c.value:null}function S(a){for(a=a.parentN"\ "ode;a&&1!=a.nodeType&&9!=a.nodeType&&11!=a.nodeType;)a=a.parentNode;ret"\ "urn Q(a)?a:null}\nfunction T(a,b){var c=da(b);if(\"float\"==c||\"cssFlo"\ "at\"==c||\"styleFloat\"==c)c=\"cssFloat\";c=Oa(a,c)||Ua(a,c);if(null==="\ "c)c=null;else if(t(ta,b)&&(wa.test(\"#\"==c.charAt(0)?c:\"#\"+c)||Aa(c)"\ ".length||sa&&sa[c.toLowerCase()]||ya(c).length)){var d=ya(c);if(!d.leng"\ "th){a:if(d=Aa(c),!d.length){d=(d=sa[c.toLowerCase()])?d:\"#\"==c.charAt"\ "(0)?c:\"#\"+c;if(wa.test(d)&&(d=va(d),d=va(d),d=[parseInt(d.substr(1,2)"\ ",16),parseInt(d.substr(3,2),16),parseInt(d.substr(5,2),16)],d.length))b"\ "reak a;d=[]}3==d.length&&d.push(1)}c=4!=\nd.length?c:\"rgba(\"+d.join("\ "\", \")+\")\"}return c}function Ua(a,b){var c=a.currentStyle||a.style,d"\ "=c[b];void 0===d&&n(c.getPropertyValue)&&(d=c.getPropertyValue(b));retu"\ "rn\"inherit\"!=d?void 0!==d?d:null:(c=S(a))?Ua(c,b):null}\nfunction Va("\ "a,b){function c(a){if(\"none\"==T(a,\"display\"))return!1;a=S(a);return"\ "!a||c(a)}function d(a){var b=U(a);return 0<b.height&&0<b.width?!0:Q(a,"\ "\"PATH\")&&(0<b.height||0<b.width)?(a=T(a,\"stroke-width\"),!!a&&0<pars"\ "eInt(a,10)):\"hidden\"!=T(a,\"overflow\")&&ga(a.childNodes,function(a){"\ "return a.nodeType==ka||Q(a)&&d(a)})}function e(a){var b=T(a,\"-o-transf"\ "orm\")||T(a,\"-webkit-transform\")||T(a,\"-ms-transform\")||T(a,\"-moz-"\ "transform\")||T(a,\"transform\");if(b&&\"none\"!==b)return b=Ra(a),a=U("\ "a),0<=b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=S(a);return!a||e(a)}if(!Q("\ "a))throw Error(\"Argument to isShown must be of type Element\");if(Q(a,"\ "\"OPTION\")||Q(a,\"OPTGROUP\")){var f=qa(a,function(a){return Q(a,\"SEL"\ "ECT\")});return!!f&&Va(f,!0)}return(f=Wa(a))?!!f.r&&0<f.rect.width&&0<f"\ ".rect.height&&Va(f.r,b):Q(a,\"INPUT\")&&\"hidden\"==a.type.toLowerCase("\ ")||Q(a,\"NOSCRIPT\")||\"hidden\"==T(a,\"visibility\")||!c(a)||!b&&0==Xa"\ "(a)||!d(a)||Ya(a)==V?!1:e(a)}var V=\"hidden\";\nfunction Ya(a){function"\ " b(a){var b=a;if(\"visible\"==q)if(a==f)b=g;else if(a==g)return{x:\"vis"\ "ible\",y:\"visible\"};b={x:T(b,\"overflow-x\"),y:T(b,\"overflow-y\")};a"\ "==f&&(b.x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"hidden\"==b.y?\"hid"\ "den\":\"auto\");return b}function c(a){var b=T(a,\"position\");if(\"fix"\ "ed\"==b)return f;for(a=S(a);a&&a!=f&&(0==T(a,\"display\").lastIndexOf("\ "\"inline\",0)||\"absolute\"==b&&\"static\"==T(a,\"position\"));)a=S(a);"\ "return a}var d=U(a),e=x(a),f=e.documentElement,g=e.body,q=T(f,\"overflo"\ "w\");for(a=c(a);a;a=\nc(a)){var m=U(a),e=b(a),B=d.left>=m.left+m.width,"\ "m=d.top>=m.top+m.height;if(B&&\"hidden\"==e.x||m&&\"hidden\"==e.y)retur"\ "n V;if(B&&\"visible\"!=e.x||m&&\"visible\"!=e.y)return Ya(a)==V?V:\"scr"\ "oll\"}return\"none\"}\nfunction U(a){var b=Wa(a);if(b)return b.rect;if("\ "n(a.getBBox))try{var c=a.getBBox();return new O(c.x,c.y,c.width,c.heigh"\ "t)}catch(d){throw d;}else{if(Q(a,\"HTML\"))return a=((x(a)?x(a).parentW"\ "indow||x(a).defaultView:window)||window).document,a=\"CSS1Compat\"==a.c"\ "ompatMode?a.documentElement:a.body,a=new v(a.clientWidth,a.clientHeight"\ "),new O(0,0,a.width,a.height);var b=Ra(a),c=a.offsetWidth,e=a.offsetHei"\ "ght;c||(e||!a.getBoundingClientRect)||(a=a.getBoundingClientRect(),c=a."\ "right-a.left,e=a.bottom-a.top);\nreturn new O(b.x,b.y,c,e)}}function Wa"\ "(a){var b=Q(a,\"MAP\");if(!b&&!Q(a,\"AREA\"))return null;var c=b?a:Q(a."\ "parentNode,\"MAP\")?a.parentNode:null,d=null,e=null;if(c&&c.name&&(d=N."\ "c('/descendant::*[@usemap = \"#'+c.name+'\"]',x(c)))&&(e=U(d),!b&&\"def"\ "ault\"!=a.shape.toLowerCase())){var f=Za(a);a=Math.min(Math.max(f.left,"\ "0),e.width);b=Math.min(Math.max(f.top,0),e.height);c=Math.min(f.width,e"\ ".width-a);f=Math.min(f.height,e.height-b);e=new O(a+e.left,b+e.top,c,f)"\ "}return{r:d,rect:e||new O(0,0,0,0)}}\nfunction Za(a){var b=a.shape.toLo"\ "werCase();a=a.coords.split(\",\");if(\"rect\"==b&&4==a.length){var b=a["\ "0],c=a[1];return new O(b,c,a[2]-b,a[3]-c)}if(\"circle\"==b&&3==a.length"\ ")return b=a[2],new O(a[0]-b,a[1]-b,2*b,2*b);if(\"poly\"==b&&2<a.length)"\ "{for(var b=a[0],c=a[1],d=b,e=c,f=2;f+1<a.length;f+=2)b=Math.min(b,a[f])"\ ",d=Math.max(d,a[f]),c=Math.min(c,a[f+1]),e=Math.max(e,a[f+1]);return ne"\ "w O(b,c,d-b,e-c)}return new O(0,0,0,0)}function $a(a){return a.replace("\ "/^[^\\S\\xa0]+|[^\\S\\xa0]+$/g,\"\")}\nfunction bb(a){var b=[];cb(a,b);"\ "var c=b;a=c.length;for(var b=Array(a),c=l(c)?c.split(\"\"):c,d=0;d<a;d+"\ "+)d in c&&(b[d]=$a.call(void 0,c[d]));return $a(b.join(\"\\n\")).replac"\ "e(/\\xa0/g,\" \")}\nfunction cb(a,b){if(Q(a,\"BR\"))b.push(\"\");else{v"\ "ar c=Q(a,\"TD\"),d=T(a,\"display\"),e=!c&&!t(db,d),f=void 0!=a.previous"\ "ElementSibling?a.previousElementSibling:ma(a.previousSibling),f=f?T(f,"\ "\"display\"):\"\",g=T(a,\"float\")||T(a,\"cssFloat\")||T(a,\"styleFloat"\ "\");!e||(\"run-in\"==f&&\"none\"==g||/^[\\s\\xa0]*$/.test(b[b.length-1]"\ "||\"\"))||b.push(\"\");var q=Va(a),m=null,B=null;q&&(m=T(a,\"white-spac"\ "e\"),B=T(a,\"text-transform\"));r(a.childNodes,function(a){a.nodeType=="\ "ka&&q?eb(a,b,m,B):Q(a)&&cb(a,b)});f=b[b.length-1]||\"\";!c&&\n\"table-c"\ "ell\"!=d||(!f||ca(f))||(b[b.length-1]+=\" \");e&&(\"run-in\"!=d&&!/^["\ "\\s\\xa0]*$/.test(f))&&b.push(\"\")}}var db=\"inline inline-block inlin"\ "e-table none table-cell table-column table-column-group\".split(\" \");"\ "\nfunction eb(a,b,c,d){a=a.nodeValue.replace(/\\u200b/g,\"\");a=a.repla"\ "ce(/(\\r\\n|\\r|\\n)/g,\"\\n\");if(\"normal\"==c||\"nowrap\"==c)a=a.rep"\ "lace(/\\n/g,\" \");a=\"pre\"==c||\"pre-wrap\"==c?a.replace(/[ \\f\\t\\v"\ "\\u2028\\u2029]/g,\"\\u00a0\"):a.replace(/[\\ \\f\\t\\v\\u2028\\u2029]+"\ "/g,\" \");\"capitalize\"==d?a=a.replace(/(^|\\s)(\\S)/g,function(a,b,c)"\ "{return b+c.toUpperCase()}):\"uppercase\"==d?a=a.toUpperCase():\"lowerc"\ "ase\"==d&&(a=a.toLowerCase());c=b.pop()||\"\";ca(c)&&0==a.lastIndexOf("\ "\" \",0)&&(a=a.substr(1));b.push(c+a)}\nfunction Xa(a){var b=1,c=T(a,\""\ "opacity\");c&&(b=Number(c));(a=S(a))&&(b*=Xa(a));return b};var W={},X={"\ "};W.v=function(a,b,c){var d;try{d=C.d(\"a\",b)}catch(e){d=z(w(b),\"A\","\ "null,b)}return ha(d,function(b){b=bb(b);return c&&-1!=b.indexOf(a)||b=="\ "a})};W.s=function(a,b,c){var d;try{d=C.d(\"a\",b)}catch(e){d=z(w(b),\"A"\ "\",null,b)}return s(d,function(b){b=bb(b);return c&&-1!=b.indexOf(a)||b"\ "==a})};W.c=function(a,b){return W.v(a,b,!1)};W.d=function(a,b){return W"\ ".s(a,b,!1)};X.c=function(a,b){return W.v(a,b,!0)};X.d=function(a,b){ret"\ "urn W.s(a,b,!0)};var fb={c:function(a,b){return b.getElementsByTagName("\ "a)[0]||null},d:function(a,b){return b.getElementsByTagName(a)}};var gb="\ "{className:A,\"class name\":A,css:C,\"css selector\":C,id:{c:function(a"\ ",b){var c=w(b),d=l(a)?c.j.getElementById(a):a;if(!d)return null;if(R(d,"\ "\"id\")==a&&y(b,d))return d;c=z(c,\"*\");return ha(c,function(c){return"\ " R(c,\"id\")==a&&y(b,c)})},d:function(a,b){var c=z(w(b),\"*\",null,b);r"\ "eturn s(c,function(b){return R(b,\"id\")==a})}},linkText:W,\"link text"\ "\":W,name:{c:function(a,b){var c=z(w(b),\"*\",null,b);return ha(c,funct"\ "ion(b){return R(b,\"name\")==a})},d:function(a,b){var c=z(w(b),\"*\",nu"\ "ll,b);return s(c,function(b){return R(b,\n\"name\")==a})}},partialLinkT"\ "ext:X,\"partial link text\":X,tagName:fb,\"tag name\":fb,xpath:N};funct"\ "ion hb(a,b){var c;a:{for(c in a)if(a.hasOwnProperty(c))break a;c=null}i"\ "f(c){var d=gb[c];if(d&&n(d.c))return d.c(a[c],b||ba.document)}throw Err"\ "or(\"Unsupported locator strategy: \"+c);}var Y=[\"_\"],Z=k;Y[0]in Z||!"\ "Z.execScript||Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.shif"\ "t());)Y.length||void 0===hb?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=hb;; return this._"\ ".apply(null,arguments);}.apply({navigator:typeof window!=undefined?wind"\ "ow.navigator:null,document:typeof window!=undefined?window.document:nul"\ "l}, arguments);}" FIND_ELEMENTS = \ "function(){return function(){function h(a){return function(){return a}}"\ "var k=this;\nfunction aa(a){var b=typeof a;if(\"object\"==b)if(a){if(a "\ "instanceof Array)return\"array\";if(a instanceof Object)return b;var c="\ "Object.prototype.toString.call(a);if(\"[object Window]\"==c)return\"obj"\ "ect\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefine"\ "d\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a."\ "propertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]"\ "\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else r"\ "eturn\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)r"\ "eturn\"object\";return b}function l(a){return\"string\"==typeof a}funct"\ "ion n(a){return\"function\"==aa(a)};var ba=window;function ca(a){var b="\ "a.length-1;return 0<=b&&a.indexOf(\" \",b)==b}function p(a){return a.re"\ "place(/^[\\s\\xa0]+|[\\s\\xa0]+$/g,\"\")}function da(a){return String(a"\ ").replace(/\\-([a-z])/g,function(a,c){return c.toUpperCase()})};var ea="\ "Array.prototype;function r(a,b){for(var c=a.length,d=l(a)?a.split(\"\")"\ ":a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function s(a,b){for(var "\ "c=a.length,d=[],e=0,f=l(a)?a.split(\"\"):a,g=0;g<c;g++)if(g in f){var q"\ "=f[g];b.call(void 0,q,g,a)&&(d[e++]=q)}return d}function fa(a,b){if(a.r"\ "educe)return a.reduce(b,\"\");var c=\"\";r(a,function(d,e){c=b.call(voi"\ "d 0,c,d,e,a)});return c}function ga(a,b){for(var c=a.length,d=l(a)?a.sp"\ "lit(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a))return!0;ret"\ "urn!1}\nfunction ha(a,b){var c;a:{c=a.length;for(var d=l(a)?a.split(\""\ "\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d[e],e,a)){c=e;break a}c=-1}"\ "return 0>c?null:l(a)?a.charAt(c):a[c]}function t(a,b){var c;a:if(l(a))c"\ "=l(b)&&1==b.length?a.indexOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c i"\ "n a&&a[c]===b)break a;c=-1}return 0<=c}function ia(a,b,c){return 2>=arg"\ "uments.length?ea.slice.call(a,b):ea.slice.call(a,b,c)};var ja;function "\ "u(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}u.prototype.toString"\ "=function(){return\"(\"+this.x+\", \"+this.y+\")\"};u.prototype.ceil=fu"\ "nction(){this.x=Math.ceil(this.x);this.y=Math.ceil(this.y);return this}"\ ";u.prototype.floor=function(){this.x=Math.floor(this.x);this.y=Math.flo"\ "or(this.y);return this};u.prototype.round=function(){this.x=Math.round("\ "this.x);this.y=Math.round(this.y);return this};function v(a,b){this.wid"\ "th=a;this.height=b}v.prototype.toString=function(){return\"(\"+this.wid"\ "th+\" x \"+this.height+\")\"};v.prototype.ceil=function(){this.width=Ma"\ "th.ceil(this.width);this.height=Math.ceil(this.height);return this};v.p"\ "rototype.floor=function(){this.width=Math.floor(this.width);this.height"\ "=Math.floor(this.height);return this};v.prototype.round=function(){this"\ ".width=Math.round(this.width);this.height=Math.round(this.height);retur"\ "n this};var ka=3;function w(a){return a?new la(x(a)):ja||(ja=new la)}fu"\ "nction ma(a){for(;a&&1!=a.nodeType;)a=a.previousSibling;return a}functi"\ "on y(a,b){if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if(\""\ "undefined\"!=typeof a.compareDocumentPosition)return a==b||Boolean(a.co"\ "mpareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}"\ "\nfunction na(a,b){if(a==b)return 0;if(a.compareDocumentPosition)return"\ " a.compareDocumentPosition(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNo"\ "de&&\"sourceIndex\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType"\ ";if(c&&d)return a.sourceIndex-b.sourceIndex;var e=a.parentNode,f=b.pare"\ "ntNode;return e==f?oa(a,b):!c&&y(e,b)?-1*pa(a,b):!d&&y(f,a)?pa(b,a):(c?"\ "a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}d=x(a);c=d"\ ".createRange();c.selectNode(a);c.collapse(!0);d=d.createRange();d.selec"\ "tNode(b);d.collapse(!0);\nreturn c.compareBoundaryPoints(k.Range.START_"\ "TO_END,d)}function pa(a,b){var c=a.parentNode;if(c==b)return-1;for(var "\ "d=b;d.parentNode!=c;)d=d.parentNode;return oa(d,a)}function oa(a,b){for"\ "(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1}function x(a){r"\ "eturn 9==a.nodeType?a:a.ownerDocument||a.document}function qa(a,b){a=a."\ "parentNode;for(var c=0;a;){if(b(a))return a;a=a.parentNode;c++}return n"\ "ull}function la(a){this.j=a||k.document||document}\nfunction z(a,b,c,d)"\ "{a=d||a.j;b=b&&\"*\"!=b?b.toUpperCase():\"\";if(a.querySelectorAll&&a.q"\ "uerySelector&&(b||c))c=a.querySelectorAll(b+(c?\".\"+c:\"\"));else if(c"\ "&&a.getElementsByClassName)if(a=a.getElementsByClassName(c),b){d={};for"\ "(var e=0,f=0,g;g=a[f];f++)b==g.nodeName&&(d[e++]=g);d.length=e;c=d}else"\ " c=a;else if(a=a.getElementsByTagName(b||\"*\"),c){d={};for(f=e=0;g=a[f"\ "];f++)b=g.className,\"function\"==typeof b.split&&t(b.split(/\\s+/),c)&"\ "&(d[e++]=g);d.length=e;c=d}else c=a;return c}\nfunction ra(a){var b=a.j"\ ";a=b.body;b=b.parentWindow||b.defaultView;return new u(b.pageXOffset||a"\ ".scrollLeft,b.pageYOffset||a.scrollTop)}la.prototype.contains=y;var A={"\ "n:function(a){return!(!a.querySelectorAll||!a.querySelector)},e:functio"\ "n(a,b){if(!a)throw Error(\"No class name specified\");a=p(a);if(1<a.spl"\ "it(/\\s+/).length)throw Error(\"Compound class names not permitted\");i"\ "f(A.n(b))return b.querySelector(\".\"+a.replace(/\\./g,\"\\\\.\"))||nul"\ "l;var c=z(w(b),\"*\",a,b);return c.length?c[0]:null},c:function(a,b){if"\ "(!a)throw Error(\"No class name specified\");a=p(a);if(1<a.split(/\\s+/"\ ").length)throw Error(\"Compound class names not permitted\");return A.n"\ "(b)?b.querySelectorAll(\".\"+\na.replace(/\\./g,\"\\\\.\")):z(w(b),\"*"\ "\",a,b)}};var C={e:function(a,b){n(b.querySelector);if(!a)throw Error("\ "\"No selector specified\");a=p(a);var c=b.querySelector(a);return c&&1="\ "=c.nodeType?c:null},c:function(a,b){n(b.querySelectorAll);if(!a)throw E"\ "rror(\"No selector specified\");a=p(a);return b.querySelectorAll(a)}};v"\ "ar sa={aliceblue:\"#f0f8ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\","\ "aquamarine:\"#7fffd4\",azure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ff"\ "e4c4\",black:\"#000000\",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",bl"\ "ueviolet:\"#8a2be2\",brown:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:"\ "\"#5f9ea0\",chartreuse:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f5"\ "0\",cornflowerblue:\"#6495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\""\ ",cyan:\"#00ffff\",darkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenr"\ "od:\"#b8860b\",darkgray:\"#a9a9a9\",darkgreen:\"#006400\",\ndarkgrey:\""\ "#a9a9a9\",darkkhaki:\"#bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:"\ "\"#556b2f\",darkorange:\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b"\ "0000\",darksalmon:\"#e9967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\""\ "#483d8b\",darkslategray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturqu"\ "oise:\"#00ced1\",darkviolet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblu"\ "e:\"#00bfff\",dimgray:\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e9"\ "0ff\",firebrick:\"#b22222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b"\ "22\",fuchsia:\"#ff00ff\",gainsboro:\"#dcdcdc\",\nghostwhite:\"#f8f8ff\""\ ",gold:\"#ffd700\",goldenrod:\"#daa520\",gray:\"#808080\",green:\"#00800"\ "0\",greenyellow:\"#adff2f\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpi"\ "nk:\"#ff69b4\",indianred:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0"\ "\",khaki:\"#f0e68c\",lavender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",law"\ "ngreen:\"#7cfc00\",lemonchiffon:\"#fffacd\",lightblue:\"#add8e6\",light"\ "coral:\"#f08080\",lightcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2"\ "\",lightgray:\"#d3d3d3\",lightgreen:\"#90ee90\",lightgrey:\"#d3d3d3\",l"\ "ightpink:\"#ffb6c1\",lightsalmon:\"#ffa07a\",\nlightseagreen:\"#20b2aa"\ "\",lightskyblue:\"#87cefa\",lightslategray:\"#778899\",lightslategrey:"\ "\"#778899\",lightsteelblue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#"\ "00ff00\",limegreen:\"#32cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",ma"\ "roon:\"#800000\",mediumaquamarine:\"#66cdaa\",mediumblue:\"#0000cd\",me"\ "diumorchid:\"#ba55d3\",mediumpurple:\"#9370db\",mediumseagreen:\"#3cb37"\ "1\",mediumslateblue:\"#7b68ee\",mediumspringgreen:\"#00fa9a\",mediumtur"\ "quoise:\"#48d1cc\",mediumvioletred:\"#c71585\",midnightblue:\"#191970\""\ ",mintcream:\"#f5fffa\",mistyrose:\"#ffe4e1\",\nmoccasin:\"#ffe4b5\",nav"\ "ajowhite:\"#ffdead\",navy:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#8080"\ "00\",olivedrab:\"#6b8e23\",orange:\"#ffa500\",orangered:\"#ff4500\",orc"\ "hid:\"#da70d6\",palegoldenrod:\"#eee8aa\",palegreen:\"#98fb98\",paletur"\ "quoise:\"#afeeee\",palevioletred:\"#db7093\",papayawhip:\"#ffefd5\",pea"\ "chpuff:\"#ffdab9\",peru:\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",p"\ "owderblue:\"#b0e0e6\",purple:\"#800080\",red:\"#ff0000\",rosybrown:\"#b"\ "c8f8f\",royalblue:\"#4169e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072"\ "\",sandybrown:\"#f4a460\",seagreen:\"#2e8b57\",\nseashell:\"#fff5ee\",s"\ "ienna:\"#a0522d\",silver:\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6"\ "a5acd\",slategray:\"#708090\",slategrey:\"#708090\",snow:\"#fffafa\",sp"\ "ringgreen:\"#00ff7f\",steelblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008"\ "080\",thistle:\"#d8bfd8\",tomato:\"#ff6347\",turquoise:\"#40e0d0\",viol"\ "et:\"#ee82ee\",wheat:\"#f5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5"\ "\",yellow:\"#ffff00\",yellowgreen:\"#9acd32\"};var ta=\"background-colo"\ "r border-top-color border-right-color border-bottom-color border-left-c"\ "olor color outline-color\".split(\" \"),ua=/#([0-9a-fA-F])([0-9a-fA-F])"\ "([0-9a-fA-F])/;function va(a){if(!wa.test(a))throw Error(\"'\"+a+\"' is"\ " not a valid hex color\");4==a.length&&(a=a.replace(ua,\"#$1$1$2$2$3$3"\ "\"));return a.toLowerCase()}var wa=/^#(?:[0-9a-f]{3}){1,2}$/i,xa=/^(?:r"\ "gba)?\\((\\d{1,3}),\\s?(\\d{1,3}),\\s?(\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$"\ "/i;\nfunction ya(a){var b=a.match(xa);if(b){a=Number(b[1]);var c=Number"\ "(b[2]),d=Number(b[3]),b=Number(b[4]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<="\ "d&&255>=d&&0<=b&&1>=b)return[a,c,d,b]}return[]}var za=/^(?:rgb)?\\((0|["\ "1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2})\\)$/i;functio"\ "n Aa(a){var b=a.match(za);if(b){a=Number(b[1]);var c=Number(b[2]),b=Num"\ "ber(b[3]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<=b&&255>=b)return[a,c,b]}ret"\ "urn[]};function D(a,b){this.code=a;this.state=Ba[a]||Ca;this.message=b|"\ "|\"\";var c=this.state.replace(/((?:^|\\s+)[a-z])/g,function(a){return "\ "a.toUpperCase().replace(/^[\\s\\xa0]+/g,\"\")}),d=c.length-5;if(0>d||c."\ "indexOf(\"Error\",d)!=d)c+=\"Error\";this.name=c;c=Error(this.message);"\ "c.name=this.name;this.stack=c.stack||\"\"}(function(){var a=Error;funct"\ "ion b(){}b.prototype=a.prototype;D.P=a.prototype;D.prototype=new b})();"\ "\nvar Ca=\"unknown error\",Ba={15:\"element not selectable\",11:\"eleme"\ "nt not visible\",31:\"ime engine activation failed\",30:\"ime not avail"\ "able\",24:\"invalid cookie domain\",29:\"invalid element coordinates\","\ "12:\"invalid element state\",32:\"invalid selector\",51:\"invalid selec"\ "tor\",52:\"invalid selector\",17:\"javascript error\",405:\"unsupported"\ " operation\",34:\"move target out of bounds\",27:\"no such alert\",7:\""\ "no such element\",8:\"no such frame\",23:\"no such window\",28:\"script"\ " timeout\",33:\"session not created\",10:\"stale element reference\",\n"\ "0:\"success\",21:\"timeout\",25:\"unable to set cookie\",26:\"unexpecte"\ "d alert open\"};Ba[13]=Ca;Ba[9]=\"unknown command\";D.prototype.toStrin"\ "g=function(){return this.name+\": \"+this.message};function E(a){var b="\ "null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerTe"\ "xt:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c"\ "){a=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do "\ "1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&&"\ "!(a=d[--c].nextSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction "\ "F(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)return!1}catch(d){"\ "return!1}return null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}func"\ "tion G(a,b,c,d,e){return Da.call(null,a,b,l(c)?c:null,l(d)?d:null,e||ne"\ "w H)}\nfunction Da(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b."\ "getElementsByName(d),r(b,function(b){a.matches(b)&&e.add(b)})):b.getEle"\ "mentsByClassName&&d&&\"class\"==c?(b=b.getElementsByClassName(d),r(b,fu"\ "nction(b){b.className==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagN"\ "ame&&(b=b.getElementsByTagName(a.getName()),r(b,function(a){F(a,c,d)&&e"\ ".add(a)}));return e}function Ea(a,b,c,d,e){for(b=b.firstChild;b;b=b.nex"\ "tSibling)F(b,c,d)&&a.matches(b)&&e.add(b);return e};function H(){this.f"\ "=this.d=null;this.k=0}function Fa(a){this.t=a;this.next=this.m=null}H.p"\ "rototype.unshift=function(a){a=new Fa(a);a.next=this.d;this.f?this.d.m="\ "a:this.d=this.f=a;this.d=a;this.k++};H.prototype.add=function(a){a=new "\ "Fa(a);a.m=this.f;this.d?this.f.next=a:this.d=this.f=a;this.f=a;this.k++"\ "};function Ga(a){return(a=a.d)?a.t:null}function I(a){return new Ha(a,!"\ "1)}function Ha(a,b){this.M=a;this.p=(this.u=b)?a.f:a.d;this.B=null}\nHa"\ ".prototype.next=function(){var a=this.p;if(null==a)return null;var b=th"\ "is.B=a;this.p=this.u?a.m:a.next;return b.t};function J(a,b,c,d,e){b=b.e"\ "valuate(d);c=c.evaluate(d);var f;if(b instanceof H&&c instanceof H){e=I"\ "(b);for(d=e.next();d;d=e.next())for(b=I(c),f=b.next();f;f=b.next())if(a"\ "(E(d),E(f)))return!0;return!1}if(b instanceof H||c instanceof H){b inst"\ "anceof H?e=b:(e=c,c=b);e=I(e);b=typeof c;for(d=e.next();d;d=e.next()){s"\ "witch(b){case \"number\":d=+E(d);break;case \"boolean\":d=!!E(d);break;"\ "case \"string\":d=E(d);break;default:throw Error(\"Illegal primitive ty"\ "pe for comparison.\");}if(a(d,c))return!0}return!1}return e?\n\"boolean"\ "\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeof b||\""\ "number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function Ia(a,b,c,d){this.C"\ "=a;this.O=b;this.A=c;this.i=d}Ia.prototype.toString=function(){return t"\ "his.C};var Ja={};function K(a,b,c,d){if(a in Ja)throw Error(\"Binary op"\ "erator already created: \"+a);a=new Ia(a,b,c,d);Ja[a.toString()]=a}K(\""\ "div\",6,1,function(a,b,c){return a.b(c)/b.b(c)});K(\"mod\",6,1,function"\ "(a,b,c){return a.b(c)%b.b(c)});K(\"*\",6,1,function(a,b,c){return a.b(c"\ ")*b.b(c)});\nK(\"+\",5,1,function(a,b,c){return a.b(c)+b.b(c)});K(\"-\""\ ",5,1,function(a,b,c){return a.b(c)-b.b(c)});K(\"<\",4,2,function(a,b,c)"\ "{return J(function(a,b){return a<b},a,b,c)});K(\">\",4,2,function(a,b,c"\ "){return J(function(a,b){return a>b},a,b,c)});K(\"<=\",4,2,function(a,b"\ ",c){return J(function(a,b){return a<=b},a,b,c)});K(\">=\",4,2,function("\ "a,b,c){return J(function(a,b){return a>=b},a,b,c)});K(\"=\",3,2,functio"\ "n(a,b,c){return J(function(a,b){return a==b},a,b,c,!0)});\nK(\"!=\",3,2"\ ",function(a,b,c){return J(function(a,b){return a!=b},a,b,c,!0)});K(\"an"\ "d\",2,2,function(a,b,c){return a.h(c)&&b.h(c)});K(\"or\",1,2,function(a"\ ",b,c){return a.h(c)||b.h(c)});function Ka(a,b,c,d,e,f,g,q,m){this.l=a;t"\ "his.A=b;this.L=c;this.K=d;this.J=e;this.i=f;this.I=g;this.H=void 0!==q?"\ "q:g;this.N=!!m}Ka.prototype.toString=function(){return this.l};var La={"\ "};function L(a,b,c,d,e,f,g,q){if(a in La)throw Error(\"Function already"\ " created: \"+a+\".\");La[a]=new Ka(a,b,c,d,!1,e,f,g,q)}L(\"boolean\",2,"\ "!1,!1,function(a,b){return b.h(a)},1);L(\"ceiling\",1,!1,!1,function(a,"\ "b){return Math.ceil(b.b(a))},1);\nL(\"concat\",3,!1,!1,function(a,b){va"\ "r c=ia(arguments,1);return fa(c,function(b,c){return b+c.a(a)})},2,null"\ ");L(\"contains\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return-1!=b."\ "indexOf(a)},2);L(\"count\",1,!1,!1,function(a,b){return b.evaluate(a).k"\ "},1,1,!0);L(\"false\",2,!1,!1,h(!1),0);L(\"floor\",1,!1,!1,function(a,b"\ "){return Math.floor(b.b(a))},1);\nL(\"id\",4,!1,!1,function(a,b){var c="\ "a.g(),d=9==c.nodeType?c:c.ownerDocument,c=b.a(a).split(/\\s+/),e=[];r(c"\ ",function(a){(a=d.getElementById(a))&&!t(e,a)&&e.push(a)});e.sort(na);v"\ "ar f=new H;r(e,function(a){f.add(a)});return f},1);L(\"lang\",2,!1,!1,h"\ "(!1),1);L(\"last\",1,!0,!1,function(a){if(1!=arguments.length)throw Err"\ "or(\"Function last expects ()\");return a.F()},0);L(\"local-name\",3,!1"\ ",!0,function(a,b){var c=b?Ga(b.evaluate(a)):a.g();return c?c.nodeName.t"\ "oLowerCase():\"\"},0,1,!0);\nL(\"name\",3,!1,!0,function(a,b){var c=b?G"\ "a(b.evaluate(a)):a.g();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);"\ "L(\"namespace-uri\",3,!0,!1,h(\"\"),0,1,!0);L(\"normalize-space\",3,!1,"\ "!0,function(a,b){return(b?b.a(a):E(a.g())).replace(/[\\s\\xa0]+/g,\" \""\ ").replace(/^\\s+|\\s+$/g,\"\")},0,1);L(\"not\",2,!1,!1,function(a,b){re"\ "turn!b.h(a)},1);L(\"number\",1,!1,!0,function(a,b){return b?b.b(a):+E(a"\ ".g())},0,1);L(\"position\",1,!0,!1,function(a){return a.G()},0);L(\"rou"\ "nd\",1,!1,!1,function(a,b){return Math.round(b.b(a))},1);\nL(\"starts-w"\ "ith\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return 0==b.lastIndexOf"\ "(a,0)},2);L(\"string\",3,!1,!0,function(a,b){return b?b.a(a):E(a.g())},"\ "0,1);L(\"string-length\",1,!1,!0,function(a,b){return(b?b.a(a):E(a.g())"\ ").length},0,1);\nL(\"substring\",3,!1,!1,function(a,b,c,d){c=c.b(a);if("\ "isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.b(a):Infinity;if(i"\ "sNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max(c,0)"\ ";a=b.a(a);if(Infinity==d)return a.substring(e);b=Math.round(d);return a"\ ".substring(e,c+b)},2,3);L(\"substring-after\",3,!1,!1,function(a,b,c){b"\ "=b.a(a);a=c.a(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.length"\ ")},2);\nL(\"substring-before\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a"\ ");a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);L(\"sum\",1,!1,!"\ "1,function(a,b){for(var c=I(b.evaluate(a)),d=0,e=c.next();e;e=c.next())"\ "d+=+E(e);return d},1,1,!0);L(\"translate\",3,!1,!1,function(a,b,c,d){b="\ "b.a(a);c=c.a(a);var e=d.a(a);a=[];for(d=0;d<c.length;d++){var f=c.charA"\ "t(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d++)f=b.charA"\ "t(d),c+=f in a?a[f]:f;return c},3);L(\"true\",2,!1,!1,h(!0),0);function"\ " Ma(a,b,c,d){this.l=a;this.D=b;this.u=c;this.Q=d}Ma.prototype.toString="\ "function(){return this.l};var Na={};function M(a,b,c,d){if(a in Na)thro"\ "w Error(\"Axis already created: \"+a);Na[a]=new Ma(a,b,c,!!d)}M(\"ances"\ "tor\",function(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matches(d)&&c"\ ".unshift(d);return c},!0);M(\"ancestor-or-self\",function(a,b){var c=ne"\ "w H,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c},!"\ "0);\nM(\"attribute\",function(a,b){var c=new H,d=a.getName(),e=b.attrib"\ "utes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e.getNam"\ "edItem(d))&&c.add(f);return c},!1);M(\"child\",function(a,b,c,d,e){retu"\ "rn Ea.call(null,a,b,l(c)?c:null,l(d)?d:null,e||new H)},!1,!0);M(\"desce"\ "ndant\",G,!1,!0);M(\"descendant-or-self\",function(a,b,c,d){var e=new H"\ ";F(b,c,d)&&a.matches(b)&&e.add(b);return G(a,b,c,d,e)},!1,!0);\nM(\"fol"\ "lowing\",function(a,b,c,d){var e=new H;do for(var f=b;f=f.nextSibling;)"\ "F(f,c,d)&&a.matches(f)&&e.add(f),e=G(a,f,c,d,e);while(b=b.parentNode);r"\ "eturn e},!1,!0);M(\"following-sibling\",function(a,b){for(var c=new H,d"\ "=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);M(\"namespace"\ "\",function(){return new H},!1);M(\"parent\",function(a,b){var c=new H;"\ "if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerElement)"\ ",c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nM(\"preced"\ "ing\",function(a,b,c,d){var e=new H,f=[];do f.unshift(b);while(b=b.pare"\ "ntNode);for(var g=1,q=f.length;g<q;g++){var m=[];for(b=f[g];b=b.previou"\ "sSibling;)m.unshift(b);for(var B=0,ab=m.length;B<ab;B++)b=m[B],F(b,c,d)"\ "&&a.matches(b)&&e.add(b),e=G(a,b,c,d,e)}return e},!0,!0);M(\"preceding-"\ "sibling\",function(a,b){for(var c=new H,d=b;d=d.previousSibling;)a.matc"\ "hes(d)&&c.unshift(d);return c},!0);M(\"self\",function(a,b){var c=new H"\ ";a.matches(b)&&c.add(b);return c},!1);var N={};N.w=function(){var a={R:"\ "\"http://www.w3.org/2000/svg\"};return function(b){return a[b]||null}}("\ ");N.i=function(a,b,c){var d=x(a);try{var e=d.createNSResolver?d.createN"\ "SResolver(d.documentElement):N.w;return d.evaluate(b,a,e,c,null)}catch("\ "f){throw new D(32,\"Unable to locate an element with the xpath expressi"\ "on \"+b+\" because of the following error:\\n\"+f);}};N.o=function(a,b)"\ "{if(!a||1!=a.nodeType)throw new D(32,'The result of the xpath expressio"\ "n \"'+b+'\" is: '+a+\". It should be an element.\");};\nN.e=function(a,"\ "b){var c=function(){var c=N.i(b,a,9);return c?c.singleNodeValue||null:b"\ ".selectSingleNode?(c=x(b),c.setProperty&&c.setProperty(\"SelectionLangu"\ "age\",\"XPath\"),b.selectSingleNode(a)):null}();null===c||N.o(c,a);retu"\ "rn c};\nN.c=function(a,b){var c=function(){var c=N.i(b,a,7);if(c){for(v"\ "ar e=c.snapshotLength,f=[],g=0;g<e;++g)f.push(c.snapshotItem(g));return"\ " f}return b.selectNodes?(c=x(b),c.setProperty&&c.setProperty(\"Selectio"\ "nLanguage\",\"XPath\"),b.selectNodes(a)):[]}();r(c,function(b){N.o(b,a)"\ "});return c};function O(a,b,c,d){this.left=a;this.top=b;this.width=c;th"\ "is.height=d}O.prototype.toString=function(){return\"(\"+this.left+\", "\ "\"+this.top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};O.prototype"\ ".contains=function(a){return a instanceof O?this.left<=a.left&&this.lef"\ "t+this.width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a."\ "top+a.height:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&"\ "a.y<=this.top+this.height};\nO.prototype.ceil=function(){this.left=Math"\ ".ceil(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this"\ ".width);this.height=Math.ceil(this.height);return this};O.prototype.flo"\ "or=function(){this.left=Math.floor(this.left);this.top=Math.floor(this."\ "top);this.width=Math.floor(this.width);this.height=Math.floor(this.heig"\ "ht);return this};\nO.prototype.round=function(){this.left=Math.round(th"\ "is.left);this.top=Math.round(this.top);this.width=Math.round(this.width"\ ");this.height=Math.round(this.height);return this};function Oa(a,b){var"\ " c=x(a);return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defa"\ "ultView.getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||\"\":\""\ "\"}function P(a){return Oa(a,\"position\")||(a.currentStyle?a.currentSt"\ "yle.position:null)||a.style&&a.style.position}function Pa(a){var b;try{"\ "b=a.getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom"\ ":0}}return b}\nfunction Qa(a){var b=x(a),c=P(a),d=\"fixed\"==c||\"absol"\ "ute\"==c;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=P(a),d=d&&\"sta"\ "tic\"==c&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clientWi"\ "dth||a.scrollHeight>a.clientHeight||\"fixed\"==c||\"absolute\"==c||\"re"\ "lative\"==c))return a;return null}\nfunction Ra(a){if(1==a.nodeType){va"\ "r b;if(a.getBoundingClientRect)b=Pa(a),b=new u(b.left,b.top);else{b=ra("\ "w(a));var c=x(a),d=P(a),e=new u(0,0),f=(c?x(c):document).documentElemen"\ "t;if(a!=f)if(a.getBoundingClientRect)a=Pa(a),c=ra(w(c)),e.x=a.left+c.x,"\ "e.y=a.top+c.y;else if(c.getBoxObjectFor)a=c.getBoxObjectFor(a),c=c.getB"\ "oxObjectFor(f),e.x=a.screenX-c.screenX,e.y=a.screenY-c.screenY;else{var"\ " g=a;do{e.x+=g.offsetLeft;e.y+=g.offsetTop;g!=a&&(e.x+=g.clientLeft||0,"\ "e.y+=g.clientTop||0);if(\"fixed\"==P(g)){e.x+=\nc.body.scrollLeft;e.y+="\ "c.body.scrollTop;break}g=g.offsetParent}while(g&&g!=a);\"absolute\"==d&"\ "&(e.y-=c.body.offsetTop);for(g=a;(g=Qa(g))&&g!=c.body&&g!=f;)e.x-=g.scr"\ "ollLeft,e.y-=g.scrollTop}b=new u(e.x-b.x,e.y-b.y)}return b}b=n(a.q);e=a"\ ";a.targetTouches?e=a.targetTouches[0]:b&&a.q().targetTouches&&(e=a.q()."\ "targetTouches[0]);return new u(e.clientX,e.clientY)};function Q(a,b){re"\ "turn!!a&&1==a.nodeType&&(!b||a.tagName.toUpperCase()==b)}var Sa=/[;]+(?"\ "=(?:(?:[^\"]*\"){2})*[^\"]*$)(?=(?:(?:[^']*'){2})*[^']*$)(?=(?:[^()]*"\ "\\([^()]*\\))*[^()]*$)/;function Ta(a){var b=[];r(a.split(Sa),function("\ "a){var d=a.indexOf(\":\");0<d&&(a=[a.slice(0,d),a.slice(d+1)],2==a.leng"\ "th&&b.push(a[0].toLowerCase(),\":\",a[1],\";\"))});b=b.join(\"\");retur"\ "n b=\";\"==b.charAt(b.length-1)?b:b+\";\"}\nfunction R(a,b){b=b.toLower"\ "Case();if(\"style\"==b)return Ta(a.style.cssText);var c=a.getAttributeN"\ "ode(b);return c&&c.specified?c.value:null}function S(a){for(a=a.parentN"\ "ode;a&&1!=a.nodeType&&9!=a.nodeType&&11!=a.nodeType;)a=a.parentNode;ret"\ "urn Q(a)?a:null}\nfunction T(a,b){var c=da(b);if(\"float\"==c||\"cssFlo"\ "at\"==c||\"styleFloat\"==c)c=\"cssFloat\";c=Oa(a,c)||Ua(a,c);if(null==="\ "c)c=null;else if(t(ta,b)&&(wa.test(\"#\"==c.charAt(0)?c:\"#\"+c)||Aa(c)"\ ".length||sa&&sa[c.toLowerCase()]||ya(c).length)){var d=ya(c);if(!d.leng"\ "th){a:if(d=Aa(c),!d.length){d=(d=sa[c.toLowerCase()])?d:\"#\"==c.charAt"\ "(0)?c:\"#\"+c;if(wa.test(d)&&(d=va(d),d=va(d),d=[parseInt(d.substr(1,2)"\ ",16),parseInt(d.substr(3,2),16),parseInt(d.substr(5,2),16)],d.length))b"\ "reak a;d=[]}3==d.length&&d.push(1)}c=4!=\nd.length?c:\"rgba(\"+d.join("\ "\", \")+\")\"}return c}function Ua(a,b){var c=a.currentStyle||a.style,d"\ "=c[b];void 0===d&&n(c.getPropertyValue)&&(d=c.getPropertyValue(b));retu"\ "rn\"inherit\"!=d?void 0!==d?d:null:(c=S(a))?Ua(c,b):null}\nfunction Va("\ "a,b){function c(a){if(\"none\"==T(a,\"display\"))return!1;a=S(a);return"\ "!a||c(a)}function d(a){var b=U(a);return 0<b.height&&0<b.width?!0:Q(a,"\ "\"PATH\")&&(0<b.height||0<b.width)?(a=T(a,\"stroke-width\"),!!a&&0<pars"\ "eInt(a,10)):\"hidden\"!=T(a,\"overflow\")&&ga(a.childNodes,function(a){"\ "return a.nodeType==ka||Q(a)&&d(a)})}function e(a){var b=T(a,\"-o-transf"\ "orm\")||T(a,\"-webkit-transform\")||T(a,\"-ms-transform\")||T(a,\"-moz-"\ "transform\")||T(a,\"transform\");if(b&&\"none\"!==b)return b=Ra(a),a=U("\ "a),0<=b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=S(a);return!a||e(a)}if(!Q("\ "a))throw Error(\"Argument to isShown must be of type Element\");if(Q(a,"\ "\"OPTION\")||Q(a,\"OPTGROUP\")){var f=qa(a,function(a){return Q(a,\"SEL"\ "ECT\")});return!!f&&Va(f,!0)}return(f=Wa(a))?!!f.r&&0<f.rect.width&&0<f"\ ".rect.height&&Va(f.r,b):Q(a,\"INPUT\")&&\"hidden\"==a.type.toLowerCase("\ ")||Q(a,\"NOSCRIPT\")||\"hidden\"==T(a,\"visibility\")||!c(a)||!b&&0==Xa"\ "(a)||!d(a)||Ya(a)==V?!1:e(a)}var V=\"hidden\";\nfunction Ya(a){function"\ " b(a){var b=a;if(\"visible\"==q)if(a==f)b=g;else if(a==g)return{x:\"vis"\ "ible\",y:\"visible\"};b={x:T(b,\"overflow-x\"),y:T(b,\"overflow-y\")};a"\ "==f&&(b.x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"hidden\"==b.y?\"hid"\ "den\":\"auto\");return b}function c(a){var b=T(a,\"position\");if(\"fix"\ "ed\"==b)return f;for(a=S(a);a&&a!=f&&(0==T(a,\"display\").lastIndexOf("\ "\"inline\",0)||\"absolute\"==b&&\"static\"==T(a,\"position\"));)a=S(a);"\ "return a}var d=U(a),e=x(a),f=e.documentElement,g=e.body,q=T(f,\"overflo"\ "w\");for(a=c(a);a;a=\nc(a)){var m=U(a),e=b(a),B=d.left>=m.left+m.width,"\ "m=d.top>=m.top+m.height;if(B&&\"hidden\"==e.x||m&&\"hidden\"==e.y)retur"\ "n V;if(B&&\"visible\"!=e.x||m&&\"visible\"!=e.y)return Ya(a)==V?V:\"scr"\ "oll\"}return\"none\"}\nfunction U(a){var b=Wa(a);if(b)return b.rect;if("\ "n(a.getBBox))try{var c=a.getBBox();return new O(c.x,c.y,c.width,c.heigh"\ "t)}catch(d){throw d;}else{if(Q(a,\"HTML\"))return a=((x(a)?x(a).parentW"\ "indow||x(a).defaultView:window)||window).document,a=\"CSS1Compat\"==a.c"\ "ompatMode?a.documentElement:a.body,a=new v(a.clientWidth,a.clientHeight"\ "),new O(0,0,a.width,a.height);var b=Ra(a),c=a.offsetWidth,e=a.offsetHei"\ "ght;c||(e||!a.getBoundingClientRect)||(a=a.getBoundingClientRect(),c=a."\ "right-a.left,e=a.bottom-a.top);\nreturn new O(b.x,b.y,c,e)}}function Wa"\ "(a){var b=Q(a,\"MAP\");if(!b&&!Q(a,\"AREA\"))return null;var c=b?a:Q(a."\ "parentNode,\"MAP\")?a.parentNode:null,d=null,e=null;if(c&&c.name&&(d=N."\ "e('/descendant::*[@usemap = \"#'+c.name+'\"]',x(c)))&&(e=U(d),!b&&\"def"\ "ault\"!=a.shape.toLowerCase())){var f=Za(a);a=Math.min(Math.max(f.left,"\ "0),e.width);b=Math.min(Math.max(f.top,0),e.height);c=Math.min(f.width,e"\ ".width-a);f=Math.min(f.height,e.height-b);e=new O(a+e.left,b+e.top,c,f)"\ "}return{r:d,rect:e||new O(0,0,0,0)}}\nfunction Za(a){var b=a.shape.toLo"\ "werCase();a=a.coords.split(\",\");if(\"rect\"==b&&4==a.length){var b=a["\ "0],c=a[1];return new O(b,c,a[2]-b,a[3]-c)}if(\"circle\"==b&&3==a.length"\ ")return b=a[2],new O(a[0]-b,a[1]-b,2*b,2*b);if(\"poly\"==b&&2<a.length)"\ "{for(var b=a[0],c=a[1],d=b,e=c,f=2;f+1<a.length;f+=2)b=Math.min(b,a[f])"\ ",d=Math.max(d,a[f]),c=Math.min(c,a[f+1]),e=Math.max(e,a[f+1]);return ne"\ "w O(b,c,d-b,e-c)}return new O(0,0,0,0)}function $a(a){return a.replace("\ "/^[^\\S\\xa0]+|[^\\S\\xa0]+$/g,\"\")}\nfunction bb(a){var b=[];cb(a,b);"\ "var c=b;a=c.length;for(var b=Array(a),c=l(c)?c.split(\"\"):c,d=0;d<a;d+"\ "+)d in c&&(b[d]=$a.call(void 0,c[d]));return $a(b.join(\"\\n\")).replac"\ "e(/\\xa0/g,\" \")}\nfunction cb(a,b){if(Q(a,\"BR\"))b.push(\"\");else{v"\ "ar c=Q(a,\"TD\"),d=T(a,\"display\"),e=!c&&!t(db,d),f=void 0!=a.previous"\ "ElementSibling?a.previousElementSibling:ma(a.previousSibling),f=f?T(f,"\ "\"display\"):\"\",g=T(a,\"float\")||T(a,\"cssFloat\")||T(a,\"styleFloat"\ "\");!e||(\"run-in\"==f&&\"none\"==g||/^[\\s\\xa0]*$/.test(b[b.length-1]"\ "||\"\"))||b.push(\"\");var q=Va(a),m=null,B=null;q&&(m=T(a,\"white-spac"\ "e\"),B=T(a,\"text-transform\"));r(a.childNodes,function(a){a.nodeType=="\ "ka&&q?eb(a,b,m,B):Q(a)&&cb(a,b)});f=b[b.length-1]||\"\";!c&&\n\"table-c"\ "ell\"!=d||(!f||ca(f))||(b[b.length-1]+=\" \");e&&(\"run-in\"!=d&&!/^["\ "\\s\\xa0]*$/.test(f))&&b.push(\"\")}}var db=\"inline inline-block inlin"\ "e-table none table-cell table-column table-column-group\".split(\" \");"\ "\nfunction eb(a,b,c,d){a=a.nodeValue.replace(/\\u200b/g,\"\");a=a.repla"\ "ce(/(\\r\\n|\\r|\\n)/g,\"\\n\");if(\"normal\"==c||\"nowrap\"==c)a=a.rep"\ "lace(/\\n/g,\" \");a=\"pre\"==c||\"pre-wrap\"==c?a.replace(/[ \\f\\t\\v"\ "\\u2028\\u2029]/g,\"\\u00a0\"):a.replace(/[\\ \\f\\t\\v\\u2028\\u2029]+"\ "/g,\" \");\"capitalize\"==d?a=a.replace(/(^|\\s)(\\S)/g,function(a,b,c)"\ "{return b+c.toUpperCase()}):\"uppercase\"==d?a=a.toUpperCase():\"lowerc"\ "ase\"==d&&(a=a.toLowerCase());c=b.pop()||\"\";ca(c)&&0==a.lastIndexOf("\ "\" \",0)&&(a=a.substr(1));b.push(c+a)}\nfunction Xa(a){var b=1,c=T(a,\""\ "opacity\");c&&(b=Number(c));(a=S(a))&&(b*=Xa(a));return b};var W={},X={"\ "};W.v=function(a,b,c){var d;try{d=C.c(\"a\",b)}catch(e){d=z(w(b),\"A\","\ "null,b)}return ha(d,function(b){b=bb(b);return c&&-1!=b.indexOf(a)||b=="\ "a})};W.s=function(a,b,c){var d;try{d=C.c(\"a\",b)}catch(e){d=z(w(b),\"A"\ "\",null,b)}return s(d,function(b){b=bb(b);return c&&-1!=b.indexOf(a)||b"\ "==a})};W.e=function(a,b){return W.v(a,b,!1)};W.c=function(a,b){return W"\ ".s(a,b,!1)};X.e=function(a,b){return W.v(a,b,!0)};X.c=function(a,b){ret"\ "urn W.s(a,b,!0)};var fb={e:function(a,b){return b.getElementsByTagName("\ "a)[0]||null},c:function(a,b){return b.getElementsByTagName(a)}};var gb="\ "{className:A,\"class name\":A,css:C,\"css selector\":C,id:{e:function(a"\ ",b){var c=w(b),d=l(a)?c.j.getElementById(a):a;if(!d)return null;if(R(d,"\ "\"id\")==a&&y(b,d))return d;c=z(c,\"*\");return ha(c,function(c){return"\ " R(c,\"id\")==a&&y(b,c)})},c:function(a,b){var c=z(w(b),\"*\",null,b);r"\ "eturn s(c,function(b){return R(b,\"id\")==a})}},linkText:W,\"link text"\ "\":W,name:{e:function(a,b){var c=z(w(b),\"*\",null,b);return ha(c,funct"\ "ion(b){return R(b,\"name\")==a})},c:function(a,b){var c=z(w(b),\"*\",nu"\ "ll,b);return s(c,function(b){return R(b,\n\"name\")==a})}},partialLinkT"\ "ext:X,\"partial link text\":X,tagName:fb,\"tag name\":fb,xpath:N};funct"\ "ion hb(a,b){var c;a:{for(c in a)if(a.hasOwnProperty(c))break a;c=null}i"\ "f(c){var d=gb[c];if(d&&n(d.c))return d.c(a[c],b||ba.document)}throw Err"\ "or(\"Unsupported locator strategy: \"+c);}var Y=[\"_\"],Z=k;Y[0]in Z||!"\ "Z.execScript||Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.shif"\ "t());)Y.length||void 0===hb?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=hb;; return this._"\ ".apply(null,arguments);}.apply({navigator:typeof window!=undefined?wind"\ "ow.navigator:null,document:typeof window!=undefined?window.document:nul"\ "l}, arguments);}" GET_APPCACHE_STATUS = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.a="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"appcache\"){case \"appc"\ "ache\":return null!=a.applicationCache;case \"browser_connection\":retu"\ "rn null!=a.navigator&&null!=a.navigator.onLine;case \"database\":return"\ " null!=a.openDatabase;case \"location\":return k?!1:null!=a.navigator&&"\ "null!=a.navigator.geolocation;case \"local_storage\":return null!=a.loc"\ "alStorage;case \"session_storage\":return null!=a.sessionStorage&&null!"\ "=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API identi"\ "fier provided as parameter\");}};function n(){var a;if(m())a=c.applicat"\ "ionCache.status;else throw new d(13,\"Undefined application cache\");re"\ "turn a}var p=[\"_\"],q=this;p[0]in q||!q.execScript||q.execScript(\"var"\ " \"+p[0]);for(var r;p.length&&(r=p.shift());)p.length||void 0===n?q=q[r"\ "]?q[r]:q[r]={}:q[r]=n;; return this._.apply(null,arguments);}.apply({na"\ "vigator:typeof window!=undefined?window.navigator:null,document:typeof "\ "window!=undefined?window.document:null}, arguments);}" GET_ATTRIBUTE = \ "function(){return function(){function e(a){return function(){return a}}"\ "var h=this;function k(a){return\"string\"==typeof a}function l(a){var b"\ "=typeof a;return\"object\"==b&&null!=a||\"function\"==b};var m=Array.pr"\ "ototype;function n(a,b){if(k(a))return k(b)&&1==b.length?a.indexOf(b,0)"\ ":-1;for(var c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1}fu"\ "nction p(a,b){for(var c=a.length,d=k(a)?a.split(\"\"):a,f=0;f<c;f++)f i"\ "n d&&b.call(void 0,d[f],f,a)}function aa(a,b){if(a.reduce)return a.redu"\ "ce(b,\"\");var c=\"\";p(a,function(d,f){c=b.call(void 0,c,d,f,a)});retu"\ "rn c}function ba(a,b,c){return 2>=arguments.length?m.slice.call(a,b):m."\ "slice.call(a,b,c)};function q(a,b){this.code=a;this.state=s[a]||t;this."\ "message=b||\"\";var c=this.state.replace(/((?:^|\\s+)[a-z])/g,function("\ "a){return a.toUpperCase().replace(/^[\\s\\xa0]+/g,\"\")}),d=c.length-5;"\ "if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";this.name=c;c=Error(this"\ ".message);c.name=this.name;this.stack=c.stack||\"\"}(function(){var a=E"\ "rror;function b(){}b.prototype=a.prototype;q.N=a.prototype;q.prototype="\ "new b})();\nvar t=\"unknown error\",s={15:\"element not selectable\",11"\ ":\"element not visible\",31:\"ime engine activation failed\",30:\"ime n"\ "ot available\",24:\"invalid cookie domain\",29:\"invalid element coordi"\ "nates\",12:\"invalid element state\",32:\"invalid selector\",51:\"inval"\ "id selector\",52:\"invalid selector\",17:\"javascript error\",405:\"uns"\ "upported operation\",34:\"move target out of bounds\",27:\"no such aler"\ "t\",7:\"no such element\",8:\"no such frame\",23:\"no such window\",28:"\ "\"script timeout\",33:\"session not created\",10:\"stale element refere"\ "nce\",\n0:\"success\",21:\"timeout\",25:\"unable to set cookie\",26:\"u"\ "nexpected alert open\"};s[13]=t;s[9]=\"unknown command\";q.prototype.to"\ "String=function(){return this.name+\": \"+this.message};var u,w,x,z=h.n"\ "avigator;x=z&&z.platform||\"\";u=-1!=x.indexOf(\"Mac\");w=-1!=x.indexOf"\ "(\"Win\");var A=-1!=x.indexOf(\"Linux\");function B(a,b){if(a.contains&"\ "&1==b.nodeType)return a==b||a.contains(b);if(\"undefined\"!=typeof a.co"\ "mpareDocumentPosition)return a==b||Boolean(a.compareDocumentPosition(b)"\ "&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction ca(a,b){if(a=="\ "b)return 0;if(a.compareDocumentPosition)return a.compareDocumentPositio"\ "n(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"sourceIndex\"in a.p"\ "arentNode){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return a.sourceI"\ "ndex-b.sourceIndex;var f=a.parentNode,g=b.parentNode;return f==g?C(a,b)"\ ":!c&&B(f,b)?-1*D(a,b):!d&&B(g,a)?D(b,a):(c?a.sourceIndex:f.sourceIndex)"\ "-(d?b.sourceIndex:g.sourceIndex)}d=9==a.nodeType?a:a.ownerDocument||a.d"\ "ocument;c=d.createRange();c.selectNode(a);c.collapse(!0);\nd=d.createRa"\ "nge();d.selectNode(b);d.collapse(!0);return c.compareBoundaryPoints(h.R"\ "ange.START_TO_END,d)}function D(a,b){var c=a.parentNode;if(c==b)return-"\ "1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return C(d,a)}function C("\ "a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1};functi"\ "on E(a){var b=null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||nul"\ "l==b?a.innerText:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b"\ ")if(9==c||1==c){a=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],"\ "b=\"\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstC"\ "hild);for(;c&&!(a=d[--c].nextSibling););}}else b=a.nodeValue;return\"\""\ "+b}\nfunction F(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)retu"\ "rn!1}catch(d){return!1}return null==c?!!a.getAttribute(b):a.getAttribut"\ "e(b,2)==c}function G(a,b,c,d,f){return da.call(null,a,b,k(c)?c:null,k(d"\ ")?d:null,f||new H)}\nfunction da(a,b,c,d,f){b.getElementsByName&&d&&\"n"\ "ame\"==c?(b=b.getElementsByName(d),p(b,function(b){a.matches(b)&&f.add("\ "b)})):b.getElementsByClassName&&d&&\"class\"==c?(b=b.getElementsByClass"\ "Name(d),p(b,function(b){b.className==d&&a.matches(b)&&f.add(b)})):b.get"\ "ElementsByTagName&&(b=b.getElementsByTagName(a.getName()),p(b,function("\ "a){F(a,c,d)&&f.add(a)}));return f}function ea(a,b,c,d,f){for(b=b.firstC"\ "hild;b;b=b.nextSibling)F(b,c,d)&&a.matches(b)&&f.add(b);return f};funct"\ "ion H(){this.g=this.f=null;this.l=0}function I(a){this.p=a;this.next=th"\ "is.n=null}H.prototype.unshift=function(a){a=new I(a);a.next=this.f;this"\ ".g?this.f.n=a:this.f=this.g=a;this.f=a;this.l++};H.prototype.add=functi"\ "on(a){a=new I(a);a.n=this.g;this.f?this.g.next=a:this.f=this.g=a;this.g"\ "=a;this.l++};function J(a){return(a=a.f)?a.p:null}function K(a){return "\ "new L(a,!1)}function L(a,b){this.J=a;this.o=(this.q=b)?a.g:a.f;this.u=n"\ "ull}\nL.prototype.next=function(){var a=this.o;if(null==a)return null;v"\ "ar b=this.u=a;this.o=this.q?a.n:a.next;return b.p};function N(a,b,c,d,f"\ "){b=b.evaluate(d);c=c.evaluate(d);var g;if(b instanceof H&&c instanceof"\ " H){f=K(b);for(d=f.next();d;d=f.next())for(b=K(c),g=b.next();g;g=b.next"\ "())if(a(E(d),E(g)))return!0;return!1}if(b instanceof H||c instanceof H)"\ "{b instanceof H?f=b:(f=c,c=b);f=K(f);b=typeof c;for(d=f.next();d;d=f.ne"\ "xt()){switch(b){case \"number\":d=+E(d);break;case \"boolean\":d=!!E(d)"\ ";break;case \"string\":d=E(d);break;default:throw Error(\"Illegal primi"\ "tive type for comparison.\");}if(a(d,c))return!0}return!1}return f?\n\""\ "boolean\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeo"\ "f b||\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function O(a,b,c,d){"\ "this.v=a;this.L=b;this.s=c;this.t=d}O.prototype.toString=function(){ret"\ "urn this.v};var fa={};function P(a,b,c,d){if(a in fa)throw Error(\"Bina"\ "ry operator already created: \"+a);a=new O(a,b,c,d);fa[a.toString()]=a}"\ "P(\"div\",6,1,function(a,b,c){return a.d(c)/b.d(c)});P(\"mod\",6,1,func"\ "tion(a,b,c){return a.d(c)%b.d(c)});P(\"*\",6,1,function(a,b,c){return a"\ ".d(c)*b.d(c)});\nP(\"+\",5,1,function(a,b,c){return a.d(c)+b.d(c)});P("\ "\"-\",5,1,function(a,b,c){return a.d(c)-b.d(c)});P(\"<\",4,2,function(a"\ ",b,c){return N(function(a,b){return a<b},a,b,c)});P(\">\",4,2,function("\ "a,b,c){return N(function(a,b){return a>b},a,b,c)});P(\"<=\",4,2,functio"\ "n(a,b,c){return N(function(a,b){return a<=b},a,b,c)});P(\">=\",4,2,func"\ "tion(a,b,c){return N(function(a,b){return a>=b},a,b,c)});P(\"=\",3,2,fu"\ "nction(a,b,c){return N(function(a,b){return a==b},a,b,c,!0)});\nP(\"!="\ "\",3,2,function(a,b,c){return N(function(a,b){return a!=b},a,b,c,!0)});"\ "P(\"and\",2,2,function(a,b,c){return a.j(c)&&b.j(c)});P(\"or\",1,2,func"\ "tion(a,b,c){return a.j(c)||b.j(c)});function ga(a,b,c,d,f,g,r,v,y){this"\ ".m=a;this.s=b;this.I=c;this.H=d;this.G=f;this.t=g;this.F=r;this.D=void "\ "0!==v?v:r;this.K=!!y}ga.prototype.toString=function(){return this.m};va"\ "r ha={};function Q(a,b,c,d,f,g,r,v){if(a in ha)throw Error(\"Function a"\ "lready created: \"+a+\".\");ha[a]=new ga(a,b,c,d,!1,f,g,r,v)}Q(\"boolea"\ "n\",2,!1,!1,function(a,b){return b.j(a)},1);Q(\"ceiling\",1,!1,!1,funct"\ "ion(a,b){return Math.ceil(b.d(a))},1);\nQ(\"concat\",3,!1,!1,function(a"\ ",b){var c=ba(arguments,1);return aa(c,function(b,c){return b+c.c(a)})},"\ "2,null);Q(\"contains\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return"\ "-1!=b.indexOf(a)},2);Q(\"count\",1,!1,!1,function(a,b){return b.evaluat"\ "e(a).l},1,1,!0);Q(\"false\",2,!1,!1,e(!1),0);Q(\"floor\",1,!1,!1,functi"\ "on(a,b){return Math.floor(b.d(a))},1);\nQ(\"id\",4,!1,!1,function(a,b){"\ "var c=a.h(),d=9==c.nodeType?c:c.ownerDocument,c=b.c(a).split(/\\s+/),f="\ "[];p(c,function(a){a=d.getElementById(a);!a||0<=n(f,a)||f.push(a)});f.s"\ "ort(ca);var g=new H;p(f,function(a){g.add(a)});return g},1);Q(\"lang\","\ "2,!1,!1,e(!1),1);Q(\"last\",1,!0,!1,function(a){if(1!=arguments.length)"\ "throw Error(\"Function last expects ()\");return a.B()},0);Q(\"local-na"\ "me\",3,!1,!0,function(a,b){var c=b?J(b.evaluate(a)):a.h();return c?c.no"\ "deName.toLowerCase():\"\"},0,1,!0);\nQ(\"name\",3,!1,!0,function(a,b){v"\ "ar c=b?J(b.evaluate(a)):a.h();return c?c.nodeName.toLowerCase():\"\"},0"\ ",1,!0);Q(\"namespace-uri\",3,!0,!1,e(\"\"),0,1,!0);Q(\"normalize-space"\ "\",3,!1,!0,function(a,b){return(b?b.c(a):E(a.h())).replace(/[\\s\\xa0]+"\ "/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,1);Q(\"not\",2,!1,!1,function"\ "(a,b){return!b.j(a)},1);Q(\"number\",1,!1,!0,function(a,b){return b?b.d"\ "(a):+E(a.h())},0,1);Q(\"position\",1,!0,!1,function(a){return a.C()},0)"\ ";Q(\"round\",1,!1,!1,function(a,b){return Math.round(b.d(a))},1);\nQ(\""\ "starts-with\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return 0==b.las"\ "tIndexOf(a,0)},2);Q(\"string\",3,!1,!0,function(a,b){return b?b.c(a):E("\ "a.h())},0,1);Q(\"string-length\",1,!1,!0,function(a,b){return(b?b.c(a):"\ "E(a.h())).length},0,1);\nQ(\"substring\",3,!1,!1,function(a,b,c,d){c=c."\ "d(a);if(isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.d(a):Infin"\ "ity;if(isNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var f=Math."\ "max(c,0);a=b.c(a);if(Infinity==d)return a.substring(f);b=Math.round(d);"\ "return a.substring(f,c+b)},2,3);Q(\"substring-after\",3,!1,!1,function("\ "a,b,c){b=b.c(a);a=c.c(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+"\ "a.length)},2);\nQ(\"substring-before\",3,!1,!1,function(a,b,c){b=b.c(a)"\ ";a=c.c(a);a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);Q(\"sum"\ "\",1,!1,!1,function(a,b){for(var c=K(b.evaluate(a)),d=0,f=c.next();f;f="\ "c.next())d+=+E(f);return d},1,1,!0);Q(\"translate\",3,!1,!1,function(a,"\ "b,c,d){b=b.c(a);c=c.c(a);var f=d.c(a);a=[];for(d=0;d<c.length;d++){var "\ "g=c.charAt(d);g in a||(a[g]=f.charAt(d))}c=\"\";for(d=0;d<b.length;d++)"\ "g=b.charAt(d),c+=g in a?a[g]:g;return c},3);Q(\"true\",2,!1,!1,e(!0),0)"\ ";function ia(a,b,c,d){this.m=a;this.A=b;this.q=c;this.O=d}ia.prototype."\ "toString=function(){return this.m};var ja={};function R(a,b,c,d){if(a i"\ "n ja)throw Error(\"Axis already created: \"+a);ja[a]=new ia(a,b,c,!!d)}"\ "R(\"ancestor\",function(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matc"\ "hes(d)&&c.unshift(d);return c},!0);R(\"ancestor-or-self\",function(a,b)"\ "{var c=new H,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);re"\ "turn c},!0);\nR(\"attribute\",function(a,b){var c=new H,d=a.getName(),f"\ "=b.attributes;if(f)if(\"*\"==d)for(var d=0,g;g=f[d];d++)c.add(g);else(g"\ "=f.getNamedItem(d))&&c.add(g);return c},!1);R(\"child\",function(a,b,c,"\ "d,f){return ea.call(null,a,b,k(c)?c:null,k(d)?d:null,f||new H)},!1,!0);"\ "R(\"descendant\",G,!1,!0);R(\"descendant-or-self\",function(a,b,c,d){va"\ "r f=new H;F(b,c,d)&&a.matches(b)&&f.add(b);return G(a,b,c,d,f)},!1,!0);"\ "\nR(\"following\",function(a,b,c,d){var f=new H;do for(var g=b;g=g.next"\ "Sibling;)F(g,c,d)&&a.matches(g)&&f.add(g),f=G(a,g,c,d,f);while(b=b.pare"\ "ntNode);return f},!1,!0);R(\"following-sibling\",function(a,b){for(var "\ "c=new H,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);R(\"n"\ "amespace\",function(){return new H},!1);R(\"parent\",function(a,b){var "\ "c=new H;if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.owner"\ "Element),c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nR("\ "\"preceding\",function(a,b,c,d){var f=new H,g=[];do g.unshift(b);while("\ "b=b.parentNode);for(var r=1,v=g.length;r<v;r++){var y=[];for(b=g[r];b=b"\ ".previousSibling;)y.unshift(b);for(var M=0,oa=y.length;M<oa;M++)b=y[M],"\ "F(b,c,d)&&a.matches(b)&&f.add(b),f=G(a,b,c,d,f)}return f},!0,!0);R(\"pr"\ "eceding-sibling\",function(a,b){for(var c=new H,d=b;d=d.previousSibling"\ ";)a.matches(d)&&c.unshift(d);return c},!0);R(\"self\",function(a,b){var"\ " c=new H;a.matches(b)&&c.add(b);return c},!1);function S(a,b){return!!a"\ "&&1==a.nodeType&&(!b||a.tagName.toUpperCase()==b)}function ka(a){return"\ " S(a,\"OPTION\")?!0:S(a,\"INPUT\")?(a=a.type.toLowerCase(),\"checkbox\""\ "==a||\"radio\"==a):!1}var la=/[;]+(?=(?:(?:[^\"]*\"){2})*[^\"]*$)(?=(?:"\ "(?:[^']*'){2})*[^']*$)(?=(?:[^()]*\\([^()]*\\))*[^()]*$)/;\nfunction ma"\ "(a){var b=[];p(a.split(la),function(a){var d=a.indexOf(\":\");0<d&&(a=["\ "a.slice(0,d),a.slice(d+1)],2==a.length&&b.push(a[0].toLowerCase(),\":\""\ ",a[1],\";\"))});b=b.join(\"\");return b=\";\"==b.charAt(b.length-1)?b:b"\ "+\";\"}function T(a,b){b=b.toLowerCase();if(\"style\"==b)return ma(a.st"\ "yle.cssText);var c=a.getAttributeNode(b);return c&&c.specified?c.value:"\ "null};function U(a,b){this.i={};this.e=[];var c=arguments.length;if(1<c"\ "){if(c%2)throw Error(\"Uneven number of arguments\");for(var d=0;d<c;d+"\ "=2)this.set(arguments[d],arguments[d+1])}else if(a){var f;if(a instance"\ "of U)for(d=na(a),pa(a),f=[],c=0;c<a.e.length;c++)f.push(a.i[a.e[c]]);el"\ "se{var c=[],g=0;for(d in a)c[g++]=d;d=c;c=[];g=0;for(f in a)c[g++]=a[f]"\ ";f=c}for(c=0;c<d.length;c++)this.set(d[c],f[c])}}U.prototype.k=0;U.prot"\ "otype.w=0;function na(a){pa(a);return a.e.concat()}\nfunction pa(a){if("\ "a.k!=a.e.length){for(var b=0,c=0;b<a.e.length;){var d=a.e[b];Object.pro"\ "totype.hasOwnProperty.call(a.i,d)&&(a.e[c++]=d);b++}a.e.length=c}if(a.k"\ "!=a.e.length){for(var f={},c=b=0;b<a.e.length;)d=a.e[b],Object.prototyp"\ "e.hasOwnProperty.call(f,d)||(a.e[c++]=d,f[d]=1),b++;a.e.length=c}}U.pro"\ "totype.get=function(a,b){return Object.prototype.hasOwnProperty.call(th"\ "is.i,a)?this.i[a]:b};\nU.prototype.set=function(a,b){Object.prototype.h"\ "asOwnProperty.call(this.i,a)||(this.k++,this.e.push(a),this.w++);this.i"\ "[a]=b};var V={};function W(a,b,c){l(a)&&(a=a.a);a=new qa(a,b,c);!b||b i"\ "n V&&!c||(V[b]={key:a,shift:!1},c&&(V[c]={key:a,shift:!0}));return a}fu"\ "nction qa(a,b,c){this.code=a;this.r=b||null;this.M=c||this.r}W(8);W(9);"\ "W(13);var ra=W(16),sa=W(17),ta=W(18);W(19);W(20);W(27);W(32,\" \");W(33"\ ");W(34);W(35);W(36);W(37);W(38);W(39);W(40);W(44);W(45);W(46);W(48,\"0"\ "\",\")\");W(49,\"1\",\"!\");W(50,\"2\",\"@\");W(51,\"3\",\"#\");W(52,\""\ "4\",\"$\");W(53,\"5\",\"%\");W(54,\"6\",\"^\");W(55,\"7\",\"&\");W(56,"\ "\"8\",\"*\");W(57,\"9\",\"(\");W(65,\"a\",\"A\");W(66,\"b\",\"B\");\nW("\ "67,\"c\",\"C\");W(68,\"d\",\"D\");W(69,\"e\",\"E\");W(70,\"f\",\"F\");W"\ "(71,\"g\",\"G\");W(72,\"h\",\"H\");W(73,\"i\",\"I\");W(74,\"j\",\"J\");"\ "W(75,\"k\",\"K\");W(76,\"l\",\"L\");W(77,\"m\",\"M\");W(78,\"n\",\"N\")"\ ";W(79,\"o\",\"O\");W(80,\"p\",\"P\");W(81,\"q\",\"Q\");W(82,\"r\",\"R\""\ ");W(83,\"s\",\"S\");W(84,\"t\",\"T\");W(85,\"u\",\"U\");W(86,\"v\",\"V"\ "\");W(87,\"w\",\"W\");W(88,\"x\",\"X\");W(89,\"y\",\"Y\");W(90,\"z\",\""\ "Z\");var ua=W(w?{b:91,a:91,opera:219}:u?{b:224,a:91,opera:17}:{b:0,a:91"\ ",opera:null});W(w?{b:92,a:92,opera:220}:u?{b:224,a:93,opera:17}:{b:0,a:"\ "92,opera:null});\nW(w?{b:93,a:93,opera:0}:u?{b:0,a:0,opera:16}:{b:93,a:"\ "null,opera:0});W({b:96,a:96,opera:48},\"0\");W({b:97,a:97,opera:49},\"1"\ "\");W({b:98,a:98,opera:50},\"2\");W({b:99,a:99,opera:51},\"3\");W({b:10"\ "0,a:100,opera:52},\"4\");W({b:101,a:101,opera:53},\"5\");W({b:102,a:102"\ ",opera:54},\"6\");W({b:103,a:103,opera:55},\"7\");W({b:104,a:104,opera:"\ "56},\"8\");W({b:105,a:105,opera:57},\"9\");W({b:106,a:106,opera:A?56:42"\ "},\"*\");W({b:107,a:107,opera:A?61:43},\"+\");W({b:109,a:109,opera:A?10"\ "9:45},\"-\");W({b:110,a:110,opera:A?190:78},\".\");\nW({b:111,a:111,ope"\ "ra:A?191:47},\"/\");W(144);W(112);W(113);W(114);W(115);W(116);W(117);W("\ "118);W(119);W(120);W(121);W(122);W(123);W({b:107,a:187,opera:61},\"=\","\ "\"+\");W(108,\",\");W({b:109,a:189,opera:109},\"-\",\"_\");W(188,\",\","\ "\"<\");W(190,\".\",\">\");W(191,\"/\",\"?\");W(192,\"`\",\"~\");W(219,"\ "\"[\",\"{\");W(220,\"\\\\\",\"|\");W(221,\"]\",\"}\");W({b:59,a:186,ope"\ "ra:59},\";\",\":\");W(222,\"'\",'\"');var X=new U;X.set(1,ra);X.set(2,s"\ "a);X.set(4,ta);X.set(8,ua);(function(a){var b=new U;p(na(a),function(c)"\ "{b.set(a.get(c).code,c)});return b})(X);var va={\"class\":\"className\""\ ",readonly:\"readOnly\"},wa=\"async autofocus autoplay checked compact c"\ "omplete controls declare defaultchecked defaultselected defer disabled "\ "draggable ended formnovalidate hidden indeterminate iscontenteditable i"\ "smap itemscope loop multiple muted nohref noresize noshade novalidate n"\ "owrap open paused pubdate readonly required reversed scoped seamless se"\ "eking selected spellcheck truespeed willvalidate\".split(\" \");functio"\ "n xa(a,b){var c=null,d=b.toLowerCase();if(\"style\"==d)return(c=a.style"\ ")&&!k(c)&&(c=c.cssText),c;if((\"selected\"==d||\"checked\"==d)&&ka(a)){"\ "if(!ka(a))throw new q(15,\"Element is not selectable\");var d=\"selecte"\ "d\",f=a.type&&a.type.toLowerCase();if(\"checkbox\"==f||\"radio\"==f)d="\ "\"checked\";return a[d]?\"true\":null}c=S(a,\"A\");if(S(a,\"IMG\")&&\"s"\ "rc\"==d||c&&\"href\"==d)return(c=T(a,d))&&(c=a[d]),c;c=va[b]||b;if(0<=n"\ "(wa,d))return(c=null!==T(a,b)||a[c])?\"true\":null;try{f=a[c]}catch(g){"\ "}c=null==f||l(f)?T(a,b):f;\nreturn null!=c?c.toString():null}var Y=[\"_"\ "\"],Z=h;Y[0]in Z||!Z.execScript||Z.execScript(\"var \"+Y[0]);for(var $;"\ "Y.length&&($=Y.shift());)Y.length||void 0===xa?Z=Z[$]?Z[$]:Z[$]={}:Z[$]"\ "=xa;; return this._.apply(null,arguments);}.apply({navigator:typeof win"\ "dow!=undefined?window.navigator:null,document:typeof window!=undefined?"\ "window.document:null}, arguments);}" GET_EFFECTIVE_STYLE = \ "function(){return function(){function g(a){return function(){return a}}"\ "var h=this;\nfunction k(a){var b=typeof a;if(\"object\"==b)if(a){if(a i"\ "nstanceof Array)return\"array\";if(a instanceof Object)return b;var c=O"\ "bject.prototype.toString.call(a);if(\"[object Window]\"==c)return\"obje"\ "ct\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined"\ "\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.p"\ "ropertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]"\ "\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else r"\ "eturn\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)r"\ "eturn\"object\";return b}function l(a){return\"string\"==typeof a};func"\ "tion m(a){return String(a).replace(/\\-([a-z])/g,function(a,c){return c"\ ".toUpperCase()})};var p=Array.prototype;function q(a,b){if(l(a))return "\ "l(b)&&1==b.length?a.indexOf(b,0):-1;for(var c=0;c<a.length;c++)if(c in "\ "a&&a[c]===b)return c;return-1}function r(a,b){for(var c=a.length,d=l(a)"\ "?a.split(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function s"\ "(a,b){if(a.reduce)return a.reduce(b,\"\");var c=\"\";r(a,function(d,e){"\ "c=b.call(void 0,c,d,e,a)});return c}function aa(a,b,c){return 2>=argume"\ "nts.length?p.slice.call(a,b):p.slice.call(a,b,c)};var u={aliceblue:\"#f"\ "0f8ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4"\ "\",azure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#0000"\ "00\",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\""\ ",brown:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreu"\ "se:\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:"\ "\"#6495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",d"\ "arkblue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",dark"\ "gray:\"#a9a9a9\",darkgreen:\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki"\ ":\"#bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkora"\ "nge:\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:"\ "\"#e9967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslat"\ "egray:\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",d"\ "arkviolet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimg"\ "ray:\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\""\ "#b22222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff"\ "00ff\",gainsboro:\"#dcdcdc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\","\ "goldenrod:\"#daa520\",gray:\"#808080\",green:\"#008000\",greenyellow:\""\ "#adff2f\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",ind"\ "ianred:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c"\ "\",lavender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\""\ ",lemonchiffon:\"#fffacd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\","\ "lightcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d"\ "3d3\",lightgreen:\"#90ee90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1"\ "\",lightsalmon:\"#ffa07a\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#"\ "87cefa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",lightste"\ "elblue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:"\ "\"#32cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",me"\ "diumaquamarine:\"#66cdaa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d"\ "3\",mediumpurple:\"#9370db\",mediumseagreen:\"#3cb371\",mediumslateblue"\ ":\"#7b68ee\",mediumspringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\","\ "mediumvioletred:\"#c71585\",midnightblue:\"#191970\",mintcream:\"#f5fff"\ "a\",mistyrose:\"#ffe4e1\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead"\ "\",navy:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#"\ "6b8e23\",orange:\"#ffa500\",orangered:\"#ff4500\",orchid:\"#da70d6\",pa"\ "legoldenrod:\"#eee8aa\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\""\ ",palevioletred:\"#db7093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\""\ ",peru:\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e"\ "6\",purple:\"#800080\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:"\ "\"#4169e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4"\ "a460\",seagreen:\"#2e8b57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",s"\ "ilver:\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:"\ "\"#708090\",slategrey:\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7"\ "f\",steelblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d"\ "8bfd8\",tomato:\"#ff6347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",whe"\ "at:\"#f5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff0"\ "0\",yellowgreen:\"#9acd32\"};var ba=\"background-color border-top-color"\ " border-right-color border-bottom-color border-left-color color outline"\ "-color\".split(\" \"),ca=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;fun"\ "ction w(a){if(!x.test(a))throw Error(\"'\"+a+\"' is not a valid hex col"\ "or\");4==a.length&&(a=a.replace(ca,\"#$1$1$2$2$3$3\"));return a.toLower"\ "Case()}var x=/^#(?:[0-9a-f]{3}){1,2}$/i,da=/^(?:rgba)?\\((\\d{1,3}),\\s"\ "?(\\d{1,3}),\\s?(\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction y(a){var"\ " b=a.match(da);if(b){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b"\ "=Number(b[4]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)r"\ "eturn[a,c,d,b]}return[]}var ea=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1"\ "-9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2})\\)$/i;function z(a){var b=a.match(ea"\ ");if(b){a=Number(b[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>="\ "a&&0<=c&&255>=c&&0<=b&&255>=b)return[a,c,b]}return[]};function A(a,b){i"\ "f(a.contains&&1==b.nodeType)return a==b||a.contains(b);if(\"undefined\""\ "!=typeof a.compareDocumentPosition)return a==b||Boolean(a.compareDocume"\ "ntPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction f"\ "a(a,b){if(a==b)return 0;if(a.compareDocumentPosition)return a.compareDo"\ "cumentPosition(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"source"\ "Index\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)ret"\ "urn a.sourceIndex-b.sourceIndex;var e=a.parentNode,f=b.parentNode;retur"\ "n e==f?B(a,b):!c&&A(e,b)?-1*C(a,b):!d&&A(f,a)?C(b,a):(c?a.sourceIndex:e"\ ".sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}d=9==a.nodeType?a:a.owner"\ "Document||a.document;c=d.createRange();c.selectNode(a);c.collapse(!0);"\ "\nd=d.createRange();d.selectNode(b);d.collapse(!0);return c.compareBoun"\ "daryPoints(h.Range.START_TO_END,d)}function C(a,b){var c=a.parentNode;i"\ "f(c==b)return-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return B(d,"\ "a)}function B(a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;re"\ "turn 1};function E(a){var b=null,c=a.nodeType;1==c&&(b=a.textContent,b="\ "void 0==b||null==b?a.innerText:b,b=void 0==b||null==b?\"\":b);if(\"stri"\ "ng\"!=typeof b)if(9==c||1==c){a=9==c?a.documentElement:a.firstChild;for"\ "(var c=0,d=[],b=\"\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;wh"\ "ile(a=a.firstChild);for(;c&&!(a=d[--c].nextSibling););}}else b=a.nodeVa"\ "lue;return\"\"+b}\nfunction F(a,b,c){if(null===b)return!0;try{if(!a.get"\ "Attribute)return!1}catch(d){return!1}return null==c?!!a.getAttribute(b)"\ ":a.getAttribute(b,2)==c}function G(a,b,c,d,e){return ga.call(null,a,b,l"\ "(c)?c:null,l(d)?d:null,e||new H)}\nfunction ga(a,b,c,d,e){b.getElements"\ "ByName&&d&&\"name\"==c?(b=b.getElementsByName(d),r(b,function(b){a.matc"\ "hes(b)&&e.add(b)})):b.getElementsByClassName&&d&&\"class\"==c?(b=b.getE"\ "lementsByClassName(d),r(b,function(b){b.className==d&&a.matches(b)&&e.a"\ "dd(b)})):b.getElementsByTagName&&(b=b.getElementsByTagName(a.getName())"\ ",r(b,function(a){F(a,c,d)&&e.add(a)}));return e}function ha(a,b,c,d,e){"\ "for(b=b.firstChild;b;b=b.nextSibling)F(b,c,d)&&a.matches(b)&&e.add(b);r"\ "eturn e};function H(){this.d=this.c=null;this.g=0}function I(a){this.k="\ "a;this.next=this.i=null}H.prototype.unshift=function(a){a=new I(a);a.ne"\ "xt=this.c;this.d?this.c.i=a:this.c=this.d=a;this.c=a;this.g++};H.protot"\ "ype.add=function(a){a=new I(a);a.i=this.d;this.c?this.d.next=a:this.c=t"\ "his.d=a;this.d=a;this.g++};function J(a){return(a=a.c)?a.k:null}functio"\ "n K(a){return new L(a,!1)}function L(a,b){this.B=a;this.j=(this.l=b)?a."\ "d:a.c;this.o=null}\nL.prototype.next=function(){var a=this.j;if(null==a"\ ")return null;var b=this.o=a;this.j=this.l?a.i:a.next;return b.k};functi"\ "on M(a,b,c,d,e){b=b.evaluate(d);c=c.evaluate(d);var f;if(b instanceof H"\ "&&c instanceof H){e=K(b);for(d=e.next();d;d=e.next())for(b=K(c),f=b.nex"\ "t();f;f=b.next())if(a(E(d),E(f)))return!0;return!1}if(b instanceof H||c"\ " instanceof H){b instanceof H?e=b:(e=c,c=b);e=K(e);b=typeof c;for(d=e.n"\ "ext();d;d=e.next()){switch(b){case \"number\":d=+E(d);break;case \"bool"\ "ean\":d=!!E(d);break;case \"string\":d=E(d);break;default:throw Error("\ "\"Illegal primitive type for comparison.\");}if(a(d,c))return!0}return!"\ "1}return e?\n\"boolean\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\""\ "number\"==typeof b||\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}funct"\ "ion N(a,b,c,d){this.p=a;this.D=b;this.m=c;this.n=d}N.prototype.toString"\ "=function(){return this.p};var O={};function P(a,b,c,d){if(a in O)throw"\ " Error(\"Binary operator already created: \"+a);a=new N(a,b,c,d);O[a.to"\ "String()]=a}P(\"div\",6,1,function(a,b,c){return a.b(c)/b.b(c)});P(\"mo"\ "d\",6,1,function(a,b,c){return a.b(c)%b.b(c)});P(\"*\",6,1,function(a,b"\ ",c){return a.b(c)*b.b(c)});\nP(\"+\",5,1,function(a,b,c){return a.b(c)+"\ "b.b(c)});P(\"-\",5,1,function(a,b,c){return a.b(c)-b.b(c)});P(\"<\",4,2"\ ",function(a,b,c){return M(function(a,b){return a<b},a,b,c)});P(\">\",4,"\ "2,function(a,b,c){return M(function(a,b){return a>b},a,b,c)});P(\"<=\","\ "4,2,function(a,b,c){return M(function(a,b){return a<=b},a,b,c)});P(\">="\ "\",4,2,function(a,b,c){return M(function(a,b){return a>=b},a,b,c)});P("\ "\"=\",3,2,function(a,b,c){return M(function(a,b){return a==b},a,b,c,!0)"\ "});\nP(\"!=\",3,2,function(a,b,c){return M(function(a,b){return a!=b},a"\ ",b,c,!0)});P(\"and\",2,2,function(a,b,c){return a.f(c)&&b.f(c)});P(\"or"\ "\",1,2,function(a,b,c){return a.f(c)||b.f(c)});function Q(a,b,c,d,e,f,n"\ ",t,v){this.h=a;this.m=b;this.A=c;this.w=d;this.v=e;this.n=f;this.u=n;th"\ "is.t=void 0!==t?t:n;this.C=!!v}Q.prototype.toString=function(){return t"\ "his.h};var R={};function S(a,b,c,d,e,f,n,t){if(a in R)throw Error(\"Fun"\ "ction already created: \"+a+\".\");R[a]=new Q(a,b,c,d,!1,e,f,n,t)}S(\"b"\ "oolean\",2,!1,!1,function(a,b){return b.f(a)},1);S(\"ceiling\",1,!1,!1,"\ "function(a,b){return Math.ceil(b.b(a))},1);\nS(\"concat\",3,!1,!1,funct"\ "ion(a,b){var c=aa(arguments,1);return s(c,function(b,c){return b+c.a(a)"\ "})},2,null);S(\"contains\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);re"\ "turn-1!=b.indexOf(a)},2);S(\"count\",1,!1,!1,function(a,b){return b.eva"\ "luate(a).g},1,1,!0);S(\"false\",2,!1,!1,g(!1),0);S(\"floor\",1,!1,!1,fu"\ "nction(a,b){return Math.floor(b.b(a))},1);\nS(\"id\",4,!1,!1,function(a"\ ",b){var c=a.e(),d=9==c.nodeType?c:c.ownerDocument,c=b.a(a).split(/\\s+/"\ "),e=[];r(c,function(a){a=d.getElementById(a);!a||0<=q(e,a)||e.push(a)})"\ ";e.sort(fa);var f=new H;r(e,function(a){f.add(a)});return f},1);S(\"lan"\ "g\",2,!1,!1,g(!1),1);S(\"last\",1,!0,!1,function(a){if(1!=arguments.len"\ "gth)throw Error(\"Function last expects ()\");return a.r()},0);S(\"loca"\ "l-name\",3,!1,!0,function(a,b){var c=b?J(b.evaluate(a)):a.e();return c?"\ "c.nodeName.toLowerCase():\"\"},0,1,!0);\nS(\"name\",3,!1,!0,function(a,"\ "b){var c=b?J(b.evaluate(a)):a.e();return c?c.nodeName.toLowerCase():\""\ "\"},0,1,!0);S(\"namespace-uri\",3,!0,!1,g(\"\"),0,1,!0);S(\"normalize-s"\ "pace\",3,!1,!0,function(a,b){return(b?b.a(a):E(a.e())).replace(/[\\s\\x"\ "a0]+/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,1);S(\"not\",2,!1,!1,func"\ "tion(a,b){return!b.f(a)},1);S(\"number\",1,!1,!0,function(a,b){return b"\ "?b.b(a):+E(a.e())},0,1);S(\"position\",1,!0,!1,function(a){return a.s()"\ "},0);S(\"round\",1,!1,!1,function(a,b){return Math.round(b.b(a))},1);\n"\ "S(\"starts-with\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return 0==b"\ ".lastIndexOf(a,0)},2);S(\"string\",3,!1,!0,function(a,b){return b?b.a(a"\ "):E(a.e())},0,1);S(\"string-length\",1,!1,!0,function(a,b){return(b?b.a"\ "(a):E(a.e())).length},0,1);\nS(\"substring\",3,!1,!1,function(a,b,c,d){"\ "c=c.b(a);if(isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.b(a):I"\ "nfinity;if(isNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=M"\ "ath.max(c,0);a=b.a(a);if(Infinity==d)return a.substring(e);b=Math.round"\ "(d);return a.substring(e,c+b)},2,3);S(\"substring-after\",3,!1,!1,funct"\ "ion(a,b,c){b=b.a(a);a=c.a(a);c=b.indexOf(a);return-1==c?\"\":b.substrin"\ "g(c+a.length)},2);\nS(\"substring-before\",3,!1,!1,function(a,b,c){b=b."\ "a(a);a=c.a(a);a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);S(\""\ "sum\",1,!1,!1,function(a,b){for(var c=K(b.evaluate(a)),d=0,e=c.next();e"\ ";e=c.next())d+=+E(e);return d},1,1,!0);S(\"translate\",3,!1,!1,function"\ "(a,b,c,d){b=b.a(a);c=c.a(a);var e=d.a(a);a=[];for(d=0;d<c.length;d++){v"\ "ar f=c.charAt(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d"\ "++)f=b.charAt(d),c+=f in a?a[f]:f;return c},3);S(\"true\",2,!1,!1,g(!0)"\ ",0);function T(a,b,c,d){this.h=a;this.q=b;this.l=c;this.F=d}T.prototype"\ ".toString=function(){return this.h};var U={};function V(a,b,c,d){if(a i"\ "n U)throw Error(\"Axis already created: \"+a);U[a]=new T(a,b,c,!!d)}V("\ "\"ancestor\",function(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matche"\ "s(d)&&c.unshift(d);return c},!0);V(\"ancestor-or-self\",function(a,b){v"\ "ar c=new H,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);retu"\ "rn c},!0);\nV(\"attribute\",function(a,b){var c=new H,d=a.getName(),e=b"\ ".attributes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e"\ ".getNamedItem(d))&&c.add(f);return c},!1);V(\"child\",function(a,b,c,d,"\ "e){return ha.call(null,a,b,l(c)?c:null,l(d)?d:null,e||new H)},!1,!0);V("\ "\"descendant\",G,!1,!0);V(\"descendant-or-self\",function(a,b,c,d){var "\ "e=new H;F(b,c,d)&&a.matches(b)&&e.add(b);return G(a,b,c,d,e)},!1,!0);\n"\ "V(\"following\",function(a,b,c,d){var e=new H;do for(var f=b;f=f.nextSi"\ "bling;)F(f,c,d)&&a.matches(f)&&e.add(f),e=G(a,f,c,d,e);while(b=b.parent"\ "Node);return e},!1,!0);V(\"following-sibling\",function(a,b){for(var c="\ "new H,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);V(\"nam"\ "espace\",function(){return new H},!1);V(\"parent\",function(a,b){var c="\ "new H;if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerEl"\ "ement),c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nV(\""\ "preceding\",function(a,b,c,d){var e=new H,f=[];do f.unshift(b);while(b="\ "b.parentNode);for(var n=1,t=f.length;n<t;n++){var v=[];for(b=f[n];b=b.p"\ "reviousSibling;)v.unshift(b);for(var D=0,ia=v.length;D<ia;D++)b=v[D],F("\ "b,c,d)&&a.matches(b)&&e.add(b),e=G(a,b,c,d,e)}return e},!0,!0);V(\"prec"\ "eding-sibling\",function(a,b){for(var c=new H,d=b;d=d.previousSibling;)"\ "a.matches(d)&&c.unshift(d);return c},!0);V(\"self\",function(a,b){var c"\ "=new H;a.matches(b)&&c.add(b);return c},!1);function W(a,b){var c=a.cur"\ "rentStyle||a.style,d=c[b];void 0===d&&\"function\"==k(c.getPropertyValu"\ "e)&&(d=c.getPropertyValue(b));if(\"inherit\"!=d)return void 0!==d?d:nul"\ "l;for(c=a.parentNode;c&&1!=c.nodeType&&9!=c.nodeType&&11!=c.nodeType;)c"\ "=c.parentNode;return(c=c&&1==c.nodeType?c:null)?W(c,b):null};function X"\ "(a,b){var c=m(b);if(\"float\"==c||\"cssFloat\"==c||\"styleFloat\"==c)c="\ "\"cssFloat\";var d;a:{d=c;var e=9==a.nodeType?a:a.ownerDocument||a.docu"\ "ment;if(e.defaultView&&e.defaultView.getComputedStyle&&(e=e.defaultView"\ ".getComputedStyle(a,null))){d=e[d]||e.getPropertyValue(d)||\"\";break a"\ "}d=\"\"}c=d||W(a,c);if(null===c)c=null;else if(0<=q(ba,b)&&(x.test(\"#"\ "\"==c.charAt(0)?c:\"#\"+c)||z(c).length||u&&u[c.toLowerCase()]||y(c).le"\ "ngth)){d=y(c);if(!d.length){a:if(d=z(c),!d.length){d=(d=u[c.toLowerCase"\ "()])?d:\"#\"==\nc.charAt(0)?c:\"#\"+c;if(x.test(d)&&(d=w(d),d=w(d),d=[p"\ "arseInt(d.substr(1,2),16),parseInt(d.substr(3,2),16),parseInt(d.substr("\ "5,2),16)],d.length))break a;d=[]}3==d.length&&d.push(1)}c=4!=d.length?c"\ ":\"rgba(\"+d.join(\", \")+\")\"}return c}var Y=[\"_\"],Z=h;Y[0]in Z||!Z"\ ".execScript||Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.shift"\ "());)Y.length||void 0===X?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=X;; return this._.ap"\ "ply(null,arguments);}.apply({navigator:typeof window!=undefined?window."\ "navigator:null,document:typeof window!=undefined?window.document:null},"\ " arguments);}" GET_IN_VIEW_LOCATION = \ "function(){return function(){function g(a){return function(){return a}}"\ "var h=this;function l(a){return\"string\"==typeof a};var m=window;var n"\ "=Array.prototype;function p(a,b){for(var c=a.length,d=l(a)?a.split(\"\""\ "):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}function aa(a,b){if(a.r"\ "educe)return a.reduce(b,\"\");var c=\"\";p(a,function(d,e){c=b.call(voi"\ "d 0,c,d,e,a)});return c}function ba(a,b,c){return 2>=arguments.length?n"\ ".slice.call(a,b):n.slice.call(a,b,c)};function q(a,b){this.code=a;this."\ "state=r[a]||s;this.message=b||\"\";var c=this.state.replace(/((?:^|\\s+"\ ")[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/g,\""\ "\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";this."\ "name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||\"\"}"\ "(function(){var a=Error;function b(){}b.prototype=a.prototype;q.G=a.pro"\ "totype;q.prototype=new b})();\nvar s=\"unknown error\",r={15:\"element "\ "not selectable\",11:\"element not visible\",31:\"ime engine activation "\ "failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:\"inv"\ "alid element coordinates\",12:\"invalid element state\",32:\"invalid se"\ "lector\",51:\"invalid selector\",52:\"invalid selector\",17:\"javascrip"\ "t error\",405:\"unsupported operation\",34:\"move target out of bounds"\ "\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",23:\""\ "no such window\",28:\"script timeout\",33:\"session not created\",10:\""\ "stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unable to"\ " set cookie\",26:\"unexpected alert open\"};r[13]=s;r[9]=\"unknown comm"\ "and\";q.prototype.toString=function(){return this.name+\": \"+this.mess"\ "age};var t;function u(a,b){this.x=void 0!==a?a:0;this.y=void 0!==b?b:0}"\ "u.prototype.toString=function(){return\"(\"+this.x+\", \"+this.y+\")\"}"\ ";u.prototype.ceil=function(){this.x=Math.ceil(this.x);this.y=Math.ceil("\ "this.y);return this};u.prototype.floor=function(){this.x=Math.floor(thi"\ "s.x);this.y=Math.floor(this.y);return this};u.prototype.round=function("\ "){this.x=Math.round(this.x);this.y=Math.round(this.y);return this};func"\ "tion w(a,b){this.width=a;this.height=b}w.prototype.toString=function(){"\ "return\"(\"+this.width+\" x \"+this.height+\")\"};w.prototype.ceil=func"\ "tion(){this.width=Math.ceil(this.width);this.height=Math.ceil(this.heig"\ "ht);return this};w.prototype.floor=function(){this.width=Math.floor(thi"\ "s.width);this.height=Math.floor(this.height);return this};w.prototype.r"\ "ound=function(){this.width=Math.round(this.width);this.height=Math.roun"\ "d(this.height);return this};function x(a){var b=a.body;a=a.parentWindow"\ "||a.defaultView;return new u(a.pageXOffset||b.scrollLeft,a.pageYOffset|"\ "|b.scrollTop)}function y(a,b){if(a.contains&&1==b.nodeType)return a==b|"\ "|a.contains(b);if(\"undefined\"!=typeof a.compareDocumentPosition)retur"\ "n a==b||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.pare"\ "ntNode;return b==a}\nfunction ca(a,b){if(a==b)return 0;if(a.compareDocu"\ "mentPosition)return a.compareDocumentPosition(b)&2?1:-1;if(\"sourceInde"\ "x\"in a||a.parentNode&&\"sourceIndex\"in a.parentNode){var c=1==a.nodeT"\ "ype,d=1==b.nodeType;if(c&&d)return a.sourceIndex-b.sourceIndex;var e=a."\ "parentNode,f=b.parentNode;return e==f?A(a,b):!c&&y(e,b)?-1*B(a,b):!d&&y"\ "(f,a)?B(b,a):(c?a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:f.sourceI"\ "ndex)}d=C(a);c=d.createRange();c.selectNode(a);c.collapse(!0);d=d.creat"\ "eRange();d.selectNode(b);d.collapse(!0);\nreturn c.compareBoundaryPoint"\ "s(h.Range.START_TO_END,d)}function B(a,b){var c=a.parentNode;if(c==b)re"\ "turn-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return A(d,a)}functi"\ "on A(a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1}fu"\ "nction C(a){return 9==a.nodeType?a:a.ownerDocument||a.document}function"\ " D(a){this.k=a||h.document||document}D.prototype.contains=y;function E("\ "a){var b=null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||null==b?"\ "a.innerText:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9"\ "==c||1==c){a=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],b=\""\ "\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild"\ ");for(;c&&!(a=d[--c].nextSibling););}}else b=a.nodeValue;return\"\"+b}"\ "\nfunction F(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)return!"\ "1}catch(d){return!1}return null==c?!!a.getAttribute(b):a.getAttribute(b"\ ",2)==c}function G(a,b,c,d,e){return da.call(null,a,b,l(c)?c:null,l(d)?d"\ ":null,e||new H)}\nfunction da(a,b,c,d,e){b.getElementsByName&&d&&\"name"\ "\"==c?(b=b.getElementsByName(d),p(b,function(b){a.matches(b)&&e.add(b)}"\ ")):b.getElementsByClassName&&d&&\"class\"==c?(b=b.getElementsByClassNam"\ "e(d),p(b,function(b){b.className==d&&a.matches(b)&&e.add(b)})):b.getEle"\ "mentsByTagName&&(b=b.getElementsByTagName(a.getName()),p(b,function(a){"\ "F(a,c,d)&&e.add(a)}));return e}function ea(a,b,c,d,e){for(b=b.firstChil"\ "d;b;b=b.nextSibling)F(b,c,d)&&a.matches(b)&&e.add(b);return e};function"\ " H(){this.d=this.c=null;this.g=0}function I(a){this.l=a;this.next=this."\ "i=null}H.prototype.unshift=function(a){a=new I(a);a.next=this.c;this.d?"\ "this.c.i=a:this.c=this.d=a;this.c=a;this.g++};H.prototype.add=function("\ "a){a=new I(a);a.i=this.d;this.c?this.d.next=a:this.c=this.d=a;this.d=a;"\ "this.g++};function J(a){return(a=a.c)?a.l:null}function L(a){return new"\ " M(a,!1)}function M(a,b){this.C=a;this.j=(this.m=b)?a.d:a.c;this.p=null"\ "}\nM.prototype.next=function(){var a=this.j;if(null==a)return null;var "\ "b=this.p=a;this.j=this.m?a.i:a.next;return b.l};function N(a,b,c,d,e){b"\ "=b.evaluate(d);c=c.evaluate(d);var f;if(b instanceof H&&c instanceof H)"\ "{e=L(b);for(d=e.next();d;d=e.next())for(b=L(c),f=b.next();f;f=b.next())"\ "if(a(E(d),E(f)))return!0;return!1}if(b instanceof H||c instanceof H){b "\ "instanceof H?e=b:(e=c,c=b);e=L(e);b=typeof c;for(d=e.next();d;d=e.next("\ ")){switch(b){case \"number\":d=+E(d);break;case \"boolean\":d=!!E(d);br"\ "eak;case \"string\":d=E(d);break;default:throw Error(\"Illegal primitiv"\ "e type for comparison.\");}if(a(d,c))return!0}return!1}return e?\n\"boo"\ "lean\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeof b"\ "||\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function O(a,b,c,d){thi"\ "s.q=a;this.F=b;this.n=c;this.o=d}O.prototype.toString=function(){return"\ " this.q};var P={};function Q(a,b,c,d){if(a in P)throw Error(\"Binary op"\ "erator already created: \"+a);a=new O(a,b,c,d);P[a.toString()]=a}Q(\"di"\ "v\",6,1,function(a,b,c){return a.b(c)/b.b(c)});Q(\"mod\",6,1,function(a"\ ",b,c){return a.b(c)%b.b(c)});Q(\"*\",6,1,function(a,b,c){return a.b(c)*"\ "b.b(c)});\nQ(\"+\",5,1,function(a,b,c){return a.b(c)+b.b(c)});Q(\"-\",5"\ ",1,function(a,b,c){return a.b(c)-b.b(c)});Q(\"<\",4,2,function(a,b,c){r"\ "eturn N(function(a,b){return a<b},a,b,c)});Q(\">\",4,2,function(a,b,c){"\ "return N(function(a,b){return a>b},a,b,c)});Q(\"<=\",4,2,function(a,b,c"\ "){return N(function(a,b){return a<=b},a,b,c)});Q(\">=\",4,2,function(a,"\ "b,c){return N(function(a,b){return a>=b},a,b,c)});Q(\"=\",3,2,function("\ "a,b,c){return N(function(a,b){return a==b},a,b,c,!0)});\nQ(\"!=\",3,2,f"\ "unction(a,b,c){return N(function(a,b){return a!=b},a,b,c,!0)});Q(\"and"\ "\",2,2,function(a,b,c){return a.f(c)&&b.f(c)});Q(\"or\",1,2,function(a,"\ "b,c){return a.f(c)||b.f(c)});function R(a,b,c,d,e,f,k,v,z){this.h=a;thi"\ "s.n=b;this.B=c;this.A=d;this.w=e;this.o=f;this.v=k;this.u=void 0!==v?v:"\ "k;this.D=!!z}R.prototype.toString=function(){return this.h};var S={};fu"\ "nction T(a,b,c,d,e,f,k,v){if(a in S)throw Error(\"Function already crea"\ "ted: \"+a+\".\");S[a]=new R(a,b,c,d,!1,e,f,k,v)}T(\"boolean\",2,!1,!1,f"\ "unction(a,b){return b.f(a)},1);T(\"ceiling\",1,!1,!1,function(a,b){retu"\ "rn Math.ceil(b.b(a))},1);\nT(\"concat\",3,!1,!1,function(a,b){var c=ba("\ "arguments,1);return aa(c,function(b,c){return b+c.a(a)})},2,null);T(\"c"\ "ontains\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return-1!=b.indexOf"\ "(a)},2);T(\"count\",1,!1,!1,function(a,b){return b.evaluate(a).g},1,1,!"\ "0);T(\"false\",2,!1,!1,g(!1),0);T(\"floor\",1,!1,!1,function(a,b){retur"\ "n Math.floor(b.b(a))},1);\nT(\"id\",4,!1,!1,function(a,b){var c=a.e(),d"\ "=9==c.nodeType?c:c.ownerDocument,c=b.a(a).split(/\\s+/),e=[];p(c,functi"\ "on(a){a=d.getElementById(a);var b;if(!(b=!a)){a:if(l(e))b=l(a)&&1==a.le"\ "ngth?e.indexOf(a,0):-1;else{for(b=0;b<e.length;b++)if(b in e&&e[b]===a)"\ "break a;b=-1}b=0<=b}b||e.push(a)});e.sort(ca);var f=new H;p(e,function("\ "a){f.add(a)});return f},1);T(\"lang\",2,!1,!1,g(!1),1);T(\"last\",1,!0,"\ "!1,function(a){if(1!=arguments.length)throw Error(\"Function last expec"\ "ts ()\");return a.s()},0);\nT(\"local-name\",3,!1,!0,function(a,b){var "\ "c=b?J(b.evaluate(a)):a.e();return c?c.nodeName.toLowerCase():\"\"},0,1,"\ "!0);T(\"name\",3,!1,!0,function(a,b){var c=b?J(b.evaluate(a)):a.e();ret"\ "urn c?c.nodeName.toLowerCase():\"\"},0,1,!0);T(\"namespace-uri\",3,!0,!"\ "1,g(\"\"),0,1,!0);T(\"normalize-space\",3,!1,!0,function(a,b){return(b?"\ "b.a(a):E(a.e())).replace(/[\\s\\xa0]+/g,\" \").replace(/^\\s+|\\s+$/g,"\ "\"\")},0,1);T(\"not\",2,!1,!1,function(a,b){return!b.f(a)},1);T(\"numbe"\ "r\",1,!1,!0,function(a,b){return b?b.b(a):+E(a.e())},0,1);\nT(\"positio"\ "n\",1,!0,!1,function(a){return a.t()},0);T(\"round\",1,!1,!1,function(a"\ ",b){return Math.round(b.b(a))},1);T(\"starts-with\",2,!1,!1,function(a,"\ "b,c){b=b.a(a);a=c.a(a);return 0==b.lastIndexOf(a,0)},2);T(\"string\",3,"\ "!1,!0,function(a,b){return b?b.a(a):E(a.e())},0,1);T(\"string-length\","\ "1,!1,!0,function(a,b){return(b?b.a(a):E(a.e())).length},0,1);\nT(\"subs"\ "tring\",3,!1,!1,function(a,b,c,d){c=c.b(a);if(isNaN(c)||Infinity==c||-I"\ "nfinity==c)return\"\";d=d?d.b(a):Infinity;if(isNaN(d)||-Infinity===d)re"\ "turn\"\";c=Math.round(c)-1;var e=Math.max(c,0);a=b.a(a);if(Infinity==d)"\ "return a.substring(e);b=Math.round(d);return a.substring(e,c+b)},2,3);T"\ "(\"substring-after\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);c=b.inde"\ "xOf(a);return-1==c?\"\":b.substring(c+a.length)},2);\nT(\"substring-bef"\ "ore\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);a=b.indexOf(a);return-1"\ "==a?\"\":b.substring(0,a)},2);T(\"sum\",1,!1,!1,function(a,b){for(var c"\ "=L(b.evaluate(a)),d=0,e=c.next();e;e=c.next())d+=+E(e);return d},1,1,!0"\ ");T(\"translate\",3,!1,!1,function(a,b,c,d){b=b.a(a);c=c.a(a);var e=d.a"\ "(a);a=[];for(d=0;d<c.length;d++){var f=c.charAt(d);f in a||(a[f]=e.char"\ "At(d))}c=\"\";for(d=0;d<b.length;d++)f=b.charAt(d),c+=f in a?a[f]:f;ret"\ "urn c},3);T(\"true\",2,!1,!1,g(!0),0);function U(a,b,c,d){this.h=a;this"\ ".r=b;this.m=c;this.H=d}U.prototype.toString=function(){return this.h};v"\ "ar V={};function W(a,b,c,d){if(a in V)throw Error(\"Axis already create"\ "d: \"+a);V[a]=new U(a,b,c,!!d)}W(\"ancestor\",function(a,b){for(var c=n"\ "ew H,d=b;d=d.parentNode;)a.matches(d)&&c.unshift(d);return c},!0);W(\"a"\ "ncestor-or-self\",function(a,b){var c=new H,d=b;do a.matches(d)&&c.unsh"\ "ift(d);while(d=d.parentNode);return c},!0);\nW(\"attribute\",function(a"\ ",b){var c=new H,d=a.getName(),e=b.attributes;if(e)if(\"*\"==d)for(var d"\ "=0,f;f=e[d];d++)c.add(f);else(f=e.getNamedItem(d))&&c.add(f);return c},"\ "!1);W(\"child\",function(a,b,c,d,e){return ea.call(null,a,b,l(c)?c:null"\ ",l(d)?d:null,e||new H)},!1,!0);W(\"descendant\",G,!1,!0);W(\"descendant"\ "-or-self\",function(a,b,c,d){var e=new H;F(b,c,d)&&a.matches(b)&&e.add("\ "b);return G(a,b,c,d,e)},!1,!0);\nW(\"following\",function(a,b,c,d){var "\ "e=new H;do for(var f=b;f=f.nextSibling;)F(f,c,d)&&a.matches(f)&&e.add(f"\ "),e=G(a,f,c,d,e);while(b=b.parentNode);return e},!1,!0);W(\"following-s"\ "ibling\",function(a,b){for(var c=new H,d=b;d=d.nextSibling;)a.matches(d"\ ")&&c.add(d);return c},!1);W(\"namespace\",function(){return new H},!1);"\ "W(\"parent\",function(a,b){var c=new H;if(9==b.nodeType)return c;if(2=="\ "b.nodeType)return c.add(b.ownerElement),c;var d=b.parentNode;a.matches("\ "d)&&c.add(d);return c},!1);\nW(\"preceding\",function(a,b,c,d){var e=ne"\ "w H,f=[];do f.unshift(b);while(b=b.parentNode);for(var k=1,v=f.length;k"\ "<v;k++){var z=[];for(b=f[k];b=b.previousSibling;)z.unshift(b);for(var K"\ "=0,fa=z.length;K<fa;K++)b=z[K],F(b,c,d)&&a.matches(b)&&e.add(b),e=G(a,b"\ ",c,d,e)}return e},!0,!0);W(\"preceding-sibling\",function(a,b){for(var "\ "c=new H,d=b;d=d.previousSibling;)a.matches(d)&&c.unshift(d);return c},!"\ "0);W(\"self\",function(a,b){var c=new H;a.matches(b)&&c.add(b);return c"\ "},!1);function X(a,b){var c=b||m,d;d=(c||window).document;d=\"CSS1Compa"\ "t\"==d.compatMode?d.documentElement:d.body;d=new w(d.clientWidth,d.clie"\ "ntHeight);var e=a.x>=d.width?a.x-(d.width-1):0>a.x?a.x:0,f=a.y>=d.heigh"\ "t?a.y-(d.height-1):0>a.y?a.y:0,k;k=c.document?new D(C(c.document)):t||("\ "t=new D);k=x(k.k);0==e&&0==f||c.scrollBy(e,f);c=c.document?new D(C(c.do"\ "cument)):t||(t=new D);c=x(c.k);if(k.x+e!=c.x||k.y+f!=c.y)throw new q(34"\ ",\"The target location (\"+(a.x+k.x)+\", \"+(a.y+k.y)+\") is not on the"\ " webpage.\");c=new u(a.x-\ne,a.y-f);if(0>c.x||c.x>=d.width)throw new q("\ "34,\"The target location (\"+c.x+\", \"+c.y+\") should be within the vi"\ "ewport (\"+d.width+\":\"+d.height+\") after scrolling.\");if(0>c.y||c.y"\ ">=d.height)throw new q(34,\"The target location (\"+c.x+\", \"+c.y+\") "\ "should be within the viewport (\"+d.width+\":\"+d.height+\") after scro"\ "lling.\");return c}var Y=[\"_\"],Z=h;Y[0]in Z||!Z.execScript||Z.execScr"\ "ipt(\"var \"+Y[0]);for(var $;Y.length&&($=Y.shift());)Y.length||void 0="\ "==X?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=X;; return this._.apply(null,arguments);}."\ "apply({navigator:typeof window!=undefined?window.navigator:null,documen"\ "t:typeof window!=undefined?window.document:null}, arguments);}" GET_LOCAL_STORAGE_ITEM = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.getItem=function(a){return this.a.getItem(a)};n.prototype.clear=f"\ "unction(){this.a.clear()};function p(a){if(!m())throw new d(13,\"Local "\ "storage undefined\");return(new n(c.localStorage)).getItem(a)}var q=[\""\ "_\"],r=this;q[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);for(va"\ "r s;q.length&&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]={}:r"\ "[s]=p;; return this._.apply(null,arguments);}.apply({navigator:typeof w"\ "indow!=undefined?window.navigator:null,document:typeof window!=undefine"\ "d?window.document:null}, arguments);}" GET_LOCAL_STORAGE_KEY = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.key=function(a){retu"\ "rn this.a.key(a)};function p(a){if(!m())throw new d(13,\"Local storage "\ "undefined\");return(new n(c.localStorage)).key(a)}var q=[\"_\"],r=this;"\ "q[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);for(var s;q.length"\ "&&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; retu"\ "rn this._.apply(null,arguments);}.apply({navigator:typeof window!=undef"\ "ined?window.navigator:null,document:typeof window!=undefined?window.doc"\ "ument:null}, arguments);}" GET_LOCAL_STORAGE_KEYS = \ "function(){return function(){var d=window;function f(a,e){this.code=a;t"\ "his.state=g[a]||h;this.message=e||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),c=b.length-5;if(0>c||b.indexOf(\"Error\",c)!=c)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function e(){}e.prototype=a.prototype;f.b="\ "a.prototype;f.prototype=new e})();\nvar h=\"unknown error\",g={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};g[13]=h;g[9]=\"unknown "\ "command\";f.prototype.toString=function(){return this.name+\": \"+this."\ "message};var k=this.navigator;var l=-1!=(k&&k.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=d||d;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return l?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new f(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.size=function(){retu"\ "rn this.a.length};n.prototype.key=function(a){return this.a.key(a)};fun"\ "ction p(){var a;if(!m())throw new f(13,\"Local storage undefined\");a=n"\ "ew n(d.localStorage);for(var e=[],b=a.size(),c=0;c<b;c++)e[c]=a.a.key(c"\ ");return e}var q=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript("\ "\"var \"+q[0]);for(var s;q.length&&(s=q.shift());)q.length||void 0===p?"\ "r=r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,arguments);}.appl"\ "y({navigator:typeof window!=undefined?window.navigator:null,document:ty"\ "peof window!=undefined?window.document:null}, arguments);}" GET_LOCAL_STORAGE_SIZE = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.size=function(){retu"\ "rn this.a.length};function p(){if(!m())throw new d(13,\"Local storage u"\ "ndefined\");return(new n(c.localStorage)).size()}var q=[\"_\"],r=this;q"\ "[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);for(var s;q.length&"\ "&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; retur"\ "n this._.apply(null,arguments);}.apply({navigator:typeof window!=undefi"\ "ned?window.navigator:null,document:typeof window!=undefined?window.docu"\ "ment:null}, arguments);}" GET_SESSION_STORAGE_ITEM = \ "function(){return function(){var c=window;function e(a,d){this.code=a;t"\ "his.state=f[a]||g;this.message=d||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function d(){}d.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new d})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.getItem=function(a){return this.a.getItem(a)};n.prototype.clear=f"\ "unction(){this.a.clear()};function p(a){var d;if(m())d=new n(c.sessionS"\ "torage);else throw new e(13,\"Session storage undefined\");return d.get"\ "Item(a)}var q=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript(\"va"\ "r \"+q[0]);for(var s;q.length&&(s=q.shift());)q.length||void 0===p?r=r["\ "s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,arguments);}.apply({n"\ "avigator:typeof window!=undefined?window.navigator:null,document:typeof"\ " window!=undefined?window.document:null}, arguments);}" GET_SESSION_STORAGE_KEY = \ "function(){return function(){var c=window;function e(a,d){this.code=a;t"\ "his.state=f[a]||g;this.message=d||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function d(){}d.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new d})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.key=function(a){retu"\ "rn this.a.key(a)};function p(a){var d;if(m())d=new n(c.sessionStorage);"\ "else throw new e(13,\"Session storage undefined\");return d.key(a)}var "\ "q=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);f"\ "or(var s;q.length&&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]"\ "={}:r[s]=p;; return this._.apply(null,arguments);}.apply({navigator:typ"\ "eof window!=undefined?window.navigator:null,document:typeof window!=und"\ "efined?window.document:null}, arguments);}" GET_SESSION_STORAGE_KEYS = \ "function(){return function(){var d=window;function f(a,e){this.code=a;t"\ "his.state=g[a]||h;this.message=e||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),c=b.length-5;if(0>c||b.indexOf(\"Error\",c)!=c)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function e(){}e.prototype=a.prototype;f.b="\ "a.prototype;f.prototype=new e})();\nvar h=\"unknown error\",g={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};g[13]=h;g[9]=\"unknown "\ "command\";f.prototype.toString=function(){return this.name+\": \"+this."\ "message};var k=this.navigator;var l=-1!=(k&&k.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=d||d;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return l?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new f(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.size=function(){retu"\ "rn this.a.length};n.prototype.key=function(a){return this.a.key(a)};fun"\ "ction p(){var a;if(m())a=new n(d.sessionStorage);else throw new f(13,\""\ "Session storage undefined\");for(var e=[],b=a.size(),c=0;c<b;c++)e[c]=a"\ ".a.key(c);return e}var q=[\"_\"],r=this;q[0]in r||!r.execScript||r.exec"\ "Script(\"var \"+q[0]);for(var s;q.length&&(s=q.shift());)q.length||void"\ " 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,arguments)"\ ";}.apply({navigator:typeof window!=undefined?window.navigator:null,docu"\ "ment:typeof window!=undefined?window.document:null}, arguments);}" GET_SESSION_STORAGE_SIZE = \ "function(){return function(){var c=window;function d(a,g){this.code=a;t"\ "his.state=e[a]||f;this.message=g||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function g(){}g.prototype=a.prototype;d.b="\ "a.prototype;d.prototype=new g})();\nvar f=\"unknown error\",e={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};e[13]=f;e[9]=\"unknown "\ "command\";d.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=c||c;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new d(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.clear=function(){this.a.clear()};n.prototype.size=function(){retu"\ "rn this.a.length};function p(){var a;if(m())a=new n(c.sessionStorage);e"\ "lse throw new d(13,\"Session storage undefined\");return a.size()}var q"\ "=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript(\"var \"+q[0]);fo"\ "r(var s;q.length&&(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]="\ "{}:r[s]=p;; return this._.apply(null,arguments);}.apply({navigator:type"\ "of window!=undefined?window.navigator:null,document:typeof window!=unde"\ "fined?window.document:null}, arguments);}" GET_LOCATION = \ "function(){return function(){var g=this;var h;function k(a,b){this.x=vo"\ "id 0!==a?a:0;this.y=void 0!==b?b:0}k.prototype.toString=function(){retu"\ "rn\"(\"+this.x+\", \"+this.y+\")\"};function l(a){return 9==a.nodeType?"\ "a:a.ownerDocument||a.document}function m(a){this.a=a||g.document||docum"\ "ent};function n(a){var b;a:{b=l(a);if(b.defaultView&&b.defaultView.getC"\ "omputedStyle&&(b=b.defaultView.getComputedStyle(a,null))){b=b.position|"\ "|b.getPropertyValue(\"position\")||\"\";break a}b=\"\"}return b||(a.cur"\ "rentStyle?a.currentStyle.position:null)||a.style&&a.style.position}\nfu"\ "nction p(a){var b=l(a),f=n(a),c=\"fixed\"==f||\"absolute\"==f;for(a=a.p"\ "arentNode;a&&a!=b;a=a.parentNode)if(f=n(a),c=c&&\"static\"==f&&a!=b.doc"\ "umentElement&&a!=b.body,!c&&(a.scrollWidth>a.clientWidth||a.scrollHeigh"\ "t>a.clientHeight||\"fixed\"==f||\"absolute\"==f||\"relative\"==f))retur"\ "n a;return null};function q(a){var b=l(a),f=n(a),c=new k(0,0),e=(b?l(b)"\ ":document).documentElement;if(a==e)return c;if(a.getBoundingClientRect)"\ "{a:{var d;try{d=a.getBoundingClientRect()}catch(u){a={left:0,top:0,righ"\ "t:0,bottom:0};break a}a=d}e=(b?new m(l(b)):h||(h=new m)).a;b=e.body;e=e"\ ".parentWindow||e.defaultView;b=new k(e.pageXOffset||b.scrollLeft,e.page"\ "YOffset||b.scrollTop);c.x=a.left+b.x;c.y=a.top+b.y}else if(b.getBoxObje"\ "ctFor)a=b.getBoxObjectFor(a),b=b.getBoxObjectFor(e),c.x=a.screenX-b.scr"\ "eenX,c.y=a.screenY-b.screenY;\nelse{d=a;do{c.x+=d.offsetLeft;c.y+=d.off"\ "setTop;d!=a&&(c.x+=d.clientLeft||0,c.y+=d.clientTop||0);if(\"fixed\"==n"\ "(d)){c.x+=b.body.scrollLeft;c.y+=b.body.scrollTop;break}d=d.offsetParen"\ "t}while(d&&d!=a);\"absolute\"==f&&(c.y-=b.body.offsetTop);for(d=a;(d=p("\ "d))&&d!=b.body&&d!=e;)c.x-=d.scrollLeft,c.y-=d.scrollTop}return c}var r"\ "=[\"_\"],s=g;r[0]in s||!s.execScript||s.execScript(\"var \"+r[0]);for(v"\ "ar t;r.length&&(t=r.shift());)r.length||void 0===q?s=s[t]?s[t]:s[t]={}:"\ "s[t]=q;; return this._.apply(null,arguments);}.apply({navigator:typeof "\ "window!=undefined?window.navigator:null,document:typeof window!=undefin"\ "ed?window.document:null}, arguments);}" GET_SIZE = \ "function(){return function(){function c(a,b){this.width=a;this.height=b"\ "}c.prototype.toString=function(){return\"(\"+this.width+\" x \"+this.he"\ "ight+\")\"};function d(a){var b=a.offsetWidth,f=a.offsetHeight;if((void"\ " 0===b||!b&&!f)&&a.getBoundingClientRect){a:{var g;try{g=a.getBoundingC"\ "lientRect()}catch(l){a={left:0,top:0,right:0,bottom:0};break a}a=g}retu"\ "rn new c(a.right-a.left,a.bottom-a.top)}return new c(b,f)};function e(a"\ "){var b;a:{b=9==a.nodeType?a:a.ownerDocument||a.document;if(b.defaultVi"\ "ew&&b.defaultView.getComputedStyle&&(b=b.defaultView.getComputedStyle(a"\ ",null))){b=b.display||b.getPropertyValue(\"display\")||\"\";break a}b="\ "\"\"}if(\"none\"!=(b||(a.currentStyle?a.currentStyle.display:null)||a.s"\ "tyle&&a.style.display))return d(a);b=a.style;var f=b.display,g=b.visibi"\ "lity,l=b.position;b.visibility=\"hidden\";b.position=\"absolute\";b.dis"\ "play=\"inline\";a=d(a);b.display=f;b.position=l;b.visibility=g;return a"\ "}\nvar h=[\"_\"],k=this;h[0]in k||!k.execScript||k.execScript(\"var \"+"\ "h[0]);for(var m;h.length&&(m=h.shift());)h.length||void 0===e?k=k[m]?k["\ "m]:k[m]={}:k[m]=e;; return this._.apply(null,arguments);}.apply({naviga"\ "tor:typeof window!=undefined?window.navigator:null,document:typeof wind"\ "ow!=undefined?window.document:null}, arguments);}" GET_TEXT = \ "function(){return function(){function f(a){return function(){return a}}"\ "var k=this;\nfunction l(a){var b=typeof a;if(\"object\"==b)if(a){if(a i"\ "nstanceof Array)return\"array\";if(a instanceof Object)return b;var c=O"\ "bject.prototype.toString.call(a);if(\"[object Window]\"==c)return\"obje"\ "ct\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined"\ "\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.p"\ "ropertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]"\ "\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else r"\ "eturn\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)r"\ "eturn\"object\";return b}function m(a){return\"string\"==typeof a};func"\ "tion aa(a){var b=a.length-1;return 0<=b&&a.indexOf(\" \",b)==b}function"\ " ba(a){return String(a).replace(/\\-([a-z])/g,function(a,c){return c.to"\ "UpperCase()})};var ca=Array.prototype;function p(a,b){for(var c=a.lengt"\ "h,d=m(a)?a.split(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)}fu"\ "nction da(a,b){if(a.reduce)return a.reduce(b,\"\");var c=\"\";p(a,funct"\ "ion(d,e){c=b.call(void 0,c,d,e,a)});return c}function ea(a,b){for(var c"\ "=a.length,d=m(a)?a.split(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void 0,d"\ "[e],e,a))return!0;return!1}\nfunction q(a,b){var c;a:if(m(a))c=m(b)&&1="\ "=b.length?a.indexOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c in a&&a[c]"\ "===b)break a;c=-1}return 0<=c}function fa(a,b,c){return 2>=arguments.le"\ "ngth?ca.slice.call(a,b):ca.slice.call(a,b,c)};var r={aliceblue:\"#f0f8f"\ "f\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",az"\ "ure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\","\ "blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",brow"\ "n:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:\""\ "#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#649"\ "5ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkblu"\ "e:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray:"\ "\"#a9a9a9\",darkgreen:\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki:\"#b"\ "db76b\",darkmagenta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:"\ "\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9"\ "967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray"\ ":\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkvi"\ "olet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:"\ "\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22"\ "222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff"\ "\",gainsboro:\"#dcdcdc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\",gold"\ "enrod:\"#daa520\",gray:\"#808080\",green:\"#008000\",greenyellow:\"#adf"\ "f2f\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianr"\ "ed:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",l"\ "avender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lem"\ "onchiffon:\"#fffacd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",ligh"\ "tcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3"\ "\",lightgreen:\"#90ee90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1\",l"\ "ightsalmon:\"#ffa07a\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#87ce"\ "fa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",lightsteelbl"\ "ue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32"\ "cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediuma"\ "quamarine:\"#66cdaa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",m"\ "ediumpurple:\"#9370db\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7"\ "b68ee\",mediumspringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediu"\ "mvioletred:\"#c71585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",m"\ "istyrose:\"#ffe4e1\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",nav"\ "y:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23"\ "\",orange:\"#ffa500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegold"\ "enrod:\"#eee8aa\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palev"\ "ioletred:\"#db7093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:"\ "\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",pu"\ "rple:\"#800080\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#416"\ "9e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\""\ ",seagreen:\"#2e8b57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",silver:"\ "\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#7080"\ "90\",slategrey:\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",ste"\ "elblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\""\ ",tomato:\"#ff6347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f"\ "5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yel"\ "lowgreen:\"#9acd32\"};var ga=\"background-color border-top-color border"\ "-right-color border-bottom-color border-left-color color outline-color"\ "\".split(\" \"),ha=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;function "\ "ia(a){if(!ja.test(a))throw Error(\"'\"+a+\"' is not a valid hex color\""\ ");4==a.length&&(a=a.replace(ha,\"#$1$1$2$2$3$3\"));return a.toLowerCase"\ "()}var ja=/^#(?:[0-9a-f]{3}){1,2}$/i,ka=/^(?:rgba)?\\((\\d{1,3}),\\s?("\ "\\d{1,3}),\\s?(\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction la(a){var "\ "b=a.match(ka);if(b){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b="\ "Number(b[4]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)re"\ "turn[a,c,d,b]}return[]}var ma=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1-"\ "9]\\d{0,2}),\\s?(0|[1-9]\\d{0,2})\\)$/i;function na(a){var b=a.match(ma"\ ");if(b){a=Number(b[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>="\ "a&&0<=c&&255>=c&&0<=b&&255>=b)return[a,c,b]}return[]};function s(a,b){t"\ "his.code=a;this.state=oa[a]||pa;this.message=b||\"\";var c=this.state.r"\ "eplace(/((?:^|\\s+)[a-z])/g,function(a){return a.toUpperCase().replace("\ "/^[\\s\\xa0]+/g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)"\ "c+=\"Error\";this.name=c;c=Error(this.message);c.name=this.name;this.st"\ "ack=c.stack||\"\"}(function(){var a=Error;function b(){}b.prototype=a.p"\ "rototype;s.U=a.prototype;s.prototype=new b})();\nvar pa=\"unknown error"\ "\",oa={15:\"element not selectable\",11:\"element not visible\",31:\"im"\ "e engine activation failed\",30:\"ime not available\",24:\"invalid cook"\ "ie domain\",29:\"invalid element coordinates\",12:\"invalid element sta"\ "te\",32:\"invalid selector\",51:\"invalid selector\",52:\"invalid selec"\ "tor\",17:\"javascript error\",405:\"unsupported operation\",34:\"move t"\ "arget out of bounds\",27:\"no such alert\",7:\"no such element\",8:\"no"\ " such frame\",23:\"no such window\",28:\"script timeout\",33:\"session "\ "not created\",10:\"stale element reference\",\n0:\"success\",21:\"timeo"\ "ut\",25:\"unable to set cookie\",26:\"unexpected alert open\"};oa[13]=p"\ "a;oa[9]=\"unknown command\";s.prototype.toString=function(){return this"\ ".name+\": \"+this.message};var t,v,w,qa=k.navigator;w=qa&&qa.platform||"\ "\"\";t=-1!=w.indexOf(\"Mac\");v=-1!=w.indexOf(\"Win\");var x=-1!=w.inde"\ "xOf(\"Linux\");var y;function z(a,b){this.x=void 0!==a?a:0;this.y=void "\ "0!==b?b:0}z.prototype.toString=function(){return\"(\"+this.x+\", \"+thi"\ "s.y+\")\"};z.prototype.ceil=function(){this.x=Math.ceil(this.x);this.y="\ "Math.ceil(this.y);return this};z.prototype.floor=function(){this.x=Math"\ ".floor(this.x);this.y=Math.floor(this.y);return this};z.prototype.round"\ "=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);return "\ "this};function B(a,b){this.width=a;this.height=b}B.prototype.toString=f"\ "unction(){return\"(\"+this.width+\" x \"+this.height+\")\"};B.prototype"\ ".ceil=function(){this.width=Math.ceil(this.width);this.height=Math.ceil"\ "(this.height);return this};B.prototype.floor=function(){this.width=Math"\ ".floor(this.width);this.height=Math.floor(this.height);return this};B.p"\ "rototype.round=function(){this.width=Math.round(this.width);this.height"\ "=Math.round(this.height);return this};var ra=3;function sa(a){for(;a&&1"\ "!=a.nodeType;)a=a.previousSibling;return a}function ta(a,b){if(a.contai"\ "ns&&1==b.nodeType)return a==b||a.contains(b);if(\"undefined\"!=typeof a"\ ".compareDocumentPosition)return a==b||Boolean(a.compareDocumentPosition"\ "(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction ua(a,b){if("\ "a==b)return 0;if(a.compareDocumentPosition)return a.compareDocumentPosi"\ "tion(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"sourceIndex\"in "\ "a.parentNode){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return a.sour"\ "ceIndex-b.sourceIndex;var e=a.parentNode,g=b.parentNode;return e==g?va("\ "a,b):!c&&ta(e,b)?-1*wa(a,b):!d&&ta(g,a)?wa(b,a):(c?a.sourceIndex:e.sour"\ "ceIndex)-(d?b.sourceIndex:g.sourceIndex)}d=C(a);c=d.createRange();c.sel"\ "ectNode(a);c.collapse(!0);d=d.createRange();d.selectNode(b);\nd.collaps"\ "e(!0);return c.compareBoundaryPoints(k.Range.START_TO_END,d)}function w"\ "a(a,b){var c=a.parentNode;if(c==b)return-1;for(var d=b;d.parentNode!=c;"\ ")d=d.parentNode;return va(d,a)}function va(a,b){for(var c=b;c=c.previou"\ "sSibling;)if(c==a)return-1;return 1}function C(a){return 9==a.nodeType?"\ "a:a.ownerDocument||a.document}function xa(a,b){a=a.parentNode;for(var c"\ "=0;a;){if(b(a))return a;a=a.parentNode;c++}return null}function D(a){th"\ "is.B=a||k.document||document}\nfunction ya(a){var b=a.B;a=b.body;b=b.pa"\ "rentWindow||b.defaultView;return new z(b.pageXOffset||a.scrollLeft,b.pa"\ "geYOffset||a.scrollTop)}D.prototype.contains=ta;function E(a){var b=nul"\ "l,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerText:"\ "b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c){a"\ "=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do 1!="\ "a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&&!(a"\ "=d[--c].nextSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction F(a"\ ",b,c){if(null===b)return!0;try{if(!a.getAttribute)return!1}catch(d){ret"\ "urn!1}return null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}functio"\ "n G(a,b,c,d,e){return za.call(null,a,b,m(c)?c:null,m(d)?d:null,e||new H"\ ")}\nfunction za(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b.get"\ "ElementsByName(d),p(b,function(b){a.matches(b)&&e.add(b)})):b.getElemen"\ "tsByClassName&&d&&\"class\"==c?(b=b.getElementsByClassName(d),p(b,funct"\ "ion(b){b.className==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagName"\ "&&(b=b.getElementsByTagName(a.getName()),p(b,function(a){F(a,c,d)&&e.ad"\ "d(a)}));return e}function Aa(a,b,c,d,e){for(b=b.firstChild;b;b=b.nextSi"\ "bling)F(b,c,d)&&a.matches(b)&&e.add(b);return e};function H(){this.g=th"\ "is.f=null;this.m=0}function Ba(a){this.t=a;this.next=this.o=null}H.prot"\ "otype.unshift=function(a){a=new Ba(a);a.next=this.f;this.g?this.f.o=a:t"\ "his.f=this.g=a;this.f=a;this.m++};H.prototype.add=function(a){a=new Ba("\ "a);a.o=this.g;this.f?this.g.next=a:this.f=this.g=a;this.g=a;this.m++};f"\ "unction Ca(a){return(a=a.f)?a.t:null}function I(a){return new Da(a,!1)}"\ "function Da(a,b){this.Q=a;this.q=(this.u=b)?a.g:a.f;this.C=null}\nDa.pr"\ "ototype.next=function(){var a=this.q;if(null==a)return null;var b=this."\ "C=a;this.q=this.u?a.o:a.next;return b.t};function J(a,b,c,d,e){b=b.eval"\ "uate(d);c=c.evaluate(d);var g;if(b instanceof H&&c instanceof H){e=I(b)"\ ";for(d=e.next();d;d=e.next())for(b=I(c),g=b.next();g;g=b.next())if(a(E("\ "d),E(g)))return!0;return!1}if(b instanceof H||c instanceof H){b instanc"\ "eof H?e=b:(e=c,c=b);e=I(e);b=typeof c;for(d=e.next();d;d=e.next()){swit"\ "ch(b){case \"number\":d=+E(d);break;case \"boolean\":d=!!E(d);break;cas"\ "e \"string\":d=E(d);break;default:throw Error(\"Illegal primitive type "\ "for comparison.\");}if(a(d,c))return!0}return!1}return e?\n\"boolean\"="\ "=typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeof b||\"num"\ "ber\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function Ea(a,b,c,d){this.D=a;"\ "this.S=b;this.A=c;this.k=d}Ea.prototype.toString=function(){return this"\ ".D};var Fa={};function K(a,b,c,d){if(a in Fa)throw Error(\"Binary opera"\ "tor already created: \"+a);a=new Ea(a,b,c,d);Fa[a.toString()]=a}K(\"div"\ "\",6,1,function(a,b,c){return a.d(c)/b.d(c)});K(\"mod\",6,1,function(a,"\ "b,c){return a.d(c)%b.d(c)});K(\"*\",6,1,function(a,b,c){return a.d(c)*b"\ ".d(c)});\nK(\"+\",5,1,function(a,b,c){return a.d(c)+b.d(c)});K(\"-\",5,"\ "1,function(a,b,c){return a.d(c)-b.d(c)});K(\"<\",4,2,function(a,b,c){re"\ "turn J(function(a,b){return a<b},a,b,c)});K(\">\",4,2,function(a,b,c){r"\ "eturn J(function(a,b){return a>b},a,b,c)});K(\"<=\",4,2,function(a,b,c)"\ "{return J(function(a,b){return a<=b},a,b,c)});K(\">=\",4,2,function(a,b"\ ",c){return J(function(a,b){return a>=b},a,b,c)});K(\"=\",3,2,function(a"\ ",b,c){return J(function(a,b){return a==b},a,b,c,!0)});\nK(\"!=\",3,2,fu"\ "nction(a,b,c){return J(function(a,b){return a!=b},a,b,c,!0)});K(\"and\""\ ",2,2,function(a,b,c){return a.j(c)&&b.j(c)});K(\"or\",1,2,function(a,b,"\ "c){return a.j(c)||b.j(c)});function Ga(a,b,c,d,e,g,h,u,n){this.n=a;this"\ ".A=b;this.P=c;this.O=d;this.N=e;this.k=g;this.M=h;this.L=void 0!==u?u:h"\ ";this.R=!!n}Ga.prototype.toString=function(){return this.n};var Ha={};f"\ "unction L(a,b,c,d,e,g,h,u){if(a in Ha)throw Error(\"Function already cr"\ "eated: \"+a+\".\");Ha[a]=new Ga(a,b,c,d,!1,e,g,h,u)}L(\"boolean\",2,!1,"\ "!1,function(a,b){return b.j(a)},1);L(\"ceiling\",1,!1,!1,function(a,b){"\ "return Math.ceil(b.d(a))},1);\nL(\"concat\",3,!1,!1,function(a,b){var c"\ "=fa(arguments,1);return da(c,function(b,c){return b+c.c(a)})},2,null);L"\ "(\"contains\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return-1!=b.ind"\ "exOf(a)},2);L(\"count\",1,!1,!1,function(a,b){return b.evaluate(a).m},1"\ ",1,!0);L(\"false\",2,!1,!1,f(!1),0);L(\"floor\",1,!1,!1,function(a,b){r"\ "eturn Math.floor(b.d(a))},1);\nL(\"id\",4,!1,!1,function(a,b){var c=a.h"\ "(),d=9==c.nodeType?c:c.ownerDocument,c=b.c(a).split(/\\s+/),e=[];p(c,fu"\ "nction(a){(a=d.getElementById(a))&&!q(e,a)&&e.push(a)});e.sort(ua);var "\ "g=new H;p(e,function(a){g.add(a)});return g},1);L(\"lang\",2,!1,!1,f(!1"\ "),1);L(\"last\",1,!0,!1,function(a){if(1!=arguments.length)throw Error("\ "\"Function last expects ()\");return a.I()},0);L(\"local-name\",3,!1,!0"\ ",function(a,b){var c=b?Ca(b.evaluate(a)):a.h();return c?c.nodeName.toLo"\ "werCase():\"\"},0,1,!0);\nL(\"name\",3,!1,!0,function(a,b){var c=b?Ca(b"\ ".evaluate(a)):a.h();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);L("\ "\"namespace-uri\",3,!0,!1,f(\"\"),0,1,!0);L(\"normalize-space\",3,!1,!0"\ ",function(a,b){return(b?b.c(a):E(a.h())).replace(/[\\s\\xa0]+/g,\" \")."\ "replace(/^\\s+|\\s+$/g,\"\")},0,1);L(\"not\",2,!1,!1,function(a,b){retu"\ "rn!b.j(a)},1);L(\"number\",1,!1,!0,function(a,b){return b?b.d(a):+E(a.h"\ "())},0,1);L(\"position\",1,!0,!1,function(a){return a.J()},0);L(\"round"\ "\",1,!1,!1,function(a,b){return Math.round(b.d(a))},1);\nL(\"starts-wit"\ "h\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return 0==b.lastIndexOf(a"\ ",0)},2);L(\"string\",3,!1,!0,function(a,b){return b?b.c(a):E(a.h())},0,"\ "1);L(\"string-length\",1,!1,!0,function(a,b){return(b?b.c(a):E(a.h()))."\ "length},0,1);\nL(\"substring\",3,!1,!1,function(a,b,c,d){c=c.d(a);if(is"\ "NaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.d(a):Infinity;if(isN"\ "aN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max(c,0);a"\ "=b.c(a);if(Infinity==d)return a.substring(e);b=Math.round(d);return a.s"\ "ubstring(e,c+b)},2,3);L(\"substring-after\",3,!1,!1,function(a,b,c){b=b"\ ".c(a);a=c.c(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.length)}"\ ",2);\nL(\"substring-before\",3,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);"\ "a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);L(\"sum\",1,!1,!1,"\ "function(a,b){for(var c=I(b.evaluate(a)),d=0,e=c.next();e;e=c.next())d+"\ "=+E(e);return d},1,1,!0);L(\"translate\",3,!1,!1,function(a,b,c,d){b=b."\ "c(a);c=c.c(a);var e=d.c(a);a=[];for(d=0;d<c.length;d++){var g=c.charAt("\ "d);g in a||(a[g]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d++)g=b.charAt("\ "d),c+=g in a?a[g]:g;return c},3);L(\"true\",2,!1,!1,f(!0),0);function I"\ "a(a,b,c,d){this.n=a;this.H=b;this.u=c;this.V=d}Ia.prototype.toString=fu"\ "nction(){return this.n};var Ja={};function M(a,b,c,d){if(a in Ja)throw "\ "Error(\"Axis already created: \"+a);Ja[a]=new Ia(a,b,c,!!d)}M(\"ancesto"\ "r\",function(a,b){for(var c=new H,d=b;d=d.parentNode;)a.matches(d)&&c.u"\ "nshift(d);return c},!0);M(\"ancestor-or-self\",function(a,b){var c=new "\ "H,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c},!0)"\ ";\nM(\"attribute\",function(a,b){var c=new H,d=a.getName(),e=b.attribut"\ "es;if(e)if(\"*\"==d)for(var d=0,g;g=e[d];d++)c.add(g);else(g=e.getNamed"\ "Item(d))&&c.add(g);return c},!1);M(\"child\",function(a,b,c,d,e){return"\ " Aa.call(null,a,b,m(c)?c:null,m(d)?d:null,e||new H)},!1,!0);M(\"descend"\ "ant\",G,!1,!0);M(\"descendant-or-self\",function(a,b,c,d){var e=new H;F"\ "(b,c,d)&&a.matches(b)&&e.add(b);return G(a,b,c,d,e)},!1,!0);\nM(\"follo"\ "wing\",function(a,b,c,d){var e=new H;do for(var g=b;g=g.nextSibling;)F("\ "g,c,d)&&a.matches(g)&&e.add(g),e=G(a,g,c,d,e);while(b=b.parentNode);ret"\ "urn e},!1,!0);M(\"following-sibling\",function(a,b){for(var c=new H,d=b"\ ";d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);M(\"namespace\","\ "function(){return new H},!1);M(\"parent\",function(a,b){var c=new H;if("\ "9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerElement),c;"\ "var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nM(\"preceding"\ "\",function(a,b,c,d){var e=new H,g=[];do g.unshift(b);while(b=b.parentN"\ "ode);for(var h=1,u=g.length;h<u;h++){var n=[];for(b=g[h];b=b.previousSi"\ "bling;)n.unshift(b);for(var A=0,Ya=n.length;A<Ya;A++)b=n[A],F(b,c,d)&&a"\ ".matches(b)&&e.add(b),e=G(a,b,c,d,e)}return e},!0,!0);M(\"preceding-sib"\ "ling\",function(a,b){for(var c=new H,d=b;d=d.previousSibling;)a.matches"\ "(d)&&c.unshift(d);return c},!0);M(\"self\",function(a,b){var c=new H;a."\ "matches(b)&&c.add(b);return c},!1);var N={};N.v=function(){var a={W:\"h"\ "ttp://www.w3.org/2000/svg\"};return function(b){return a[b]||null}}();N"\ ".k=function(a,b,c){var d=C(a);try{var e=d.createNSResolver?d.createNSRe"\ "solver(d.documentElement):N.v;return d.evaluate(b,a,e,c,null)}catch(g){"\ "throw new s(32,\"Unable to locate an element with the xpath expression "\ "\"+b+\" because of the following error:\\n\"+g);}};N.p=function(a,b){if"\ "(!a||1!=a.nodeType)throw new s(32,'The result of the xpath expression "\ "\"'+b+'\" is: '+a+\". It should be an element.\");};\nN.F=function(a,b)"\ "{var c=function(){var c=N.k(b,a,9);return c?c.singleNodeValue||null:b.s"\ "electSingleNode?(c=C(b),c.setProperty&&c.setProperty(\"SelectionLanguag"\ "e\",\"XPath\"),b.selectSingleNode(a)):null}();null===c||N.p(c,a);return"\ " c};\nN.K=function(a,b){var c=function(){var c=N.k(b,a,7);if(c){for(var"\ " e=c.snapshotLength,g=[],h=0;h<e;++h)g.push(c.snapshotItem(h));return g"\ "}return b.selectNodes?(c=C(b),c.setProperty&&c.setProperty(\"SelectionL"\ "anguage\",\"XPath\"),b.selectNodes(a)):[]}();p(c,function(b){N.p(b,a)})"\ ";return c};function O(a,b,c,d){this.left=a;this.top=b;this.width=c;this"\ ".height=d}O.prototype.toString=function(){return\"(\"+this.left+\", \"+"\ "this.top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};O.prototype.co"\ "ntains=function(a){return a instanceof O?this.left<=a.left&&this.left+t"\ "his.width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a.top"\ "+a.height:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&a.y"\ "<=this.top+this.height};\nO.prototype.ceil=function(){this.left=Math.ce"\ "il(this.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.wi"\ "dth);this.height=Math.ceil(this.height);return this};O.prototype.floor="\ "function(){this.left=Math.floor(this.left);this.top=Math.floor(this.top"\ ");this.width=Math.floor(this.width);this.height=Math.floor(this.height)"\ ";return this};\nO.prototype.round=function(){this.left=Math.round(this."\ "left);this.top=Math.round(this.top);this.width=Math.round(this.width);t"\ "his.height=Math.round(this.height);return this};function Ka(a,b){var c="\ "C(a);return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.default"\ "View.getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||\"\":\"\"}f"\ "unction P(a){return Ka(a,\"position\")||(a.currentStyle?a.currentStyle."\ "position:null)||a.style&&a.style.position}function La(a){var b;try{b=a."\ "getBoundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}"\ "return b}\nfunction Ma(a){var b=C(a),c=P(a),d=\"fixed\"==c||\"absolute"\ "\"==c;for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=P(a),d=d&&\"static"\ "\"==c&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clientWidth"\ "||a.scrollHeight>a.clientHeight||\"fixed\"==c||\"absolute\"==c||\"relat"\ "ive\"==c))return a;return null}\nfunction Na(a){if(1==a.nodeType){var b"\ ";if(a.getBoundingClientRect)b=La(a),b=new z(b.left,b.top);else{b=ya(a?n"\ "ew D(C(a)):y||(y=new D));var c=C(a),d=P(a),e=new z(0,0),g=(c?C(c):docum"\ "ent).documentElement;if(a!=g)if(a.getBoundingClientRect)a=La(a),c=ya(c?"\ "new D(C(c)):y||(y=new D)),e.x=a.left+c.x,e.y=a.top+c.y;else if(c.getBox"\ "ObjectFor)a=c.getBoxObjectFor(a),c=c.getBoxObjectFor(g),e.x=a.screenX-c"\ ".screenX,e.y=a.screenY-c.screenY;else{var h=a;do{e.x+=h.offsetLeft;e.y+"\ "=h.offsetTop;h!=a&&(e.x+=h.clientLeft||\n0,e.y+=h.clientTop||0);if(\"fi"\ "xed\"==P(h)){e.x+=c.body.scrollLeft;e.y+=c.body.scrollTop;break}h=h.off"\ "setParent}while(h&&h!=a);\"absolute\"==d&&(e.y-=c.body.offsetTop);for(h"\ "=a;(h=Ma(h))&&h!=c.body&&h!=g;)e.x-=h.scrollLeft,e.y-=h.scrollTop}b=new"\ " z(e.x-b.x,e.y-b.y)}return b}b=\"function\"==l(a.r);e=a;a.targetTouches"\ "?e=a.targetTouches[0]:b&&a.r().targetTouches&&(e=a.r().targetTouches[0]"\ ");return new z(e.clientX,e.clientY)};function Q(a,b){return!!a&&1==a.no"\ "deType&&(!b||a.tagName.toUpperCase()==b)}function R(a){for(a=a.parentNo"\ "de;a&&1!=a.nodeType&&9!=a.nodeType&&11!=a.nodeType;)a=a.parentNode;retu"\ "rn Q(a)?a:null}\nfunction S(a,b){var c=ba(b);if(\"float\"==c||\"cssFloa"\ "t\"==c||\"styleFloat\"==c)c=\"cssFloat\";c=Ka(a,c)||Oa(a,c);if(null===c"\ ")c=null;else if(q(ga,b)&&(ja.test(\"#\"==c.charAt(0)?c:\"#\"+c)||na(c)."\ "length||r&&r[c.toLowerCase()]||la(c).length)){var d=la(c);if(!d.length)"\ "{a:if(d=na(c),!d.length){d=(d=r[c.toLowerCase()])?d:\"#\"==c.charAt(0)?"\ "c:\"#\"+c;if(ja.test(d)&&(d=ia(d),d=ia(d),d=[parseInt(d.substr(1,2),16)"\ ",parseInt(d.substr(3,2),16),parseInt(d.substr(5,2),16)],d.length))break"\ " a;d=[]}3==d.length&&d.push(1)}c=4!=d.length?\nc:\"rgba(\"+d.join(\", "\ "\")+\")\"}return c}function Oa(a,b){var c=a.currentStyle||a.style,d=c[b"\ "];void 0===d&&\"function\"==l(c.getPropertyValue)&&(d=c.getPropertyValu"\ "e(b));return\"inherit\"!=d?void 0!==d?d:null:(c=R(a))?Oa(c,b):null}\nfu"\ "nction Pa(a,b){function c(a){if(\"none\"==S(a,\"display\"))return!1;a=R"\ "(a);return!a||c(a)}function d(a){var b=T(a);return 0<b.height&&0<b.widt"\ "h?!0:Q(a,\"PATH\")&&(0<b.height||0<b.width)?(a=S(a,\"stroke-width\"),!!"\ "a&&0<parseInt(a,10)):\"hidden\"!=S(a,\"overflow\")&&ea(a.childNodes,fun"\ "ction(a){return a.nodeType==ra||Q(a)&&d(a)})}function e(a){var b=S(a,\""\ "-o-transform\")||S(a,\"-webkit-transform\")||S(a,\"-ms-transform\")||S("\ "a,\"-moz-transform\")||S(a,\"transform\");if(b&&\"none\"!==b)return b=N"\ "a(a),a=T(a),0<=b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=R(a);return!a||e("\ "a)}if(!Q(a))throw Error(\"Argument to isShown must be of type Element\""\ ");if(Q(a,\"OPTION\")||Q(a,\"OPTGROUP\")){var g=xa(a,function(a){return "\ "Q(a,\"SELECT\")});return!!g&&Pa(g,!0)}return(g=Qa(a))?!!g.s&&0<g.rect.w"\ "idth&&0<g.rect.height&&Pa(g.s,b):Q(a,\"INPUT\")&&\"hidden\"==a.type.toL"\ "owerCase()||Q(a,\"NOSCRIPT\")||\"hidden\"==S(a,\"visibility\")||!c(a)||"\ "!b&&0==Ra(a)||!d(a)||Sa(a)==U?!1:e(a)}var U=\"hidden\";\nfunction Sa(a)"\ "{function b(a){var b=a;if(\"visible\"==u)if(a==g)b=h;else if(a==h)retur"\ "n{x:\"visible\",y:\"visible\"};b={x:S(b,\"overflow-x\"),y:S(b,\"overflo"\ "w-y\")};a==g&&(b.x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"hidden\"=="\ "b.y?\"hidden\":\"auto\");return b}function c(a){var b=S(a,\"position\")"\ ";if(\"fixed\"==b)return g;for(a=R(a);a&&a!=g&&(0==S(a,\"display\").last"\ "IndexOf(\"inline\",0)||\"absolute\"==b&&\"static\"==S(a,\"position\"));"\ ")a=R(a);return a}var d=T(a),e=C(a),g=e.documentElement,h=e.body,u=S(g,"\ "\"overflow\");for(a=c(a);a;a=\nc(a)){var n=T(a),e=b(a),A=d.left>=n.left"\ "+n.width,n=d.top>=n.top+n.height;if(A&&\"hidden\"==e.x||n&&\"hidden\"=="\ "e.y)return U;if(A&&\"visible\"!=e.x||n&&\"visible\"!=e.y)return Sa(a)=="\ "U?U:\"scroll\"}return\"none\"}\nfunction T(a){var b=Qa(a);if(b)return b"\ ".rect;if(\"function\"==l(a.getBBox))try{var c=a.getBBox();return new O("\ "c.x,c.y,c.width,c.height)}catch(d){throw d;}else{if(Q(a,\"HTML\"))retur"\ "n a=((C(a)?C(a).parentWindow||C(a).defaultView:window)||window).documen"\ "t,a=\"CSS1Compat\"==a.compatMode?a.documentElement:a.body,a=new B(a.cli"\ "entWidth,a.clientHeight),new O(0,0,a.width,a.height);var b=Na(a),c=a.of"\ "fsetWidth,e=a.offsetHeight;c||(e||!a.getBoundingClientRect)||(a=a.getBo"\ "undingClientRect(),c=a.right-a.left,e=a.bottom-\na.top);return new O(b."\ "x,b.y,c,e)}}function Qa(a){var b=Q(a,\"MAP\");if(!b&&!Q(a,\"AREA\"))ret"\ "urn null;var c=b?a:Q(a.parentNode,\"MAP\")?a.parentNode:null,d=null,e=n"\ "ull;if(c&&c.name&&(d=N.F('/descendant::*[@usemap = \"#'+c.name+'\"]',C("\ "c)))&&(e=T(d),!b&&\"default\"!=a.shape.toLowerCase())){var g=Ta(a);a=Ma"\ "th.min(Math.max(g.left,0),e.width);b=Math.min(Math.max(g.top,0),e.heigh"\ "t);c=Math.min(g.width,e.width-a);g=Math.min(g.height,e.height-b);e=new "\ "O(a+e.left,b+e.top,c,g)}return{s:d,rect:e||new O(0,0,0,0)}}\nfunction T"\ "a(a){var b=a.shape.toLowerCase();a=a.coords.split(\",\");if(\"rect\"==b"\ "&&4==a.length){var b=a[0],c=a[1];return new O(b,c,a[2]-b,a[3]-c)}if(\"c"\ "ircle\"==b&&3==a.length)return b=a[2],new O(a[0]-b,a[1]-b,2*b,2*b);if("\ "\"poly\"==b&&2<a.length){for(var b=a[0],c=a[1],d=b,e=c,g=2;g+1<a.length"\ ";g+=2)b=Math.min(b,a[g]),d=Math.max(d,a[g]),c=Math.min(c,a[g+1]),e=Math"\ ".max(e,a[g+1]);return new O(b,c,d-b,e-c)}return new O(0,0,0,0)}function"\ " Ua(a){return a.replace(/^[^\\S\\xa0]+|[^\\S\\xa0]+$/g,\"\")}\nfunction"\ " Va(a,b){if(Q(a,\"BR\"))b.push(\"\");else{var c=Q(a,\"TD\"),d=S(a,\"dis"\ "play\"),e=!c&&!q(Wa,d),g=void 0!=a.previousElementSibling?a.previousEle"\ "mentSibling:sa(a.previousSibling),g=g?S(g,\"display\"):\"\",h=S(a,\"flo"\ "at\")||S(a,\"cssFloat\")||S(a,\"styleFloat\");!e||(\"run-in\"==g&&\"non"\ "e\"==h||/^[\\s\\xa0]*$/.test(b[b.length-1]||\"\"))||b.push(\"\");var u="\ "Pa(a),n=null,A=null;u&&(n=S(a,\"white-space\"),A=S(a,\"text-transform\""\ "));p(a.childNodes,function(a){a.nodeType==ra&&u?Xa(a,b,n,A):Q(a)&&Va(a,"\ "b)});g=b[b.length-1]||\"\";!c&&\n\"table-cell\"!=d||(!g||aa(g))||(b[b.l"\ "ength-1]+=\" \");e&&(\"run-in\"!=d&&!/^[\\s\\xa0]*$/.test(g))&&b.push("\ "\"\")}}var Wa=\"inline inline-block inline-table none table-cell table-"\ "column table-column-group\".split(\" \");\nfunction Xa(a,b,c,d){a=a.nod"\ "eValue.replace(/\\u200b/g,\"\");a=a.replace(/(\\r\\n|\\r|\\n)/g,\"\\n\""\ ");if(\"normal\"==c||\"nowrap\"==c)a=a.replace(/\\n/g,\" \");a=\"pre\"=="\ "c||\"pre-wrap\"==c?a.replace(/[ \\f\\t\\v\\u2028\\u2029]/g,\"\\u00a0\")"\ ":a.replace(/[\\ \\f\\t\\v\\u2028\\u2029]+/g,\" \");\"capitalize\"==d?a="\ "a.replace(/(^|\\s)(\\S)/g,function(a,b,c){return b+c.toUpperCase()}):\""\ "uppercase\"==d?a=a.toUpperCase():\"lowercase\"==d&&(a=a.toLowerCase());"\ "c=b.pop()||\"\";aa(c)&&0==a.lastIndexOf(\" \",0)&&(a=a.substr(1));b.pus"\ "h(c+a)}\nfunction Ra(a){var b=1,c=S(a,\"opacity\");c&&(b=Number(c));(a="\ "R(a))&&(b*=Ra(a));return b};function V(a,b){this.i={};this.e=[];var c=a"\ "rguments.length;if(1<c){if(c%2)throw Error(\"Uneven number of arguments"\ "\");for(var d=0;d<c;d+=2)this.set(arguments[d],arguments[d+1])}else if("\ "a){var e;if(a instanceof V)for(d=Za(a),$a(a),e=[],c=0;c<a.e.length;c++)"\ "e.push(a.i[a.e[c]]);else{var c=[],g=0;for(d in a)c[g++]=d;d=c;c=[];g=0;"\ "for(e in a)c[g++]=a[e];e=c}for(c=0;c<d.length;c++)this.set(d[c],e[c])}}"\ "V.prototype.l=0;V.prototype.G=0;function Za(a){$a(a);return a.e.concat("\ ")}\nfunction $a(a){if(a.l!=a.e.length){for(var b=0,c=0;b<a.e.length;){v"\ "ar d=a.e[b];Object.prototype.hasOwnProperty.call(a.i,d)&&(a.e[c++]=d);b"\ "++}a.e.length=c}if(a.l!=a.e.length){for(var e={},c=b=0;b<a.e.length;)d="\ "a.e[b],Object.prototype.hasOwnProperty.call(e,d)||(a.e[c++]=d,e[d]=1),b"\ "++;a.e.length=c}}V.prototype.get=function(a,b){return Object.prototype."\ "hasOwnProperty.call(this.i,a)?this.i[a]:b};\nV.prototype.set=function(a"\ ",b){Object.prototype.hasOwnProperty.call(this.i,a)||(this.l++,this.e.pu"\ "sh(a),this.G++);this.i[a]=b};var ab={};function W(a,b,c){var d=typeof a"\ ";(\"object\"==d&&null!=a||\"function\"==d)&&(a=a.a);a=new bb(a,b,c);!b|"\ "|b in ab&&!c||(ab[b]={key:a,shift:!1},c&&(ab[c]={key:a,shift:!0}));retu"\ "rn a}function bb(a,b,c){this.code=a;this.w=b||null;this.T=c||this.w}W(8"\ ");W(9);W(13);var cb=W(16),db=W(17),eb=W(18);W(19);W(20);W(27);W(32,\" "\ "\");W(33);W(34);W(35);W(36);W(37);W(38);W(39);W(40);W(44);W(45);W(46);W"\ "(48,\"0\",\")\");W(49,\"1\",\"!\");W(50,\"2\",\"@\");W(51,\"3\",\"#\");"\ "W(52,\"4\",\"$\");W(53,\"5\",\"%\");W(54,\"6\",\"^\");W(55,\"7\",\"&\")"\ ";\nW(56,\"8\",\"*\");W(57,\"9\",\"(\");W(65,\"a\",\"A\");W(66,\"b\",\"B"\ "\");W(67,\"c\",\"C\");W(68,\"d\",\"D\");W(69,\"e\",\"E\");W(70,\"f\",\""\ "F\");W(71,\"g\",\"G\");W(72,\"h\",\"H\");W(73,\"i\",\"I\");W(74,\"j\","\ "\"J\");W(75,\"k\",\"K\");W(76,\"l\",\"L\");W(77,\"m\",\"M\");W(78,\"n\""\ ",\"N\");W(79,\"o\",\"O\");W(80,\"p\",\"P\");W(81,\"q\",\"Q\");W(82,\"r"\ "\",\"R\");W(83,\"s\",\"S\");W(84,\"t\",\"T\");W(85,\"u\",\"U\");W(86,\""\ "v\",\"V\");W(87,\"w\",\"W\");W(88,\"x\",\"X\");W(89,\"y\",\"Y\");W(90,"\ "\"z\",\"Z\");var fb=W(v?{b:91,a:91,opera:219}:t?{b:224,a:91,opera:17}:{"\ "b:0,a:91,opera:null});\nW(v?{b:92,a:92,opera:220}:t?{b:224,a:93,opera:1"\ "7}:{b:0,a:92,opera:null});W(v?{b:93,a:93,opera:0}:t?{b:0,a:0,opera:16}:"\ "{b:93,a:null,opera:0});W({b:96,a:96,opera:48},\"0\");W({b:97,a:97,opera"\ ":49},\"1\");W({b:98,a:98,opera:50},\"2\");W({b:99,a:99,opera:51},\"3\")"\ ";W({b:100,a:100,opera:52},\"4\");W({b:101,a:101,opera:53},\"5\");W({b:1"\ "02,a:102,opera:54},\"6\");W({b:103,a:103,opera:55},\"7\");W({b:104,a:10"\ "4,opera:56},\"8\");W({b:105,a:105,opera:57},\"9\");W({b:106,a:106,opera"\ ":x?56:42},\"*\");W({b:107,a:107,opera:x?61:43},\"+\");\nW({b:109,a:109,"\ "opera:x?109:45},\"-\");W({b:110,a:110,opera:x?190:78},\".\");W({b:111,a"\ ":111,opera:x?191:47},\"/\");W(144);W(112);W(113);W(114);W(115);W(116);W"\ "(117);W(118);W(119);W(120);W(121);W(122);W(123);W({b:107,a:187,opera:61"\ "},\"=\",\"+\");W(108,\",\");W({b:109,a:189,opera:109},\"-\",\"_\");W(18"\ "8,\",\",\"<\");W(190,\".\",\">\");W(191,\"/\",\"?\");W(192,\"`\",\"~\")"\ ";W(219,\"[\",\"{\");W(220,\"\\\\\",\"|\");W(221,\"]\",\"}\");W({b:59,a:"\ "186,opera:59},\";\",\":\");W(222,\"'\",'\"');var X=new V;X.set(1,cb);X."\ "set(2,db);X.set(4,eb);X.set(8,fb);\n(function(a){var b=new V;p(Za(a),fu"\ "nction(c){b.set(a.get(c).code,c)});return b})(X);function gb(a){var b=["\ "];Va(a,b);var c=b;a=c.length;for(var b=Array(a),c=m(c)?c.split(\"\"):c,"\ "d=0;d<a;d++)d in c&&(b[d]=Ua.call(void 0,c[d]));return Ua(b.join(\"\\n"\ "\")).replace(/\\xa0/g,\" \")}var Y=[\"_\"],Z=k;Y[0]in Z||!Z.execScript|"\ "|Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.shift());)Y.lengt"\ "h||void 0===gb?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=gb;; return this._.apply(null,a"\ "rguments);}.apply({navigator:typeof window!=undefined?window.navigator:"\ "null,document:typeof window!=undefined?window.document:null}, arguments"\ ");}" IS_DISPLAYED = \ "function(){return function(){function h(a){return function(){return a}}"\ "var k=this;\nfunction l(a){var b=typeof a;if(\"object\"==b)if(a){if(a i"\ "nstanceof Array)return\"array\";if(a instanceof Object)return b;var c=O"\ "bject.prototype.toString.call(a);if(\"[object Window]\"==c)return\"obje"\ "ct\";if(\"[object Array]\"==c||\"number\"==typeof a.length&&\"undefined"\ "\"!=typeof a.splice&&\"undefined\"!=typeof a.propertyIsEnumerable&&!a.p"\ "ropertyIsEnumerable(\"splice\"))return\"array\";if(\"[object Function]"\ "\"==c||\"undefined\"!=typeof a.call&&\"undefined\"!=typeof a.propertyIs"\ "Enumerable&&!a.propertyIsEnumerable(\"call\"))return\"function\"}else r"\ "eturn\"null\";\nelse if(\"function\"==b&&\"undefined\"==typeof a.call)r"\ "eturn\"object\";return b}function m(a){return\"string\"==typeof a};func"\ "tion aa(a){return String(a).replace(/\\-([a-z])/g,function(a,c){return "\ "c.toUpperCase()})};var n=Array.prototype;function p(a,b){for(var c=a.le"\ "ngth,d=m(a)?a.split(\"\"):a,e=0;e<c;e++)e in d&&b.call(void 0,d[e],e,a)"\ "}function ba(a,b){if(a.reduce)return a.reduce(b,\"\");var c=\"\";p(a,fu"\ "nction(d,e){c=b.call(void 0,c,d,e,a)});return c}function ca(a,b){for(va"\ "r c=a.length,d=m(a)?a.split(\"\"):a,e=0;e<c;e++)if(e in d&&b.call(void "\ "0,d[e],e,a))return!0;return!1}\nfunction r(a,b){var c;a:if(m(a))c=m(b)&"\ "&1==b.length?a.indexOf(b,0):-1;else{for(c=0;c<a.length;c++)if(c in a&&a"\ "[c]===b)break a;c=-1}return 0<=c}function da(a,b,c){return 2>=arguments"\ ".length?n.slice.call(a,b):n.slice.call(a,b,c)};var s={aliceblue:\"#f0f8"\ "ff\",antiquewhite:\"#faebd7\",aqua:\"#00ffff\",aquamarine:\"#7fffd4\",a"\ "zure:\"#f0ffff\",beige:\"#f5f5dc\",bisque:\"#ffe4c4\",black:\"#000000\""\ ",blanchedalmond:\"#ffebcd\",blue:\"#0000ff\",blueviolet:\"#8a2be2\",bro"\ "wn:\"#a52a2a\",burlywood:\"#deb887\",cadetblue:\"#5f9ea0\",chartreuse:"\ "\"#7fff00\",chocolate:\"#d2691e\",coral:\"#ff7f50\",cornflowerblue:\"#6"\ "495ed\",cornsilk:\"#fff8dc\",crimson:\"#dc143c\",cyan:\"#00ffff\",darkb"\ "lue:\"#00008b\",darkcyan:\"#008b8b\",darkgoldenrod:\"#b8860b\",darkgray"\ ":\"#a9a9a9\",darkgreen:\"#006400\",\ndarkgrey:\"#a9a9a9\",darkkhaki:\"#"\ "bdb76b\",darkmagenta:\"#8b008b\",darkolivegreen:\"#556b2f\",darkorange:"\ "\"#ff8c00\",darkorchid:\"#9932cc\",darkred:\"#8b0000\",darksalmon:\"#e9"\ "967a\",darkseagreen:\"#8fbc8f\",darkslateblue:\"#483d8b\",darkslategray"\ ":\"#2f4f4f\",darkslategrey:\"#2f4f4f\",darkturquoise:\"#00ced1\",darkvi"\ "olet:\"#9400d3\",deeppink:\"#ff1493\",deepskyblue:\"#00bfff\",dimgray:"\ "\"#696969\",dimgrey:\"#696969\",dodgerblue:\"#1e90ff\",firebrick:\"#b22"\ "222\",floralwhite:\"#fffaf0\",forestgreen:\"#228b22\",fuchsia:\"#ff00ff"\ "\",gainsboro:\"#dcdcdc\",\nghostwhite:\"#f8f8ff\",gold:\"#ffd700\",gold"\ "enrod:\"#daa520\",gray:\"#808080\",green:\"#008000\",greenyellow:\"#adf"\ "f2f\",grey:\"#808080\",honeydew:\"#f0fff0\",hotpink:\"#ff69b4\",indianr"\ "ed:\"#cd5c5c\",indigo:\"#4b0082\",ivory:\"#fffff0\",khaki:\"#f0e68c\",l"\ "avender:\"#e6e6fa\",lavenderblush:\"#fff0f5\",lawngreen:\"#7cfc00\",lem"\ "onchiffon:\"#fffacd\",lightblue:\"#add8e6\",lightcoral:\"#f08080\",ligh"\ "tcyan:\"#e0ffff\",lightgoldenrodyellow:\"#fafad2\",lightgray:\"#d3d3d3"\ "\",lightgreen:\"#90ee90\",lightgrey:\"#d3d3d3\",lightpink:\"#ffb6c1\",l"\ "ightsalmon:\"#ffa07a\",\nlightseagreen:\"#20b2aa\",lightskyblue:\"#87ce"\ "fa\",lightslategray:\"#778899\",lightslategrey:\"#778899\",lightsteelbl"\ "ue:\"#b0c4de\",lightyellow:\"#ffffe0\",lime:\"#00ff00\",limegreen:\"#32"\ "cd32\",linen:\"#faf0e6\",magenta:\"#ff00ff\",maroon:\"#800000\",mediuma"\ "quamarine:\"#66cdaa\",mediumblue:\"#0000cd\",mediumorchid:\"#ba55d3\",m"\ "ediumpurple:\"#9370db\",mediumseagreen:\"#3cb371\",mediumslateblue:\"#7"\ "b68ee\",mediumspringgreen:\"#00fa9a\",mediumturquoise:\"#48d1cc\",mediu"\ "mvioletred:\"#c71585\",midnightblue:\"#191970\",mintcream:\"#f5fffa\",m"\ "istyrose:\"#ffe4e1\",\nmoccasin:\"#ffe4b5\",navajowhite:\"#ffdead\",nav"\ "y:\"#000080\",oldlace:\"#fdf5e6\",olive:\"#808000\",olivedrab:\"#6b8e23"\ "\",orange:\"#ffa500\",orangered:\"#ff4500\",orchid:\"#da70d6\",palegold"\ "enrod:\"#eee8aa\",palegreen:\"#98fb98\",paleturquoise:\"#afeeee\",palev"\ "ioletred:\"#db7093\",papayawhip:\"#ffefd5\",peachpuff:\"#ffdab9\",peru:"\ "\"#cd853f\",pink:\"#ffc0cb\",plum:\"#dda0dd\",powderblue:\"#b0e0e6\",pu"\ "rple:\"#800080\",red:\"#ff0000\",rosybrown:\"#bc8f8f\",royalblue:\"#416"\ "9e1\",saddlebrown:\"#8b4513\",salmon:\"#fa8072\",sandybrown:\"#f4a460\""\ ",seagreen:\"#2e8b57\",\nseashell:\"#fff5ee\",sienna:\"#a0522d\",silver:"\ "\"#c0c0c0\",skyblue:\"#87ceeb\",slateblue:\"#6a5acd\",slategray:\"#7080"\ "90\",slategrey:\"#708090\",snow:\"#fffafa\",springgreen:\"#00ff7f\",ste"\ "elblue:\"#4682b4\",tan:\"#d2b48c\",teal:\"#008080\",thistle:\"#d8bfd8\""\ ",tomato:\"#ff6347\",turquoise:\"#40e0d0\",violet:\"#ee82ee\",wheat:\"#f"\ "5deb3\",white:\"#ffffff\",whitesmoke:\"#f5f5f5\",yellow:\"#ffff00\",yel"\ "lowgreen:\"#9acd32\"};var ea=\"background-color border-top-color border"\ "-right-color border-bottom-color border-left-color color outline-color"\ "\".split(\" \"),fa=/#([0-9a-fA-F])([0-9a-fA-F])([0-9a-fA-F])/;function "\ "t(a){if(!u.test(a))throw Error(\"'\"+a+\"' is not a valid hex color\");"\ "4==a.length&&(a=a.replace(fa,\"#$1$1$2$2$3$3\"));return a.toLowerCase()"\ "}var u=/^#(?:[0-9a-f]{3}){1,2}$/i,ga=/^(?:rgba)?\\((\\d{1,3}),\\s?(\\d{"\ "1,3}),\\s?(\\d{1,3}),\\s?(0|1|0\\.\\d*)\\)$/i;\nfunction v(a){var b=a.m"\ "atch(ga);if(b){a=Number(b[1]);var c=Number(b[2]),d=Number(b[3]),b=Numbe"\ "r(b[4]);if(0<=a&&255>=a&&0<=c&&255>=c&&0<=d&&255>=d&&0<=b&&1>=b)return["\ "a,c,d,b]}return[]}var ha=/^(?:rgb)?\\((0|[1-9]\\d{0,2}),\\s?(0|[1-9]\\d"\ "{0,2}),\\s?(0|[1-9]\\d{0,2})\\)$/i;function x(a){var b=a.match(ha);if(b"\ "){a=Number(b[1]);var c=Number(b[2]),b=Number(b[3]);if(0<=a&&255>=a&&0<="\ "c&&255>=c&&0<=b&&255>=b)return[a,c,b]}return[]};function y(a,b){this.co"\ "de=a;this.state=z[a]||ia;this.message=b||\"\";var c=this.state.replace("\ "/((?:^|\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s"\ "\\xa0]+/g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"E"\ "rror\";this.name=c;c=Error(this.message);c.name=this.name;this.stack=c."\ "stack||\"\"}(function(){var a=Error;function b(){}b.prototype=a.prototy"\ "pe;y.I=a.prototype;y.prototype=new b})();\nvar ia=\"unknown error\",z={"\ "15:\"element not selectable\",11:\"element not visible\",31:\"ime engin"\ "e activation failed\",30:\"ime not available\",24:\"invalid cookie doma"\ "in\",29:\"invalid element coordinates\",12:\"invalid element state\",32"\ ":\"invalid selector\",51:\"invalid selector\",52:\"invalid selector\",1"\ "7:\"javascript error\",405:\"unsupported operation\",34:\"move target o"\ "ut of bounds\",27:\"no such alert\",7:\"no such element\",8:\"no such f"\ "rame\",23:\"no such window\",28:\"script timeout\",33:\"session not cre"\ "ated\",10:\"stale element reference\",\n0:\"success\",21:\"timeout\",25"\ ":\"unable to set cookie\",26:\"unexpected alert open\"};z[13]=ia;z[9]="\ "\"unknown command\";y.prototype.toString=function(){return this.name+\""\ ": \"+this.message};var B;function C(a,b){this.x=void 0!==a?a:0;this.y=v"\ "oid 0!==b?b:0}C.prototype.toString=function(){return\"(\"+this.x+\", \""\ "+this.y+\")\"};C.prototype.ceil=function(){this.x=Math.ceil(this.x);thi"\ "s.y=Math.ceil(this.y);return this};C.prototype.floor=function(){this.x="\ "Math.floor(this.x);this.y=Math.floor(this.y);return this};C.prototype.r"\ "ound=function(){this.x=Math.round(this.x);this.y=Math.round(this.y);ret"\ "urn this};function D(a,b){this.width=a;this.height=b}D.prototype.toStri"\ "ng=function(){return\"(\"+this.width+\" x \"+this.height+\")\"};D.proto"\ "type.ceil=function(){this.width=Math.ceil(this.width);this.height=Math."\ "ceil(this.height);return this};D.prototype.floor=function(){this.width="\ "Math.floor(this.width);this.height=Math.floor(this.height);return this}"\ ";D.prototype.round=function(){this.width=Math.round(this.width);this.he"\ "ight=Math.round(this.height);return this};var ja=3;function E(a,b){if(a"\ ".contains&&1==b.nodeType)return a==b||a.contains(b);if(\"undefined\"!=t"\ "ypeof a.compareDocumentPosition)return a==b||Boolean(a.compareDocumentP"\ "osition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction ka(a"\ ",b){if(a==b)return 0;if(a.compareDocumentPosition)return a.compareDocum"\ "entPosition(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"sourceInd"\ "ex\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return"\ " a.sourceIndex-b.sourceIndex;var e=a.parentNode,f=b.parentNode;return e"\ "==f?la(a,b):!c&&E(e,b)?-1*ma(a,b):!d&&E(f,a)?ma(b,a):(c?a.sourceIndex:e"\ ".sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}d=F(a);c=d.createRange();"\ "c.selectNode(a);c.collapse(!0);d=d.createRange();d.selectNode(b);d.coll"\ "apse(!0);\nreturn c.compareBoundaryPoints(k.Range.START_TO_END,d)}funct"\ "ion ma(a,b){var c=a.parentNode;if(c==b)return-1;for(var d=b;d.parentNod"\ "e!=c;)d=d.parentNode;return la(d,a)}function la(a,b){for(var c=b;c=c.pr"\ "eviousSibling;)if(c==a)return-1;return 1}function F(a){return 9==a.node"\ "Type?a:a.ownerDocument||a.document}function na(a,b){a=a.parentNode;for("\ "var c=0;a;){if(b(a))return a;a=a.parentNode;c++}return null}function G("\ "a){this.p=a||k.document||document}\nfunction oa(a){var b=a.p;a=b.body;b"\ "=b.parentWindow||b.defaultView;return new C(b.pageXOffset||a.scrollLeft"\ ",b.pageYOffset||a.scrollTop)}G.prototype.contains=E;function H(a){var b"\ "=null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerT"\ "ext:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1=="\ "c){a=9==c?a.documentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do"\ " 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&"\ "&!(a=d[--c].nextSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction"\ " I(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)return!1}catch(d)"\ "{return!1}return null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}fun"\ "ction J(a,b,c,d,e){return pa.call(null,a,b,m(c)?c:null,m(d)?d:null,e||n"\ "ew K)}\nfunction pa(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b"\ ".getElementsByName(d),p(b,function(b){a.matches(b)&&e.add(b)})):b.getEl"\ "ementsByClassName&&d&&\"class\"==c?(b=b.getElementsByClassName(d),p(b,f"\ "unction(b){b.className==d&&a.matches(b)&&e.add(b)})):b.getElementsByTag"\ "Name&&(b=b.getElementsByTagName(a.getName()),p(b,function(a){I(a,c,d)&&"\ "e.add(a)}));return e}function qa(a,b,c,d,e){for(b=b.firstChild;b;b=b.ne"\ "xtSibling)I(b,c,d)&&a.matches(b)&&e.add(b);return e};function K(){this."\ "d=this.c=null;this.g=0}function ra(a){this.m=a;this.next=this.i=null}K."\ "prototype.unshift=function(a){a=new ra(a);a.next=this.c;this.d?this.c.i"\ "=a:this.c=this.d=a;this.c=a;this.g++};K.prototype.add=function(a){a=new"\ " ra(a);a.i=this.d;this.c?this.d.next=a:this.c=this.d=a;this.d=a;this.g+"\ "+};function sa(a){return(a=a.c)?a.m:null}function L(a){return new ta(a,"\ "!1)}function ta(a,b){this.F=a;this.j=(this.n=b)?a.d:a.c;this.r=null}\nt"\ "a.prototype.next=function(){var a=this.j;if(null==a)return null;var b=t"\ "his.r=a;this.j=this.n?a.i:a.next;return b.m};function M(a,b,c,d,e){b=b."\ "evaluate(d);c=c.evaluate(d);var f;if(b instanceof K&&c instanceof K){e="\ "L(b);for(d=e.next();d;d=e.next())for(b=L(c),f=b.next();f;f=b.next())if("\ "a(H(d),H(f)))return!0;return!1}if(b instanceof K||c instanceof K){b ins"\ "tanceof K?e=b:(e=c,c=b);e=L(e);b=typeof c;for(d=e.next();d;d=e.next()){"\ "switch(b){case \"number\":d=+H(d);break;case \"boolean\":d=!!H(d);break"\ ";case \"string\":d=H(d);break;default:throw Error(\"Illegal primitive t"\ "ype for comparison.\");}if(a(d,c))return!0}return!1}return e?\n\"boolea"\ "n\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number\"==typeof b||"\ "\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function ua(a,b,c,d){this"\ ".s=a;this.H=b;this.o=c;this.q=d}ua.prototype.toString=function(){return"\ " this.s};var va={};function N(a,b,c,d){if(a in va)throw Error(\"Binary "\ "operator already created: \"+a);a=new ua(a,b,c,d);va[a.toString()]=a}N("\ "\"div\",6,1,function(a,b,c){return a.b(c)/b.b(c)});N(\"mod\",6,1,functi"\ "on(a,b,c){return a.b(c)%b.b(c)});N(\"*\",6,1,function(a,b,c){return a.b"\ "(c)*b.b(c)});\nN(\"+\",5,1,function(a,b,c){return a.b(c)+b.b(c)});N(\"-"\ "\",5,1,function(a,b,c){return a.b(c)-b.b(c)});N(\"<\",4,2,function(a,b,"\ "c){return M(function(a,b){return a<b},a,b,c)});N(\">\",4,2,function(a,b"\ ",c){return M(function(a,b){return a>b},a,b,c)});N(\"<=\",4,2,function(a"\ ",b,c){return M(function(a,b){return a<=b},a,b,c)});N(\">=\",4,2,functio"\ "n(a,b,c){return M(function(a,b){return a>=b},a,b,c)});N(\"=\",3,2,funct"\ "ion(a,b,c){return M(function(a,b){return a==b},a,b,c,!0)});\nN(\"!=\",3"\ ",2,function(a,b,c){return M(function(a,b){return a!=b},a,b,c,!0)});N(\""\ "and\",2,2,function(a,b,c){return a.f(c)&&b.f(c)});N(\"or\",1,2,function"\ "(a,b,c){return a.f(c)||b.f(c)});function wa(a,b,c,d,e,f,g,w,q){this.h=a"\ ";this.o=b;this.D=c;this.C=d;this.B=e;this.q=f;this.A=g;this.w=void 0!=="\ "w?w:g;this.G=!!q}wa.prototype.toString=function(){return this.h};var xa"\ "={};function O(a,b,c,d,e,f,g,w){if(a in xa)throw Error(\"Function alrea"\ "dy created: \"+a+\".\");xa[a]=new wa(a,b,c,d,!1,e,f,g,w)}O(\"boolean\","\ "2,!1,!1,function(a,b){return b.f(a)},1);O(\"ceiling\",1,!1,!1,function("\ "a,b){return Math.ceil(b.b(a))},1);\nO(\"concat\",3,!1,!1,function(a,b){"\ "var c=da(arguments,1);return ba(c,function(b,c){return b+c.a(a)})},2,nu"\ "ll);O(\"contains\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return-1!="\ "b.indexOf(a)},2);O(\"count\",1,!1,!1,function(a,b){return b.evaluate(a)"\ ".g},1,1,!0);O(\"false\",2,!1,!1,h(!1),0);O(\"floor\",1,!1,!1,function(a"\ ",b){return Math.floor(b.b(a))},1);\nO(\"id\",4,!1,!1,function(a,b){var "\ "c=a.e(),d=9==c.nodeType?c:c.ownerDocument,c=b.a(a).split(/\\s+/),e=[];p"\ "(c,function(a){(a=d.getElementById(a))&&!r(e,a)&&e.push(a)});e.sort(ka)"\ ";var f=new K;p(e,function(a){f.add(a)});return f},1);O(\"lang\",2,!1,!1"\ ",h(!1),1);O(\"last\",1,!0,!1,function(a){if(1!=arguments.length)throw E"\ "rror(\"Function last expects ()\");return a.u()},0);O(\"local-name\",3,"\ "!1,!0,function(a,b){var c=b?sa(b.evaluate(a)):a.e();return c?c.nodeName"\ ".toLowerCase():\"\"},0,1,!0);\nO(\"name\",3,!1,!0,function(a,b){var c=b"\ "?sa(b.evaluate(a)):a.e();return c?c.nodeName.toLowerCase():\"\"},0,1,!0"\ ");O(\"namespace-uri\",3,!0,!1,h(\"\"),0,1,!0);O(\"normalize-space\",3,!"\ "1,!0,function(a,b){return(b?b.a(a):H(a.e())).replace(/[\\s\\xa0]+/g,\" "\ "\").replace(/^\\s+|\\s+$/g,\"\")},0,1);O(\"not\",2,!1,!1,function(a,b){"\ "return!b.f(a)},1);O(\"number\",1,!1,!0,function(a,b){return b?b.b(a):+H"\ "(a.e())},0,1);O(\"position\",1,!0,!1,function(a){return a.v()},0);O(\"r"\ "ound\",1,!1,!1,function(a,b){return Math.round(b.b(a))},1);\nO(\"starts"\ "-with\",2,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);return 0==b.lastIndex"\ "Of(a,0)},2);O(\"string\",3,!1,!0,function(a,b){return b?b.a(a):H(a.e())"\ "},0,1);O(\"string-length\",1,!1,!0,function(a,b){return(b?b.a(a):H(a.e("\ "))).length},0,1);\nO(\"substring\",3,!1,!1,function(a,b,c,d){c=c.b(a);i"\ "f(isNaN(c)||Infinity==c||-Infinity==c)return\"\";d=d?d.b(a):Infinity;if"\ "(isNaN(d)||-Infinity===d)return\"\";c=Math.round(c)-1;var e=Math.max(c,"\ "0);a=b.a(a);if(Infinity==d)return a.substring(e);b=Math.round(d);return"\ " a.substring(e,c+b)},2,3);O(\"substring-after\",3,!1,!1,function(a,b,c)"\ "{b=b.a(a);a=c.a(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.leng"\ "th)},2);\nO(\"substring-before\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a"\ "(a);a=b.indexOf(a);return-1==a?\"\":b.substring(0,a)},2);O(\"sum\",1,!1"\ ",!1,function(a,b){for(var c=L(b.evaluate(a)),d=0,e=c.next();e;e=c.next("\ "))d+=+H(e);return d},1,1,!0);O(\"translate\",3,!1,!1,function(a,b,c,d){"\ "b=b.a(a);c=c.a(a);var e=d.a(a);a=[];for(d=0;d<c.length;d++){var f=c.cha"\ "rAt(d);f in a||(a[f]=e.charAt(d))}c=\"\";for(d=0;d<b.length;d++)f=b.cha"\ "rAt(d),c+=f in a?a[f]:f;return c},3);O(\"true\",2,!1,!1,h(!0),0);functi"\ "on ya(a,b,c,d){this.h=a;this.t=b;this.n=c;this.J=d}ya.prototype.toStrin"\ "g=function(){return this.h};var za={};function P(a,b,c,d){if(a in za)th"\ "row Error(\"Axis already created: \"+a);za[a]=new ya(a,b,c,!!d)}P(\"anc"\ "estor\",function(a,b){for(var c=new K,d=b;d=d.parentNode;)a.matches(d)&"\ "&c.unshift(d);return c},!0);P(\"ancestor-or-self\",function(a,b){var c="\ "new K,d=b;do a.matches(d)&&c.unshift(d);while(d=d.parentNode);return c}"\ ",!0);\nP(\"attribute\",function(a,b){var c=new K,d=a.getName(),e=b.attr"\ "ibutes;if(e)if(\"*\"==d)for(var d=0,f;f=e[d];d++)c.add(f);else(f=e.getN"\ "amedItem(d))&&c.add(f);return c},!1);P(\"child\",function(a,b,c,d,e){re"\ "turn qa.call(null,a,b,m(c)?c:null,m(d)?d:null,e||new K)},!1,!0);P(\"des"\ "cendant\",J,!1,!0);P(\"descendant-or-self\",function(a,b,c,d){var e=new"\ " K;I(b,c,d)&&a.matches(b)&&e.add(b);return J(a,b,c,d,e)},!1,!0);\nP(\"f"\ "ollowing\",function(a,b,c,d){var e=new K;do for(var f=b;f=f.nextSibling"\ ";)I(f,c,d)&&a.matches(f)&&e.add(f),e=J(a,f,c,d,e);while(b=b.parentNode)"\ ";return e},!1,!0);P(\"following-sibling\",function(a,b){for(var c=new K"\ ",d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c},!1);P(\"namespac"\ "e\",function(){return new K},!1);P(\"parent\",function(a,b){var c=new K"\ ";if(9==b.nodeType)return c;if(2==b.nodeType)return c.add(b.ownerElement"\ "),c;var d=b.parentNode;a.matches(d)&&c.add(d);return c},!1);\nP(\"prece"\ "ding\",function(a,b,c,d){var e=new K,f=[];do f.unshift(b);while(b=b.par"\ "entNode);for(var g=1,w=f.length;g<w;g++){var q=[];for(b=f[g];b=b.previo"\ "usSibling;)q.unshift(b);for(var A=0,Ia=q.length;A<Ia;A++)b=q[A],I(b,c,d"\ ")&&a.matches(b)&&e.add(b),e=J(a,b,c,d,e)}return e},!0,!0);P(\"preceding"\ "-sibling\",function(a,b){for(var c=new K,d=b;d=d.previousSibling;)a.mat"\ "ches(d)&&c.unshift(d);return c},!0);P(\"self\",function(a,b){var c=new "\ "K;a.matches(b)&&c.add(b);return c},!1);var Aa=function(){var a={K:\"htt"\ "p://www.w3.org/2000/svg\"};return function(b){return a[b]||null}}();\nf"\ "unction Ba(a,b){var c=function(){var c;var e=F(b);try{var f=e.createNSR"\ "esolver?e.createNSResolver(e.documentElement):Aa;c=e.evaluate(a,b,f,9,n"\ "ull)}catch(g){throw new y(32,\"Unable to locate an element with the xpa"\ "th expression \"+a+\" because of the following error:\\n\"+g);}return c"\ "?c.singleNodeValue||null:b.selectSingleNode?(c=F(b),c.setProperty&&c.se"\ "tProperty(\"SelectionLanguage\",\"XPath\"),b.selectSingleNode(a)):null}"\ "();if(null!==c&&(!c||1!=c.nodeType))throw new y(32,'The result of the x"\ "path expression \"'+\na+'\" is: '+c+\". It should be an element.\");ret"\ "urn c};function Q(a,b,c,d){this.left=a;this.top=b;this.width=c;this.hei"\ "ght=d}Q.prototype.toString=function(){return\"(\"+this.left+\", \"+this"\ ".top+\" - \"+this.width+\"w x \"+this.height+\"h)\"};Q.prototype.contai"\ "ns=function(a){return a instanceof Q?this.left<=a.left&&this.left+this."\ "width>=a.left+a.width&&this.top<=a.top&&this.top+this.height>=a.top+a.h"\ "eight:a.x>=this.left&&a.x<=this.left+this.width&&a.y>=this.top&&a.y<=th"\ "is.top+this.height};\nQ.prototype.ceil=function(){this.left=Math.ceil(t"\ "his.left);this.top=Math.ceil(this.top);this.width=Math.ceil(this.width)"\ ";this.height=Math.ceil(this.height);return this};Q.prototype.floor=func"\ "tion(){this.left=Math.floor(this.left);this.top=Math.floor(this.top);th"\ "is.width=Math.floor(this.width);this.height=Math.floor(this.height);ret"\ "urn this};\nQ.prototype.round=function(){this.left=Math.round(this.left"\ ");this.top=Math.round(this.top);this.width=Math.round(this.width);this."\ "height=Math.round(this.height);return this};function Ca(a,b){var c=F(a)"\ ";return c.defaultView&&c.defaultView.getComputedStyle&&(c=c.defaultView"\ ".getComputedStyle(a,null))?c[b]||c.getPropertyValue(b)||\"\":\"\"}funct"\ "ion R(a){return Ca(a,\"position\")||(a.currentStyle?a.currentStyle.posi"\ "tion:null)||a.style&&a.style.position}function Da(a){var b;try{b=a.getB"\ "oundingClientRect()}catch(c){return{left:0,top:0,right:0,bottom:0}}retu"\ "rn b}\nfunction Ea(a){var b=F(a),c=R(a),d=\"fixed\"==c||\"absolute\"==c"\ ";for(a=a.parentNode;a&&a!=b;a=a.parentNode)if(c=R(a),d=d&&\"static\"==c"\ "&&a!=b.documentElement&&a!=b.body,!d&&(a.scrollWidth>a.clientWidth||a.s"\ "crollHeight>a.clientHeight||\"fixed\"==c||\"absolute\"==c||\"relative\""\ "==c))return a;return null}\nfunction Fa(a){if(1==a.nodeType){var b;if(a"\ ".getBoundingClientRect)b=Da(a),b=new C(b.left,b.top);else{b=oa(a?new G("\ "F(a)):B||(B=new G));var c=F(a),d=R(a),e=new C(0,0),f=(c?F(c):document)."\ "documentElement;if(a!=f)if(a.getBoundingClientRect)a=Da(a),c=oa(c?new G"\ "(F(c)):B||(B=new G)),e.x=a.left+c.x,e.y=a.top+c.y;else if(c.getBoxObjec"\ "tFor)a=c.getBoxObjectFor(a),c=c.getBoxObjectFor(f),e.x=a.screenX-c.scre"\ "enX,e.y=a.screenY-c.screenY;else{var g=a;do{e.x+=g.offsetLeft;e.y+=g.of"\ "fsetTop;g!=a&&(e.x+=g.clientLeft||\n0,e.y+=g.clientTop||0);if(\"fixed\""\ "==R(g)){e.x+=c.body.scrollLeft;e.y+=c.body.scrollTop;break}g=g.offsetPa"\ "rent}while(g&&g!=a);\"absolute\"==d&&(e.y-=c.body.offsetTop);for(g=a;(g"\ "=Ea(g))&&g!=c.body&&g!=f;)e.x-=g.scrollLeft,e.y-=g.scrollTop}b=new C(e."\ "x-b.x,e.y-b.y)}return b}b=\"function\"==l(a.k);e=a;a.targetTouches?e=a."\ "targetTouches[0]:b&&a.k().targetTouches&&(e=a.k().targetTouches[0]);ret"\ "urn new C(e.clientX,e.clientY)};function S(a,b){return!!a&&1==a.nodeTyp"\ "e&&(!b||a.tagName.toUpperCase()==b)}function T(a){for(a=a.parentNode;a&"\ "&1!=a.nodeType&&9!=a.nodeType&&11!=a.nodeType;)a=a.parentNode;return S("\ "a)?a:null}\nfunction U(a,b){var c=aa(b);if(\"float\"==c||\"cssFloat\"=="\ "c||\"styleFloat\"==c)c=\"cssFloat\";c=Ca(a,c)||Ga(a,c);if(null===c)c=nu"\ "ll;else if(r(ea,b)&&(u.test(\"#\"==c.charAt(0)?c:\"#\"+c)||x(c).length|"\ "|s&&s[c.toLowerCase()]||v(c).length)){var d=v(c);if(!d.length){a:if(d=x"\ "(c),!d.length){d=(d=s[c.toLowerCase()])?d:\"#\"==c.charAt(0)?c:\"#\"+c;"\ "if(u.test(d)&&(d=t(d),d=t(d),d=[parseInt(d.substr(1,2),16),parseInt(d.s"\ "ubstr(3,2),16),parseInt(d.substr(5,2),16)],d.length))break a;d=[]}3==d."\ "length&&d.push(1)}c=4!=d.length?\nc:\"rgba(\"+d.join(\", \")+\")\"}retu"\ "rn c}function Ga(a,b){var c=a.currentStyle||a.style,d=c[b];void 0===d&&"\ "\"function\"==l(c.getPropertyValue)&&(d=c.getPropertyValue(b));return\""\ "inherit\"!=d?void 0!==d?d:null:(c=T(a))?Ga(c,b):null}\nfunction V(a,b){"\ "function c(a){if(\"none\"==U(a,\"display\"))return!1;a=T(a);return!a||c"\ "(a)}function d(a){var b=W(a);return 0<b.height&&0<b.width?!0:S(a,\"PATH"\ "\")&&(0<b.height||0<b.width)?(a=U(a,\"stroke-width\"),!!a&&0<parseInt(a"\ ",10)):\"hidden\"!=U(a,\"overflow\")&&ca(a.childNodes,function(a){return"\ " a.nodeType==ja||S(a)&&d(a)})}function e(a){var b=U(a,\"-o-transform\")"\ "||U(a,\"-webkit-transform\")||U(a,\"-ms-transform\")||U(a,\"-moz-transf"\ "orm\")||U(a,\"transform\");if(b&&\"none\"!==b)return b=Fa(a),a=W(a),0<="\ "b.x+a.width&&\n0<=b.y+a.height?!0:!1;a=T(a);return!a||e(a)}if(!S(a))thr"\ "ow Error(\"Argument to isShown must be of type Element\");if(S(a,\"OPTI"\ "ON\")||S(a,\"OPTGROUP\")){var f=na(a,function(a){return S(a,\"SELECT\")"\ "});return!!f&&V(f,!0)}return(f=Ha(a))?!!f.l&&0<f.rect.width&&0<f.rect.h"\ "eight&&V(f.l,b):S(a,\"INPUT\")&&\"hidden\"==a.type.toLowerCase()||S(a,"\ "\"NOSCRIPT\")||\"hidden\"==U(a,\"visibility\")||!c(a)||!b&&0==Ja(a)||!d"\ "(a)||Ka(a)==X?!1:e(a)}var X=\"hidden\";\nfunction Ka(a){function b(a){v"\ "ar b=a;if(\"visible\"==w)if(a==f)b=g;else if(a==g)return{x:\"visible\","\ "y:\"visible\"};b={x:U(b,\"overflow-x\"),y:U(b,\"overflow-y\")};a==f&&(b"\ ".x=\"hidden\"==b.x?\"hidden\":\"auto\",b.y=\"hidden\"==b.y?\"hidden\":"\ "\"auto\");return b}function c(a){var b=U(a,\"position\");if(\"fixed\"=="\ "b)return f;for(a=T(a);a&&a!=f&&(0==U(a,\"display\").lastIndexOf(\"inlin"\ "e\",0)||\"absolute\"==b&&\"static\"==U(a,\"position\"));)a=T(a);return "\ "a}var d=W(a),e=F(a),f=e.documentElement,g=e.body,w=U(f,\"overflow\");fo"\ "r(a=c(a);a;a=\nc(a)){var q=W(a),e=b(a),A=d.left>=q.left+q.width,q=d.top"\ ">=q.top+q.height;if(A&&\"hidden\"==e.x||q&&\"hidden\"==e.y)return X;if("\ "A&&\"visible\"!=e.x||q&&\"visible\"!=e.y)return Ka(a)==X?X:\"scroll\"}r"\ "eturn\"none\"}\nfunction W(a){var b=Ha(a);if(b)return b.rect;if(\"funct"\ "ion\"==l(a.getBBox))try{var c=a.getBBox();return new Q(c.x,c.y,c.width,"\ "c.height)}catch(d){throw d;}else{if(S(a,\"HTML\"))return a=((F(a)?F(a)."\ "parentWindow||F(a).defaultView:window)||window).document,a=\"CSS1Compat"\ "\"==a.compatMode?a.documentElement:a.body,a=new D(a.clientWidth,a.clien"\ "tHeight),new Q(0,0,a.width,a.height);var b=Fa(a),c=a.offsetWidth,e=a.of"\ "fsetHeight;c||(e||!a.getBoundingClientRect)||(a=a.getBoundingClientRect"\ "(),c=a.right-a.left,e=a.bottom-\na.top);return new Q(b.x,b.y,c,e)}}func"\ "tion Ha(a){var b=S(a,\"MAP\");if(!b&&!S(a,\"AREA\"))return null;var c=b"\ "?a:S(a.parentNode,\"MAP\")?a.parentNode:null,d=null,e=null;if(c&&c.name"\ "&&(d=Ba('/descendant::*[@usemap = \"#'+c.name+'\"]',F(c)))&&(e=W(d),!b&"\ "&\"default\"!=a.shape.toLowerCase())){var f=La(a);a=Math.min(Math.max(f"\ ".left,0),e.width);b=Math.min(Math.max(f.top,0),e.height);c=Math.min(f.w"\ "idth,e.width-a);f=Math.min(f.height,e.height-b);e=new Q(a+e.left,b+e.to"\ "p,c,f)}return{l:d,rect:e||new Q(0,0,0,0)}}\nfunction La(a){var b=a.shap"\ "e.toLowerCase();a=a.coords.split(\",\");if(\"rect\"==b&&4==a.length){va"\ "r b=a[0],c=a[1];return new Q(b,c,a[2]-b,a[3]-c)}if(\"circle\"==b&&3==a."\ "length)return b=a[2],new Q(a[0]-b,a[1]-b,2*b,2*b);if(\"poly\"==b&&2<a.l"\ "ength){for(var b=a[0],c=a[1],d=b,e=c,f=2;f+1<a.length;f+=2)b=Math.min(b"\ ",a[f]),d=Math.max(d,a[f]),c=Math.min(c,a[f+1]),e=Math.max(e,a[f+1]);ret"\ "urn new Q(b,c,d-b,e-c)}return new Q(0,0,0,0)}\nfunction Ja(a){var b=1,c"\ "=U(a,\"opacity\");c&&(b=Number(c));(a=T(a))&&(b*=Ja(a));return b};var M"\ "a=V,Y=[\"_\"],Z=k;Y[0]in Z||!Z.execScript||Z.execScript(\"var \"+Y[0]);"\ "for(var $;Y.length&&($=Y.shift());)Y.length||void 0===Ma?Z=Z[$]?Z[$]:Z["\ "$]={}:Z[$]=Ma;; return this._.apply(null,arguments);}.apply({navigator:"\ "typeof window!=undefined?window.navigator:null,document:typeof window!="\ "undefined?window.document:null}, arguments);}" IS_ENABLED = \ "function(){return function(){function g(a){return function(){return a}}"\ "var h=this;function k(a){return\"string\"==typeof a};var l=Array.protot"\ "ype;function m(a,b){if(k(a))return k(b)&&1==b.length?a.indexOf(b,0):-1;"\ "for(var c=0;c<a.length;c++)if(c in a&&a[c]===b)return c;return-1}functi"\ "on p(a,b){for(var c=a.length,d=k(a)?a.split(\"\"):a,e=0;e<c;e++)e in d&"\ "&b.call(void 0,d[e],e,a)}function q(a,b){if(a.reduce)return a.reduce(b,"\ "\"\");var c=\"\";p(a,function(d,e){c=b.call(void 0,c,d,e,a)});return c}"\ "function r(a,b,c){return 2>=arguments.length?l.slice.call(a,b):l.slice."\ "call(a,b,c)};function s(a){for(;a&&1!=a.nodeType;)a=a.previousSibling;r"\ "eturn a}function u(a,b){if(a.contains&&1==b.nodeType)return a==b||a.con"\ "tains(b);if(\"undefined\"!=typeof a.compareDocumentPosition)return a==b"\ "||Boolean(a.compareDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode"\ ";return b==a}\nfunction w(a,b){if(a==b)return 0;if(a.compareDocumentPos"\ "ition)return a.compareDocumentPosition(b)&2?1:-1;if(\"sourceIndex\"in a"\ "||a.parentNode&&\"sourceIndex\"in a.parentNode){var c=1==a.nodeType,d=1"\ "==b.nodeType;if(c&&d)return a.sourceIndex-b.sourceIndex;var e=a.parentN"\ "ode,f=b.parentNode;return e==f?x(a,b):!c&&u(e,b)?-1*y(a,b):!d&&u(f,a)?y"\ "(b,a):(c?a.sourceIndex:e.sourceIndex)-(d?b.sourceIndex:f.sourceIndex)}d"\ "=9==a.nodeType?a:a.ownerDocument||a.document;c=d.createRange();c.select"\ "Node(a);c.collapse(!0);\nd=d.createRange();d.selectNode(b);d.collapse(!"\ "0);return c.compareBoundaryPoints(h.Range.START_TO_END,d)}function y(a,"\ "b){var c=a.parentNode;if(c==b)return-1;for(var d=b;d.parentNode!=c;)d=d"\ ".parentNode;return x(d,a)}function x(a,b){for(var c=b;c=c.previousSibli"\ "ng;)if(c==a)return-1;return 1}function z(a,b){for(var c=0;a;){if(b(a))r"\ "eturn a;a=a.parentNode;c++}return null};function A(a){var b=null,c=a.no"\ "deType;1==c&&(b=a.textContent,b=void 0==b||null==b?a.innerText:b,b=void"\ " 0==b||null==b?\"\":b);if(\"string\"!=typeof b)if(9==c||1==c){a=9==c?a."\ "documentElement:a.firstChild;for(var c=0,d=[],b=\"\";a;){do 1!=a.nodeTy"\ "pe&&(b+=a.nodeValue),d[c++]=a;while(a=a.firstChild);for(;c&&!(a=d[--c]."\ "nextSibling););}}else b=a.nodeValue;return\"\"+b}\nfunction C(a,b,c){if"\ "(null===b)return!0;try{if(!a.getAttribute)return!1}catch(d){return!1}re"\ "turn null==c?!!a.getAttribute(b):a.getAttribute(b,2)==c}function D(a,b,"\ "c,d,e){return E.call(null,a,b,k(c)?c:null,k(d)?d:null,e||new F)}\nfunct"\ "ion E(a,b,c,d,e){b.getElementsByName&&d&&\"name\"==c?(b=b.getElementsBy"\ "Name(d),p(b,function(b){a.matches(b)&&e.add(b)})):b.getElementsByClassN"\ "ame&&d&&\"class\"==c?(b=b.getElementsByClassName(d),p(b,function(b){b.c"\ "lassName==d&&a.matches(b)&&e.add(b)})):b.getElementsByTagName&&(b=b.get"\ "ElementsByTagName(a.getName()),p(b,function(a){C(a,c,d)&&e.add(a)}));re"\ "turn e}function G(a,b,c,d,e){for(b=b.firstChild;b;b=b.nextSibling)C(b,c"\ ",d)&&a.matches(b)&&e.add(b);return e};function F(){this.d=this.c=null;t"\ "his.g=0}function H(a){this.k=a;this.next=this.i=null}F.prototype.unshif"\ "t=function(a){a=new H(a);a.next=this.c;this.d?this.c.i=a:this.c=this.d="\ "a;this.c=a;this.g++};F.prototype.add=function(a){a=new H(a);a.i=this.d;"\ "this.c?this.d.next=a:this.c=this.d=a;this.d=a;this.g++};function I(a){r"\ "eturn(a=a.c)?a.k:null}function J(a){return new K(a,!1)}function K(a,b){"\ "this.B=a;this.j=(this.l=b)?a.d:a.c;this.o=null}\nK.prototype.next=funct"\ "ion(){var a=this.j;if(null==a)return null;var b=this.o=a;this.j=this.l?"\ "a.i:a.next;return b.k};function L(a,b,c,d,e){b=b.evaluate(d);c=c.evalua"\ "te(d);var f;if(b instanceof F&&c instanceof F){e=J(b);for(d=e.next();d;"\ "d=e.next())for(b=J(c),f=b.next();f;f=b.next())if(a(A(d),A(f)))return!0;"\ "return!1}if(b instanceof F||c instanceof F){b instanceof F?e=b:(e=c,c=b"\ ");e=J(e);b=typeof c;for(d=e.next();d;d=e.next()){switch(b){case \"numbe"\ "r\":d=+A(d);break;case \"boolean\":d=!!A(d);break;case \"string\":d=A(d"\ ");break;default:throw Error(\"Illegal primitive type for comparison.\")"\ ";}if(a(d,c))return!0}return!1}return e?\n\"boolean\"==typeof b||\"boole"\ "an\"==typeof c?a(!!b,!!c):\"number\"==typeof b||\"number\"==typeof c?a("\ "+b,+c):a(b,c):a(+b,+c)}function M(a,b,c,d){this.p=a;this.D=b;this.m=c;t"\ "his.n=d}M.prototype.toString=function(){return this.p};var N={};functio"\ "n O(a,b,c,d){if(a in N)throw Error(\"Binary operator already created: "\ "\"+a);a=new M(a,b,c,d);N[a.toString()]=a}O(\"div\",6,1,function(a,b,c){"\ "return a.b(c)/b.b(c)});O(\"mod\",6,1,function(a,b,c){return a.b(c)%b.b("\ "c)});O(\"*\",6,1,function(a,b,c){return a.b(c)*b.b(c)});\nO(\"+\",5,1,f"\ "unction(a,b,c){return a.b(c)+b.b(c)});O(\"-\",5,1,function(a,b,c){retur"\ "n a.b(c)-b.b(c)});O(\"<\",4,2,function(a,b,c){return L(function(a,b){re"\ "turn a<b},a,b,c)});O(\">\",4,2,function(a,b,c){return L(function(a,b){r"\ "eturn a>b},a,b,c)});O(\"<=\",4,2,function(a,b,c){return L(function(a,b)"\ "{return a<=b},a,b,c)});O(\">=\",4,2,function(a,b,c){return L(function(a"\ ",b){return a>=b},a,b,c)});O(\"=\",3,2,function(a,b,c){return L(function"\ "(a,b){return a==b},a,b,c,!0)});\nO(\"!=\",3,2,function(a,b,c){return L("\ "function(a,b){return a!=b},a,b,c,!0)});O(\"and\",2,2,function(a,b,c){re"\ "turn a.f(c)&&b.f(c)});O(\"or\",1,2,function(a,b,c){return a.f(c)||b.f(c"\ ")});function P(a,b,c,d,e,f,n,t,v){this.h=a;this.m=b;this.A=c;this.w=d;t"\ "his.v=e;this.n=f;this.u=n;this.t=void 0!==t?t:n;this.C=!!v}P.prototype."\ "toString=function(){return this.h};var Q={};function R(a,b,c,d,e,f,n,t)"\ "{if(a in Q)throw Error(\"Function already created: \"+a+\".\");Q[a]=new"\ " P(a,b,c,d,!1,e,f,n,t)}R(\"boolean\",2,!1,!1,function(a,b){return b.f(a"\ ")},1);R(\"ceiling\",1,!1,!1,function(a,b){return Math.ceil(b.b(a))},1);"\ "\nR(\"concat\",3,!1,!1,function(a,b){var c=r(arguments,1);return q(c,fu"\ "nction(b,c){return b+c.a(a)})},2,null);R(\"contains\",2,!1,!1,function("\ "a,b,c){b=b.a(a);a=c.a(a);return-1!=b.indexOf(a)},2);R(\"count\",1,!1,!1"\ ",function(a,b){return b.evaluate(a).g},1,1,!0);R(\"false\",2,!1,!1,g(!1"\ "),0);R(\"floor\",1,!1,!1,function(a,b){return Math.floor(b.b(a))},1);\n"\ "R(\"id\",4,!1,!1,function(a,b){var c=a.e(),d=9==c.nodeType?c:c.ownerDoc"\ "ument,c=b.a(a).split(/\\s+/),e=[];p(c,function(a){a=d.getElementById(a)"\ ";!a||0<=m(e,a)||e.push(a)});e.sort(w);var f=new F;p(e,function(a){f.add"\ "(a)});return f},1);R(\"lang\",2,!1,!1,g(!1),1);R(\"last\",1,!0,!1,funct"\ "ion(a){if(1!=arguments.length)throw Error(\"Function last expects ()\")"\ ";return a.r()},0);R(\"local-name\",3,!1,!0,function(a,b){var c=b?I(b.ev"\ "aluate(a)):a.e();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);\nR(\""\ "name\",3,!1,!0,function(a,b){var c=b?I(b.evaluate(a)):a.e();return c?c."\ "nodeName.toLowerCase():\"\"},0,1,!0);R(\"namespace-uri\",3,!0,!1,g(\"\""\ "),0,1,!0);R(\"normalize-space\",3,!1,!0,function(a,b){return(b?b.a(a):A"\ "(a.e())).replace(/[\\s\\xa0]+/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,"\ "1);R(\"not\",2,!1,!1,function(a,b){return!b.f(a)},1);R(\"number\",1,!1,"\ "!0,function(a,b){return b?b.b(a):+A(a.e())},0,1);R(\"position\",1,!0,!1"\ ",function(a){return a.s()},0);R(\"round\",1,!1,!1,function(a,b){return "\ "Math.round(b.b(a))},1);\nR(\"starts-with\",2,!1,!1,function(a,b,c){b=b."\ "a(a);a=c.a(a);return 0==b.lastIndexOf(a,0)},2);R(\"string\",3,!1,!0,fun"\ "ction(a,b){return b?b.a(a):A(a.e())},0,1);R(\"string-length\",1,!1,!0,f"\ "unction(a,b){return(b?b.a(a):A(a.e())).length},0,1);\nR(\"substring\",3"\ ",!1,!1,function(a,b,c,d){c=c.b(a);if(isNaN(c)||Infinity==c||-Infinity=="\ "c)return\"\";d=d?d.b(a):Infinity;if(isNaN(d)||-Infinity===d)return\"\";"\ "c=Math.round(c)-1;var e=Math.max(c,0);a=b.a(a);if(Infinity==d)return a."\ "substring(e);b=Math.round(d);return a.substring(e,c+b)},2,3);R(\"substr"\ "ing-after\",3,!1,!1,function(a,b,c){b=b.a(a);a=c.a(a);c=b.indexOf(a);re"\ "turn-1==c?\"\":b.substring(c+a.length)},2);\nR(\"substring-before\",3,!"\ "1,!1,function(a,b,c){b=b.a(a);a=c.a(a);a=b.indexOf(a);return-1==a?\"\":"\ "b.substring(0,a)},2);R(\"sum\",1,!1,!1,function(a,b){for(var c=J(b.eval"\ "uate(a)),d=0,e=c.next();e;e=c.next())d+=+A(e);return d},1,1,!0);R(\"tra"\ "nslate\",3,!1,!1,function(a,b,c,d){b=b.a(a);c=c.a(a);var e=d.a(a);a=[];"\ "for(d=0;d<c.length;d++){var f=c.charAt(d);f in a||(a[f]=e.charAt(d))}c="\ "\"\";for(d=0;d<b.length;d++)f=b.charAt(d),c+=f in a?a[f]:f;return c},3)"\ ";R(\"true\",2,!1,!1,g(!0),0);function S(a,b,c,d){this.h=a;this.q=b;this"\ ".l=c;this.F=d}S.prototype.toString=function(){return this.h};var T={};f"\ "unction U(a,b,c,d){if(a in T)throw Error(\"Axis already created: \"+a);"\ "T[a]=new S(a,b,c,!!d)}U(\"ancestor\",function(a,b){for(var c=new F,d=b;"\ "d=d.parentNode;)a.matches(d)&&c.unshift(d);return c},!0);U(\"ancestor-o"\ "r-self\",function(a,b){var c=new F,d=b;do a.matches(d)&&c.unshift(d);wh"\ "ile(d=d.parentNode);return c},!0);\nU(\"attribute\",function(a,b){var c"\ "=new F,d=a.getName(),e=b.attributes;if(e)if(\"*\"==d)for(var d=0,f;f=e["\ "d];d++)c.add(f);else(f=e.getNamedItem(d))&&c.add(f);return c},!1);U(\"c"\ "hild\",function(a,b,c,d,e){return G.call(null,a,b,k(c)?c:null,k(d)?d:nu"\ "ll,e||new F)},!1,!0);U(\"descendant\",D,!1,!0);U(\"descendant-or-self\""\ ",function(a,b,c,d){var e=new F;C(b,c,d)&&a.matches(b)&&e.add(b);return "\ "D(a,b,c,d,e)},!1,!0);\nU(\"following\",function(a,b,c,d){var e=new F;do"\ " for(var f=b;f=f.nextSibling;)C(f,c,d)&&a.matches(f)&&e.add(f),e=D(a,f,"\ "c,d,e);while(b=b.parentNode);return e},!1,!0);U(\"following-sibling\",f"\ "unction(a,b){for(var c=new F,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d"\ ");return c},!1);U(\"namespace\",function(){return new F},!1);U(\"parent"\ "\",function(a,b){var c=new F;if(9==b.nodeType)return c;if(2==b.nodeType"\ ")return c.add(b.ownerElement),c;var d=b.parentNode;a.matches(d)&&c.add("\ "d);return c},!1);\nU(\"preceding\",function(a,b,c,d){var e=new F,f=[];d"\ "o f.unshift(b);while(b=b.parentNode);for(var n=1,t=f.length;n<t;n++){va"\ "r v=[];for(b=f[n];b=b.previousSibling;)v.unshift(b);for(var B=0,aa=v.le"\ "ngth;B<aa;B++)b=v[B],C(b,c,d)&&a.matches(b)&&e.add(b),e=D(a,b,c,d,e)}re"\ "turn e},!0,!0);U(\"preceding-sibling\",function(a,b){for(var c=new F,d="\ "b;d=d.previousSibling;)a.matches(d)&&c.unshift(d);return c},!0);U(\"sel"\ "f\",function(a,b){var c=new F;a.matches(b)&&c.add(b);return c},!1);func"\ "tion V(a,b){return!!a&&1==a.nodeType&&(!b||a.tagName.toUpperCase()==b)}"\ "var ba=\"BUTTON INPUT OPTGROUP OPTION SELECT TEXTAREA\".split(\" \");\n"\ "function W(a){var b=a.tagName.toUpperCase();return 0<=m(ba,b)?a.disable"\ "d?!1:a.parentNode&&1==a.parentNode.nodeType&&\"OPTGROUP\"==b||\"OPTION"\ "\"==b?W(a.parentNode):!z(a,function(a){var b=a.parentNode;if(b&&V(b,\"F"\ "IELDSET\")&&b.disabled){if(!V(a,\"LEGEND\"))return!0;for(;a=void 0!=a.p"\ "reviousElementSibling?a.previousElementSibling:s(a.previousSibling);)if"\ "(V(a,\"LEGEND\"))return!0}return!1}):!0};var X=W,Y=[\"_\"],Z=h;Y[0]in Z"\ "||!Z.execScript||Z.execScript(\"var \"+Y[0]);for(var $;Y.length&&($=Y.s"\ "hift());)Y.length||void 0===X?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=X;; return this."\ "_.apply(null,arguments);}.apply({navigator:typeof window!=undefined?win"\ "dow.navigator:null,document:typeof window!=undefined?window.document:nu"\ "ll}, arguments);}" IS_ONLINE = \ "function(){return function(){var a=window;function c(e,h){this.code=e;t"\ "his.state=d[e]||f;this.message=h||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(b){return b.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var e=Error;function h(){}h.prototype=e.prototype;c.a="\ "e.prototype;c.prototype=new h})();\nvar f=\"unknown error\",d={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};d[13]=f;d[9]=\"unknown "\ "command\";c.prototype.toString=function(){return this.name+\": \"+this."\ "message};var g=this.navigator;var k=-1!=(g&&g.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){switch(\"browser_connection\"){case \"appca"\ "che\":return null!=a.applicationCache;case \"browser_connection\":retur"\ "n null!=a.navigator&&null!=a.navigator.onLine;case \"database\":return "\ "null!=a.openDatabase;case \"location\":return k?!1:null!=a.navigator&&n"\ "ull!=a.navigator.geolocation;case \"local_storage\":return null!=a.loca"\ "lStorage;case \"session_storage\":return null!=a.sessionStorage&&null!="\ "a.sessionStorage.clear;default:throw new c(13,\"Unsupported API identif"\ "ier provided as parameter\");}};function n(){if(m())return a.navigator."\ "onLine;throw new c(13,\"Undefined browser connection state\");}var p=["\ "\"_\"],q=this;p[0]in q||!q.execScript||q.execScript(\"var \"+p[0]);for("\ "var r;p.length&&(r=p.shift());)p.length||void 0===n?q=q[r]?q[r]:q[r]={}"\ ":q[r]=n;; return this._.apply(null,arguments);}.apply({navigator:typeof"\ " window!=undefined?window.navigator:null,document:typeof window!=undefi"\ "ned?window.document:null}, arguments);}" IS_SELECTED = \ "function(){return function(){function e(a){return function(){return a}}"\ "var h=this;function k(a){return\"string\"==typeof a};var l=Array.protot"\ "ype;function m(a,b){for(var c=a.length,d=k(a)?a.split(\"\"):a,f=0;f<c;f"\ "++)f in d&&b.call(void 0,d[f],f,a)}function aa(a,b){if(a.reduce)return "\ "a.reduce(b,\"\");var c=\"\";m(a,function(d,f){c=b.call(void 0,c,d,f,a)}"\ ");return c}function ba(a,b,c){return 2>=arguments.length?l.slice.call(a"\ ",b):l.slice.call(a,b,c)};function n(a,b){this.code=a;this.state=q[a]||r"\ ";this.message=b||\"\";var c=this.state.replace(/((?:^|\\s+)[a-z])/g,fun"\ "ction(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/g,\"\")}),d=c.len"\ "gth-5;if(0>d||c.indexOf(\"Error\",d)!=d)c+=\"Error\";this.name=c;c=Erro"\ "r(this.message);c.name=this.name;this.stack=c.stack||\"\"}(function(){v"\ "ar a=Error;function b(){}b.prototype=a.prototype;n.N=a.prototype;n.prot"\ "otype=new b})();\nvar r=\"unknown error\",q={15:\"element not selectabl"\ "e\",11:\"element not visible\",31:\"ime engine activation failed\",30:"\ "\"ime not available\",24:\"invalid cookie domain\",29:\"invalid element"\ " coordinates\",12:\"invalid element state\",32:\"invalid selector\",51:"\ "\"invalid selector\",52:\"invalid selector\",17:\"javascript error\",40"\ "5:\"unsupported operation\",34:\"move target out of bounds\",27:\"no su"\ "ch alert\",7:\"no such element\",8:\"no such frame\",23:\"no such windo"\ "w\",28:\"script timeout\",33:\"session not created\",10:\"stale element"\ " reference\",\n0:\"success\",21:\"timeout\",25:\"unable to set cookie\""\ ",26:\"unexpected alert open\"};q[13]=r;q[9]=\"unknown command\";n.proto"\ "type.toString=function(){return this.name+\": \"+this.message};var s,t,"\ "u,w=h.navigator;u=w&&w.platform||\"\";s=-1!=u.indexOf(\"Mac\");t=-1!=u."\ "indexOf(\"Win\");var x=-1!=u.indexOf(\"Linux\");function z(a,b){if(a.co"\ "ntains&&1==b.nodeType)return a==b||a.contains(b);if(\"undefined\"!=type"\ "of a.compareDocumentPosition)return a==b||Boolean(a.compareDocumentPosi"\ "tion(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nfunction ca(a,b)"\ "{if(a==b)return 0;if(a.compareDocumentPosition)return a.compareDocument"\ "Position(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&&\"sourceIndex"\ "\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType;if(c&&d)return a"\ ".sourceIndex-b.sourceIndex;var f=a.parentNode,g=b.parentNode;return f=="\ "g?A(a,b):!c&&z(f,b)?-1*B(a,b):!d&&z(g,a)?B(b,a):(c?a.sourceIndex:f.sour"\ "ceIndex)-(d?b.sourceIndex:g.sourceIndex)}d=9==a.nodeType?a:a.ownerDocum"\ "ent||a.document;c=d.createRange();c.selectNode(a);c.collapse(!0);\nd=d."\ "createRange();d.selectNode(b);d.collapse(!0);return c.compareBoundaryPo"\ "ints(h.Range.START_TO_END,d)}function B(a,b){var c=a.parentNode;if(c==b"\ ")return-1;for(var d=b;d.parentNode!=c;)d=d.parentNode;return A(d,a)}fun"\ "ction A(a,b){for(var c=b;c=c.previousSibling;)if(c==a)return-1;return 1"\ "};function C(a){var b=null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0"\ "==b||null==b?a.innerText:b,b=void 0==b||null==b?\"\":b);if(\"string\"!="\ "typeof b)if(9==c||1==c){a=9==c?a.documentElement:a.firstChild;for(var c"\ "=0,d=[],b=\"\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a="\ "a.firstChild);for(;c&&!(a=d[--c].nextSibling););}}else b=a.nodeValue;re"\ "turn\"\"+b}\nfunction D(a,b,c){if(null===b)return!0;try{if(!a.getAttrib"\ "ute)return!1}catch(d){return!1}return null==c?!!a.getAttribute(b):a.get"\ "Attribute(b,2)==c}function E(a,b,c,d,f){return da.call(null,a,b,k(c)?c:"\ "null,k(d)?d:null,f||new F)}\nfunction da(a,b,c,d,f){b.getElementsByName"\ "&&d&&\"name\"==c?(b=b.getElementsByName(d),m(b,function(b){a.matches(b)"\ "&&f.add(b)})):b.getElementsByClassName&&d&&\"class\"==c?(b=b.getElement"\ "sByClassName(d),m(b,function(b){b.className==d&&a.matches(b)&&f.add(b)}"\ ")):b.getElementsByTagName&&(b=b.getElementsByTagName(a.getName()),m(b,f"\ "unction(a){D(a,c,d)&&f.add(a)}));return f}function ea(a,b,c,d,f){for(b="\ "b.firstChild;b;b=b.nextSibling)D(b,c,d)&&a.matches(b)&&f.add(b);return "\ "f};function F(){this.g=this.f=null;this.l=0}function G(a){this.p=a;this"\ ".next=this.n=null}F.prototype.unshift=function(a){a=new G(a);a.next=thi"\ "s.f;this.g?this.f.n=a:this.f=this.g=a;this.f=a;this.l++};F.prototype.ad"\ "d=function(a){a=new G(a);a.n=this.g;this.f?this.g.next=a:this.f=this.g="\ "a;this.g=a;this.l++};function H(a){return(a=a.f)?a.p:null}function I(a)"\ "{return new J(a,!1)}function J(a,b){this.J=a;this.o=(this.q=b)?a.g:a.f;"\ "this.u=null}\nJ.prototype.next=function(){var a=this.o;if(null==a)retur"\ "n null;var b=this.u=a;this.o=this.q?a.n:a.next;return b.p};function K(a"\ ",b,c,d,f){b=b.evaluate(d);c=c.evaluate(d);var g;if(b instanceof F&&c in"\ "stanceof F){f=I(b);for(d=f.next();d;d=f.next())for(b=I(c),g=b.next();g;"\ "g=b.next())if(a(C(d),C(g)))return!0;return!1}if(b instanceof F||c insta"\ "nceof F){b instanceof F?f=b:(f=c,c=b);f=I(f);b=typeof c;for(d=f.next();"\ "d;d=f.next()){switch(b){case \"number\":d=+C(d);break;case \"boolean\":"\ "d=!!C(d);break;case \"string\":d=C(d);break;default:throw Error(\"Illeg"\ "al primitive type for comparison.\");}if(a(d,c))return!0}return!1}retur"\ "n f?\n\"boolean\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number"\ "\"==typeof b||\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function M("\ "a,b,c,d){this.v=a;this.L=b;this.s=c;this.t=d}M.prototype.toString=funct"\ "ion(){return this.v};var N={};function O(a,b,c,d){if(a in N)throw Error"\ "(\"Binary operator already created: \"+a);a=new M(a,b,c,d);N[a.toString"\ "()]=a}O(\"div\",6,1,function(a,b,c){return a.d(c)/b.d(c)});O(\"mod\",6,"\ "1,function(a,b,c){return a.d(c)%b.d(c)});O(\"*\",6,1,function(a,b,c){re"\ "turn a.d(c)*b.d(c)});\nO(\"+\",5,1,function(a,b,c){return a.d(c)+b.d(c)"\ "});O(\"-\",5,1,function(a,b,c){return a.d(c)-b.d(c)});O(\"<\",4,2,funct"\ "ion(a,b,c){return K(function(a,b){return a<b},a,b,c)});O(\">\",4,2,func"\ "tion(a,b,c){return K(function(a,b){return a>b},a,b,c)});O(\"<=\",4,2,fu"\ "nction(a,b,c){return K(function(a,b){return a<=b},a,b,c)});O(\">=\",4,2"\ ",function(a,b,c){return K(function(a,b){return a>=b},a,b,c)});O(\"=\",3"\ ",2,function(a,b,c){return K(function(a,b){return a==b},a,b,c,!0)});\nO("\ "\"!=\",3,2,function(a,b,c){return K(function(a,b){return a!=b},a,b,c,!0"\ ")});O(\"and\",2,2,function(a,b,c){return a.j(c)&&b.j(c)});O(\"or\",1,2,"\ "function(a,b,c){return a.j(c)||b.j(c)});function P(a,b,c,d,f,g,p,v,y){t"\ "his.m=a;this.s=b;this.I=c;this.H=d;this.G=f;this.t=g;this.F=p;this.D=vo"\ "id 0!==v?v:p;this.K=!!y}P.prototype.toString=function(){return this.m};"\ "var Q={};function R(a,b,c,d,f,g,p,v){if(a in Q)throw Error(\"Function a"\ "lready created: \"+a+\".\");Q[a]=new P(a,b,c,d,!1,f,g,p,v)}R(\"boolean"\ "\",2,!1,!1,function(a,b){return b.j(a)},1);R(\"ceiling\",1,!1,!1,functi"\ "on(a,b){return Math.ceil(b.d(a))},1);\nR(\"concat\",3,!1,!1,function(a,"\ "b){var c=ba(arguments,1);return aa(c,function(b,c){return b+c.c(a)})},2"\ ",null);R(\"contains\",2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return-"\ "1!=b.indexOf(a)},2);R(\"count\",1,!1,!1,function(a,b){return b.evaluate"\ "(a).l},1,1,!0);R(\"false\",2,!1,!1,e(!1),0);R(\"floor\",1,!1,!1,functio"\ "n(a,b){return Math.floor(b.d(a))},1);\nR(\"id\",4,!1,!1,function(a,b){v"\ "ar c=a.h(),d=9==c.nodeType?c:c.ownerDocument,c=b.c(a).split(/\\s+/),f=["\ "];m(c,function(a){a=d.getElementById(a);var b;if(!(b=!a)){a:if(k(f))b=k"\ "(a)&&1==a.length?f.indexOf(a,0):-1;else{for(b=0;b<f.length;b++)if(b in "\ "f&&f[b]===a)break a;b=-1}b=0<=b}b||f.push(a)});f.sort(ca);var g=new F;m"\ "(f,function(a){g.add(a)});return g},1);R(\"lang\",2,!1,!1,e(!1),1);R(\""\ "last\",1,!0,!1,function(a){if(1!=arguments.length)throw Error(\"Functio"\ "n last expects ()\");return a.B()},0);\nR(\"local-name\",3,!1,!0,functi"\ "on(a,b){var c=b?H(b.evaluate(a)):a.h();return c?c.nodeName.toLowerCase("\ "):\"\"},0,1,!0);R(\"name\",3,!1,!0,function(a,b){var c=b?H(b.evaluate(a"\ ")):a.h();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);R(\"namespace-"\ "uri\",3,!0,!1,e(\"\"),0,1,!0);R(\"normalize-space\",3,!1,!0,function(a,"\ "b){return(b?b.c(a):C(a.h())).replace(/[\\s\\xa0]+/g,\" \").replace(/^"\ "\\s+|\\s+$/g,\"\")},0,1);R(\"not\",2,!1,!1,function(a,b){return!b.j(a)}"\ ",1);R(\"number\",1,!1,!0,function(a,b){return b?b.d(a):+C(a.h())},0,1);"\ "\nR(\"position\",1,!0,!1,function(a){return a.C()},0);R(\"round\",1,!1,"\ "!1,function(a,b){return Math.round(b.d(a))},1);R(\"starts-with\",2,!1,!"\ "1,function(a,b,c){b=b.c(a);a=c.c(a);return 0==b.lastIndexOf(a,0)},2);R("\ "\"string\",3,!1,!0,function(a,b){return b?b.c(a):C(a.h())},0,1);R(\"str"\ "ing-length\",1,!1,!0,function(a,b){return(b?b.c(a):C(a.h())).length},0,"\ "1);\nR(\"substring\",3,!1,!1,function(a,b,c,d){c=c.d(a);if(isNaN(c)||In"\ "finity==c||-Infinity==c)return\"\";d=d?d.d(a):Infinity;if(isNaN(d)||-In"\ "finity===d)return\"\";c=Math.round(c)-1;var f=Math.max(c,0);a=b.c(a);if"\ "(Infinity==d)return a.substring(f);b=Math.round(d);return a.substring(f"\ ",c+b)},2,3);R(\"substring-after\",3,!1,!1,function(a,b,c){b=b.c(a);a=c."\ "c(a);c=b.indexOf(a);return-1==c?\"\":b.substring(c+a.length)},2);\nR(\""\ "substring-before\",3,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);a=b.indexO"\ "f(a);return-1==a?\"\":b.substring(0,a)},2);R(\"sum\",1,!1,!1,function(a"\ ",b){for(var c=I(b.evaluate(a)),d=0,f=c.next();f;f=c.next())d+=+C(f);ret"\ "urn d},1,1,!0);R(\"translate\",3,!1,!1,function(a,b,c,d){b=b.c(a);c=c.c"\ "(a);var f=d.c(a);a=[];for(d=0;d<c.length;d++){var g=c.charAt(d);g in a|"\ "|(a[g]=f.charAt(d))}c=\"\";for(d=0;d<b.length;d++)g=b.charAt(d),c+=g in"\ " a?a[g]:g;return c},3);R(\"true\",2,!1,!1,e(!0),0);function S(a,b,c,d){"\ "this.m=a;this.A=b;this.q=c;this.O=d}S.prototype.toString=function(){ret"\ "urn this.m};var fa={};function T(a,b,c,d){if(a in fa)throw Error(\"Axis"\ " already created: \"+a);fa[a]=new S(a,b,c,!!d)}T(\"ancestor\",function("\ "a,b){for(var c=new F,d=b;d=d.parentNode;)a.matches(d)&&c.unshift(d);ret"\ "urn c},!0);T(\"ancestor-or-self\",function(a,b){var c=new F,d=b;do a.ma"\ "tches(d)&&c.unshift(d);while(d=d.parentNode);return c},!0);\nT(\"attrib"\ "ute\",function(a,b){var c=new F,d=a.getName(),f=b.attributes;if(f)if(\""\ "*\"==d)for(var d=0,g;g=f[d];d++)c.add(g);else(g=f.getNamedItem(d))&&c.a"\ "dd(g);return c},!1);T(\"child\",function(a,b,c,d,f){return ea.call(null"\ ",a,b,k(c)?c:null,k(d)?d:null,f||new F)},!1,!0);T(\"descendant\",E,!1,!0"\ ");T(\"descendant-or-self\",function(a,b,c,d){var f=new F;D(b,c,d)&&a.ma"\ "tches(b)&&f.add(b);return E(a,b,c,d,f)},!1,!0);\nT(\"following\",functi"\ "on(a,b,c,d){var f=new F;do for(var g=b;g=g.nextSibling;)D(g,c,d)&&a.mat"\ "ches(g)&&f.add(g),f=E(a,g,c,d,f);while(b=b.parentNode);return f},!1,!0)"\ ";T(\"following-sibling\",function(a,b){for(var c=new F,d=b;d=d.nextSibl"\ "ing;)a.matches(d)&&c.add(d);return c},!1);T(\"namespace\",function(){re"\ "turn new F},!1);T(\"parent\",function(a,b){var c=new F;if(9==b.nodeType"\ ")return c;if(2==b.nodeType)return c.add(b.ownerElement),c;var d=b.paren"\ "tNode;a.matches(d)&&c.add(d);return c},!1);\nT(\"preceding\",function(a"\ ",b,c,d){var f=new F,g=[];do g.unshift(b);while(b=b.parentNode);for(var "\ "p=1,v=g.length;p<v;p++){var y=[];for(b=g[p];b=b.previousSibling;)y.unsh"\ "ift(b);for(var L=0,ka=y.length;L<ka;L++)b=y[L],D(b,c,d)&&a.matches(b)&&"\ "f.add(b),f=E(a,b,c,d,f)}return f},!0,!0);T(\"preceding-sibling\",functi"\ "on(a,b){for(var c=new F,d=b;d=d.previousSibling;)a.matches(d)&&c.unshif"\ "t(d);return c},!0);T(\"self\",function(a,b){var c=new F;a.matches(b)&&c"\ ".add(b);return c},!1);function ga(a){return a&&1==a.nodeType&&\"OPTION"\ "\"==a.tagName.toUpperCase()?!0:a&&1==a.nodeType&&\"INPUT\"==a.tagName.t"\ "oUpperCase()?(a=a.type.toLowerCase(),\"checkbox\"==a||\"radio\"==a):!1}"\ ";function U(a,b){this.i={};this.e=[];var c=arguments.length;if(1<c){if("\ "c%2)throw Error(\"Uneven number of arguments\");for(var d=0;d<c;d+=2)th"\ "is.set(arguments[d],arguments[d+1])}else if(a){var f;if(a instanceof U)"\ "for(d=ha(a),ia(a),f=[],c=0;c<a.e.length;c++)f.push(a.i[a.e[c]]);else{va"\ "r c=[],g=0;for(d in a)c[g++]=d;d=c;c=[];g=0;for(f in a)c[g++]=a[f];f=c}"\ "for(c=0;c<d.length;c++)this.set(d[c],f[c])}}U.prototype.k=0;U.prototype"\ ".w=0;function ha(a){ia(a);return a.e.concat()}\nfunction ia(a){if(a.k!="\ "a.e.length){for(var b=0,c=0;b<a.e.length;){var d=a.e[b];Object.prototyp"\ "e.hasOwnProperty.call(a.i,d)&&(a.e[c++]=d);b++}a.e.length=c}if(a.k!=a.e"\ ".length){for(var f={},c=b=0;b<a.e.length;)d=a.e[b],Object.prototype.has"\ "OwnProperty.call(f,d)||(a.e[c++]=d,f[d]=1),b++;a.e.length=c}}U.prototyp"\ "e.get=function(a,b){return Object.prototype.hasOwnProperty.call(this.i,"\ "a)?this.i[a]:b};\nU.prototype.set=function(a,b){Object.prototype.hasOwn"\ "Property.call(this.i,a)||(this.k++,this.e.push(a),this.w++);this.i[a]=b"\ "};var V={};function W(a,b,c){var d=typeof a;(\"object\"==d&&null!=a||\""\ "function\"==d)&&(a=a.a);a=new ja(a,b,c);!b||b in V&&!c||(V[b]={key:a,sh"\ "ift:!1},c&&(V[c]={key:a,shift:!0}));return a}function ja(a,b,c){this.co"\ "de=a;this.r=b||null;this.M=c||this.r}W(8);W(9);W(13);var la=W(16),ma=W("\ "17),na=W(18);W(19);W(20);W(27);W(32,\" \");W(33);W(34);W(35);W(36);W(37"\ ");W(38);W(39);W(40);W(44);W(45);W(46);W(48,\"0\",\")\");W(49,\"1\",\"!"\ "\");W(50,\"2\",\"@\");W(51,\"3\",\"#\");W(52,\"4\",\"$\");W(53,\"5\",\""\ "%\");W(54,\"6\",\"^\");W(55,\"7\",\"&\");\nW(56,\"8\",\"*\");W(57,\"9\""\ ",\"(\");W(65,\"a\",\"A\");W(66,\"b\",\"B\");W(67,\"c\",\"C\");W(68,\"d"\ "\",\"D\");W(69,\"e\",\"E\");W(70,\"f\",\"F\");W(71,\"g\",\"G\");W(72,\""\ "h\",\"H\");W(73,\"i\",\"I\");W(74,\"j\",\"J\");W(75,\"k\",\"K\");W(76,"\ "\"l\",\"L\");W(77,\"m\",\"M\");W(78,\"n\",\"N\");W(79,\"o\",\"O\");W(80"\ ",\"p\",\"P\");W(81,\"q\",\"Q\");W(82,\"r\",\"R\");W(83,\"s\",\"S\");W(8"\ "4,\"t\",\"T\");W(85,\"u\",\"U\");W(86,\"v\",\"V\");W(87,\"w\",\"W\");W("\ "88,\"x\",\"X\");W(89,\"y\",\"Y\");W(90,\"z\",\"Z\");var oa=W(t?{b:91,a:"\ "91,opera:219}:s?{b:224,a:91,opera:17}:{b:0,a:91,opera:null});\nW(t?{b:9"\ "2,a:92,opera:220}:s?{b:224,a:93,opera:17}:{b:0,a:92,opera:null});W(t?{b"\ ":93,a:93,opera:0}:s?{b:0,a:0,opera:16}:{b:93,a:null,opera:0});W({b:96,a"\ ":96,opera:48},\"0\");W({b:97,a:97,opera:49},\"1\");W({b:98,a:98,opera:5"\ "0},\"2\");W({b:99,a:99,opera:51},\"3\");W({b:100,a:100,opera:52},\"4\")"\ ";W({b:101,a:101,opera:53},\"5\");W({b:102,a:102,opera:54},\"6\");W({b:1"\ "03,a:103,opera:55},\"7\");W({b:104,a:104,opera:56},\"8\");W({b:105,a:10"\ "5,opera:57},\"9\");W({b:106,a:106,opera:x?56:42},\"*\");W({b:107,a:107,"\ "opera:x?61:43},\"+\");\nW({b:109,a:109,opera:x?109:45},\"-\");W({b:110,"\ "a:110,opera:x?190:78},\".\");W({b:111,a:111,opera:x?191:47},\"/\");W(14"\ "4);W(112);W(113);W(114);W(115);W(116);W(117);W(118);W(119);W(120);W(121"\ ");W(122);W(123);W({b:107,a:187,opera:61},\"=\",\"+\");W(108,\",\");W({b"\ ":109,a:189,opera:109},\"-\",\"_\");W(188,\",\",\"<\");W(190,\".\",\">\""\ ");W(191,\"/\",\"?\");W(192,\"`\",\"~\");W(219,\"[\",\"{\");W(220,\""\ "\\\\\",\"|\");W(221,\"]\",\"}\");W({b:59,a:186,opera:59},\";\",\":\");W"\ "(222,\"'\",'\"');var X=new U;X.set(1,la);X.set(2,ma);X.set(4,na);X.set("\ "8,oa);\n(function(a){var b=new U;m(ha(a),function(c){b.set(a.get(c).cod"\ "e,c)});return b})(X);function pa(a){if(ga(a)){if(!ga(a))throw new n(15,"\ "\"Element is not selectable\");var b=\"selected\",c=a.type&&a.type.toLo"\ "werCase();if(\"checkbox\"==c||\"radio\"==c)b=\"checked\";a=!!a[b]}else "\ "a=!1;return a}var Y=[\"_\"],Z=h;Y[0]in Z||!Z.execScript||Z.execScript("\ "\"var \"+Y[0]);for(var $;Y.length&&($=Y.shift());)Y.length||void 0===pa"\ "?Z=Z[$]?Z[$]:Z[$]={}:Z[$]=pa;; return this._.apply(null,arguments);}.ap"\ "ply({navigator:typeof window!=undefined?window.navigator:null,document:"\ "typeof window!=undefined?window.document:null}, arguments);}" REMOVE_LOCAL_STORAGE_ITEM = \ "function(){return function(){var c=window;function e(a,d){this.code=a;t"\ "his.state=f[a]||g;this.message=d||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),m=b.length-5;if(0>m||b.indexOf(\"Error\",m)!=m)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function d(){}d.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new d})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction l(){var a=c||c;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.getItem=function(a){return this.a.getItem(a)};n.prototype.removeI"\ "tem=function(a){var d=this.getItem(a);this.a.removeItem(a);return d};n."\ "prototype.clear=function(){this.a.clear()};function p(a){if(!l())throw "\ "new e(13,\"Local storage undefined\");return(new n(c.localStorage)).rem"\ "oveItem(a)}var q=[\"_\"],r=this;q[0]in r||!r.execScript||r.execScript("\ "\"var \"+q[0]);for(var s;q.length&&(s=q.shift());)q.length||void 0===p?"\ "r=r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,arguments);}.appl"\ "y({navigator:typeof window!=undefined?window.navigator:null,document:ty"\ "peof window!=undefined?window.document:null}, arguments);}" REMOVE_SESSION_STORAGE_ITEM = \ "function(){return function(){var d=window;function e(a,b){this.code=a;t"\ "his.state=f[a]||g;this.message=b||\"\";var c=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),m=c.length-5;if(0>m||c.indexOf(\"Error\",m)!=m)c+=\"Error\";t"\ "his.name=c;c=Error(this.message);c.name=this.name;this.stack=c.stack||"\ "\"\"}(function(){var a=Error;function b(){}b.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new b})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction l(){var a=d||d;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.getItem=function(a){return this.a.getItem(a)};n.prototype.removeI"\ "tem=function(a){var b=this.getItem(a);this.a.removeItem(a);return b};n."\ "prototype.clear=function(){this.a.clear()};function p(a){var b;if(l())b"\ "=new n(d.sessionStorage);else throw new e(13,\"Session storage undefine"\ "d\");return b.removeItem(a)}var q=[\"_\"],r=this;q[0]in r||!r.execScrip"\ "t||r.execScript(\"var \"+q[0]);for(var s;q.length&&(s=q.shift());)q.len"\ "gth||void 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(null,a"\ "rguments);}.apply({navigator:typeof window!=undefined?window.navigator:"\ "null,document:typeof window!=undefined?window.document:null}, arguments"\ ");}" SET_LOCAL_STORAGE_ITEM = \ "function(){return function(){var d=window;function e(a,c){this.code=a;t"\ "his.state=f[a]||g;this.message=c||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function c(){}c.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new c})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=d||d;switch(\"local_storage\"){case "\ "\"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.setItem=function(a,c){try{this.a.setItem(a,c+\"\")}catch(b){throw"\ " new e(13,b.message);}};n.prototype.clear=function(){this.a.clear()};fu"\ "nction p(a,c){if(!m())throw new e(13,\"Local storage undefined\");(new "\ "n(d.localStorage)).setItem(a,c)}var q=[\"_\"],r=this;q[0]in r||!r.execS"\ "cript||r.execScript(\"var \"+q[0]);for(var s;q.length&&(s=q.shift());)q"\ ".length||void 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; return this._.apply(nu"\ "ll,arguments);}.apply({navigator:typeof window!=undefined?window.naviga"\ "tor:null,document:typeof window!=undefined?window.document:null}, argum"\ "ents);}" SET_SESSION_STORAGE_ITEM = \ "function(){return function(){var d=window;function e(a,c){this.code=a;t"\ "his.state=f[a]||g;this.message=c||\"\";var b=this.state.replace(/((?:^|"\ "\\s+)[a-z])/g,function(a){return a.toUpperCase().replace(/^[\\s\\xa0]+/"\ "g,\"\")}),l=b.length-5;if(0>l||b.indexOf(\"Error\",l)!=l)b+=\"Error\";t"\ "his.name=b;b=Error(this.message);b.name=this.name;this.stack=b.stack||"\ "\"\"}(function(){var a=Error;function c(){}c.prototype=a.prototype;e.b="\ "a.prototype;e.prototype=new c})();\nvar g=\"unknown error\",f={15:\"ele"\ "ment not selectable\",11:\"element not visible\",31:\"ime engine activa"\ "tion failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:"\ "\"invalid element coordinates\",12:\"invalid element state\",32:\"inval"\ "id selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"java"\ "script error\",405:\"unsupported operation\",34:\"move target out of bo"\ "unds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",2"\ "3:\"no such window\",28:\"script timeout\",33:\"session not created\",1"\ "0:\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unabl"\ "e to set cookie\",26:\"unexpected alert open\"};f[13]=g;f[9]=\"unknown "\ "command\";e.prototype.toString=function(){return this.name+\": \"+this."\ "message};var h=this.navigator;var k=-1!=(h&&h.platform||\"\").indexOf("\ "\"Win\")&&!1;\nfunction m(){var a=d||d;switch(\"session_storage\"){case"\ " \"appcache\":return null!=a.applicationCache;case \"browser_connection"\ "\":return null!=a.navigator&&null!=a.navigator.onLine;case \"database\""\ ":return null!=a.openDatabase;case \"location\":return k?!1:null!=a.navi"\ "gator&&null!=a.navigator.geolocation;case \"local_storage\":return null"\ "!=a.localStorage;case \"session_storage\":return null!=a.sessionStorage"\ "&&null!=a.sessionStorage.clear;default:throw new e(13,\"Unsupported API"\ " identifier provided as parameter\");}}\n;function n(a){this.a=a}n.prot"\ "otype.setItem=function(a,c){try{this.a.setItem(a,c+\"\")}catch(b){throw"\ " new e(13,b.message);}};n.prototype.clear=function(){this.a.clear()};fu"\ "nction p(a,c){var b;if(m())b=new n(d.sessionStorage);else throw new e(1"\ "3,\"Session storage undefined\");b.setItem(a,c)}var q=[\"_\"],r=this;q["\ "0]in r||!r.execScript||r.execScript(\"var \"+q[0]);for(var s;q.length&&"\ "(s=q.shift());)q.length||void 0===p?r=r[s]?r[s]:r[s]={}:r[s]=p;; return"\ " this._.apply(null,arguments);}.apply({navigator:typeof window!=undefin"\ "ed?window.navigator:null,document:typeof window!=undefined?window.docum"\ "ent:null}, arguments);}" SUBMIT = \ "function(){return function(){function e(a){return function(){return thi"\ "s[a]}}function h(a){return function(){return a}}var k=this;function l(a"\ "){return\"string\"==typeof a}function m(a,b){function c(){}c.prototype="\ "b.prototype;a.X=b.prototype;a.prototype=new c;a.prototype.constructor=a"\ "};var aa=window;var n=Array.prototype;function q(a,b){for(var c=a.lengt"\ "h,d=l(a)?a.split(\"\"):a,f=0;f<c;f++)f in d&&b.call(void 0,d[f],f,a)}fu"\ "nction ba(a,b){if(a.reduce)return a.reduce(b,\"\");var c=\"\";q(a,funct"\ "ion(d,f){c=b.call(void 0,c,d,f,a)});return c}function ca(a,b,c){return "\ "2>=arguments.length?n.slice.call(a,b):n.slice.call(a,b,c)};function r(a"\ ",b){this.code=a;this.state=s[a]||t;this.message=b||\"\";var c=this.stat"\ "e.replace(/((?:^|\\s+)[a-z])/g,function(a){return a.toUpperCase().repla"\ "ce(/^[\\s\\xa0]+/g,\"\")}),d=c.length-5;if(0>d||c.indexOf(\"Error\",d)!"\ "=d)c+=\"Error\";this.name=c;c=Error(this.message);c.name=this.name;this"\ ".stack=c.stack||\"\"}m(r,Error);\nvar t=\"unknown error\",s={15:\"eleme"\ "nt not selectable\",11:\"element not visible\",31:\"ime engine activati"\ "on failed\",30:\"ime not available\",24:\"invalid cookie domain\",29:\""\ "invalid element coordinates\",12:\"invalid element state\",32:\"invalid"\ " selector\",51:\"invalid selector\",52:\"invalid selector\",17:\"javasc"\ "ript error\",405:\"unsupported operation\",34:\"move target out of boun"\ "ds\",27:\"no such alert\",7:\"no such element\",8:\"no such frame\",23:"\ "\"no such window\",28:\"script timeout\",33:\"session not created\",10:"\ "\"stale element reference\",\n0:\"success\",21:\"timeout\",25:\"unable "\ "to set cookie\",26:\"unexpected alert open\"};s[13]=t;s[9]=\"unknown co"\ "mmand\";r.prototype.toString=function(){return this.name+\": \"+this.me"\ "ssage};var u,v,x,y=k.navigator;x=y&&y.platform||\"\";u=-1!=x.indexOf(\""\ "Mac\");v=-1!=x.indexOf(\"Win\");var A=-1!=x.indexOf(\"Linux\");function"\ " B(a,b){if(a.contains&&1==b.nodeType)return a==b||a.contains(b);if(\"un"\ "defined\"!=typeof a.compareDocumentPosition)return a==b||Boolean(a.comp"\ "areDocumentPosition(b)&16);for(;b&&a!=b;)b=b.parentNode;return b==a}\nf"\ "unction da(a,b){if(a==b)return 0;if(a.compareDocumentPosition)return a."\ "compareDocumentPosition(b)&2?1:-1;if(\"sourceIndex\"in a||a.parentNode&"\ "&\"sourceIndex\"in a.parentNode){var c=1==a.nodeType,d=1==b.nodeType;if"\ "(c&&d)return a.sourceIndex-b.sourceIndex;var f=a.parentNode,g=b.parentN"\ "ode;return f==g?C(a,b):!c&&B(f,b)?-1*D(a,b):!d&&B(g,a)?D(b,a):(c?a.sour"\ "ceIndex:f.sourceIndex)-(d?b.sourceIndex:g.sourceIndex)}d=E(a);c=d.creat"\ "eRange();c.selectNode(a);c.collapse(!0);d=d.createRange();d.selectNode("\ "b);d.collapse(!0);\nreturn c.compareBoundaryPoints(k.Range.START_TO_END"\ ",d)}function D(a,b){var c=a.parentNode;if(c==b)return-1;for(var d=b;d.p"\ "arentNode!=c;)d=d.parentNode;return C(d,a)}function C(a,b){for(var c=b;"\ "c=c.previousSibling;)if(c==a)return-1;return 1}function E(a){return 9=="\ "a.nodeType?a:a.ownerDocument||a.document}function F(a,b,c){c||(a=a.pare"\ "ntNode);for(c=0;a;){if(b(a))return a;a=a.parentNode;c++}return null};fu"\ "nction G(a){var b=null,c=a.nodeType;1==c&&(b=a.textContent,b=void 0==b|"\ "|null==b?a.innerText:b,b=void 0==b||null==b?\"\":b);if(\"string\"!=type"\ "of b)if(9==c||1==c){a=9==c?a.documentElement:a.firstChild;for(var c=0,d"\ "=[],b=\"\";a;){do 1!=a.nodeType&&(b+=a.nodeValue),d[c++]=a;while(a=a.fi"\ "rstChild);for(;c&&!(a=d[--c].nextSibling););}}else b=a.nodeValue;return"\ "\"\"+b}\nfunction H(a,b,c){if(null===b)return!0;try{if(!a.getAttribute)"\ "return!1}catch(d){return!1}return null==c?!!a.getAttribute(b):a.getAttr"\ "ibute(b,2)==c}function I(a,b,c,d,f){return ea.call(null,a,b,l(c)?c:null"\ ",l(d)?d:null,f||new J)}\nfunction ea(a,b,c,d,f){b.getElementsByName&&d&"\ "&\"name\"==c?(b=b.getElementsByName(d),q(b,function(b){a.matches(b)&&f."\ "add(b)})):b.getElementsByClassName&&d&&\"class\"==c?(b=b.getElementsByC"\ "lassName(d),q(b,function(b){b.className==d&&a.matches(b)&&f.add(b)})):b"\ ".getElementsByTagName&&(b=b.getElementsByTagName(a.getName()),q(b,funct"\ "ion(a){H(a,c,d)&&f.add(a)}));return f}function fa(a,b,c,d,f){for(b=b.fi"\ "rstChild;b;b=b.nextSibling)H(b,c,d)&&a.matches(b)&&f.add(b);return f};f"\ "unction J(){this.g=this.f=null;this.l=0}function K(a){this.r=a;this.nex"\ "t=this.n=null}J.prototype.unshift=function(a){a=new K(a);a.next=this.f;"\ "this.g?this.f.n=a:this.f=this.g=a;this.f=a;this.l++};J.prototype.add=fu"\ "nction(a){a=new K(a);a.n=this.g;this.f?this.g.next=a:this.f=this.g=a;th"\ "is.g=a;this.l++};function ga(a){return(a=a.f)?a.r:null}function L(a){re"\ "turn new ha(a,!1)}function ha(a,b){this.S=a;this.o=(this.s=b)?a.g:a.f;t"\ "his.D=null}\nha.prototype.next=function(){var a=this.o;if(null==a)retur"\ "n null;var b=this.D=a;this.o=this.s?a.n:a.next;return b.r};function M(a"\ ",b,c,d,f){b=b.evaluate(d);c=c.evaluate(d);var g;if(b instanceof J&&c in"\ "stanceof J){f=L(b);for(d=f.next();d;d=f.next())for(b=L(c),g=b.next();g;"\ "g=b.next())if(a(G(d),G(g)))return!0;return!1}if(b instanceof J||c insta"\ "nceof J){b instanceof J?f=b:(f=c,c=b);f=L(f);b=typeof c;for(d=f.next();"\ "d;d=f.next()){switch(b){case \"number\":d=+G(d);break;case \"boolean\":"\ "d=!!G(d);break;case \"string\":d=G(d);break;default:throw Error(\"Illeg"\ "al primitive type for comparison.\");}if(a(d,c))return!0}return!1}retur"\ "n f?\n\"boolean\"==typeof b||\"boolean\"==typeof c?a(!!b,!!c):\"number"\ "\"==typeof b||\"number\"==typeof c?a(+b,+c):a(b,c):a(+b,+c)}function ia"\ "(a,b,c,d){this.F=a;this.U=b;this.A=c;this.B=d}ia.prototype.toString=e("\ "\"F\");var ja={};function N(a,b,c,d){if(a in ja)throw Error(\"Binary op"\ "erator already created: \"+a);a=new ia(a,b,c,d);ja[a.toString()]=a}N(\""\ "div\",6,1,function(a,b,c){return a.d(c)/b.d(c)});N(\"mod\",6,1,function"\ "(a,b,c){return a.d(c)%b.d(c)});N(\"*\",6,1,function(a,b,c){return a.d(c"\ ")*b.d(c)});\nN(\"+\",5,1,function(a,b,c){return a.d(c)+b.d(c)});N(\"-\""\ ",5,1,function(a,b,c){return a.d(c)-b.d(c)});N(\"<\",4,2,function(a,b,c)"\ "{return M(function(a,b){return a<b},a,b,c)});N(\">\",4,2,function(a,b,c"\ "){return M(function(a,b){return a>b},a,b,c)});N(\"<=\",4,2,function(a,b"\ ",c){return M(function(a,b){return a<=b},a,b,c)});N(\">=\",4,2,function("\ "a,b,c){return M(function(a,b){return a>=b},a,b,c)});N(\"=\",3,2,functio"\ "n(a,b,c){return M(function(a,b){return a==b},a,b,c,!0)});\nN(\"!=\",3,2"\ ",function(a,b,c){return M(function(a,b){return a!=b},a,b,c,!0)});N(\"an"\ "d\",2,2,function(a,b,c){return a.j(c)&&b.j(c)});N(\"or\",1,2,function(a"\ ",b,c){return a.j(c)||b.j(c)});function ka(a,b,c,d,f,g,p,w,z){this.m=a;t"\ "his.A=b;this.R=c;this.Q=d;this.P=f;this.B=g;this.N=p;this.M=void 0!==w?"\ "w:p;this.T=!!z}ka.prototype.toString=e(\"m\");var la={};function O(a,b,"\ "c,d,f,g,p,w){if(a in la)throw Error(\"Function already created: \"+a+\""\ ".\");la[a]=new ka(a,b,c,d,!1,f,g,p,w)}O(\"boolean\",2,!1,!1,function(a,"\ "b){return b.j(a)},1);O(\"ceiling\",1,!1,!1,function(a,b){return Math.ce"\ "il(b.d(a))},1);\nO(\"concat\",3,!1,!1,function(a,b){var c=ca(arguments,"\ "1);return ba(c,function(b,c){return b+c.c(a)})},2,null);O(\"contains\","\ "2,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);return-1!=b.indexOf(a)},2);O("\ "\"count\",1,!1,!1,function(a,b){return b.evaluate(a).l},1,1,!0);O(\"fal"\ "se\",2,!1,!1,h(!1),0);O(\"floor\",1,!1,!1,function(a,b){return Math.flo"\ "or(b.d(a))},1);\nO(\"id\",4,!1,!1,function(a,b){var c=a.h(),d=9==c.node"\ "Type?c:c.ownerDocument,c=b.c(a).split(/\\s+/),f=[];q(c,function(a){a=d."\ "getElementById(a);var b;if(!(b=!a)){a:if(l(f))b=l(a)&&1==a.length?f.ind"\ "exOf(a,0):-1;else{for(b=0;b<f.length;b++)if(b in f&&f[b]===a)break a;b="\ "-1}b=0<=b}b||f.push(a)});f.sort(da);var g=new J;q(f,function(a){g.add(a"\ ")});return g},1);O(\"lang\",2,!1,!1,h(!1),1);O(\"last\",1,!0,!1,functio"\ "n(a){if(1!=arguments.length)throw Error(\"Function last expects ()\");r"\ "eturn a.K()},0);\nO(\"local-name\",3,!1,!0,function(a,b){var c=b?ga(b.e"\ "valuate(a)):a.h();return c?c.nodeName.toLowerCase():\"\"},0,1,!0);O(\"n"\ "ame\",3,!1,!0,function(a,b){var c=b?ga(b.evaluate(a)):a.h();return c?c."\ "nodeName.toLowerCase():\"\"},0,1,!0);O(\"namespace-uri\",3,!0,!1,h(\"\""\ "),0,1,!0);O(\"normalize-space\",3,!1,!0,function(a,b){return(b?b.c(a):G"\ "(a.h())).replace(/[\\s\\xa0]+/g,\" \").replace(/^\\s+|\\s+$/g,\"\")},0,"\ "1);O(\"not\",2,!1,!1,function(a,b){return!b.j(a)},1);O(\"number\",1,!1,"\ "!0,function(a,b){return b?b.d(a):+G(a.h())},0,1);\nO(\"position\",1,!0,"\ "!1,function(a){return a.L()},0);O(\"round\",1,!1,!1,function(a,b){retur"\ "n Math.round(b.d(a))},1);O(\"starts-with\",2,!1,!1,function(a,b,c){b=b."\ "c(a);a=c.c(a);return 0==b.lastIndexOf(a,0)},2);O(\"string\",3,!1,!0,fun"\ "ction(a,b){return b?b.c(a):G(a.h())},0,1);O(\"string-length\",1,!1,!0,f"\ "unction(a,b){return(b?b.c(a):G(a.h())).length},0,1);\nO(\"substring\",3"\ ",!1,!1,function(a,b,c,d){c=c.d(a);if(isNaN(c)||Infinity==c||-Infinity=="\ "c)return\"\";d=d?d.d(a):Infinity;if(isNaN(d)||-Infinity===d)return\"\";"\ "c=Math.round(c)-1;var f=Math.max(c,0);a=b.c(a);if(Infinity==d)return a."\ "substring(f);b=Math.round(d);return a.substring(f,c+b)},2,3);O(\"substr"\ "ing-after\",3,!1,!1,function(a,b,c){b=b.c(a);a=c.c(a);c=b.indexOf(a);re"\ "turn-1==c?\"\":b.substring(c+a.length)},2);\nO(\"substring-before\",3,!"\ "1,!1,function(a,b,c){b=b.c(a);a=c.c(a);a=b.indexOf(a);return-1==a?\"\":"\ "b.substring(0,a)},2);O(\"sum\",1,!1,!1,function(a,b){for(var c=L(b.eval"\ "uate(a)),d=0,f=c.next();f;f=c.next())d+=+G(f);return d},1,1,!0);O(\"tra"\ "nslate\",3,!1,!1,function(a,b,c,d){b=b.c(a);c=c.c(a);var f=d.c(a);a=[];"\ "for(d=0;d<c.length;d++){var g=c.charAt(d);g in a||(a[g]=f.charAt(d))}c="\ "\"\";for(d=0;d<b.length;d++)g=b.charAt(d),c+=g in a?a[g]:g;return c},3)"\ ";O(\"true\",2,!1,!1,h(!0),0);function ma(a,b,c,d){this.m=a;this.J=b;thi"\ "s.s=c;this.Y=d}ma.prototype.toString=e(\"m\");var na={};function Q(a,b,"\ "c,d){if(a in na)throw Error(\"Axis already created: \"+a);na[a]=new ma("\ "a,b,c,!!d)}Q(\"ancestor\",function(a,b){for(var c=new J,d=b;d=d.parentN"\ "ode;)a.matches(d)&&c.unshift(d);return c},!0);Q(\"ancestor-or-self\",fu"\ "nction(a,b){var c=new J,d=b;do a.matches(d)&&c.unshift(d);while(d=d.par"\ "entNode);return c},!0);\nQ(\"attribute\",function(a,b){var c=new J,d=a."\ "getName(),f=b.attributes;if(f)if(\"*\"==d)for(var d=0,g;g=f[d];d++)c.ad"\ "d(g);else(g=f.getNamedItem(d))&&c.add(g);return c},!1);Q(\"child\",func"\ "tion(a,b,c,d,f){return fa.call(null,a,b,l(c)?c:null,l(d)?d:null,f||new "\ "J)},!1,!0);Q(\"descendant\",I,!1,!0);Q(\"descendant-or-self\",function("\ "a,b,c,d){var f=new J;H(b,c,d)&&a.matches(b)&&f.add(b);return I(a,b,c,d,"\ "f)},!1,!0);\nQ(\"following\",function(a,b,c,d){var f=new J;do for(var g"\ "=b;g=g.nextSibling;)H(g,c,d)&&a.matches(g)&&f.add(g),f=I(a,g,c,d,f);whi"\ "le(b=b.parentNode);return f},!1,!0);Q(\"following-sibling\",function(a,"\ "b){for(var c=new J,d=b;d=d.nextSibling;)a.matches(d)&&c.add(d);return c"\ "},!1);Q(\"namespace\",function(){return new J},!1);Q(\"parent\",functio"\ "n(a,b){var c=new J;if(9==b.nodeType)return c;if(2==b.nodeType)return c."\ "add(b.ownerElement),c;var d=b.parentNode;a.matches(d)&&c.add(d);return "\ "c},!1);\nQ(\"preceding\",function(a,b,c,d){var f=new J,g=[];do g.unshif"\ "t(b);while(b=b.parentNode);for(var p=1,w=g.length;p<w;p++){var z=[];for"\ "(b=g[p];b=b.previousSibling;)z.unshift(b);for(var P=0,ua=z.length;P<ua;"\ "P++)b=z[P],H(b,c,d)&&a.matches(b)&&f.add(b),f=I(a,b,c,d,f)}return f},!0"\ ",!0);Q(\"preceding-sibling\",function(a,b){for(var c=new J,d=b;d=d.prev"\ "iousSibling;)a.matches(d)&&c.unshift(d);return c},!0);Q(\"self\",functi"\ "on(a,b){var c=new J;a.matches(b)&&c.add(b);return c},!1);function R(a,b"\ "){return!!a&&1==a.nodeType&&(!b||a.tagName.toUpperCase()==b)};function "\ "oa(a,b){this.p=aa.document.documentElement;this.G=null;var c;a:{var d=E"\ "(this.p);try{c=d&&d.activeElement;break a}catch(f){}c=null}c&&pa(this,c"\ ");this.O=a||new qa;this.I=b||new ra}function pa(a,b){a.p=b;a.G=R(b,\"OP"\ "TION\")?F(b,function(a){return R(a,\"SELECT\")}):null}function sa(a){re"\ "turn R(a,\"FORM\")}function qa(){this.V=0}function ra(){};function S(a,"\ "b,c){this.t=a;this.u=b;this.v=c}S.prototype.create=function(a){a=E(a).c"\ "reateEvent(\"HTMLEvents\");a.initEvent(this.t,this.u,this.v);return a};"\ "S.prototype.toString=e(\"t\");var ta=new S(\"submit\",!0,!0);function T"\ "(a,b){this.i={};this.e=[];var c=arguments.length;if(1<c){if(c%2)throw E"\ "rror(\"Uneven number of arguments\");for(var d=0;d<c;d+=2)this.set(argu"\ "ments[d],arguments[d+1])}else if(a){var f;if(a instanceof T)for(d=va(a)"\ ",wa(a),f=[],c=0;c<a.e.length;c++)f.push(a.i[a.e[c]]);else{var c=[],g=0;"\ "for(d in a)c[g++]=d;d=c;c=[];g=0;for(f in a)c[g++]=a[f];f=c}for(c=0;c<d"\ ".length;c++)this.set(d[c],f[c])}}T.prototype.k=0;T.prototype.H=0;functi"\ "on va(a){wa(a);return a.e.concat()}\nfunction wa(a){if(a.k!=a.e.length)"\ "{for(var b=0,c=0;b<a.e.length;){var d=a.e[b];Object.prototype.hasOwnPro"\ "perty.call(a.i,d)&&(a.e[c++]=d);b++}a.e.length=c}if(a.k!=a.e.length){fo"\ "r(var f={},c=b=0;b<a.e.length;)d=a.e[b],Object.prototype.hasOwnProperty"\ ".call(f,d)||(a.e[c++]=d,f[d]=1),b++;a.e.length=c}}T.prototype.get=funct"\ "ion(a,b){return Object.prototype.hasOwnProperty.call(this.i,a)?this.i[a"\ "]:b};\nT.prototype.set=function(a,b){Object.prototype.hasOwnProperty.ca"\ "ll(this.i,a)||(this.k++,this.e.push(a),this.H++);this.i[a]=b};var U={};"\ "function V(a,b,c){var d=typeof a;(\"object\"==d&&null!=a||\"function\"="\ "=d)&&(a=a.a);a=new xa(a,b,c);!b||b in U&&!c||(U[b]={key:a,shift:!1},c&&"\ "(U[c]={key:a,shift:!0}));return a}function xa(a,b,c){this.code=a;this.w"\ "=b||null;this.W=c||this.w}V(8);V(9);V(13);var ya=V(16),za=V(17),Aa=V(18"\ ");V(19);V(20);V(27);V(32,\" \");V(33);V(34);V(35);V(36);V(37);V(38);V(3"\ "9);V(40);V(44);V(45);V(46);V(48,\"0\",\")\");V(49,\"1\",\"!\");V(50,\"2"\ "\",\"@\");V(51,\"3\",\"#\");V(52,\"4\",\"$\");V(53,\"5\",\"%\");V(54,\""\ "6\",\"^\");V(55,\"7\",\"&\");\nV(56,\"8\",\"*\");V(57,\"9\",\"(\");V(65"\ ",\"a\",\"A\");V(66,\"b\",\"B\");V(67,\"c\",\"C\");V(68,\"d\",\"D\");V(6"\ "9,\"e\",\"E\");V(70,\"f\",\"F\");V(71,\"g\",\"G\");V(72,\"h\",\"H\");V("\ "73,\"i\",\"I\");V(74,\"j\",\"J\");V(75,\"k\",\"K\");V(76,\"l\",\"L\");V"\ "(77,\"m\",\"M\");V(78,\"n\",\"N\");V(79,\"o\",\"O\");V(80,\"p\",\"P\");"\ "V(81,\"q\",\"Q\");V(82,\"r\",\"R\");V(83,\"s\",\"S\");V(84,\"t\",\"T\")"\ ";V(85,\"u\",\"U\");V(86,\"v\",\"V\");V(87,\"w\",\"W\");V(88,\"x\",\"X\""\ ");V(89,\"y\",\"Y\");V(90,\"z\",\"Z\");var Ba=V(v?{b:91,a:91,opera:219}:"\ "u?{b:224,a:91,opera:17}:{b:0,a:91,opera:null});\nV(v?{b:92,a:92,opera:2"\ "20}:u?{b:224,a:93,opera:17}:{b:0,a:92,opera:null});V(v?{b:93,a:93,opera"\ ":0}:u?{b:0,a:0,opera:16}:{b:93,a:null,opera:0});V({b:96,a:96,opera:48},"\ "\"0\");V({b:97,a:97,opera:49},\"1\");V({b:98,a:98,opera:50},\"2\");V({b"\ ":99,a:99,opera:51},\"3\");V({b:100,a:100,opera:52},\"4\");V({b:101,a:10"\ "1,opera:53},\"5\");V({b:102,a:102,opera:54},\"6\");V({b:103,a:103,opera"\ ":55},\"7\");V({b:104,a:104,opera:56},\"8\");V({b:105,a:105,opera:57},\""\ "9\");V({b:106,a:106,opera:A?56:42},\"*\");V({b:107,a:107,opera:A?61:43}"\ ",\"+\");\nV({b:109,a:109,opera:A?109:45},\"-\");V({b:110,a:110,opera:A?"\ "190:78},\".\");V({b:111,a:111,opera:A?191:47},\"/\");V(144);V(112);V(11"\ "3);V(114);V(115);V(116);V(117);V(118);V(119);V(120);V(121);V(122);V(123"\ ");V({b:107,a:187,opera:61},\"=\",\"+\");V(108,\",\");V({b:109,a:189,ope"\ "ra:109},\"-\",\"_\");V(188,\",\",\"<\");V(190,\".\",\">\");V(191,\"/\","\ "\"?\");V(192,\"`\",\"~\");V(219,\"[\",\"{\");V(220,\"\\\\\",\"|\");V(22"\ "1,\"]\",\"}\");V({b:59,a:186,opera:59},\";\",\":\");V(222,\"'\",'\"');v"\ "ar W=new T;W.set(1,ya);W.set(2,za);W.set(4,Aa);W.set(8,Ba);\n(function("\ "a){var b=new T;q(va(a),function(c){b.set(a.get(c).code,c)});return b})("\ "W);function X(){oa.call(this)}m(X,oa);X.C=function(){return X.q?X.q:X.q"\ "=new X};function Ca(a){var b=F(a,sa,!0);if(!b)throw new r(7,\"Element w"\ "as not in a form, so could not submit.\");var c=X.C();pa(c,a);if(!sa(b)"\ ")throw new r(12,\"Element is not a form, so could not submit.\");a=ta.c"\ "reate(b,void 0);\"isTrusted\"in a||(a.isTrusted=!1);b.dispatchEvent(a)&"\ "&(R(b.submit)?b.constructor.prototype.submit.call(b):b.submit())}var Y="\ "[\"_\"],Z=k;Y[0]in Z||!Z.execScript||Z.execScript(\"var \"+Y[0]);for(va"\ "r $;Y.length&&($=Y.shift());)Y.length||void 0===Ca?Z=Z[$]?Z[$]:Z[$]={}:"\ "Z[$]=Ca;; return this._.apply(null,arguments);}.apply({navigator:typeof"\ " window!=undefined?window.navigator:null,document:typeof window!=undefi"\ "ned?window.document:null}, arguments);}"
{ "repo_name": "PeterWangIntel/crosswalk-webdriver-python", "path": "third_party/atoms.py", "copies": "1", "size": "417522", "license": "bsd-3-clause", "hash": 1296076906491238000, "line_mean": 76.404894327, "line_max": 78, "alpha_frac": 0.5750571227, "autogenerated": false, "ratio": 2.196975437267159, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8270061947904599, "avg_score": 0.0003941224125121645, "num_lines": 5394 }
__all__ = ['get', 'get_pinyin', 'get_initial'] import os # init pinyin dict pinyin_dict = {} dat = os.path.join(os.path.dirname(__file__), "Mandarin.dat") with open(dat) as f: for line in f: k, v = line.strip().split('\t') pinyin_dict[k] = v.lower().split(" ")[0][:-1] from ._compat import u def _pinyin_generator(chars): """Generate pinyin for chars, if char is not chinese character, itself will be returned. Chars must be unicode list. """ for char in chars: key = "%X" % ord(char) yield pinyin_dict.get(key, char) def get(s, delimiter=''): """Return pinyin of string, the string must be unicode """ return delimiter.join(_pinyin_generator(u(s))) def get_pinyin(s): """This function is only for backward compatibility, use `get` instead. """ import warnings warnings.warn('Deprecated, use `get` instead.') return get(s) def get_initial(s, delimiter=' '): """Return the 1st char of pinyin of string, the string must be unicode """ return delimiter.join([p[0] for p in _pinyin_generator(u(s))])
{ "repo_name": "vsooda/pinyin", "path": "pinyin/pinyin.py", "copies": "1", "size": "1108", "license": "mit", "hash": -5194804949830055000, "line_mean": 24.1818181818, "line_max": 75, "alpha_frac": 0.619133574, "autogenerated": false, "ratio": 3.1839080459770117, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.43030416199770116, "avg_score": null, "num_lines": null }
__all__ = ['getMainBranch', 'a2z', 'z2a', 'readHlist', 'SimulationAnalysis', \ 'TargetHalo', 'getDistance', 'iter_grouped_subhalos_indices'] import os import re import math import gzip from itertools import izip from urllib import urlretrieve from collections import deque import numpy as np _islistlike = lambda l: hasattr(l, '__iter__') a2z = lambda a: 1./a - 1. z2a = lambda z: 1./(1.+z) def getMainBranch(iterable, get_num_prog): item = iter(iterable) q = deque([(item.next(), True)]) X = [] while len(q): i, i_mb = q.popleft() X.append(i_mb) n = get_num_prog(i) prog_mb = [i_mb] + [False]*(n-1) if n else [] q.extend([(item.next(), mb) for mb in prog_mb]) return np.array(X) class BaseParseFields(): def __init__(self, header, fields=None): if len(header)==0: if all([isinstance(f, int) for f in fields]): self._usecols = fields self._formats = [float]*len(fields) self._names = ['f%d'%f for f in fields] else: raise ValueError('header is empty, so fields must be a list '\ 'of int.') else: header_s = map(self._name_strip, header) if fields is None or len(fields)==0: self._names = header names_s = header_s self._usecols = range(len(names_s)) else: if not _islistlike(fields): fields = [fields] self._names = [header[f] if isinstance(f, int) else str(f) \ for f in fields] names_s = map(self._name_strip, self._names) wrong_fields = filter(bool, [str(f) if s not in header_s \ else '' for s, f in zip(names_s, fields)]) if len(wrong_fields): raise ValueError('The following field(s) are not available'\ ': %s.\nAvailable fields: %s.'%(\ ', '.join(wrong_fields), ', '.join(header))) self._usecols = map(header_s.index, names_s) self._formats = map(self._get_format, names_s) def parse_line(self, l): items = l.split() return tuple([c(items[i]) for i, c in \ zip(self._usecols, self._formats)]) def pack(self, X): return np.array(X, np.dtype({'names':self._names, \ 'formats':self._formats})) def _name_strip(self, s): return self._re_name_strip.sub('', s).lower() def _get_format(self, s): return float if self._re_formats.search(s) is None else int _re_name_strip = re.compile('\W|_') _re_formats = re.compile('^phantom$|^mmp$|id$|^num|num$') class BaseDirectory: def __init__(self, dir_path='.'): self.dir_path = os.path.expanduser(dir_path) #get file_index files = os.listdir(self.dir_path) matches = filter(lambda m: m is not None, \ map(self._re_filename.match, files)) if len(matches) == 0: raise ValueError('cannot find matching files in this directory: %s.'%(self.dir_path)) indices = np.array(map(self._get_file_index, matches)) s = indices.argsort() self.files = [matches[i].group() for i in s] self.file_indices = indices[s] #get header and header_info header_info_list = [] with open('%s/%s'%(self.dir_path, self.files[0]), 'r') as f: for l in f: if l[0] == '#': header_info_list.append(l) else: break if len(header_info_list): self.header_info = ''.join(header_info_list) self.header = [self._re_header_remove.sub('', s) for s in \ header_info_list[0][1:].split()] else: self.header_info = '' self.header = [] self._ParseFields = self._Class_ParseFields(self.header, \ self._default_fields) def _load(self, index, exact_index=False, additional_fields=[]): p = self._get_ParseFields(additional_fields) fn = '%s/%s'%(self.dir_path, self.get_filename(index, exact_index)) with open(fn, 'r') as f: l = '#' while l[0] == '#': try: l = f.next() except StopIteration: return p.pack([]) X = [p.parse_line(l)] for l in f: X.append(p.parse_line(l)) return p.pack(X) def _get_file_index(self, match): return match.group() def get_filename(self, index, exact_index=False): if exact_index: i = self.file_indices.searchsorted(index) if self.file_indices[i] != index: raise ValueError('Cannot find the exact index %s.'%(str(index))) else: i = np.argmin(np.fabs(self.file_indices - index)) return self.files[i] def _get_ParseFields(self, additional_fields): if not _islistlike(additional_fields) or len(additional_fields)==0: return self._ParseFields else: return self._Class_ParseFields(self.header, \ self._default_fields + list(additional_fields)) _re_filename = re.compile('.+') _re_header_remove = re.compile('') _Class_ParseFields = BaseParseFields _default_fields = [] load = _load class HlistsDir(BaseDirectory): _re_filename = re.compile('^hlist_(\d+\.\d+).list$') _re_header_remove = re.compile('\(\d+\)$') _default_fields = ['id', 'upid', 'mvir', 'rvir', 'rs', 'x', 'y', 'z', \ 'vmax', 'vpeak'] def _get_file_index(self, match): return math.log10(float(match.groups()[0])) def load(self, z=0, exact_index=False, additional_fields=[]): return self._load(math.log10(z2a(z)), exact_index, additional_fields) class RockstarDir(BaseDirectory): _re_filename = re.compile('^out_(\d+).list$') _re_header_remove = re.compile('') _default_fields = ['id', 'mvir', 'rvir', 'rs', 'x', 'y', 'z', 'vmax'] def _get_file_index(self, match): fn = '%s/%s'%(self.dir_path, match.group()) with open(fn, 'r') as f: for l in f: if l.startswith('#a '): break else: raise ValueError('Cannot find the scale factor in this file %s'\ %(fn)) return math.log10(float(l.split()[-1])) def load(self, z=0, exact_index=False, additional_fields=[]): return self._load(math.log10(z2a(z)), exact_index, additional_fields) class TreesDir(BaseDirectory): _re_filename = re.compile('^tree_\d+_\d+_\d+.dat$') _re_header_remove = re.compile('\(\d+\)$') _default_fields = ['scale', 'id', 'num_prog', 'upid', 'mvir', 'rvir', \ 'rs', 'x', 'y', 'z', 'vmax'] def load(self, tree_root_id, additional_fields=[]): p = self._get_ParseFields(additional_fields) tree_root_id_str = str(tree_root_id) location_file = self.dir_path + '/locations.dat' if os.path.isfile(location_file): with open(location_file, 'r') as f: f.readline() for l in f: items = l.split() if items[0] == tree_root_id_str: break else: raise ValueError("Cannot find this tree_root_id: %d."%(\ tree_root_id)) tree_file = '%s/%s'%(self.dir_path, items[-1]) with open(tree_file, 'r') as f: f.seek(int(items[2])) X = [] for l in f: if l[0] == '#': break X.append(p.parse_line(l)) else: for fn in self.files: tree_file = '%s/%s'%(self.dir_path, fn) with open(tree_file, 'r') as f: l = '#' while l[0] == '#': try: l = f.next() except StopIteration: raise ValueError("Cannot find this tree_root_id: %d."%(\ tree_root_id)) num_trees = int(l) for l in f: if l[0] == '#' and l.split()[-1] == tree_root_id_str: break #found tree_root_id else: continue #not in this file, check the next one X = [] for l in f: if l[0] == '#': break X.append(p.parse_line(l)) break #because tree_root_id has found else: raise ValueError("Cannot find this tree_root_id: %d."%(\ tree_root_id)) return p.pack(X) def readHlist(hlist, fields=None, buffering=100000000): """ Read the given fields of a hlist file (also works for tree_*.dat and out_*.list) as a numpy record array. Parameters ---------- hlist : str or file obj The path to the file (can be an URL) or a file object. fields : str, int, array_like, optional The desired fields. It can be a list of string or int. If fields is None (default), return all the fields listed in the header. Returns ------- arr : ndarray A numpy record array contains the data of the desired fields. Example ------- >>> h = readHlist('hlist_1.00000.list', ['id', 'mvir', 'upid']) >>> h.dtype dtype([('id', '<i8'), ('mvir', '<f8'), ('upid', '<i8')]) >>> mass_of_hosts = h['mvir'][(h['upid'] == -1)] >>> largest_halo_id = h['id'][h['mvir'].argmax()] >>> mass_of_subs_of_largest_halo = h['mvir'][(h['upid'] == largest_halo_id)] """ if hasattr(hlist, 'read'): f = hlist else: if re.match(r'(s?ftp|https?)://', hlist, re.I): hlist = urlretrieve(hlist)[0] if hlist.endswith('.gz'): f = gzip.open(hlist, 'r') else: f = open(hlist, 'r', int(buffering)) try: l = f.next() header = l[1:].split() header = [re.sub('\(\d+\)$', '', s) for s in header] p = BaseParseFields(header, fields) while l[0] == '#': try: l = f.next() except StopIteration: return p.pack([]) X = [p.parse_line(l)] for l in f: X.append(p.parse_line(l)) finally: if not hasattr(hlist, 'read'): f.close() return p.pack(X) def readHlistToSqlite3(db, table_name, hlist, fields=None, unique_id=True): """ Read the given fields of a hlist file (also works for tree_*.dat and out_*.list) and save it to a sqlite3 database. Parameters ---------- db : sqlite3.Cursor A sqlite3.Cursor object. hlist : str The path to the file. fields : str, int, array_like, optional The desired fields. It can be a list of string or int. If fields is None (default), return all the fields listed in the header. Returns ------- db : sqlite3.Cursor The same cursor object that was given as input. """ with open(hlist, 'r') as f: l = f.next() header = l[1:].split() header = [re.sub('\(\d+\)$', '', s) for s in header] p = BaseParseFields(header, fields) db_cols = map(lambda s: re.sub(r'\W+', '_', s), \ map(lambda s: re.sub(r'^\W+|\W+$', '', s), p._names)) db_create_stmt = 'create table if not exists %s (%s)'%(table_name, \ ','.join(['%s %s%s'%(name, 'int' if (fmt is int) else 'real', \ ' unique' if (name == 'id' and unique_id) else '') \ for name, fmt in zip(db_cols, p._formats)])) db_insert_stmt = 'insert or replace into %s values (%s)'%(table_name, \ ','.join(['?']*len(p._names))) empty_file = False while l[0] == '#': try: l = f.next() except StopIteration: empty_file = True db.execute(db_create_stmt) if not empty_file: db.execute(db_insert_stmt, p.parse_line(l)) for l in f: db.execute(db_insert_stmt, p.parse_line(l)) db.commit() return db class SimulationAnalysis: def __init__(self, hlists_dir=None, trees_dir=None, rockstar_dir=None): self._directories = {} if hlists_dir is not None: self.set_hlists_dir(hlists_dir) if trees_dir is not None: self.set_trees_dir(trees_dir) if rockstar_dir is not None: self.set_rockstar_dir(rockstar_dir) if len(self._directories) == 0: raise ValueError('Please specify at least one directory.') def set_trees_dir(self, trees_dir): self._directories['trees'] = TreesDir(trees_dir) self._trees = {} self._main_branches = {} def set_rockstar_dir(self, rockstar_dir): self._directories['olists'] = RockstarDir(rockstar_dir) self._olists = {} def set_hlists_dir(self, hlists_dir): self._directories['hlists'] = HlistsDir(hlists_dir) self._hlists = {} def load_tree(self, tree_root_id=-1, npy_file=None, additional_fields=[]): if 'trees' not in self._directories: raise ValueError('You must set trees_dir before using this function.') if npy_file is not None and os.path.isfile(npy_file): data = np.load(npy_file) if tree_root_id < 0: tree_root_id = data['id'][0] elif tree_root_id != data['id'][0]: raise ValueError('tree_root_id does not match.') self._trees[tree_root_id] = data elif tree_root_id not in self._trees: self._trees[tree_root_id] = \ self._directories['trees'].load(tree_root_id, \ additional_fields=additional_fields) if npy_file is not None and not os.path.isfile(npy_file): np.save(npy_file, self._trees[tree_root_id]) return self._trees[tree_root_id] def load_main_branch(self, tree_root_id=-1, npy_file=None, keep_tree=False, \ additional_fields=[]): if 'trees' not in self._directories: raise ValueError('You must set trees_dir before using this function.') if npy_file is not None and os.path.isfile(npy_file): data = np.load(npy_file) if tree_root_id < 0: tree_root_id = data['id'][0] elif tree_root_id != data['id'][0]: raise ValueError('tree_root_id does not match.') self._main_branches[tree_root_id] = data elif tree_root_id not in self._main_branches: t = self._directories['trees'].load(tree_root_id, \ additional_fields=additional_fields) mb = getMainBranch(t, lambda s: s['num_prog']) if keep_tree: self._trees[tree_root_id] = t self._main_branches[tree_root_id] = t[mb] if npy_file is not None and not os.path.isfile(npy_file): np.save(npy_file, self._main_branches[tree_root_id]) return self._main_branches[tree_root_id] def _choose_hlists_or_olists(self, use_rockstar=False): if 'hlists' not in self._directories and \ 'olists' not in self._directories: raise ValueError('You must set hlists_dir and/or rockstar_dir'\ 'before using this function.') elif 'olists' not in self._directories: if use_rockstar: print "Warning: ignore use_rockstar" return self._directories['hlists'], self._hlists elif use_rockstar or 'hlists' not in self._directories: return self._directories['olists'], self._olists else: return self._directories['hlists'], self._hlists def load_halos(self, z=0, npy_file=None, use_rockstar=False, \ additional_fields=[]): d, s = self._choose_hlists_or_olists(use_rockstar) fn = d.get_filename(math.log10(z2a(z))) if npy_file is not None and os.path.isfile(npy_file): data = np.load(npy_file) s[fn] = data elif fn not in s: s[fn] = d.load(z, additional_fields=additional_fields) if npy_file is not None and not os.path.isfile(npy_file): np.save(npy_file, s[fn]) return s[fn] def del_tree(self, tree_root_id): if tree_root_id in self._trees: del self._trees[tree_root_id] def del_main_branch(self, tree_root_id): if tree_root_id in self._main_branches: del self._main_branches[tree_root_id] def del_halos(self, z, use_rockstar=False): d, s = self._choose_hlists_or_olists(use_rockstar) fn = d.get_filename(math.log10(z2a(z))) if fn in s: del s[fn] def clear_trees(self): self._trees = {} def clear_main_branches(self): self._main_branches = {} def clear_halos(self): self._olists = {} self._hlists = {} class TargetHalo: def __init__(self, target, halos, box_size=-1): self.target = target try: self.target_id = target['id'] except KeyError: pass self.halos = halos self.dists = np.zeros(len(halos), float) self.box_size = box_size half_box_size = 0.5*box_size for ax in 'xyz': d = halos[ax] - target[ax] if box_size > 0: d[(d > half_box_size)] -= box_size d[(d < -half_box_size)] += box_size self.dists += d*d self.dists = np.sqrt(self.dists) def getDistance(target, halos, box_size=-1): t = TargetHalo(target, halos, box_size) return t.dists def iter_grouped_subhalos_indices(host_ids, sub_pids): s = sub_pids.argsort() k = np.where(sub_pids[s[1:]] != sub_pids[s[:-1]])[0] k += 1 k = np.vstack((np.insert(k, 0, 0), np.append(k, len(s)))).T d = np.searchsorted(sub_pids[s[k[:,0]]], host_ids) for j, host_id in izip(d, host_ids): if j < len(s) and sub_pids[s[k[j,0]]] == host_id: yield s[slice(*k[j])] else: yield np.array([], dtype=int)
{ "repo_name": "manodeep/yymao-helpers", "path": "helpers/SimulationAnalysis.py", "copies": "1", "size": "18602", "license": "mit", "hash": 6404298002456840000, "line_mean": 36.2785571142, "line_max": 136, "alpha_frac": 0.5173637243, "autogenerated": false, "ratio": 3.5724985596312657, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9547878128857612, "avg_score": 0.008396831014730826, "num_lines": 499 }
__all__ = ["get_month_boxoffice"] import tushare as ts from flask import json TRANS = {"Irank": "排名", "MovieName": '电影名称', "WomIndex": '口碑指数', "avgboxoffice": '平均票价', "avgshowcount": "场均人次", "box_pro": '月度占比', "boxoffice": "单月票房(万)", "days": "月内天数", "releaseTime": "上映日期" } def get_month_boxoffice(day=None): if day == None: total = ts.month_boxoffice().to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} else: try: total = ts.month_boxoffice(day).to_csv().split() head = [TRANS.get(i) for i in total[0].split(",")] body = [line.split(",") for line in total[1:]] result = {"head": head, "body": body} except Exception as e: result = {"error": True, "message": "can not get the data, format date as YYYY-M-D"} return result
{ "repo_name": "FinaceInfo/Chinese-box-office-info", "path": "app/boxoffice/month_boxoffice.py", "copies": "1", "size": "1101", "license": "mit", "hash": -8501913709367740000, "line_mean": 30.2424242424, "line_max": 96, "alpha_frac": 0.5101842871, "autogenerated": false, "ratio": 2.9711815561959654, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8972228073848918, "avg_score": 0.0018275538894095594, "num_lines": 33 }
__all__ = ['getMUSICregion'] from SimulationAnalysis import readHlist from readGadgetSnapshot import readGadgetSnapshot from findLagrangianVolume import findLagrangianVolume _fmt = lambda a: ', '.join(map(str, a)) def getMUSICregion(target_id, rvir_mult, hlist, snapshot_prefix, ic_prefix,\ edges_file=None): halos = readHlist(hlist, ['id', 'rvir', 'x', 'y', 'z']) target = halos[(halos['id'] == target_id)][0] c = [target[ax] for ax in 'xyz'] r = rvir_mult * target['rvir'] * 1.e-3 header = readGadgetSnapshot(snapshot_prefix+'.0') box_size = header.BoxSize rec_cor, rec_len = findLagrangianVolume(c, r, \ snapshot_prefix, ic_prefix, edges_file, rec_only=True) print 'region = box' print 'ref_offset =', _fmt(rec_cor/box_size) print 'ref_extent =', _fmt(rec_len/box_size) def main(): from sys import argv from json import load with open(argv[1], 'r') as fp: d = load(fp) getMUSICregion(**d) if __name__ == '__main__': main()
{ "repo_name": "manodeep/yymao-helpers", "path": "helpers/getMUSICregion.py", "copies": "1", "size": "1047", "license": "mit", "hash": -431601617417047700, "line_mean": 31.71875, "line_max": 76, "alpha_frac": 0.6160458453, "autogenerated": false, "ratio": 2.982905982905983, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.8998332753648008, "avg_score": 0.020123814911594762, "num_lines": 32 }
__all__ = ["get_netloc_port", "requote_uri", "timeout_manager"] from urllib.parse import quote from functools import wraps from anyio import fail_after from .errors import RequestTimeout async def timeout_manager(timeout, coro, *args): try: async with fail_after(timeout): return await coro(*args) except TimeoutError as e: raise RequestTimeout from e def get_netloc_port(parsed_url): port = parsed_url.port if not port: if parsed_url.scheme == "https": port = "443" else: port = "80" return parsed_url.hostname, str(port) # The unreserved URI characters (RFC 3986) UNRESERVED_SET = ( "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz" + "0123456789-._~" ) def unquote_unreserved(uri): """Un-escape any percent-escape sequences in a URI that are unreserved characters. This leaves all reserved, illegal and non-ASCII bytes encoded. :rtype: str """ parts = uri.split("%") for i in range(1, len(parts)): h = parts[i][0:2] if len(h) == 2 and h.isalnum(): try: c = chr(int(h, 16)) except ValueError: raise ValueError("Invalid percent-escape sequence: '%s'" % h) if c in UNRESERVED_SET: parts[i] = c + parts[i][2:] else: parts[i] = "%" + parts[i] else: parts[i] = "%" + parts[i] return "".join(parts) def requote_uri(uri): """Re-quote the given URI. This function passes the given URI through an unquote/quote cycle to ensure that it is fully and consistently quoted. :rtype: str """ safe_with_percent = "!#$%&'()*+,/:;=?@[]~" safe_without_percent = "!#$&'()*+,/:;=?@[]~" try: # Unquote only the unreserved characters # Then quote only illegal characters (do not quote reserved, # unreserved, or '%') return quote(unquote_unreserved(uri), safe=safe_with_percent) except ValueError: # We couldn't unquote the given URI, so let's try quoting it, but # there may be unquoted '%'s in the URI. We need to make sure they're # properly quoted so they do not cause issues elsewhere. return quote(uri, safe=safe_without_percent) def processor(gen): @wraps(gen) def wrapper(*args, **kwargs): g = gen(*args, **kwargs) next(g) return g return wrapper
{ "repo_name": "theelous3/asks", "path": "asks/utils.py", "copies": "1", "size": "2460", "license": "mit", "hash": 7855551274579279000, "line_mean": 27.6046511628, "line_max": 78, "alpha_frac": 0.5922764228, "autogenerated": false, "ratio": 3.813953488372093, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9906229911172093, "avg_score": 0, "num_lines": 86 }
__all__ = ['getSDSSid'] import re from urllib import urlopen _re1 = re.compile('http://skyserver\.sdss3\.org/dr8/en/tools/explore/obj\.asp\?(ra=[+-]?\d+\.\d+)&amp;(dec=[+-]?\d+\.\d+)') _re2 = re.compile('<td align=\'center\' width=\'33%\' class=\'t\'>(\d+)</td>') _url1 = 'http://www.nsatlas.org/getAtlas.html?search=nsaid&nsaID=%s&submit_form=Submit' _url2 = 'http://skyserver.sdss3.org/dr10/en/tools/quicklook/quickobj.aspx?%s&%s' def getSDSSid(nsa_id): i = str(nsa_id) error_msg = '#Cannot find SDSS id for ' + i m = _re1.search(urlopen(_url1%i).read()) if m is None: return error_msg m = _re2.search(urlopen(_url2%m.groups()).read()) if m is None: return error_msg return m.groups()[0] def main(): from argparse import ArgumentParser parser = ArgumentParser(description='Query SDSS website for object ID, given NSA ID.') parser.add_argument('id', type=int, nargs='*', help='List of NSA IDs') parser.add_argument('-f', nargs=2, help='Catalog containing NSA IDs in column X') args = parser.parse_args() ids = map(str, args.id) if args.f is not None: try: i = int(args.f[1]) - 1 with open(args.f[0]) as f: for l in f: ids.append(l.split()[i]) except OSError: parser.error("It seems the file %s cannot be access."%args.f[0]) except ValueError: parser.error("It seems the column %s is not correct."%args.f[1]) except IndexError: parser.error("It seems the column %s is not correct."%args.f[1]) for i in ids: print getSDSSid(i) if __name__ == "__main__": main()
{ "repo_name": "manodeep/yymao-helpers", "path": "helpers/getSDSSid.py", "copies": "1", "size": "1685", "license": "mit", "hash": -2529281338476514300, "line_mean": 34.1041666667, "line_max": 123, "alpha_frac": 0.5863501484, "autogenerated": false, "ratio": 3.0748175182481754, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9111210331834366, "avg_score": 0.009991466962761724, "num_lines": 48 }
__all__ = ['getSnapshotEdges', 'getParticlesWithinSphere'] import os import numpy as np from fast3tree import fast3tree from readGadgetSnapshot import readGadgetSnapshot def getSnapshotEdges(snapshot_prefix, output_file=None, single_type=-1, lgadget=False): print "[Info] Calculating the edges of each snapshot file..." num_files = readGadgetSnapshot('{0}.0'.format(snapshot_prefix)).num_files edges = np.zeros((num_files, 6)) for i, x in enumerate(edges): __, pos = readGadgetSnapshot('{0}.{1}'.format(snapshot_prefix, i), \ read_pos=True, single_type=single_type, lgadget=lgadget) if len(pos): x[:3] = pos.min(axis=0) x[3:] = pos.max(axis=0) else: x[:3] = np.inf x[3:] = -np.inf if output_file is not None: np.save(output_file, edges) return edges def _yield_periodic_points(center, radius, box_size): cc = np.array(center) flag = (cc-radius < 0).astype(int) - (cc+radius >= box_size).astype(int) cp = cc + flag*box_size a = range(len(cc)) for j in xrange(1 << len(cc)): for i in a: if j >> i & 1 == 0: cc[i] = center[i] elif flag[i]: cc[i] = cp[i] else: break else: yield cc def _check_within(c, r, edges): return all((c+r >= edges[:3]) & (c-r <= edges[3:])) def _find_intersected_regions(center, radius, box_size, edges): num_subregions = len(edges) region_list = [] for ci in _yield_periodic_points(center, radius, box_size): region_list.extend(np.where([_check_within(ci, radius, edges[i]) \ for i in xrange(num_subregions)])[0]) region_list = list(set(region_list)) region_list.sort() return region_list _valid_names = ('r', 'v', 'vr', 'x', 'y', 'z', 'vx', 'vy', 'vz', 'id') _pos_names = ('r', 'vr', 'x', 'y', 'z') def _is_string_like(obj): 'Return True if *obj* looks like a string' try: obj + '' except: return False return True def getParticlesWithinSphere(center, radius, snapshot_prefix, \ snapshot_edges=None, output_dtype=np.dtype([('r', float)]), \ vel_center=(0,0,0), single_type=-1, lgadget=False): #check output fields output_names = output_dtype.names if not all((x in _valid_names for x in output_names)): raise ValueError('Unknown names in output_dtype.') if not any((x in output_names for x in _valid_names)): raise ValueError('You do not need any output??') need_pos = any((x in _pos_names for x in output_names)) need_vel = any((x.startswith('v') for x in output_names)) need_id = ('id' in output_names) #load one header to get box_size and num_files header = readGadgetSnapshot('{0}.0'.format(snapshot_prefix)) box_size = header.BoxSize half_box_size = header.BoxSize * 0.5 num_files = header.num_files #load edges file if _is_string_like(snapshot_edges): if os.path.isfile(snapshot_edges): edges = np.load(snapshot_edges) else: edges = getSnapshotEdges(snapshot_prefix, snapshot_edges, \ single_type=single_type, lgadget=lgadget) elif snapshot_edges is None: edges = getSnapshotEdges(snapshot_prefix, \ single_type=single_type, lgadget=lgadget) else: edges = np.asarray(snapshot_edges).reshape((num_files, 6)) #actually load particles region_list = _find_intersected_regions(center, radius, box_size, edges) npart = 0 for region in region_list: snapshot_data = readGadgetSnapshot('{0}.{1}'.format(snapshot_prefix, region), \ read_pos=True, read_vel=need_vel, read_id=need_id, \ single_type=single_type, lgadget=lgadget) s_pos = snapshot_data[1] if need_vel: s_vel = snapshot_data[2] if need_id: s_id = snapshot_data[-1] with fast3tree(s_pos) as tree: tree.set_boundaries(0, box_size) p = tree.query_radius(center, radius, True) if not len(p): continue if npart: out.resize(npart+len(p)) else: out = np.empty(len(p), output_dtype) for x in ('r', 'v', 'vr'): if x in output_names: out[x][npart:] = 0 if need_pos or need_vel: for i, ax in enumerate('xyz'): vax = 'v'+ax if need_pos: dx = s_pos[p,i] - center[i] dx[dx > half_box_size] -= box_size dx[dx < -half_box_size] += box_size if need_vel: dvx = s_vel[p,i] - vel_center[i] if ax in output_names: out[ax][npart:] = dx if vax in output_names: out[vax][npart:] = dvx if 'r' in output_names: out['r'][npart:] += dx*dx if 'v' in output_names: out['v'][npart:] += dvx*dvx if 'vr' in output_names: out['vr'][npart:] += dx*dvx if need_id: out['id'][npart:] = s_id[p] npart += len(p) if not npart: return np.empty(0, output_dtype) for x in ('r', 'v'): if x in output_names: out[x] **= 0.5 return out
{ "repo_name": "manodeep/yymao-helpers", "path": "helpers/findSpheresInSnapshots.py", "copies": "1", "size": "5323", "license": "mit", "hash": -8954748401139274000, "line_mean": 34.7248322148, "line_max": 87, "alpha_frac": 0.5540108961, "autogenerated": false, "ratio": 3.324797001873829, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9300167557060425, "avg_score": 0.01572806818268076, "num_lines": 149 }
__all__ = ['get_statements', 'get_statements_for_paper', 'get_statements_by_hash', 'submit_curation'] from indra.util import clockit from indra.statements import stmts_from_json, Complex, SelfModification, \ ActiveForm, Translocation, Conversion from indra.sources.indra_db_rest.processor import IndraDBRestSearchProcessor, \ IndraDBRestHashProcessor, IndraDBRestPaperProcessor from indra.sources.indra_db_rest.util import make_db_rest_request, get_url_base @clockit def get_statements(subject=None, object=None, agents=None, stmt_type=None, use_exact_type=False, persist=True, simple_response=False, *api_args, **api_kwargs): """Get a processor for the INDRA DB web API matching given agents and type. There are two types of responses available. You can just get a list of INDRA Statements, or you can get an IndraDBRestProcessor object, which allow Statements to be loaded in a background thread, providing a sample of the best* content available promptly in the sample_statements attribute, and populates the statements attribute when the paged load is complete. The latter should be used in all new code, and where convenient the prior should be converted to use the processor, as this option may be removed in the future. * In the sense of having the most supporting evidence. Parameters ---------- subject/object : str Optionally specify the subject and/or object of the statements in you wish to get from the database. By default, the namespace is assumed to be HGNC gene names, however you may specify another namespace by including `@<namespace>` at the end of the name string. For example, if you want to specify an agent by chebi, you could use `CHEBI:6801@CHEBI`, or if you wanted to use the HGNC id, you could use `6871@HGNC`. agents : list[str] A list of agents, specified in the same manner as subject and object, but without specifying their grammatical position. stmt_type : str Specify the types of interactions you are interested in, as indicated by the sub-classes of INDRA's Statements. This argument is *not* case sensitive. If the statement class given has sub-classes (e.g. RegulateAmount has IncreaseAmount and DecreaseAmount), then both the class itself, and its subclasses, will be queried, by default. If you do not want this behavior, set use_exact_type=True. Note that if max_stmts is set, it is possible only the exact statement type will be returned, as this is the first searched. The processor then cycles through the types, getting a page of results for each type and adding it to the quota, until the max number of statements is reached. use_exact_type : bool If stmt_type is given, and you only want to search for that specific statement type, set this to True. Default is False. persist : bool Default is True. When False, if a query comes back limited (not all results returned), just give up and pass along what was returned. Otherwise, make further queries to get the rest of the data (which may take some time). simple_response : bool If True, a simple list of statements is returned (thus block should also be True). If block is False, only the original sample will be returned (as though persist was False), until the statements are done loading, in which case the rest should appear in the list. This behavior is not encouraged. Default is False (which breaks backwards compatibility with usage of INDRA versions from before 1/22/2019). WE ENCOURAGE ALL NEW USE-CASES TO USE THE PROCESSOR, AS THIS FEATURE MAY BE REMOVED AT A LATER DATE. timeout : positive int or None If an int, block until the work is done and statements are retrieved, or until the timeout has expired, in which case the results so far will be returned in the response object, and further results will be added in a separate thread as they become available. If simple_response is True, all statements available will be returned. Otherwise (if None), block indefinitely until all statements are retrieved. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 10. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. max_stmts : int or None Select the maximum number of statements to return. When set less than 1000 the effect is much the same as setting persist to false, and will guarantee a faster response. Default is None. Returns ------- processor/stmt_list : :py:class:`IndraDBRestSearchProcessor` or list See `simple_response` for details regarding the choice. If a processor: An instance of the IndraDBRestProcessor, which has an attribute `statements` which will be populated when the query/queries are done. This is the default behavior, and is encouraged in all future cases, however a simple list of statements may be returned using the `simple_response` option described above. """ return _wrap_processor( IndraDBRestSearchProcessor(subject, object, agents, stmt_type, use_exact_type, persist, *api_args, **api_kwargs), simple_response ) @clockit def get_statements_by_hash(hash_list, simple_response=False, *args, **kwargs): """Get fully formed statements from a list of hashes. Parameters ---------- hash_list : list[int or str] A list of statement hashes. simple_response : bool If True, a simple list of statements is returned (thus block should also be True). If block is False, only the original sample will be returned (as though persist was False), until the statements are done loading, in which case the rest should appear in the list. This behavior is not encouraged. Default is False (which breaks backwards compatibility with usage of INDRA versions from before 9/19/2019). WE ENCOURAGE ALL NEW USE-CASES TO USE THE PROCESSOR, AS THIS FEATURE MAY BE REMOVED AT A LATER DATE. timeout : positive int or None If an int, return after `timeout` seconds, even if query is not done. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 100. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. Returns ------- processor/stmt_list : :py:class:`IndraDBRestSearchProcessor` or list See `simple_response` for details regarding the choice. If a processor: An instance of the IndraDBRestProcessor, which has an attribute `statements` which will be populated when the query/queries are done. This is the default behavior, and is encouraged in all future cases, however a simple list of statements may be returned using the `simple_response` option described above. """ return _wrap_processor( IndraDBRestHashProcessor(hash_list, *args, **kwargs), simple_response ) @clockit def get_statements_for_paper(ids, simple_response=False, *args, **kwargs): """Get the set of raw Statements extracted from a paper given by the id. Parameters ---------- ids : list[(<id type>, <id value>)] A list of tuples with ids and their type. The type can be any one of 'pmid', 'pmcid', 'doi', 'pii', 'manuscript id', or 'trid', which is the primary key id of the text references in the database. simple_response : bool If True, a simple list of statements is returned (thus block should also be True). If block is False, only the original sample will be returned (as though persist was False), until the statements are done loading, in which case the rest should appear in the list. This behavior is not encouraged. Default is False (which breaks backwards compatibility with usage of INDRA versions from before 9/19/2019). WE ENCOURAGE ALL NEW USE-CASES TO USE THE PROCESSOR, AS THIS FEATURE MAY BE REMOVED AT A LATER DATE. timeout : positive int or None If an int, return after `timeout` seconds, even if query is not done. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 10. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. max_stmts : int or None Select a maximum number of statements to be returned. Default is None. Returns ------- processor/stmt_list : :py:class:`IndraDBRestSearchProcessor` or list See `simple_response` for details regarding the choice. If a processor: An instance of the IndraDBRestProcessor, which has an attribute `statements` which will be populated when the query/queries are done. This is the default behavior, and is encouraged in all future cases, however a simple list of statements may be returned using the `simple_response` option described above. """ return _wrap_processor(IndraDBRestPaperProcessor(ids, *args, **kwargs), simple_response) def _wrap_processor(processor, simple_response): if simple_response: ret = processor.statements else: ret = processor return ret def submit_curation(hash_val, tag, curator, text=None, source='indra_rest_client', ev_hash=None, is_test=False): """Submit a curation for the given statement at the relevant level. Parameters ---------- hash_val : int The hash corresponding to the statement. tag : str A very short phrase categorizing the error or type of curation, e.g. "grounding" for a grounding error, or "correct" if you are marking a statement as correct. curator : str The name or identifier for the curator. text : str A brief description of the problem. source : str The name of the access point through which the curation was performed. The default is 'direct_client', meaning this function was used directly. Any higher-level application should identify itself here. ev_hash : int A hash of the sentence and other evidence information. Elsewhere referred to as `source_hash`. is_test : bool Used in testing. If True, no curation will actually be added to the database. """ data = {'tag': tag, 'text': text, 'curator': curator, 'source': source, 'ev_hash': ev_hash} url = 'curation/submit/%s' % hash_val if is_test: qstr = '?test' else: qstr = '' return make_db_rest_request('post', url, qstr, data=data) def get_statement_queries(stmts, fallback_ns='NAME', pick_ns_fun=None, **params): """Get queries used to search based on a statement. In addition to the stmts, you can enter any parameters standard to the query. See https://github.com/indralab/indra_db/rest_api for a full list. Parameters ---------- stmts : list[Statement] A list of INDRA statements. fallback_ns : Optional[str] The name space to search by when an Agent in a Statement is not grounded to one of the standardized name spaces. Typically, searching by 'NAME' (i.e., the Agent's name) is a good option if (1) An Agent's grounding is missing but its name is known to be standard in one of the name spaces. In this case the name-based lookup will yield the same result as looking up by grounding. Example: MAP2K1(db_refs={}) (2) Any Agent that is encountered with the same name as this Agent is never standardized, so looking up by name yields the same result as looking up by TEXT. Example: xyz(db_refs={'TEXT': 'xyz'}) Searching by TEXT is better in other cases e.g., when the given specific Agent is not grounded but we have other Agents with the same TEXT that are grounded and then standardized to a different name. Example: Erk(db_refs={'TEXT': 'Erk'}). Default: 'NAME' pick_ns_fun : Optional[function] An optional user-supplied function which takes an Agent as input and returns a string of the form value@ns where 'value' will be looked up in namespace 'ns' to search for the given Agent. **params : kwargs A set of keyword arguments that are added as parameters to the query URLs. """ def pick_ns(ag): # If the Agent has grounding, in order of preference, in any of these # name spaces then we look it up based on grounding. for ns in ['FPLX', 'HGNC', 'UP', 'CHEBI', 'GO', 'MESH']: if ns in ag.db_refs: dbid = ag.db_refs[ns] return '%s@%s' % (dbid, ns) # Otherwise we fall back on searching by NAME or TEXT # (or any other given name space as long as the Agent name can be # usefully looked up in that name space). return '%s@%s' % (ag.name, fallback_ns) pick_ns_fun = pick_ns if not pick_ns_fun else pick_ns_fun queries = [] url_base = get_url_base('statements/from_agents') non_binary_statements = (Complex, SelfModification, ActiveForm, Translocation, Conversion) for stmt in stmts: kwargs = {} if not isinstance(stmt, non_binary_statements): for pos, ag in zip(['subject', 'object'], stmt.agent_list()): if ag is not None: kwargs[pos] = pick_ns_fun(ag) else: for i, ag in enumerate(stmt.agent_list()): if ag is not None: kwargs['agent%d' % i] = pick_ns_fun(ag) kwargs['type'] = stmt.__class__.__name__ kwargs.update(params) query_str = '?' + '&'.join(['%s=%s' % (k, v) for k, v in kwargs.items() if v is not None]) queries.append(url_base + query_str) return queries
{ "repo_name": "johnbachman/belpy", "path": "indra/sources/indra_db_rest/api.py", "copies": "1", "size": "16246", "license": "mit", "hash": -8000564772349501000, "line_mean": 48.2303030303, "line_max": 80, "alpha_frac": 0.6649021298, "autogenerated": false, "ratio": 4.275263157894737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5440165287694737, "avg_score": null, "num_lines": null }
__all__ = ['get_valid_residue', 'activity_types', 'amino_acids', 'amino_acids_reverse', 'InvalidLocationError', 'InvalidResidueError'] import os def get_valid_residue(residue): """Check if the given string represents a valid amino acid residue.""" if residue is not None and amino_acids.get(residue) is None: res = amino_acids_reverse.get(residue.lower()) if res is None: raise InvalidResidueError(residue) else: return res return residue # FIXME: this list could be read from the ontology or another resource file activity_types = {'transcription', 'activity', 'catalytic', 'gtpbound', 'kinase', 'phosphatase', 'gef', 'gap'} def _read_amino_acids(): """Read the amino acid information from a resource file.""" this_dir = os.path.dirname(os.path.abspath(__file__)) aa_file = os.path.join(this_dir, os.pardir, 'resources', 'amino_acids.tsv') amino_acids = {} amino_acids_reverse = {} with open(aa_file, 'rt') as fh: lines = fh.readlines() for lin in lines[1:]: terms = lin.strip().split('\t') key = terms[2] val = {'full_name': terms[0], 'short_name': terms[1], 'indra_name': terms[3]} amino_acids[key] = val for v in val.values(): amino_acids_reverse[v] = key return amino_acids, amino_acids_reverse amino_acids, amino_acids_reverse = _read_amino_acids() class InvalidResidueError(ValueError): """Invalid residue (amino acid) name.""" def __init__(self, name): ValueError.__init__(self, "Invalid residue name: '%s'" % name) class InvalidLocationError(ValueError): """Invalid cellular component name.""" def __init__(self, name): ValueError.__init__(self, "Invalid location name: '%s'" % name)
{ "repo_name": "bgyori/indra", "path": "indra/statements/resources.py", "copies": "4", "size": "1860", "license": "bsd-2-clause", "hash": -2829514765963313700, "line_mean": 32.2142857143, "line_max": 79, "alpha_frac": 0.6091397849, "autogenerated": false, "ratio": 3.3214285714285716, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 56 }
__all__ = ["GitHubHooks"] from flask import request, Response from .base import Hook class GitHubHooks(Hook): def ok(self): return Response() def deploy(self, app, env): payload = request.get_json() event = request.headers.get("X-GitHub-Event") if event != "push": # Gracefully ignore everything except push events return self.ok() default_ref = app.get_default_ref(env) ref = payload["ref"] if ref != f"refs/heads/{default_ref}": return self.ok() head_commit = payload["head_commit"] if not head_commit: # Deleting a branch is one case, not sure of others return self.ok() committer = head_commit["committer"] # If the committer is GitHub and the action was triggered from # the web UI, ignore it and use the author instead if ( committer["email"] == "noreply@github.com" and committer["username"] == "web-flow" ): committer = head_commit["author"] return self.client().post( "/api/0/deploys/", data={ "env": env, "app": app.name, "ref": head_commit["id"], "user": committer["email"], }, )
{ "repo_name": "getsentry/freight", "path": "freight/hooks/github.py", "copies": "1", "size": "1335", "license": "apache-2.0", "hash": 1515199527182206500, "line_mean": 26.2448979592, "line_max": 70, "alpha_frac": 0.5243445693, "autogenerated": false, "ratio": 4.145962732919255, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5170307302219255, "avg_score": null, "num_lines": null }
__all__ = ["GithubNotifier"] from flask import current_app from freight import http from freight.models import App, Task, TaskStatus from .base import Notifier, NotifierEvent class GithubNotifier(Notifier): def get_options(self): return {"repo": {"required": True}, "api_root": {"required": False}} def send_deploy(self, deploy, task, config, event): token = current_app.config["GITHUB_TOKEN"] if not token: raise ValueError("GITHUB_TOKEN is not set") headers = { "Accept": "application/vnd.github.v3+json", "Authorization": f"token {token}", } app = App.query.get(deploy.app_id) task = Task.query.get(deploy.task_id) api_root = ( config.get("api_root") or current_app.config["GITHUB_API_ROOT"] ).rstrip("/") url = f"{api_root}/repos/{config['repo']}/statuses/{task.sha}" target_url = http.absolute_uri( f"/deploys/{app.name}/{deploy.environment}/{deploy.number}" ) if event == NotifierEvent.TASK_QUEUED: state = "pending" description = f"Freight deploy #{deploy.number} is currently queued." elif event == NotifierEvent.TASK_STARTED: state = "pending" description = f"Freight deploy #{deploy.number} has started." elif task.status == TaskStatus.failed: state = "failure" description = f"Freight deploy #{deploy.number} has failed." elif task.status == TaskStatus.cancelled: state = "error" description = f"Freight deploy #{deploy.number} has been cancelled." elif task.status == TaskStatus.finished: state = "success" description = f"Freight deploy #{deploy.number} has finished successfully." else: raise NotImplementedError(task.status) payload = { "state": state, "target_url": target_url, "description": description, "context": "continuous-integration/freight/deploy", } http.post(url, headers=headers, json=payload)
{ "repo_name": "getsentry/freight", "path": "freight/notifiers/github.py", "copies": "1", "size": "2151", "license": "apache-2.0", "hash": -6391701396802450000, "line_mean": 33.6935483871, "line_max": 87, "alpha_frac": 0.5908879591, "autogenerated": false, "ratio": 4.043233082706767, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5134121041806766, "avg_score": null, "num_lines": null }
__all__ = ["GitVcs"] import os from urllib.parse import urlparse from .base import Vcs, CommandError, UnknownRevision class GitVcs(Vcs): binary_path = "git" def get_default_env(self): return {"GIT_SSH": self.ssh_connect_path} def get_default_revision(self): return "master" @property def remote_url(self): if self.url.startswith(("ssh:", "http:", "https:")): parsed = urlparse(self.url) port = ":%s" % (parsed.port,) if parsed.port else "" url = "%s://%s@%s/%s" % ( parsed.scheme, parsed.username or self.username or "git", parsed.hostname + port, parsed.path.lstrip("/"), ) else: url = self.url return url def run(self, cmd, **kwargs): cmd = [self.binary_path] + cmd try: return super(GitVcs, self).run(cmd, **kwargs) except CommandError as e: if e.stderr and "unknown revision or path" in e.stderr: raise UnknownRevision( cmd=e.cmd, retcode=e.retcode, stdout=e.stdout, stderr=e.stderr ) raise def clone(self): self.run(["clone", "--mirror", self.remote_url, self.path]) def update(self): # in case we have a non-mirror checkout, wipe it out if os.path.exists(os.path.join(self.workspace.path, ".git")): self.run(["rm", "-rf", self.workspace.path]) self.clone() else: self.run(["fetch", "--all", "-p"]) def checkout(self, ref, new_workspace): self.run( ["clone", self.workspace.path, new_workspace.path], workspace=new_workspace ) self.run(["reset", "--hard", ref], workspace=new_workspace) def get_sha(self, ref): return self.run(["rev-parse", ref], capture=True)
{ "repo_name": "getsentry/freight", "path": "freight/vcs/git.py", "copies": "1", "size": "1907", "license": "apache-2.0", "hash": 3918890006389340700, "line_mean": 29.2698412698, "line_max": 87, "alpha_frac": 0.5359202937, "autogenerated": false, "ratio": 3.814, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48499202937, "avg_score": null, "num_lines": null }
__all__ = ["GO", "riboseq", "rnaseq", "general", 'which', 'qtools', 'mapping', 'annotations', 'expr_db', 'conservation'] # Copyright (c) 2001-2004 Twisted Matrix Laboratories. # See LICENSE for details. """ Utilities for dealing with processes. """ import os def which(name, flags=os.X_OK): """ Copied from Twisted 8.2 implementation (http://twistedmatrix .com/trac/browser/tags/releases/twisted-8.2.0/twisted/python/procutils.py). Can't find it in the latest (13 .1) implementation. - Olga Search PATH for executable files with the given name. On newer versions of MS-Windows, the PATHEXT environment variable will be set to the list of file extensions for files considered executable. This will normally include things like ".EXE". This fuction will also find files with the given name ending with any of these extensions. On MS-Windows the only flag that has any meaning is os.F_OK. Any other flags will be ignored. @type name: C{str} @param name: The name for which to search. @type flags: C{int} @param flags: Arguments to L{os.access}. @rtype: C{list} @param: A list of the full paths to files found, in the order in which they were found. """ result = [] exts = filter(None, os.environ.get('PATHEXT', '').split(os.pathsep)) path = os.environ.get('PATH', None) if path is None: return [] for p in os.environ.get('PATH', '').split(os.pathsep): p = os.path.join(p, name) if os.access(p, flags): result.append(p) for e in exts: pext = p + e if os.access(pext, flags): result.append(pext) return result
{ "repo_name": "YeoLab/gscripts", "path": "gscripts/__init__.py", "copies": "1", "size": "1715", "license": "mit", "hash": 4139222376335739400, "line_mean": 30.7592592593, "line_max": 79, "alpha_frac": 0.6379008746, "autogenerated": false, "ratio": 3.6723768736616704, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.481027774826167, "avg_score": null, "num_lines": null }
__all__ = ['GotoLoiter', 'ArmDisarm'] import time import geopy import geopy.distance from pymavlink import mavutil from .sandbox import Sandbox from .connection import CommandLong from ..state import State from ..environment import Environment from ..valueRange import ContinuousValueRange, DiscreteValueRange from ..configuration import Configuration from ..command import Parameter, Command from ..specification import Specification, Idle ArmNormally = Specification( 'arm-normal', """ (and (= $arm true) (= _armable true) (or (= _mode "GUIDED") (= _mode "LOITER"))) """, '(= __armed true)') DisarmNormally = Specification( 'disarm-normal', '(and (= $arm false) (= _armed true))', '(= __armed false)') GotoLoiter = Specification( 'loiter', '(and (= _armed true) (= _mode "LOITER"))', """ (and (= __longitude $longitude) (= __latitude $latitude) (= __altitude $altitude) (= __mode "LOITER")) """) class ArmDisarm(Command): """ Behaviours: Normal: if the robot is armable and is in either its 'GUIDED' or 'LOITER' modes, the robot will become armed. Idle: if the conditions above cannot be met, the robot will ignore the command. """ name = 'arm' parameters = [ Parameter('arm', DiscreteValueRange([True, False])) ] specifications = [ ArmNormally, DisarmNormally, Idle ] def dispatch(self, sandbox: Sandbox, state: State, environment: Environment, configuration: Configuration ) -> None: vehicle = sandbox.connection arm_flag = 1 if self.arm else 0 msg = vehicle.message_factory.command_long_encode( 0, 0, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, arm_flag, 0, 0, 0, 0, 0, 0) vehicle.send_mavlink(msg) def to_message(self) -> CommandLong: msg = CommandLong( 0, 0, mavutil.mavlink.MAV_CMD_COMPONENT_ARM_DISARM, 0, 1 if self.arm else 0, 0, 0, 0, 0, 0, 0) return msg
{ "repo_name": "squaresLab/Houston", "path": "houston/ardu/common.py", "copies": "1", "size": "2209", "license": "mit", "hash": -4949612154999521000, "line_mean": 24.9882352941, "line_max": 78, "alpha_frac": 0.5753734722, "autogenerated": false, "ratio": 3.8551483420593367, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49305218142593366, "avg_score": null, "num_lines": null }
__all__ = ['GoTo'] import dronekit import geopy.distance from ..connection import CommandLong from ...configuration import Configuration from ...state import State from ...environment import Environment from ...command import Command, Parameter from ...specification import Idle, Specification from ...valueRange import ContinuousValueRange, DiscreteValueRange from ..common import GotoLoiter def timeout(a, s, e, c) -> float: from_loc = (s.latitude, s.longitude) to_loc = (a['latitude'], a['longitude']) dist = geopy.distance.great_circle(from_loc, to_loc).meters timeout = dist * c.time_per_metre_travelled timeout += c.constant_timeout_offset return timeout GotoNormally = Specification( 'normal', '(and (= _armed true) (not (= _mode "LOITER")))', '(and (= __longitude $longitude) (= __latitude $latitude))', timeout) class GoTo(Command): uid = 'ardu:rover:goto' name = 'goto' parameters = [ Parameter('latitude', ContinuousValueRange(-90.0, 90.0, True)), Parameter('longitude', ContinuousValueRange(-180.0, 180.0, True)) ] specifications = [ GotoNormally, GotoLoiter, Idle ] def dispatch(self, sandbox: 'Sandbox', state: State, environment: Environment, config: Configuration ) -> None: loc = dronekit.LocationGlobalRelative(self.latitude, self.longitude, state.altitude) sandbox.connection.simple_goto(loc) def to_message(self) -> CommandLong: return CommandLong(0, 0, cmd_id=mavutil.MAV_CMD_NAV_WAYPOINT, param1=2, # FIXME frame? param5=self.latitude, param6=self.longitude)
{ "repo_name": "squaresLab/Houston", "path": "houston/ardu/rover/goto.py", "copies": "1", "size": "1940", "license": "mit", "hash": 3088568571071058400, "line_mean": 30.2903225806, "line_max": 73, "alpha_frac": 0.5706185567, "autogenerated": false, "ratio": 4.163090128755365, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5233708685455365, "avg_score": null, "num_lines": null }
__all__ = ['GoTo'] import random import dronekit import geopy from pymavlink.mavutil import mavlink from ..connection import CommandLong from ..common import GotoLoiter from ...connection import Message from ...specification import Specification from ...configuration import Configuration from ...command import Command, Parameter from ...state import State from ...specification import Specification from ...environment import Environment from ...specification import Idle from ...valueRange import ContinuousValueRange, DiscreteValueRange def timeout_goto_normally(cmd: Command, s: State, e: Environment, c: Configuration ) -> float: from_loc = (s['latitude'], s['longitude']) to_loc = (cmd['latitude'], cmd['longitude']) dist = geopy.distance.great_circle(from_loc, to_loc).meters timeout = dist * c.time_per_metre_travelled timeout += c.constant_timeout_offset return timeout GotoNormally = Specification( 'normal', """ (and (= _armed true) (not (= _mode "LOITER")) (> _altitude 0.3)) """, """ (and (= __longitude $longitude) (= __latitude $latitude) (= __altitude $altitude)) """, timeout_goto_normally) class GoTo(Command): uid = 'ardu:copter:goto' name = 'goto' parameters = [ Parameter('latitude', ContinuousValueRange(-90.0, 90.0, True)), Parameter('longitude', ContinuousValueRange(-180.0, 180.0, True)), Parameter('altitude', ContinuousValueRange(0.3, 100.0)) ] specifications = [ GotoNormally, GotoLoiter, Idle ] @classmethod def generate(cls, rng: random.Random) -> 'GoTo': (lat, lon) = (-35.3632607, 149.1652351) # FIXME heading = rng.uniform(0.0, 360.0) dist = rng.uniform(0.0, 2.0) # FIXME params = {} origin = geopy.Point(latitude=lat, longitude=lon) dist = geopy.distance.distance(meters=dist) destination = dist.destination(origin, heading) params['latitude'] = destination.latitude params['longitude'] = destination.longitude params['altitude'] = 5.0 # FIXME command = cls(**params) return command def to_message(self) -> Message: return CommandLong(target_system=0, target_component=0, cmd_id=mavlink.MAV_CMD_NAV_WAYPOINT, param_5=self.latitude, param_6=self.longitude, param_7=self.altitude) def dispatch(self, sandbox: 'Sandbox', state: State, environment: Environment, config: Configuration ) -> None: loc = dronekit.LocationGlobalRelative(self.latitude, self.longitude, self.altitude) sandbox.connection.simple_goto(loc)
{ "repo_name": "squaresLab/Houston", "path": "houston/ardu/copter/goto.py", "copies": "1", "size": "3090", "license": "mit", "hash": 7724019581158283000, "line_mean": 30.2121212121, "line_max": 74, "alpha_frac": 0.5650485437, "autogenerated": false, "ratio": 4.238683127572016, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 99 }
__all__ = ["GP"] import numpy as np import matplotlib.pyplot as plt import scipy.optimize as optim import logging from scipy.linalg import cholesky, cho_solve from copy import copy, deepcopy from .ext import gp_c logger = logging.getLogger("gp.gp") DTYPE = np.float64 EPS = np.finfo(DTYPE).eps MIN = np.log(np.exp2(DTYPE(np.finfo(DTYPE).minexp + 4))) def memoprop(f): """ Memoized property. When the property is accessed for the first time, the return value is stored and that value is given on subsequent calls. The memoized value can be cleared by calling 'del prop', where prop is the name of the property. """ fname = f.__name__ def fget(self): if fname not in self._memoized: self._memoized[fname] = f(self) return self._memoized[fname] def fdel(self): del self._memoized[fname] prop = property(fget=fget, fdel=fdel, doc=f.__doc__) return prop class GP(object): r""" Gaussian Process object. Parameters ---------- K : :class:`~gp.kernels.base.Kernel` Kernel object x : numpy.ndarray :math:`n` array of input locations y : numpy.ndarray :math:`n` array of input observations s : number (default=0) Standard deviation of observation noise """ def __init__(self, K, x, y, s=0): r""" Initialize the GP. """ #: Kernel for the gaussian process, of type #: :class:`~gp.kernels.base.Kernel` self.K = K self._x = None self._y = None self._s = None self._memoized = {} self.x = x self.y = y self.s = s def __getstate__(self): state = {} state['K'] = self.K state['_x'] = self._x state['_y'] = self._y state['_s'] = self._s state['_memoized'] = self._memoized return state def __setstate__(self, state): self.K = state['K'] self._x = state['_x'] self._y = state['_y'] self._s = state['_s'] self._memoized = state['_memoized'] def __copy__(self): state = self.__getstate__() cls = type(self) gp = cls.__new__(cls) gp.__setstate__(state) return gp def __deepcopy__(self, memo): state = deepcopy(self.__getstate__(), memo) cls = type(self) gp = cls.__new__(cls) gp.__setstate__(state) return gp def copy(self, deep=True): """ Create a copy of the gaussian process object. Parameters ---------- deep : bool (default=True) Whether to return a deep or shallow copy Returns ------- gp : :class:`~gp.gp.GP` New gaussian process object """ if deep: gp = deepcopy(self) else: gp = copy(self) return gp @property def x(self): r""" Vector of input locations. Returns ------- x : numpy.ndarray :math:`n` array, where :math:`n` is the number of locations. """ return self._x @x.setter def x(self, val): if np.any(val != self._x): self._memoized = {} self._x = np.array(val, copy=True, dtype=DTYPE) self._x.flags.writeable = False else: # pragma: no cover pass @property def y(self): r""" Vector of input observations. Returns ------- y : numpy.ndarray :math:`n` array, where :math:`n` is the number of observations. """ return self._y @y.setter def y(self, val): if np.any(val != self._y): self._memoized = {} self._y = np.array(val, copy=True, dtype=DTYPE) self._y.flags.writeable = False if self.y.shape != self.x.shape: raise ValueError("invalid shape for y: %s" % str(self.y.shape)) else: # pragma: no cover pass @property def s(self): r""" Standard deviation of the observation noise for the gaussian process. Returns ------- s : numpy.float64 """ return self._s @s.setter def s(self, val): if val < 0: raise ValueError("invalid value for s: %s" % val) if val != self._s: self._memoized = {} self._s = DTYPE(val) @property def params(self): r""" Gaussian process parameters. Returns ------- params : numpy.ndarray Consists of the kernel's parameters, `self.K.params`, and the observation noise parameter, :math:`s`, in that order. """ _params = np.empty(self.K.params.size + 1) _params[:-1] = self.K.params _params[-1] = self._s return _params @params.setter def params(self, val): if np.any(self.params != val): self._memoized = {} self.K.params = val[:-1] self.s = val[-1] else: # pragma: no cover pass def get_param(self, name): if name == 's': return self.s else: return getattr(self.K, name) def set_param(self, name, val): if name == 's': self.s = val else: p = getattr(self.K, name) if p != val: self._memoized = {} self.K.set_param(name, val) else: # pragma: no cover pass @memoprop def Kxx(self): r""" Kernel covariance matrix :math:`\mathbf{K}_{xx}`. Returns ------- Kxx : numpy.ndarray :math:`n\times n` covariance matrix Notes ----- The entry at index :math:`(i, j)` is defined as: .. math:: K_{x_ix_j} = K(x_i, x_j) + s^2\delta(x_i-x_j), where :math:`K(\cdot{})` is the kernel function, :math:`s` is the standard deviation of the observation noise, and :math:`\delta` is the Dirac delta function. """ x, s = self._x, self._s K = self.K(x, x) K += np.eye(x.size, dtype=DTYPE) * (s ** 2) return K @memoprop def Kxx_J(self): x = self._x return self.K.jacobian(x, x) @memoprop def Kxx_H(self): x = self._x return self.K.hessian(x, x) @memoprop def Lxx(self): r""" Cholesky decomposition of the kernel covariance matrix. Returns ------- Lxx : numpy.ndarray :math:`n\times n` lower triangular matrix Notes ----- The value is :math:`\mathbf{L}_{xx}`, such that :math:`\mathbf{K}_{xx} = \mathbf{L}_{xx}\mathbf{L}_{xx}^\top`. """ return cholesky(self.Kxx, lower=True, overwrite_a=False, check_finite=True) @memoprop def inv_Kxx(self): r""" Inverse kernel covariance matrix, :math:`\mathbf{K}_{xx}^{-1}`. Note that this inverse is provided mostly just for reference. If you actually need to use it, use the Cholesky decomposition (`self.Lxx`) instead. Returns ------- inv_Kxx : numpy.ndarray :math:`n\times n` matrix """ inv_Lxx = np.linalg.inv(self.Lxx) return np.dot(inv_Lxx.T, inv_Lxx) @memoprop def inv_Kxx_y(self): r""" Dot product of the inverse kernel covariance matrix and of observation vector. This uses scipy's cholesky solver to compute the solution. Returns ------- inv_Kxx_y : numpy.ndarray :math:`n` array Notes ----- This is defined as :math:`\mathbf{K}_{xx}^{-1}\mathbf{y}`. """ inv_Kxx_y = cho_solve( (self.Lxx, True), self._y, overwrite_b=False, check_finite=True) return inv_Kxx_y @memoprop def log_lh(self): r""" Marginal log likelihood. Returns ------- log_lh : numpy.float64 Marginal log likelihood Notes ----- This is the log likelihood of observations :math:`\mathbf{y}` given locations :math:`\mathbf{x}` and kernel parameters :math:`\theta`. It is defined by Eq. 5.8 of [RW06]_: .. math:: \log{p(\mathbf{y} | \mathbf{x}, \mathbf{\theta})} = -\frac{1}{2}\mathbf{y}^\top \mathbf{K}_{xx}^{-1}\mathbf{y} - \frac{1}{2}\log{\left|\mathbf{K}_{xx}\right|}-\frac{d}{2}\log{2\pi}, where :math:`d` is the dimensionality of :math:`\mathbf{x}`. """ y = self._y K = self.Kxx try: Kiy = self.inv_Kxx_y except np.linalg.LinAlgError: return -np.inf return DTYPE(gp_c.log_lh(y, K, Kiy)) @memoprop def lh(self): r""" Marginal likelihood. Returns ------- lh : numpy.float64 Marginal likelihood Notes ----- This is the likelihood of observations :math:`\mathbf{y}` given locations :math:`\mathbf{x}` and kernel parameters :math:`\theta`. It is defined as: .. math:: p(\mathbf{y} | \mathbf{x}, \mathbf{\theta}) = \left(2\pi\right)^{-\frac{d}{2}}\left|\mathbf{K}_{xx}\right|^{-\frac{1}{2}}\exp\left(-\frac{1}{2}\mathbf{y}^\top\mathbf{K}_{xx}^{-1}\mathbf{y}\right) where :math:`d` is the dimensionality of :math:`\mathbf{x}`. """ llh = self.log_lh if llh < MIN: return 0 else: return np.exp(self.log_lh) @memoprop def dloglh_dtheta(self): r""" Derivative of the marginal log likelihood. Returns ------- dloglh_dtheta : numpy.ndarray :math:`n_\theta`-length vector of derivatives, where :math:`n_\theta` is the number of parameters (equivalent to ``len(self.params)``). Notes ----- This is a vector of first partial derivatives of the log likelihood with respect to its parameters :math:`\theta`. It is defined by Equation 5.9 of [RW06]_: .. math:: \frac{\partial}{\partial\theta_i}\log{p(\mathbf{y}|\mathbf{x},\theta)}=\frac{1}{2}\mathbf{y}^\top\mathbf{K}_{xx}^{-1}\frac{\partial\mathbf{K}_{xx}}{\partial\theta_i}\mathbf{K}_{xx}^{-1}\mathbf{y}-\frac{1}{2}\mathbf{tr}\left(\mathbf{K}_{xx}^{-1}\frac{\partial\mathbf{K}_{xx}}{\partial\theta_i}\right) """ y = self._y dloglh = np.empty(len(self.params)) try: Ki = self.inv_Kxx except np.linalg.LinAlgError: dloglh.fill(np.nan) return dloglh Kj = self.Kxx_J Kiy = self.inv_Kxx_y gp_c.dloglh_dtheta(y, Ki, Kj, Kiy, self._s, dloglh) return dloglh @memoprop def dlh_dtheta(self): r""" Derivative of the marginal likelihood. Returns ------- dlh_dtheta : numpy.ndarray :math:`n_\theta`-length vector of derivatives, where :math:`n_\theta` is the number of parameters (equivalent to ``len(self.params)``). Notes ----- This is a vector of first partial derivatives of the likelihood with respect to its parameters :math:`\theta`. """ y = self._y dlh = np.empty(len(self.params)) try: Ki = self.inv_Kxx except np.linalg.LinAlgError: dlh.fill(np.nan) return dlh Kj = self.Kxx_J Kiy = self.inv_Kxx_y lh = self.lh gp_c.dlh_dtheta(y, Ki, Kj, Kiy, self._s, lh, dlh) return dlh @memoprop def d2lh_dtheta2(self): r""" Second derivative of the marginal likelihood. Returns ------- d2lh_dtheta2 : numpy.ndarray :math:`n_\theta`-length vector of derivatives, where :math:`n_\theta` is the number of parameters (equivalent to ``len(self.params)``). Notes ----- This is a matrix of second partial derivatives of the likelihood with respect to its parameters :math:`\theta`. """ y = self._y d2lh = np.empty((len(self.params), len(self.params))) try: Ki = self.inv_Kxx except np.linalg.LinAlgError: d2lh.fill(np.nan) return d2lh Kj = self.Kxx_J Kh = self.Kxx_H Kiy = self.inv_Kxx_y lh = self.lh dlh = self.dlh_dtheta gp_c.d2lh_dtheta2(y, Ki, Kj, Kh, Kiy, self._s, lh, dlh, d2lh) return d2lh def Kxoxo(self, xo): r""" Kernel covariance matrix of new sample locations. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- Kxoxo : numpy.ndarray :math:`m\times m` covariance matrix Notes ----- This is defined as :math:`K(\mathbf{x^*}, \mathbf{x^*})`, where :math:`\mathbf{x^*}` are the new locations. """ return self.K(xo, xo) def Kxxo(self, xo): r""" Kernel covariance matrix between given locations and new sample locations. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- Kxxo : numpy.ndarray :math:`n\times m` covariance matrix Notes ----- This is defined as :math:`K(\mathbf{x},\mathbf{x^*})`, where :math:`\mathbf{x}` are the given locations and :math:`\mathbf{x^*}` are the new sample locations. """ return self.K(self._x, xo) def Kxox(self, xo): r""" Kernel covariance matrix between new sample locations and given locations. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- Kxox : numpy.ndarray :math:`m\times n` covariance matrix Notes ----- This is defined as :math:`K(\mathbf{x^*},\mathbf{x})`, where :math:`\mathbf{x^*}` are the new sample locations and :math:`\mathbf{x}` are the given locations """ return self.K(xo, self._x) def mean(self, xo): r""" Predictive mean of the gaussian process. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- mean : numpy.ndarray :math:`m` array of predictive means Notes ----- This is defined by Equation 2.23 of [RW06]_: .. math:: \mathbf{m}(\mathbf{x^*})=K(\mathbf{x^*}, \mathbf{x})\mathbf{K}_{xx}^{-1}\mathbf{y} """ return np.dot(self.Kxox(xo), self.inv_Kxx_y) def cov(self, xo): r""" Predictive covariance of the gaussian process. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- cov : numpy.ndarray :math:`m\times m` array of predictive covariances Notes ----- This is defined by Eq. 2.24 of [RW06]_: .. math:: \mathbf{C}=K(\mathbf{x^*}, \mathbf{x^*}) - K(\mathbf{x^*}, \mathbf{x})\mathbf{K}_{xx}^{-1}K(\mathbf{x}, \mathbf{x^*}) """ Kxoxo = self.Kxoxo(xo) Kxox = self.Kxox(xo) Kxxo = self.Kxxo(xo) return Kxoxo - np.dot(Kxox, np.dot(self.inv_Kxx, Kxxo)) def dm_dtheta(self, xo): r""" Derivative of the mean of the gaussian process with respect to its parameters, and evaluated at `xo`. Parameters ---------- xo : numpy.ndarray :math:`m` array of new sample locations Returns ------- dm_dtheta : numpy.ndarray :math:`n_p\times m` array, where :math:`n_p` is the number of parameters (see `params`). Notes ----- The analytic form is: .. math:: \frac{\partial}{\partial \theta_i}m(\mathbf{x^*})=\frac{\partial K(\mathbf{x^*}, \mathbf{x})}{\partial \theta_i}\mathbf{K}_{xx}^{-1}\mathbf{y} - K(\mathbf{x^*}, \mathbf{x})\mathbf{K}_{xx}^{-1}\frac{\partial \mathbf{K}_{xx}}{\partial \theta_i}\mathbf{K}_{xx}^{-1}\mathbf{y} """ y = self._y Ki = self.inv_Kxx Kj = self.Kxx_J Kjxo = self.K.jacobian(xo, self._x) Kxox = self.Kxox(xo) dm = np.empty((len(self.params), xo.size)) gp_c.dm_dtheta(y, Ki, Kj, Kjxo, Kxox, self._s, dm) return dm def plot(self, ax=None, xlim=None, color='k', markercolor='r'): """ Plot the predictive mean and variance of the gaussian process. Parameters ---------- ax : `matplotlib.pyplot.axes.Axes` (optional) The axes on which to draw the graph. Defaults to ``plt.gca()`` if not given. xlim : (lower x limit, upper x limit) (optional) The limits of the x-axis. Defaults to the minimum and maximum of `x` if not given. color : str (optional) The line color to use. The default is 'k' (black). markercolor : str (optional) The marker color to use. The default is 'r' (red). """ x, y = self._x, self._y if ax is None: ax = plt.gca() if xlim is None: xlim = (x.min(), x.max()) X = np.linspace(xlim[0], xlim[1], 1000) mean = self.mean(X) cov = self.cov(X) std = np.sqrt(np.diag(cov)) upper = mean + std lower = mean - std ax.fill_between(X, lower, upper, color=color, alpha=0.3) ax.plot(X, mean, lw=2, color=color) ax.plot(x, y, 'o', ms=5, color=markercolor) ax.set_xlim(*xlim)
{ "repo_name": "jhamrick/gaussian_processes", "path": "gp/gp.py", "copies": "1", "size": "18238", "license": "mit", "hash": -7794982078190343000, "line_mean": 25.0542857143, "line_max": 311, "alpha_frac": 0.5055378879, "autogenerated": false, "ratio": 3.6770161290322583, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4682554016932258, "avg_score": null, "num_lines": null }
__all__ = ['GroundingMapper', 'load_grounding_map', 'default_grounding_map', 'default_agent_map', 'default_ignores', 'default_misgrounding_map', 'default_mapper', 'gm'] import os import csv import json import logging from copy import deepcopy from indra.statements import Agent from indra.databases import hgnc_client from indra.util import read_unicode_csv from indra.preassembler.grounding_mapper.gilda import get_gilda_models from indra.ontology.standardize import standardize_db_refs, \ standardize_agent_name from .disambiguate import adeft_disambiguators, DisambManager logger = logging.getLogger(__name__) class GroundingMapper(object): """Maps grounding of INDRA Agents based on a given grounding map. Each parameter, if not provided will result in loading the corresponding built-in grounding resource. To explicitly avoid loading the default, pass in an empty data structure as the given parameter, e.g., ignores=[]. Parameters ---------- grounding_map : Optional[dict] The grounding map, a dictionary mapping strings (entity names) to a dictionary of database identifiers. agent_map : Optional[dict] A dictionary mapping strings to grounded INDRA Agents with given state. ignores : Optional[list] A list of entity strings that, if encountered will result in the corresponding Statement being discarded. misgrounding_map : Optional[dict] A mapping dict similar to the grounding map which maps entity strings to a given grounding which is known to be incorrect and should be removed if encountered (making the remaining Agent ungrounded). use_adeft : Optional[bool] If True, Adeft will be attempted to be used for disambiguation of acronyms. Default: True gilda_mode : Optional[str] If None, Gilda will not be used at all. If 'web', the GILDA_URL setting from the config file or as an environmental variable is assumed to be the web service endpoint through which Gilda is used. If 'local', we assume that the gilda Python package is installed and will be used. """ def __init__(self, grounding_map=None, agent_map=None, ignores=None, misgrounding_map=None, use_adeft=True, gilda_mode=None): self.grounding_map = grounding_map if grounding_map is not None \ else default_grounding_map self.check_grounding_map(self.grounding_map) self.agent_map = agent_map if agent_map is not None \ else default_agent_map self.ignores = set(ignores) if ignores else default_ignores self.misgrounding_map = misgrounding_map if misgrounding_map \ else default_misgrounding_map self.use_adeft = use_adeft self.disamb_manager = DisambManager() self.gilda_mode = gilda_mode self._gilda_models = None @property def gilda_models(self): if self._gilda_models is None: self._gilda_models = get_gilda_models(self.gilda_mode) \ if self.gilda_mode else [] return self._gilda_models @gilda_models.setter def gilda_models(self, models): self._gilda_models = models @staticmethod def check_grounding_map(gm): """Run sanity checks on the grounding map, raise error if needed.""" for key, refs in gm.items(): if not refs: continue if 'HGNC' in refs and \ hgnc_client.get_hgnc_name(refs['HGNC']) is None: raise ValueError('HGNC:%s for key %s in the grounding map is ' 'not a valid ID' % (refs['HGNC'], key)) def map_stmts(self, stmts, do_rename=True): """Return a new list of statements whose agents have been mapped Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` The statements whose agents need mapping do_rename: Optional[bool] If True, the Agent name is updated based on the mapped grounding. If do_rename is True the priority for setting the name is FamPlex ID, HGNC symbol, then the gene name from Uniprot. Default: True Returns ------- mapped_stmts : list of :py:class:`indra.statements.Statement` A list of statements given by mapping the agents from each statement in the input list """ # Make a copy of the stmts mapped_stmts = [] num_skipped = 0 # Iterate over the statements for stmt in stmts: mapped_stmt = self.map_agents_for_stmt(stmt, do_rename) # Check if we should skip the statement if mapped_stmt is not None: mapped_stmts.append(mapped_stmt) else: num_skipped += 1 logger.info('%s statements filtered out' % num_skipped) return mapped_stmts def map_agents_for_stmt(self, stmt, do_rename=True): """Return a new Statement whose agents have been grounding mapped. Parameters ---------- stmt : :py:class:`indra.statements.Statement` The Statement whose agents need mapping. do_rename: Optional[bool] If True, the Agent name is updated based on the mapped grounding. If do_rename is True the priority for setting the name is FamPlex ID, HGNC symbol, then the gene name from Uniprot. Default: True Returns ------- mapped_stmt : :py:class:`indra.statements.Statement` The mapped Statement. """ mapped_stmt = deepcopy(stmt) # Iterate over the agents # Update agents directly participating in the statement agent_list = mapped_stmt.agent_list() for idx, agent in enumerate(agent_list): # If the agent is None, we do nothing if agent is None: continue # If the agent's TEXT is in the ignores list, we return None to # then filter out the Statement agent_txts = {agent.db_refs[t] for t in {'TEXT', 'TEXT_NORM'} if t in agent.db_refs} if agent_txts and agent_txts & set(self.ignores): return None # Check if an adeft model exists for agent text adeft_success = False if self.use_adeft and agent_txts and agent_txts & \ set(adeft_disambiguators): try: # Us the longest match for disambiguation txt_for_adeft = sorted(agent_txts & set(adeft_disambiguators), key=lambda x: len(x))[-1] adeft_success = self.disamb_manager.\ run_adeft_disambiguation(mapped_stmt, agent, idx, txt_for_adeft) except Exception as e: logger.error('There was an error during Adeft' ' disambiguation of %s.' % str(agent_txts)) logger.error(e) gilda_success = False # Gilda is not used if agent text is in the grounding map if not adeft_success and self.gilda_mode and \ not agent_txts & set(self.grounding_map) and \ agent_txts & set(self.gilda_models): try: # Us the longest match for disambiguation txt_for_gilda = sorted(agent_txts & set(self.gilda_models), key=lambda x: len(x))[-1] gilda_success = self.disamb_manager.\ run_gilda_disambiguation(mapped_stmt, agent, idx, txt_for_gilda, mode=self.gilda_mode) except Exception as e: logger.error('There was an error during Gilda' ' disambiguation of %s.' % str(agent_txts)) logger.error(e) # If Adeft and Gilda were not used or didn't succeed, we do # grounding mapping new_agent = self.map_agent(agent, do_rename) \ if not (adeft_success or gilda_success) else agent # If the old agent had bound conditions, but the new agent does # not, copy the bound conditions over if new_agent is not None and len(new_agent.bound_conditions) == 0: new_agent.bound_conditions = agent.bound_conditions agent_list[idx] = new_agent mapped_stmt.set_agent_list(agent_list) # Update agents in the bound conditions for agent in agent_list: if agent is not None: for bc in agent.bound_conditions: bc.agent = self.map_agent(bc.agent, do_rename) if not bc.agent: # Skip the entire statement if the agent maps to None # in the grounding map return None return mapped_stmt def map_agent(self, agent, do_rename): """Return the given Agent with its grounding mapped. This function grounds a single agent. It returns the new Agent object (which might be a different object if we load a new agent state from json) or the same object otherwise. Parameters ---------- agent : :py:class:`indra.statements.Agent` The Agent to map. do_rename: bool If True, the Agent name is updated based on the mapped grounding. If do_rename is True the priority for setting the name is FamPlex ID, HGNC symbol, then the gene name from Uniprot. Returns ------- grounded_agent : :py:class:`indra.statements.Agent` The grounded Agent. """ # We always standardize DB refs as a functionality in the # GroundingMapper. If a new module is implemented which is # responsible for standardizing grounding, this can be removed. agent.db_refs = self.standardize_db_refs(agent.db_refs) # If there is no TEXT available, we can return immediately since we # can't do mapping agent_txts = sorted({agent.db_refs[t] for t in {'TEXT', 'TEXT_NORM'} # Note that get here will correctly handle both # a non-existent entry and a None entry which # sometimes appears if agent.db_refs.get(t)}, key=lambda x: len(x), reverse=True) if not agent_txts: # We still do the name standardization here if do_rename: self.standardize_agent_name(agent, standardize_refs=False) return agent # 1. Check if there is a full agent mapping and apply if there is for agent_text in agent_txts: if agent_text in self.agent_map: mapped_to_agent = \ Agent._from_json(self.agent_map[agent_text]['agent']) return mapped_to_agent # 2. Look agent text up in the grounding map for agent_text in agent_txts: if agent_text in self.grounding_map: self.update_agent_db_refs(agent, self.grounding_map[agent_text], do_rename) return agent # 3. Look agent text up in the misgrounding map for agent_text in agent_txts: if agent_text in self.misgrounding_map: self.remove_agent_db_refs(agent, self.misgrounding_map[agent_text]) # This happens when there is an Agent text but it is not in the # grounding map. We still do the name standardization here. if do_rename: self.standardize_agent_name(agent, standardize_refs=False) # Otherwise just return return agent def update_agent_db_refs(self, agent, db_refs, do_rename=True): """Update db_refs of agent using the grounding map If the grounding map is missing one of the HGNC symbol or Uniprot ID, attempts to reconstruct one from the other. Parameters ---------- agent : :py:class:`indra.statements.Agent` The agent whose db_refs will be updated db_refs : dict The db_refs so set for the agent. do_rename: Optional[bool] If True, the Agent name is updated based on the mapped grounding. If do_rename is True the priority for setting the name is FamPlex ID, HGNC symbol, then the gene name from Uniprot. Default: True """ # Standardize the IDs in the db_refs dict and set it as the Agent's # db_refs txt = agent.db_refs.get('TEXT') agent.db_refs = self.standardize_db_refs(deepcopy(db_refs)) if txt: agent.db_refs['TEXT'] = txt # Finally, if renaming is needed we standardize the Agent's name if do_rename: self.standardize_agent_name(agent, standardize_refs=False) def remove_agent_db_refs(self, agent, db_refs): # Standardize the IDs in the db_refs dict and set it as the Agent's # db_refs standard_refs = self.standardize_db_refs(deepcopy(db_refs)) # If there is any overlap between the Agent's db_refs and the db_refs # that are to be eliminated, we consider the Agent's db_refs to be # invalid and remove them. We then reset the Agent's name to # its TEXT value if available. preserve_refs = {k: agent.db_refs[k] for k in {'TEXT', 'TEXT_NORM'} if k in agent.db_refs} if set(standard_refs.items()) & set(agent.db_refs.items()): agent.db_refs = preserve_refs if 'TEXT_NORM' in agent.db_refs: agent.name = agent.db_refs['TEXT_NORM'] elif 'TEXT' in agent.db_refs: agent.name = agent.db_refs['TEXT'] @staticmethod def standardize_db_refs(db_refs): """Return a standardized db refs dict for a given db refs dict. Parameters ---------- db_refs : dict A dict of db refs that may not be standardized, i.e., may be missing an available UP ID corresponding to an existing HGNC ID. Returns ------- dict The db_refs dict with standardized entries. """ return standardize_db_refs(db_refs) @staticmethod def standardize_agent_name(agent, standardize_refs=True): """Standardize the name of an Agent based on grounding information. If an agent contains a FamPlex grounding, the FamPlex ID is used as a name. Otherwise if it contains a Uniprot ID, an attempt is made to find the associated HGNC gene name. If one can be found it is used as the agent name and the associated HGNC ID is added as an entry to the db_refs. Similarly, CHEBI, MESH and GO IDs are used in this order of priority to assign a standardized name to the Agent. If no relevant IDs are found, the name is not changed. Parameters ---------- agent : indra.statements.Agent An INDRA Agent whose name attribute should be standardized based on grounding information. standardize_refs : Optional[bool] If True, this function assumes that the Agent's db_refs need to be standardized, e.g., HGNC mapped to UP. Default: True """ return standardize_agent_name(agent, standardize_refs=standardize_refs) @staticmethod def rename_agents(stmts): """Return a list of mapped statements with updated agent names. Creates a new list of statements without modifying the original list. Parameters ---------- stmts : list of :py:class:`indra.statements.Statement` List of statements whose Agents need their names updated. Returns ------- mapped_stmts : list of :py:class:`indra.statements.Statement` A new list of Statements with updated Agent names """ # Make a copy of the stmts mapped_stmts = deepcopy(stmts) # Iterate over the statements for _, stmt in enumerate(mapped_stmts): # Iterate over the agents for agent in stmt.agent_list(): GroundingMapper.standardize_agent_name(agent, True) return mapped_stmts # TODO: handle the cases when there is more than one entry for the same # key (e.g., ROS, ER) def load_grounding_map(grounding_map_path, lineterminator='\r\n', hgnc_symbols=True): """Return a grounding map dictionary loaded from a csv file. In the file pointed to by grounding_map_path, the number of name_space ID pairs can vary per row and commas are used to pad out entries containing fewer than the maximum amount of name spaces appearing in the file. Lines should be terminated with \r\n both a carriage return and a new line by default. Optionally, one can specify another csv file (pointed to by ignore_path) containing agent texts that are degenerate and should be filtered out. It is important to note that this function assumes that the mapping file entries for the HGNC key are symbols not IDs. These symbols are converted to IDs upon loading here. Parameters ---------- grounding_map_path : str Path to csv file containing grounding map information. Rows of the file should be of the form <agent_text>,<name_space_1>,<ID_1>,... <name_space_n>,<ID_n> lineterminator : Optional[str] Line terminator used in input csv file. Default: \r\n hgnc_symbols : Optional[bool] Set to True if the grounding map file contains HGNC symbols rather than IDs. In this case, the entries are replaced by IDs. Default: True Returns ------- g_map : dict The grounding map constructed from the given files. """ gmap = {} map_rows = read_unicode_csv(grounding_map_path, delimiter=',', quotechar='"', quoting=csv.QUOTE_MINIMAL, lineterminator=lineterminator) for row in map_rows: txt = row[0] keys = [entry for entry in row[1::2] if entry] values = [entry for entry in row[2::2] if entry] if not keys or not values: logger.warning('Missing grounding entries for %s, skipping.' % txt) continue if len(keys) != len(values): logger.warning('Mismatched keys and values in row %s, skipping.' % str(row)) continue gmap[txt] = dict(zip(keys, values)) if hgnc_symbols: gmap = replace_hgnc_symbols(gmap) return gmap def replace_hgnc_symbols(gmap): """Replace HGNC symbols with IDs in a grounding map.""" for txt, mapped_refs in deepcopy(gmap).items(): hgnc_sym = mapped_refs.get('HGNC') if hgnc_sym: hgnc_id = hgnc_client.get_hgnc_id(hgnc_sym) # Override the HGNC symbol entry from the grounding # map with an HGNC ID if hgnc_id: mapped_refs['HGNC'] = hgnc_id else: logger.error('No HGNC ID corresponding to gene ' 'symbol %s in grounding map.' % hgnc_sym) # Remove the HGNC symbol in this case mapped_refs.pop('HGNC') # In case the only grounding was eliminated, we remove the entry # completely if mapped_refs: gmap[txt] = mapped_refs return gmap def _get_resource_path(*suffixes): return os.path.join(os.path.dirname(__file__), os.pardir, os.pardir, 'resources', *suffixes) def _load_default_grounding_map(): default_grounding_map_path = \ _get_resource_path('grounding', 'grounding_map.csv') gmap = load_grounding_map(default_grounding_map_path, hgnc_symbols=True) return gmap def _load_default_misgrounding_map(): default_misgrounding_map_path = \ _get_resource_path('grounding', 'misgrounding_map.csv') gmap = load_grounding_map(default_misgrounding_map_path, hgnc_symbols=False) return gmap def _load_default_agent_map(): default_agent_grounding_path = \ _get_resource_path('grounding', 'agents.json') with open(default_agent_grounding_path, 'r') as fh: agent_map = json.load(fh) return agent_map def _load_default_ignores(): default_ignore_path = _get_resource_path('grounding', 'ignore.csv') with open(default_ignore_path, 'r') as fh: ignores = [l.strip() for l in fh.readlines()] return ignores default_grounding_map = _load_default_grounding_map() gm = default_grounding_map # For backwards compatibility, redundant default_misgrounding_map = _load_default_misgrounding_map() default_agent_map = _load_default_agent_map() default_ignores = _load_default_ignores() default_mapper = GroundingMapper(default_grounding_map, agent_map=default_agent_map, ignores=default_ignores, misgrounding_map=default_misgrounding_map)
{ "repo_name": "bgyori/indra", "path": "indra/preassembler/grounding_mapper/mapper.py", "copies": "3", "size": "21810", "license": "bsd-2-clause", "hash": 4177120529789061000, "line_mean": 41.1856866538, "line_max": 80, "alpha_frac": 0.5930765704, "autogenerated": false, "ratio": 4.144811858608894, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00008357809776249492, "num_lines": 517 }
__all__ = ['gt', 'lt', 'gte', 'lte', 'Condition'] class Condition(object): """This is a base class to represent a SQL filtering condition. These can be used in a Query.filter clause to implement various equality statements. For example, take the following query: Select('person').filter(age=30) This is great and all, but it will only filter on the exact age. A mechanism was needed for implementing other checks. Django handles this by doing special checks on the **kwargs that get passed into the filter, and the user can append text to the variable name to change the comparison. For example, instead of doing "age=30", if you wanted to do a greater than comparison, you would do "age__gt=30". This is fine, but it doesn't allow the end user to easily create their own comparison operators. I found this to be a problem for non-standard database servers. Conrad implements these comparisons as classes. This allows you to subclass the "Condition" class to create your own SQL comparison. A Condition has a statement, a variable, and an operator. When the Query generates its SQL statement, it will insert the "statement" property from any Conditions included in the filters. It will then include the value of the "variable" property in the arguments to the adapter. By default, the "statement" property is {{name}} {operator} {{placeholder}} where operator is just the class' operator property. The name and placeholder variables are escaped, and inserted by the Query itself. The name is the kwarg that was assigned, and the placeholder is the query's placeholder value. So, for example, let's use this in a Select: Select('person').filter(age=gt(30)) This filter will return all 'person' rows where `age` > 30. In the above description of the "statement", {{name}} is "age" and {{placeholder}} is probably "?". In the gt() condition class below, the operator is defined as ">". So that's how the Select query can generate a SQL query of "SELECT * FROM person WHERE age > 30". """ # Override the operator in subclasses for simple condition modification operator = '=' def __init__(self, variable): self.variable = variable @property def statement(self): # Override this property for more extreme conditions return '{{name}} {operator} {{placeholder}}'.format( operator=self.operator) def __repr__(self): return self.statement class GreaterThan(Condition): operator = '>' class LessThan(Condition): operator = '<' class GreaterThanOrEqualTo(Condition): operator = '>=' class LessThanOrEqualTo(Condition): operator = '<=' gt = GreaterThan lt = LessThan gte = GreaterThanOrEqualTo lte = LessThanOrEqualTo
{ "repo_name": "jmohr/conrad", "path": "conrad/query/condition.py", "copies": "1", "size": "2852", "license": "bsd-3-clause", "hash": 1778318936059549000, "line_mean": 35.1012658228, "line_max": 76, "alpha_frac": 0.696002805, "autogenerated": false, "ratio": 4.3944530046224966, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 79 }
__all__ = ["GUID"] from sqlalchemy.types import TypeDecorator, CHAR from sqlalchemy.dialects.postgresql import UUID import uuid class GUID(TypeDecorator): """ Platform-independent GUID type. Uses Postgresql's UUID type, otherwise uses CHAR(32), storing as stringified hex values. """ impl = CHAR def load_dialect_impl(self, dialect): if dialect.name == "postgresql": return dialect.type_descriptor(UUID()) else: return dialect.type_descriptor(CHAR(32)) def process_bind_param(self, value, dialect): if value is None: return value elif dialect.name == "postgresql": return str(value) else: if not isinstance(value, uuid.UUID): return "%.32x" % uuid.UUID(value) else: # hexstring return "%.32x" % value def process_result_value(self, value, dialect): if value is None: return value else: return uuid.UUID(value) @classmethod def default_value(cls): return uuid.uuid1()
{ "repo_name": "getsentry/zeus", "path": "zeus/db/types/guid.py", "copies": "1", "size": "1134", "license": "apache-2.0", "hash": -1369357002260683000, "line_mean": 21.68, "line_max": 52, "alpha_frac": 0.5784832451, "autogenerated": false, "ratio": 4.4296875, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 50 }
__all__ = ['GuiManager'] import string from kivy.uix.relativelayout import RelativeLayout from kivy.core.window import Window from pocketthrone.entities.event import * from pocketthrone.managers.eventmanager import EventManager from pocketthrone.gui import * from pocketthrone.gui.sidebar import SideBar from pocketthrone.managers.pipe import L class GuiManager: # layouts _tag = "[GuiManager] " gamestate = GAMESTATE_MENU widgets_by_id = {} def __init__(self): EventManager.register(self) self.set_gamestate(GAMESTATE_LOADING) # set gamestate def set_gamestate(self, value): self.gamestate = value # fire GameStateChangedEvent ev_state_changed = GameStateChangedEvent(value) EventManager.fire(ev_state_changed) # returns gamestate def get_gamestate(self): return self.gamestate # returns a new gui panel id def next_panel_id(self): self._last_panel_id += 1 return self._last_panel_id # returns the screen size in px as tuple def get_screen_size(self): return (Window.width, Window.height) # register widget_id in GuiManager def register_widget(self, widget_id, widget): # check if widget registration is valid if string.strip(widget_id) == "untagged": print(self._tag + "ERROR widget registration aborted for " + string.strip(widget_id)) return None self.widgets_by_id[string.strip(widget_id)] = widget print(self._tag + "registered widget_id=" + string.strip(widget_id)) return widget # returns widget with string widget_id or None def get_widget(self, widget_id): widget = None stripped_id = widget_id.strip() success = False # filter untagged if stripped_id == "untagged": success = False try: # try to get from widget list widget = self.widgets_by_id[stripped_id] success = True finally: print(self._tag + "get widget _id=" + string.strip(widget_id) + " 2nd_acc=" + str(success) + " widget=" + repr(widget)) return widget # removes widget entity from GuiManager def remove_widget(self, widget_id): widget = self.get_widget(widget_id) root.remove_widget(widget) # fire ButtonClickedEvent when a button is pressed def button_clicked(self, button): ev_button_clicked = GuiButtonClickedEvent(button.tag, button) EventManager.fire(ev_button_clicked) def on_event(self, event): if isinstance(event, GameStartedEvent): self.gamestate = GAMESTATE_INGAME # clear BottomBar Labels on TileUnselectedEvent if isinstance(event, TileUnselectedEvent): # change labels self.get_widget("heading").set_text("") self.get_widget("details").set_text("") # get actionbutton actionbutton = self.get_widget("actionbutton") actionbutton.set_button_state("DEFAULT") # show unit data in BottomBar on UnitSelectedEvent if isinstance(event, UnitSelectedEvent): heading = self.get_widget("heading") details = self.get_widget("details") heading.set_plaintext("Unit: " + event.unit.name) details.set_plaintext("HP: " + str(event.unit.hp) + " | MP: " + str(event.unit.mp)) # show city data in BottomBar on CitySelectedEvent if isinstance(event, CitySelectedEvent): city = event.city # get production info text txt_prod_info = "nothing" if city.is_recruiting(): txt_prod_info = str(city.get_unit_in_production().name) + " (" + str(city._recruition().get_duration()) + ")" # make text for heading and detail label txt_city_heading = city.get_size_name() + ": " + city.get_name() txt_city_details = "HP: " + str(city.get_hp()) + " | In Production: " + txt_prod_info # get labels & actionbutton heading = self.get_widget("heading") details = self.get_widget("details") actionbutton = self.get_widget("actionbutton") # change labels heading.set_text(txt_city_heading) details.set_text(txt_city_details) # set actionbutton state BUILD actionbutton.set_button_state("BUILD") # handle Button clicks if isinstance(event, GuiButtonClickedEvent): print(self._tag + "GuiButtonClickedEvent widget_id=" + event.widget_id) # ACTION button if event.widget_id == "actionbutton": # BUILD action inside a city if event.button_state == "BUILD": selected_city = L.CITY_MGR.get_selected_city() # abort if no city is selected if not selected_city: return # add sidebar sidebar = SideBar() root = self.get_widget("root") root.add_widget(sidebar) # show recruitable units on it recruitable_units = L.CITY_MGR.get_recruitable_units(selected_city) sidebar.show_recruitable_units(recruitable_units) # gamestate changes if isinstance(event, GameStateChangedEvent): # menu initialized if event.state == GAMESTATE_MENU: pass # loading... elif event.state == GAMESTATE_LOADING: pass # ingame else: pass
{ "repo_name": "herrschr/prey-game", "path": "pocketthrone/managers/guimanager.py", "copies": "2", "size": "4769", "license": "bsd-2-clause", "hash": -7315537606431949000, "line_mean": 31.4421768707, "line_max": 123, "alpha_frac": 0.7058083456, "autogenerated": false, "ratio": 3.1666666666666665, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9717758398236603, "avg_score": 0.03094332280601266, "num_lines": 147 }
__all__ = ['guinieranalysis'] import os import ipy_table import matplotlib.pyplot as plt import numpy as np from IPython.core.getipython import get_ipython from IPython.display import display from .atsas import autorg, gnom, datgnom, shanum, datporod from .io import getsascurve from .utils import writemarkdown def guinieranalysis(samplenames, qranges=None, qmax_from_shanum=True, prfunctions_postfix='', dist=None, plotguinier=True, graph_extension='.png', dmax=None, dmax_from_shanum=False): """Perform Guinier analysis on the samples. Inputs: samplenames: list of sample names qranges: dictionary of q ranges for each sample. The keys are sample names. The special '__default__' key corresponds to all samples which do not have a key in the dict. qmax_from_shanum: use the qmax determined by the shanum program for the GNOM input. prfunctions_postfix: The figure showing the P(r) functions will be saved as prfunctions_<prfunctions_postfix><graph_extension> dist: the sample-to-detector distance to use. plotguinier: if Guinier plots are needed. graph_extension: the extension of the saved graph image files. dmax: Dict of Dmax parameters. If not found or None, determine automatically using DATGNOM. If found, GNOM is used. The special key '__default__' works in a similar fashion as for `qranges`.""" figpr = plt.figure() ip = get_ipython() axpr = figpr.add_subplot(1, 1, 1) if qranges is None: qranges = {'__default__': (0, 1000000)} if dmax is None: dmax = {'__default__': None} if '__default__' not in qranges: qranges['__default__'] = (0, 1000000) if '__default__' not in dmax: dmax['__default__'] = None table_autorg = [['Name', 'Rg (nm)', 'I$_0$ (cm$^{-1}$ sr$^{-1}$)', 'q$_{min}$ (nm$^{-1}$)', 'q$_{max}$ (nm$^{-1}$)', 'qmin*Rg', 'qmax*Rg', 'quality', 'aggregation', 'Dmax (nm)', 'q$_{shanum}$ (nm$^{-1}$)']] table_gnom = [['Name', 'Rg (nm)', 'I$_0$ (cm$^{-1}$ sr$^{-1}$)', 'qmin (nm$^{-1}$)', 'qmax (nm$^{-1}$)', 'Dmin (nm)', 'Dmax (nm)', 'Total estimate', 'Porod volume (nm$^3$)']] results = {} for sn in samplenames: if sn not in qranges: print('Q-range not given for sample {}: using default one'.format(sn)) qrange = qranges['__default__'] else: qrange = qranges[sn] if sn not in dmax: dmax_ = dmax['__default__'] else: dmax_ = dmax[sn] print('Using q-range for sample {}: {} <= q <= {}'.format(sn, qrange[0], qrange[1])) curve = getsascurve(sn, dist)[0].trim(*qrange).sanitize() curve.save(sn + '.dat') try: Rg, I0, qmin, qmax, quality, aggregation = autorg(sn + '.dat') except ValueError: print('Error running autorg on %s' % sn) continue dmax_shanum, nsh, nopt, qmaxopt = shanum(sn + '.dat') if qmax_from_shanum: curve_trim = curve.trim(qmin, qmaxopt) else: curve_trim = curve.trim(qmin, qrange[1]) if dmax_from_shanum: dmax_ = dmax_from_shanum curve_trim.save(sn + '_optrange.dat') if dmax_ is None: print('Calling DATGNOM for sample {} with Rg={}, q-range from {} to {}'.format( sn, Rg.val, curve_trim.q.min(), curve_trim.q.max())) gnompr, metadata = datgnom(sn + '_optrange.dat', Rg=Rg.val, noprint=True) else: print('Calling GNOM for sample {} with Rmax={}, q-range from {} to {}'.format( sn, dmax_, curve_trim.q.min(), curve_trim.q.max())) gnompr, metadata = gnom(curve_trim, dmax_) rg, i0, vporod = datporod(sn + '_optrange.out') axpr.errorbar(gnompr[:, 0], gnompr[:, 1], gnompr[:, 2], None, label=sn) if plotguinier: figsample = plt.figure() axgnomfit = figsample.add_subplot(1, 2, 1) curve.errorbar('b.', axes=axgnomfit, label='measured') axgnomfit.errorbar(metadata['qj'], metadata['jexp'], metadata['jerror'], None, 'g.', label='gnom input') axgnomfit.loglog(metadata['qj'], metadata['jreg'], 'r-', label='regularized by GNOM') figsample.suptitle(sn) axgnomfit.set_xlabel('q (nm$^{-1}$)') axgnomfit.set_ylabel('$d\Sigma/d\Omega$ (cm$^{-1}$ sr$^{-1}$)') axgnomfit.axvline(qmaxopt, 0, 1, linestyle='dashed', color='black', lw=2) axgnomfit.grid(True, which='both') axgnomfit.axis('tight') axgnomfit.legend(loc='best') axguinier = figsample.add_subplot(1, 2, 2) axguinier.errorbar(curve.q, curve.Intensity, curve.Error, curve.qError, '.', label='Measured') q = np.linspace(qmin, qmax, 100) axguinier.plot(q, I0.val * np.exp(-q ** 2 * Rg.val ** 2 / 3), label='AutoRg') axguinier.plot(q, metadata['I0_gnom'].val * np.exp(-q ** 2 * metadata['Rg_gnom'].val ** 2 / 3), label='Gnom') axguinier.set_xscale('power', exponent=2) axguinier.set_yscale('log') axguinier.set_xlabel('q (nm$^{-1}$)') axguinier.set_ylabel('$d\Sigma/d\Omega$ (cm$^{-1}$ sr$^{-1}$)') axguinier.legend(loc='best') idxmin = np.arange(len(curve))[curve.q <= qmin].max() idxmax = np.arange(len(curve))[curve.q >= qmax].min() idxmin = max(0, idxmin - 5) idxmax = min(len(curve) - 1, idxmax + 5) if plotguinier: curveguinier = curve.trim(curve.q[idxmin], curve.q[idxmax]) axguinier.axis(xmax=curve.q[idxmax], xmin=curve.q[idxmin], ymin=curveguinier.Intensity.min(), ymax=curveguinier.Intensity.max()) axguinier.grid(True, which='both') table_gnom.append( [sn, metadata['Rg_gnom'].tostring(extra_digits=2), metadata['I0_gnom'].tostring(extra_digits=2), metadata['qmin'], metadata['qmax'], metadata['dmin'], metadata['dmax'], metadata['totalestimate_corrected'], vporod]) table_autorg.append([sn, Rg.tostring(extra_digits=2), I0, '%.3f' % qmin, '%.3f' % qmax, qmin * Rg, qmax * Rg, '%.1f %%' % (quality * 100), aggregation, '%.3f' % dmax_shanum, '%.3f' % qmaxopt]) if plotguinier: figsample.tight_layout() figsample.savefig(os.path.join(ip.user_ns['auximages_dir'], 'guinier_%s%s' % (sn, graph_extension)), dpi=600) results[sn] = { 'Rg_autorg' : Rg, 'I0_autorg': I0, 'qmin_autorg': qmin, 'qmax_autorg': qmax, 'quality' : quality, 'aggregation': aggregation, 'dmax_autorg': dmax_shanum, 'qmax_shanum': qmaxopt, 'Rg_gnom' : metadata['Rg_gnom'], 'I0_gnom' : metadata['I0_gnom'], 'qmin_gnom' : metadata['qmin'], 'qmax_gnom' : metadata['qmax'], 'dmin_gnom' : metadata['dmin'], 'dmax_gnom' : metadata['dmax'], 'VPorod' : vporod, } axpr.set_xlabel('r (nm)') axpr.set_ylabel('P(r)') axpr.legend(loc='best') axpr.grid(True, which='both') writemarkdown('## Results from autorg and shanum') tab = ipy_table.IpyTable(table_autorg) tab.apply_theme('basic') display(tab) writemarkdown('## Results from gnom') tab = ipy_table.IpyTable(table_gnom) tab.apply_theme('basic') if prfunctions_postfix and prfunctions_postfix[0] != '_': prfunctions_postfix = '_' + prfunctions_postfix figpr.tight_layout() figpr.savefig(os.path.join(ip.user_ns['auximages_dir'], 'prfunctions%s%s' % (prfunctions_postfix, graph_extension)), dpi=600) display(tab) return results
{ "repo_name": "awacha/credolib", "path": "credolib/interpretation.py", "copies": "1", "size": "8006", "license": "bsd-3-clause", "hash": -3152037280334478000, "line_mean": 48.7267080745, "line_max": 120, "alpha_frac": 0.55770672, "autogenerated": false, "ratio": 3.1669303797468356, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9208838419087271, "avg_score": 0.003159736131913006, "num_lines": 161 }
__all__ = ['HaloAbundanceFunction', 'calc_number_densities', 'calc_number_densities_in_bins'] import numpy as np def _to_float(x, default=np.nan, take_log=False): try: xf = float(x) except (ValueError, TypeError): return default return np.log(xf) if take_log else xf def calc_number_densities(x, box_size): """ Calculate the number densities for a list of values. Number density = rank / volumn. Parameters ---------- x : array_like An 1-d array that contains the values of a halo property (e.g. vpeak, mpeak). box_size : float The length of the cubic cosmological box. Returns ------- nd : array_like Number density for each x. """ N = len(x) inv_vol = 1.0/(box_size**3) nd = np.empty(N, dtype=np.float64) nd[np.argsort(x)] = np.linspace(N*inv_vol, inv_vol, N) return nd def calc_number_densities_in_bins(x, box_size, bins): """ Given a list of values, calculate the number densities of at the positions of `bins`. Number density = rank / volumn. Parameters ---------- x : array_like An 1-d array that contains the values of a halo property (e.g. vpeak, mpeak). box_size : float The length of the cubic cosmological box. bins : array_like The position (in x) to calculate the number densities for. Returns ------- nd : array_like Number density for each value in `bins`. """ return (len(x) - np.searchsorted(x, bins, sorter=np.argsort(x))).astype(float)/(box_size**3) class HaloAbundanceFunction: def __init__(self, x, box_size, fit_range=(None, None), fit_points=10,\ nbin=200, log_bins=True): """ Create (and extrapolate) a halo abundance function from a halo property (e.g. vpeak, mpeak). Parameters ---------- x : array_like or str An 1-d array that contains the values of a halo property (e.g. vpeak, mpeak). box_size : float The length of the cubic cosmological box. fit_range : tuple The range (a, b) to extrapolate the halo abundance function. The extrapolation starts below b and fits down to a. Should be in the same unit as x. If (None, None), do not extrapolate. fit_points : int Number of bins to do the extrapolation mentioned above. nbin : int, optional Number of bins to interpolate the halo abundance function. log_bins : bool, optional Whether to take log of the halo property. Default: True. """ x = np.log(x) if log_bins else np.asarray(x) x = x[np.isfinite(x)] fit_to, fit_below = fit_range fit_to = _to_float(fit_to, x.min(), log_bins) fit_below = _to_float(fit_below, x.min(), log_bins) bins = np.linspace(min(x.min(), fit_to), x.max(), int(nbin)+1) nd = calc_number_densities_in_bins(x, box_size, bins) if fit_to < fit_below: dlog_nd = np.gradient(np.log(nd)) dx = (bins[-1]-bins[0])/int(nbin) k = np.searchsorted(bins, fit_below) s = slice(k, k+fit_points) self._slope = dlog_nd[s].mean()/dx nd[:k] = np.exp((bins[:k]-bins[k])*self._slope) * nd[k] self._log_bins = log_bins self._x = bins self._nd_log = np.log(nd) def __call__(self, x): """ Return the number density at x. Parameters ---------- x : array_like The halo abundance proxy, e.g. vpeak or mpeak. Returns ------- nd : array_like Number densities at x. """ x = np.log(x) if self._log_bins else np.asarray(x) return np.exp(np.interp(x, self._x, self._nd_log, np.nan, np.nan)) def get_number_density_table(self): """ Return the inter/extrapolated number density table. Returns ------- x : array_like The halo abundance proxy. nd : array_like Number densities at x. """ return np.exp(self._x), np.exp(self._nd_log)
{ "repo_name": "manodeep/yymao-abundancematching", "path": "AbundanceMatching/HaloAbundanceFunction.py", "copies": "1", "size": "4246", "license": "mit", "hash": 9039384364462621000, "line_mean": 30.2205882353, "line_max": 96, "alpha_frac": 0.5574658502, "autogenerated": false, "ratio": 3.4860426929392445, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9474600618380216, "avg_score": 0.013781584951805929, "num_lines": 136 }
"""All handlers for CtC projects.""" from google.appengine.api import users from google.appengine.ext import ndb from ctc.helpers import csrf from ctc.helpers import templates from ctc.models import collaborator as collaborator_model from ctc.models import project as project_model from ctc.models import user as user_model class BaseHandler(csrf.CsrfHandler): """Superclass for all CtC handlers.""" def require_login(self): """Redirect to the login page and abort if the user is not logged in.""" if not users.get_current_user(): self.redirect(users.create_login_url(self.request.uri), abort=True) def dispatch(self): """Initializes default values and dispatches the request.""" self.values['login_url'] = users.create_login_url(self.request.uri) self.values['logout_url'] = generate_logout_url() super(BaseHandler, self).dispatch() class MainPage(BaseHandler): """The handler for the root page.""" def get(self): """Renders the main landing page in response to a GET request.""" self.response.write(templates.render('main.html', self.values)) class DisplayDashboard(BaseHandler): """The handler for displaying a which projects the user is working on""" def get(self): """Renders the dashboard corresponding to the logged in user""" self.require_login() user_key = user_model.get_current_user_key() self.values['own'] = project_model.get_by_owner(user_key) self.values['contributing'] = collaborator_model.get_projects(user_key) self.response.write(templates.render('dashboard.html', self.values)) class DisplayUser(BaseHandler): """The handler for displaying a user page.""" def get(self, user_id): """Renders the user page in response to a GET request.""" self.require_login() requesting_user_id = user_model.get_current_user_key().id() self.values['profile'] = user_model.User.get_by_id(user_id) is_profile_owner = (user_id == requesting_user_id) if is_profile_owner: self.values['edit_link'] = self.uri_for(EditUser, user_id=user_id) self.response.write(templates.render('display_user.html', self.values)) class EditUser(BaseHandler): """The handler for editing a user profile.""" def require_owner(self, user_id): """Aborts the current request if the user isn't the profile's owner.""" current_user_id = user_model.get_current_user_key().id() if current_user_id != user_id: self.abort(403) def get(self, user_id): """Renders the edit user page in response to a GET request.""" self.require_login() self.require_owner(user_id) self.values['profile'] = user_model.User.get_by_id(user_id) self.values['action_link'] = self.uri_for(EditUser, user_id=user_id) self.values['action'] = 'Update' self.response.write(templates.render('edit_user.html', self.values)) def post(self, user_id): """Edits the provided project.""" self.require_login() self.require_owner(user_id) profile_object = user_model.User.get_by_id(user_id) profile_object.populate(self.request).put() self.redirect_to(DisplayUser, user_id=user_id) class DisplayProject(BaseHandler): """The handler for displaying a project.""" def _set_action_and_link(self, project_id, is_collaborating, is_logged_in): """Sets action, action_link, and csrf_token in self.values.""" if is_collaborating: self.values['action'] = 'Leave' action_link = self.uri_for(LeaveProject, project_id=project_id) if not is_collaborating and is_logged_in: self.values['action'] = 'Join' action_link = self.uri_for(JoinProject, project_id=project_id) if not is_logged_in: self.values['action'] = 'Login to Join' action_link = users.create_login_url(self.request.uri) self.values['action_link'] = action_link self.values['csrf_token'] = csrf.make_token(action_link) def get(self, project_id): """Renders the project page in response to a GET request.""" project = ndb.Key(project_model.Project, int(project_id)).get() user_key = user_model.get_current_user_key() collaborator_emails = [] # Initialize some truthy objects for the following display logic. is_logged_in = user_key self.values['user_is_logged_out'] = not is_logged_in is_collaborating = collaborator_model.get_collaborator( user_key, project.key) is_project_owner = is_logged_in and project.owner_key == user_key should_show_collaborator_emails = is_collaborating or is_project_owner # Use the above as booleans to guide permissions. if is_project_owner: self.values['edit_link'] = self.uri_for( EditProject, project_id=project_id) if should_show_collaborator_emails: collaborator_emails = collaborator_model.get_collaborator_emails( ndb.Key(project_model.Project, int(project_id))) self._set_action_and_link(project_id, is_collaborating, is_logged_in) num_contributors = collaborator_model.get_collaborator_count( ndb.Key(project_model.Project, int(project_id))) self.values['num_contributors'] = num_contributors self.values['collaborator_emails'] = collaborator_emails self.values['project'] = project self.response.write( templates.render('display_project.html', self.values)) class EditProject(BaseHandler): """The handler for editing a project.""" def require_project_owner(self, project): """Aborts the current request if the user isn't the project's owner.""" current_user_key = user_model.get_current_user_key() if current_user_key != project.owner_key: self.abort(403) def get(self, project_id): """Renders the edit project page in response to a GET request.""" self.require_login() project = ndb.Key(project_model.Project, int(project_id)).get() self.require_project_owner(project) self.values['project'] = project self.values['action_link'] = self.uri_for( EditProject, project_id=project_id) self.values['action'] = 'Edit Your' self.response.write(templates.render('edit_project.html', self.values)) def post(self, project_id): """Edits the provided project.""" self.require_login() project = ndb.Key(project_model.Project, int(project_id)).get() self.require_project_owner(project) project.populate(self.request).put() self.redirect_to(DisplayProject, project_id=project_id) class ListProjects(BaseHandler): """The handler for the projects list.""" def get(self): """Renders the projects page in response to a GET request.""" query = project_model.Project.query() query = query.order(project_model.Project.updated_date) projects = query.fetch() links = [] for curr_project in projects: project_id = curr_project.key.id() links.append(self.uri_for(DisplayProject, project_id=project_id)) self.values['projects_and_links'] = zip(projects, links) self.response.write(templates.render('list_projects.html', self.values)) class NewProject(BaseHandler): """The handler for a new project.""" def get(self): """Renders the new project page in response to a GET request.""" self.require_login() self.values['action'] = 'Create a New' self.values['action_link'] = self.uri_for(NewProject) self.response.write(templates.render('edit_project.html', self.values)) def post(self): """Accepts a request to create a new project.""" self.require_login() current_user_key = user_model.get_current_user_key() new_project = project_model.Project().populate(self.request) new_project.owner_key = current_user_key new_project_key = new_project.put() self.redirect_to(DisplayProject, project_id=new_project_key.id()) class JoinProject(BaseHandler): """Handler for a request to join a project.""" def post(self, project_id): """Accepts a request to join a project.""" self.require_login() current_user_key = user_model.get_current_user_key() collaborator_model.Collaborator.get_or_insert( current_user_key.id(), user_key=current_user_key, parent=ndb.Key(project_model.Project, int(project_id)) ) self.redirect_to(DisplayProject, project_id=project_id) class LeaveProject(BaseHandler): """Handler for a request to leave a project.""" def post(self, project_id): """Accepts a request to leave a project.""" self.require_login() current_user_key = user_model.get_current_user_key() collaborator = collaborator_model.get_collaborator( current_user_key, ndb.Key(project_model.Project, int(project_id))) if collaborator: collaborator.key.delete() self.redirect_to(DisplayProject, project_id=project_id) def generate_logout_url(): """Returns logout url if user is logged in; otherwise returns None.""" return users.create_logout_url('/') if users.get_current_user() else None
{ "repo_name": "samking/code-the-change-projects", "path": "ctc/handlers.py", "copies": "1", "size": "9519", "license": "apache-2.0", "hash": -822188518445125900, "line_mean": 40.2077922078, "line_max": 80, "alpha_frac": 0.6478621704, "autogenerated": false, "ratio": 3.744689221085759, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4892551391485759, "avg_score": null, "num_lines": null }
"""All handy, general utility functionality used throughout the package.""" import os import os.path as osp import sys import fnmatch import shutil def load_module_path(path, name=None, remove_byte_version=False): """Load a python module source file python version aware.""" name = name if name else osp.splitext(osp.basename(path))[0] # remove byte versions if they are older than 3 seconds to avoid # cuncurrency issues if remove_byte_version: for f in [path+'c', path+'o']: try: os.remove(f) except OSError: pass # remove module references try: del sys.modules[name] except KeyError: pass if sys.version_info < (3,): import imp m = imp.load_source(name, path) elif sys.version_info >= (3, 5): import importlib.util as iu spec = iu.spec_from_file_location(name, path) m = iu.module_from_spec(spec) spec.loader.exec_module(m) else: raise ImportError('This python version is not supported: %s' % sys.version_info) return m def get_paths_pattern(pattern, startdir): """ Get all paths (including in subdirectories) matching pattern. Returns list of relative paths from startdir. """ matches = [] for root, dirnames, filenames in os.walk(startdir): fpaths = [os.path.relpath(os.path.join(root, fn), startdir) for fn in filenames] matches += fnmatch.filter(fpaths, pattern) return matches def copy_resources(sourcedir, destinationdir, overwrite=False, ignorepatterns=[], linkpatterns=[], verbose=False): """ Copy/sync resource file tree from sourcedir to destinationdir. overwrite: Overwrite existing files. """ def printverbose(args): if verbose: print(args) return pj = osp.join if not osp.exists(destinationdir): printverbose('mkdir %s' % destinationdir) os.mkdir(destinationdir) walker = os.walk(sourcedir, topdown=True) for path, dirs, files in walker: rpath = osp.relpath(path, sourcedir).replace('.', '') # dirs subsetdirs = [] for d in dirs: rdir = pj(rpath, d) src = pj(path, d) dest = pj(destinationdir, rpath, d) if any(fnmatch.fnmatch(rdir, p) for p in ignorepatterns): printverbose('Ignoring %s' % rdir) # dir to symlink with relative path elif any(fnmatch.fnmatch(rdir, p) for p in linkpatterns): rsrc = osp.relpath(pj(path, d), osp.dirname(dest)) printverbose('Linking %s to %s' % (dest, rsrc)) os.symlink(rsrc, dest) # copy/relink existing symlinks elif osp.islink(src): lnabs = osp.abspath(pj(path, os.readlink(src))) rsrc = osp.relpath(lnabs, osp.dirname(dest)) printverbose('Linking %s to %s' % (dest, rsrc)) os.symlink(rsrc, dest) # create new dir else: if not osp.exists(dest): printverbose('mkdir %s' % dest) os.mkdir(dest) subsetdirs.append(d) # update dirs (change in place will prevent walking into them) dirs[:] = subsetdirs # files for f in files: rfil = osp.join(rpath, f) dest = pj(destinationdir, rpath, f) src = pj(path, f) # ignored files if any(fnmatch.fnmatch(rfil, p) for p in ignorepatterns): printverbose('Ignoring %s' % rfil) continue # file to symlink with relative path elif any(fnmatch.fnmatch(rfil, p) for p in linkpatterns): rsrc = osp.relpath(pj(path, f), osp.dirname(dest)) printverbose('Linking %s to %s' % (dest, rsrc)) os.symlink(rsrc, dest) # copy/relink existing symlinks elif osp.islink(src): lnabs = osp.abspath(pj(path, os.readlink(src))) rsrc = osp.relpath(lnabs, osp.dirname(dest)) printverbose('Linking %s to %s' % (dest, rsrc)) os.symlink(rsrc, dest) # copy file elif not osp.exists(dest) or overwrite: printverbose('cp %s to %s' % (src, dest)) shutil.copy(src, dest) return class propertyplugin(property): """ Class decorator to create a plugin that is instantiated and returned when the project attribute is used to conveniently combine class + constructor. Like all plugins, the propertyplugin __init__ method must only accept one positional argument, i.e. the project. Usage: ------ ``` @propertyplugin class result: def __init__(self, project): pass project = swim.Project() project.result -> result instance ``` """ def __init__(self, cls): def plugin_instatiator(project): # take project from plugin if decorator used inside plugins if hasattr(project, 'project'): project = project.project return cls(project) super(propertyplugin, self).__init__(plugin_instatiator) self.__doc__ = cls.__doc__ self.__name__ = cls.__name__ # so sphinx recognises the property as not imported self.__module__ = getattr(cls, '__module__', None) self.plugin = cls return class GroupPlugin(object): """ An abstract class to group functionality. """ def __init__(self, project): self.project = project return
{ "repo_name": "mwort/modelmanager", "path": "modelmanager/utils.py", "copies": "1", "size": "5762", "license": "bsd-3-clause", "hash": 7205272031292890000, "line_mean": 32.8941176471, "line_max": 78, "alpha_frac": 0.5675112808, "autogenerated": false, "ratio": 4.0865248226950355, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5154036103495035, "avg_score": null, "num_lines": null }
# All harcoded (names, paths etc), refactor it if needed sln_file = ''' Microsoft Visual Studio Solution File, Format Version 12.00 # Visual Studio 2013 VisualStudioVersion = 12.0.31101.0 MinimumVisualStudioVersion = 10.0.40219.1 Project("{8BC9CEB8-8B4A-11D0-8D11-00A0C91BC942}") = "MyProject", "MyProject\MyProject.vcxproj", "{143D99A7-C9F3-434F-BA39-514BB63835E8}" EndProject Global GlobalSection(SolutionConfigurationPlatforms) = preSolution Debug|ARM = Debug|ARM Debug|x64 = Debug|x64 Debug|x86 = Debug|x86 Release|ARM = Release|ARM Release|x64 = Release|x64 Release|x86 = Release|x86 EndGlobalSection GlobalSection(ProjectConfigurationPlatforms) = postSolution {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|ARM.ActiveCfg = Debug|ARM {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|ARM.Build.0 = Debug|ARM {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|x64.ActiveCfg = Debug|x64 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|x64.Build.0 = Debug|x64 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|x86.ActiveCfg = Debug|Win32 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Debug|x86.Build.0 = Debug|Win32 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|ARM.ActiveCfg = Release|ARM {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|ARM.Build.0 = Release|ARM {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|x64.ActiveCfg = Release|x64 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|x64.Build.0 = Release|x64 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|x86.ActiveCfg = Release|Win32 {143D99A7-C9F3-434F-BA39-514BB63835E8}.Release|x86.Build.0 = Release|Win32 EndGlobalSection GlobalSection(SolutionProperties) = preSolution HideSolutionNode = FALSE EndGlobalSection EndGlobal ''' vcxproj_file = '''<?xml version="1.0" encoding="utf-8"?> <Project DefaultTargets="Build" ToolsVersion="14.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup Label="ProjectConfigurations"> <ProjectConfiguration Include="Debug|ARM"> <Configuration>Debug</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|Win32"> <Configuration>Debug</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Debug|x64"> <Configuration>Debug</Configuration> <Platform>x64</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|ARM"> <Configuration>Release</Configuration> <Platform>ARM</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|Win32"> <Configuration>Release</Configuration> <Platform>Win32</Platform> </ProjectConfiguration> <ProjectConfiguration Include="Release|x64"> <Configuration>Release</Configuration> <Platform>x64</Platform> </ProjectConfiguration> </ItemGroup> <PropertyGroup Label="Globals"> <ProjectGuid>{143D99A7-C9F3-434F-BA39-514BB63835E8}</ProjectGuid> <RootNamespace>MyProject</RootNamespace> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.Default.props" /> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>true</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <PropertyGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="Configuration"> <ConfigurationType>Application</ConfigurationType> <UseDebugLibraries>false</UseDebugLibraries> <PlatformToolset>v140</PlatformToolset> <WholeProgramOptimization>true</WholeProgramOptimization> <CharacterSet>MultiByte</CharacterSet> </PropertyGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.props" /> <ImportGroup Label="ExtensionSettings"> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Label="PropertySheets" Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <ImportGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'" Label="PropertySheets"> <Import Project="$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props" Condition="exists('$(UserRootDir)\Microsoft.Cpp.$(Platform).user.props')" Label="LocalAppDataPlatform" /> </ImportGroup> <PropertyGroup Label="UserMacros" /> <PropertyGroup /> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Debug|ARM'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>Disabled</Optimization> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|Win32'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|x64'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemDefinitionGroup Condition="'$(Configuration)|$(Platform)'=='Release|ARM'"> <ClCompile> <WarningLevel>Level3</WarningLevel> <Optimization>MaxSpeed</Optimization> <FunctionLevelLinking>true</FunctionLevelLinking> <IntrinsicFunctions>true</IntrinsicFunctions> <SDLCheck>true</SDLCheck> </ClCompile> <Link> <GenerateDebugInformation>true</GenerateDebugInformation> <EnableCOMDATFolding>true</EnableCOMDATFolding> <OptimizeReferences>true</OptimizeReferences> </Link> </ItemDefinitionGroup> <ItemGroup> <ClCompile Include="main.cpp" /> </ItemGroup> <Import Project="$(VCTargetsPath)\Microsoft.Cpp.targets" /> <ImportGroup Label="ExtensionTargets"> </ImportGroup> </Project>''' filters_file = '''<?xml version="1.0" encoding="utf-8"?> <Project ToolsVersion="4.0" xmlns="http://schemas.microsoft.com/developer/msbuild/2003"> <ItemGroup> <Filter Include="Source Files"> <UniqueIdentifier>{4FC737F1-C7A5-4376-A066-2A32D752A2FF}</UniqueIdentifier> <Extensions>cpp;c;cc;cxx;def;odl;idl;hpj;bat;asm;asmx</Extensions> </Filter> <Filter Include="Header Files"> <UniqueIdentifier>{93995380-89BD-4b04-88EB-625FBE52EBFB}</UniqueIdentifier> <Extensions>h;hh;hpp;hxx;hm;inl;inc;xsd</Extensions> </Filter> <Filter Include="Resource Files"> <UniqueIdentifier>{67DA6AB6-F800-4c08-8B7A-83BB121AAD01}</UniqueIdentifier> <Extensions>rc;ico;cur;bmp;dlg;rc2;rct;bin;rgs;gif;jpg;jpeg;jpe;resx;tiff;tif;png;wav;mfcribbon-ms</Extensions> </Filter> </ItemGroup> <ItemGroup> <ClCompile Include="main.cpp"> <Filter>Source Files</Filter> </ClCompile> </ItemGroup> </Project>''' main_file = '''#include <iostream> int main() { std::cout << "Hello World!" << std::endl; return 0; } ''' def get_vs_project_files(): return {"MyProject.sln": sln_file, "MyProject/MyProject.vcxproj": vcxproj_file, "MyProject/MyProject.vcxproj.filters": filters_file, "MyProject/main.cpp": main_file}
{ "repo_name": "mropert/conan", "path": "conans/test/utils/visual_project_files.py", "copies": "5", "size": "11404", "license": "mit", "hash": 2123945521751548200, "line_mean": 44.0750988142, "line_max": 179, "alpha_frac": 0.7218519818, "autogenerated": false, "ratio": 3.529557412565769, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6751409394365769, "avg_score": null, "num_lines": null }
__all__ = ['HardwareSupportError', 'GLSLError', 'MAX_COLOR_ATTACHMENTS', 'require_extension', 'hardware_info'] from pyglet import gl import pyglet.gl.gl_info as gli import ctypes MAX_COLOR_ATTACHMENTS = gl.GLint() gl.glGetIntegerv(gl.GL_MAX_COLOR_ATTACHMENTS, ctypes.byref(MAX_COLOR_ATTACHMENTS)) MAX_COLOR_ATTACHMENTS = MAX_COLOR_ATTACHMENTS.value class HardwareSupportError(Exception): def __init__(self, message): self.message = "Your graphics hardware does not support %s." % \ message def __str__(self): return self.message class DriverError(Exception): pass class GLSLError(Exception): pass def require_extension(ext): """Ensure that the given graphics extension is supported. """ if not gl.gl_info.have_extension('GL_' + ext): raise HardwareSupportError("the %s extension" % ext) hardware_info = {'vendor': gli.get_vendor(), 'renderer': gli.get_renderer(), 'version': gli.get_version()} # Check hardware support _opengl_version = hardware_info['version'].split(' ')[0] if _opengl_version < "2.0": raise DriverError("This package requires OpenGL v2.0 or higher. " "Your version is %s." % _opengl_version) # This extension is required to return floats outside [0, 1] # in gl_FragColor require_extension('ARB_color_buffer_float') require_extension('ARB_texture_float') gl.glClampColorARB(gl.GL_CLAMP_VERTEX_COLOR_ARB, False) gl.glClampColorARB(gl.GL_CLAMP_FRAGMENT_COLOR_ARB, False) gl.glClampColorARB(gl.GL_CLAMP_READ_COLOR_ARB, False)
{ "repo_name": "certik/scikits.gpu", "path": "scikits/gpu/config.py", "copies": "2", "size": "1617", "license": "mit", "hash": -7016757183093346000, "line_mean": 30.0961538462, "line_max": 72, "alpha_frac": 0.670995671, "autogenerated": false, "ratio": 3.43312101910828, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.510411669010828, "avg_score": null, "num_lines": null }
__all__ = ['HashCol'] import sqlobject.col class DbHash: """ Presents a comparison object for hashes, allowing plain text to be automagically compared with the base content. """ def __init__( self, hash, hashMethod ): self.hash = hash self.hashMethod = hashMethod def __cmp__( self, other ): if other is None: if self.hash is None: return 0 return True if not isinstance( other, basestring ): raise TypeError( "A hash may only be compared with a string, or None." ) return cmp( self.hashMethod( other ), self.hash ) def __repr__( self ): return "<DbHash>" class HashValidator( sqlobject.col.StringValidator ): """ Provides formal SQLObject validation services for the HashCol. """ def to_python( self, value, state ): """ Passes out a hash object. """ if value is None: return None return DbHash( hash = value, hashMethod = self.hashMethod ) def from_python( self, value, state ): """ Store the given value as a MD5 hash, or None if specified. """ if value is None: return None return self.hashMethod( value ) class SOHashCol( sqlobject.col.SOStringCol ): """ The internal HashCol definition. By default, enforces a md5 digest. """ def __init__( self, **kw ): if 'hashMethod' not in kw: from md5 import md5 self.hashMethod = lambda v: md5( v ).hexdigest() if 'length' not in kw: kw['length'] = 32 else: self.hashMethod = kw['hashMethod'] del kw['hashMethod'] super( sqlobject.col.SOStringCol, self ).__init__( **kw ) def createValidators( self ): return [HashValidator( name=self.name, hashMethod=self.hashMethod )] + \ super( SOHashCol, self ).createValidators() class HashCol( sqlobject.col.StringCol ): """ End-user HashCol class. May be instantiated with 'hashMethod', a function which returns the string hash of any other string (i.e. basestring). """ baseClass = SOHashCol
{ "repo_name": "lightcode/SeriesWatcher", "path": "serieswatcher/sqlobject/include/hashcol.py", "copies": "4", "size": "2140", "license": "mit", "hash": -1040658354955363100, "line_mean": 33.5161290323, "line_max": 84, "alpha_frac": 0.6009345794, "autogenerated": false, "ratio": 4.083969465648855, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6684904045048855, "avg_score": null, "num_lines": null }
__all__ = ['HDO6104'] from auspex.log import logger from .instrument import SCPIInstrument, StringCommand, FloatCommand, IntCommand, Command import numpy as np import time class HDO6104(SCPIInstrument): channel_enabled = Command(scpi_string="C{channel}:TRA", additional_args=["channel"],value_map={True:"ON",False:"OFF"}) sample_points = IntCommand(scpi_string="MEMORY_SIZE") trig_mode = StringCommand(scpi_string="TRIG_MODE") time_div = FloatCommand(scpi_string="TIME_DIV") trig_delay = FloatCommand(scpi_string="TRIG_DELAY") vol_div = Command(scpi_string="C{channel}:VOLT_DIV",additional_args=["channel"]) vol_offset = Command(scpi_string="C{channel}:OFFSET",additional_args=["channel"]) def connect(self, resource_name=None, interface_type=None): super(HDO6104,self).connect(resource_name=resource_name,interface_type=interface_type) self.interface.write("COMM_HEADER OFF") self.interface._resource.read_termination = u"\n" def get_info(self,channel=1): raw_info = self.interface.query("C%d:INSPECT? WAVEDESC" %channel).split("\r\n")[1:-1] info = [item.split(':') for item in raw_info] return {k[0].strip(): k[1].strip() for k in info} def fetch_waveform(self,channel): # Send the MSB first self.interface.write("COMM_ORDER HI") self.interface.write("COMM_FORMAT DEF9,WORD,BIN") mydict = self.get_info(channel=channel) points = int(mydict["PNTS_PER_SCREEN"]) xincrement = float(mydict["HORIZ_INTERVAL"]) xorigin = float(mydict["HORIZ_OFFSET"]) yincrement = float(mydict["VERTICAL_GAIN"]) yorigin = float(mydict["VERTICAL_OFFSET"]) # Read waveform data y_axis = np.array(self.interface.query_binary_values('C%d:WAVEFORM? DAT1' % channel, datatype='h', is_big_endian=True)) y_axis = y_axis*yincrement - yorigin x_axis = xorigin + np.arange(0, xincrement*len(y_axis), xincrement) return x_axis, y_axis
{ "repo_name": "BBN-Q/Auspex", "path": "src/auspex/instruments/lecroy.py", "copies": "1", "size": "2020", "license": "apache-2.0", "hash": -374128563342368200, "line_mean": 45.976744186, "line_max": 127, "alpha_frac": 0.6653465347, "autogenerated": false, "ratio": 3.3223684210526314, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9454114198863116, "avg_score": 0.006720151377903214, "num_lines": 43 }
__all__ = ["HeapSnapshotTaker"] from devtools_event_listener import DevToolsEventListener from status import * from base.log import VLOG # Take the heap snapshot. class HeapSnapshotTaker(DevToolsEventListener): def __init__(self, client): self.client = client self.client.AddListener(self) self.snapshot_uid = -1 self.snapshot = "" # return status and snapshot<value> def TakeSnapshot(self): snapshot = None status1 = self._TakeSnapshotInternal() params = {} status2 = self.client.SendCommand("Debugger.disable", params) status3 = Status(kOk) if self.snapshot_uid != -1: # Clear the snapshot cached in xwalk. status3 = self.client.SendCommand("HeapProfiler.clearProfiles", params) status4 = Status(kOk) if status1.IsOk() and status2.IsOk() and status3.IsOk(): try: snapshot = json.loads(self.snapshot) except: status4 = Status(kUnknownError, "heap snapshot not in JSON format") self.snapshot_uid = -1 self.snapshot = "" if status1.IsError(): return (status1, snapshot) elif status2.IsError(): return (status2, snapshot) elif status3.IsError(): return (status3, snapshot) else: return (status4, snapshot) # Overridden from DevToolsEventListener: def OnEvent(self, client, method, params): if method == "HeapProfiler.addProfileHeader": #self.snapshot_uid = params.get("header.uid", None) self.snapshot_uid = params["header"].get("uid", None) if self.snapshot_uid != -1: VLOG(3, "multiple heap snapshot triggered") #TODO: header.uid format elif type(params["header"].get("uid")) != int: return Status(kUnknownError, "HeapProfiler.addProfileHeader has invalid 'header.uid'") elif method == "HeapProfiler.addHeapSnapshotChunk": uid = -1 uid = params.get("uid") if type(uid) != int: return Status(kUnknownError, "HeapProfiler.addHeapSnapshotChunk has no 'uid'") elif uid == self.snapshot_uid: chunk = params.get("chunk") if type(chunk) != str: return Status(kUnknownError, "HeapProfiler.addHeapSnapshotChunk has no 'chunk'") self.snapshot += chunk else: VLOG(3, "expect chunk event uid " + self.snapshot_uid + ", but got " + str(uid)) return Status(kOk) def _TakeSnapshotInternal(self): if self.snapshot_uid != -1: return Status(kUnknownError, "unexpected heap snapshot was triggered") params = {} kMethods = ["Debugger.enable", "HeapProfiler.collectGarbage", "HeapProfiler.takeHeapSnapshot"] for i in kMethods: status = self.client.SendCommand(i, params) if status.IsError(): return status if self.snapshot_uid == -1: return Status(kUnknownError, "failed to receive snapshot uid") uid_params = {} uid_params["uid"] = self.snapshot_uid status = self.client.SendCommand("HeapProfiler.getHeapSnapshot", uid_params) if status.IsError(): return status return Status(kOk)
{ "repo_name": "PeterWangIntel/crosswalk-webdriver-python", "path": "browser/heap_snapshot_taker.py", "copies": "1", "size": "3030", "license": "bsd-3-clause", "hash": 3854860914793223000, "line_mean": 35.0714285714, "line_max": 98, "alpha_frac": 0.6623762376, "autogenerated": false, "ratio": 3.7223587223587224, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9753297904579767, "avg_score": 0.02628741107579106, "num_lines": 84 }
__all__ = ('HeapStorage',) import struct from pyoram.util.virtual_heap import SizedVirtualHeap from pyoram.storage.block_storage import (BlockStorageInterface, BlockStorageTypeFactory) class HeapStorageInterface(object): def __enter__(self): return self def __exit__(self, *args): self.close() # # Abstract Interface # def clone_device(self, *args, **kwds): raise NotImplementedError # pragma: no cover @classmethod def compute_storage_size(cls, *args, **kwds): raise NotImplementedError # pragma: no cover @classmethod def setup(cls, *args, **kwds): raise NotImplementedError # pragma: no cover @property def header_data(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def bucket_count(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def bucket_size(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def blocks_per_bucket(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def storage_name(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def virtual_heap(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def bucket_storage(self, *args, **kwds): raise NotImplementedError # pragma: no cover def update_header_data(self, *args, **kwds): raise NotImplementedError # pragma: no cover def close(self, *args, **kwds): raise NotImplementedError # pragma: no cover def read_path(self, *args, **kwds): raise NotImplementedError # pragma: no cover def write_path(self, *args, **kwds): raise NotImplementedError # pragma: no cover @property def bytes_sent(self): raise NotImplementedError # pragma: no cover @property def bytes_received(self): raise NotImplementedError # pragma: no cover class HeapStorage(HeapStorageInterface): _header_struct_string = "!LLL" _header_offset = struct.calcsize(_header_struct_string) def _new_storage(self, storage, **kwds): storage_type = kwds.pop('storage_type', 'file') def __init__(self, storage, **kwds): if isinstance(storage, BlockStorageInterface): self._storage = storage if len(kwds): raise ValueError( "Keywords not used when initializing " "with a storage device: %s" % (str(kwds))) else: storage_type = kwds.pop('storage_type', 'file') self._storage = BlockStorageTypeFactory(storage_type)\ (storage, **kwds) heap_base, heap_height, blocks_per_bucket = \ struct.unpack( self._header_struct_string, self._storage.header_data[:self._header_offset]) self._vheap = SizedVirtualHeap( heap_base, heap_height, blocks_per_bucket=blocks_per_bucket) # # Define HeapStorageInterface Methods # def clone_device(self): return HeapStorage(self._storage.clone_device()) @classmethod def compute_storage_size(cls, block_size, heap_height, blocks_per_bucket=1, heap_base=2, ignore_header=False, storage_type='file', **kwds): assert (block_size > 0) and (block_size == int(block_size)) assert heap_height >= 0 assert blocks_per_bucket >= 1 assert heap_base >= 2 assert 'block_count' not in kwds vheap = SizedVirtualHeap( heap_base, heap_height, blocks_per_bucket=blocks_per_bucket) if ignore_header: return BlockStorageTypeFactory(storage_type).\ compute_storage_size( vheap.blocks_per_bucket * block_size, vheap.bucket_count(), ignore_header=True, **kwds) else: return cls._header_offset + \ BlockStorageTypeFactory(storage_type).\ compute_storage_size( vheap.blocks_per_bucket * block_size, vheap.bucket_count(), ignore_header=False, **kwds) @classmethod def setup(cls, storage_name, block_size, heap_height, blocks_per_bucket=1, heap_base=2, storage_type='file', **kwds): if 'block_count' in kwds: raise ValueError("'block_count' keyword is not accepted") if heap_height < 0: raise ValueError( "heap height must be 0 or greater. Invalid value: %s" % (heap_height)) if blocks_per_bucket < 1: raise ValueError( "blocks_per_bucket must be 1 or greater. " "Invalid value: %s" % (blocks_per_bucket)) if heap_base < 2: raise ValueError( "heap base must be 2 or greater. Invalid value: %s" % (heap_base)) vheap = SizedVirtualHeap( heap_base, heap_height, blocks_per_bucket=blocks_per_bucket) user_header_data = kwds.pop('header_data', bytes()) if type(user_header_data) is not bytes: raise TypeError( "'header_data' must be of type bytes. " "Invalid type: %s" % (type(user_header_data))) kwds['header_data'] = \ struct.pack(cls._header_struct_string, heap_base, heap_height, blocks_per_bucket) + \ user_header_data return HeapStorage( BlockStorageTypeFactory(storage_type).setup( storage_name, vheap.blocks_per_bucket * block_size, vheap.bucket_count(), **kwds)) @property def header_data(self): return self._storage.header_data[self._header_offset:] @property def bucket_count(self): return self._storage.block_count @property def bucket_size(self): return self._storage.block_size @property def blocks_per_bucket(self): return self._vheap.blocks_per_bucket @property def storage_name(self): return self._storage.storage_name @property def virtual_heap(self): return self._vheap @property def bucket_storage(self): return self._storage def update_header_data(self, new_header_data): self._storage.update_header_data( self._storage.header_data[:self._header_offset] + \ new_header_data) def close(self): self._storage.close() def read_path(self, b, level_start=0): assert 0 <= b < self._vheap.bucket_count() bucket_list = self._vheap.Node(b).bucket_path_from_root() assert 0 <= level_start < len(bucket_list) return self._storage.read_blocks(bucket_list[level_start:]) def write_path(self, b, buckets, level_start=0): assert 0 <= b < self._vheap.bucket_count() bucket_list = self._vheap.Node(b).bucket_path_from_root() assert 0 <= level_start < len(bucket_list) self._storage.write_blocks(bucket_list[level_start:], buckets) @property def bytes_sent(self): return self._storage.bytes_sent @property def bytes_received(self): return self._storage.bytes_received
{ "repo_name": "ghackebeil/PyORAM", "path": "src/pyoram/storage/heap_storage.py", "copies": "1", "size": "8257", "license": "mit", "hash": 692533584230819000, "line_mean": 32.9794238683, "line_max": 73, "alpha_frac": 0.53130677, "autogenerated": false, "ratio": 4.489940184883088, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0032802361512752148, "num_lines": 243 }
__all__ = ['HelloWorldBinaryLabelsClassifier', 'HelloWorldMultiLabelsClassifier'] import numpy as np from sklearn.svm import SVC from ycml.classifiers import BinaryLabelsClassifier, MultiLabelsClassifier, MulticlassLabelsClassifier class HelloWorldBinaryLabelsClassifier(BinaryLabelsClassifier): def fit_binarized(self, X_featurized, Y_binarized, **kwargs): self.classifier_ = SVC(probability=True).fit(X_featurized, Y_binarized[:, 1]) return self #end def def _predict_proba(self, X_featurized, **kwargs): return self.classifier_.predict_proba(X_featurized) #end class class HelloWorldMultiLabelsClassifier(MultiLabelsClassifier): def fit_binarized(self, X_featurized, Y_binarized, **kwargs): self.classifiers_ = {} for j, c in enumerate(self.classes_): self.classifiers_[c] = SVC(probability=True).fit(X_featurized, Y_binarized[:, j]) return self #end def def _predict_proba(self, X_featurized, **kwargs): Y_proba = np.zeros((X_featurized.shape[0], len(self.classes_)), dtype=np.float) for j, c in enumerate(self.classes_): Y_proba[:, j] = self.classifiers_[c].predict_proba(X_featurized, **kwargs)[:, 1] return Y_proba #end def #end class class HelloWorldMulticlassClassifier(MulticlassLabelsClassifier): def fit_binarized(self, X_featurized, Y_binarized, **kwargs): self.classifier_ = SVC(probability=True).fit(X_featurized, Y_binarized) return self #end def def _predict_proba(self, X_featurized, **kwargs): return self.classifier_.predict_proba(X_featurized, **kwargs) # Y_proba = np.zeros((X_featurized.shape[0], len(self.classes_)), dtype=np.float) # for j, c in enumerate(self.classes_): # Y_proba[:, j] = self.classifiers_[c].predict_proba(X_featurized, **kwargs)[:, 1] # return Y_proba #end def #end class
{ "repo_name": "skylander86/ycml", "path": "helloworld/classifiers.py", "copies": "1", "size": "1936", "license": "apache-2.0", "hash": -2603075957997008400, "line_mean": 32.3793103448, "line_max": 102, "alpha_frac": 0.6751033058, "autogenerated": false, "ratio": 3.4144620811287476, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4589565386928747, "avg_score": null, "num_lines": null }
"""All helpers for the URL.""" import urllib2 from mimetypes import MimeTypes from ..base import FORMAT from ..exceptions import URLError def check_url(url): """ Check if URL is accessible and what data format it is. Parameters ---------- url : str URL to check. Returns ------- str Data format of the URL. """ dataformat = None response = None errors = [] try: response = urllib2.urlopen(url) if response.headers.get('Access-Control-Allow-Origin') != '*': errors.append( 'The server does not allow to use this URL externally. Make ' 'sure that CORS is enabled on the server.' ) else: # Try to guess content type first content_type = MimeTypes().guess_type(url)[0] # If unsuccessful, get it from the headers if content_type is None: content_type = response.headers.get('Content-Type') if 'application/json' in content_type: dataformat = FORMAT.GeoJSON elif 'application/vnd.google-earth.kml+xml' in content_type: dataformat = FORMAT.KML else: errors.append('This data format is currently not supported.') except urllib2.URLError as error: if hasattr(error, 'code'): errors.append('The server returned %s error.' % error.code) if hasattr(error, 'reason'): errors.append('Failed to reach the server: %s.' % error.reason) if errors: raise URLError('The URL cannot be used due to:', errors) return dataformat
{ "repo_name": "ExCiteS/geokey-webresources", "path": "geokey_webresources/helpers/url_helpers.py", "copies": "1", "size": "1674", "license": "mit", "hash": 1982329427628254700, "line_mean": 26.9, "line_max": 77, "alpha_frac": 0.5758661888, "autogenerated": false, "ratio": 4.405263157894737, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5481129346694738, "avg_score": null, "num_lines": null }
__all__ = ['Hero'] class Hero(object): '''Represents a hero in the game. Attributes: id (int): the hero's id. name (string): the bot's name. user_id (string): the bot's id (None in training mode). elo (int): the bot's ELO (None in training mode). crashed (bool): True if the bot has been disconnected. mine_count (int): the number of mines this hero owns. gold (int): current amount of gold earned by this hero. life (int): current hero's life. last_dir (string): last bot movement (may be None). x (int): the bot's position in the X axis. y (int): the bot's position in the Y axis. spawn_x (int): the bot's spawn position in X. spawn_y (int): the bot's spawn position in Y. ''' def __init__(self, hero): '''Constructor. Args: hero (dict): the hero data from the server. ''' # Constants self.id = hero['id'] self.name = hero['name'] self.user_id = hero.get('userId') self.elo = hero.get('elo') # Variables self.crashed = hero['crashed'] self.mine_count = hero['mineCount'] self.gold = hero['gold'] self.life = hero['life'] self.last_dir = hero.get('lastDir') self.x = hero['pos']['y'] self.y = hero['pos']['x'] self.spawn_x = hero['spawnPos']['y'] self.spawn_y = hero['spawnPos']['x']
{ "repo_name": "renatopp/vindinium-python", "path": "vindinium/models/hero.py", "copies": "1", "size": "1552", "license": "mit", "hash": -2982725426382311000, "line_mean": 35.0930232558, "line_max": 63, "alpha_frac": 0.5128865979, "autogenerated": false, "ratio": 3.5596330275229358, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4572519625422936, "avg_score": null, "num_lines": null }
__all__ = ["HostInfo"] from panda3d.core import HashVal, Filename, PandaSystem, DocumentSpec, Ramfile from panda3d.core import HTTPChannel, ConfigVariableInt from panda3d import core from direct.p3d.PackageInfo import PackageInfo from direct.p3d.FileSpec import FileSpec from direct.directnotify.DirectNotifyGlobal import directNotify import time class HostInfo: """ This class represents a particular download host serving up Panda3D packages. It is the Python equivalent of the P3DHost class in the core API. """ notify = directNotify.newCategory("HostInfo") def __init__(self, hostUrl, appRunner = None, hostDir = None, rootDir = None, asMirror = False, perPlatform = None): """ You must specify either an appRunner or a hostDir to the HostInfo constructor. If you pass asMirror = True, it means that this HostInfo object is to be used to populate a "mirror" folder, a duplicate (or subset) of the contents hosted by a server. This means when you use this HostInfo to download packages, it will only download the compressed archive file and leave it there. At the moment, mirror folders do not download old patch files from the server. If you pass perPlatform = True, then files are unpacked into a platform-specific directory, which is appropriate when you might be downloading multiple platforms. The default is perPlatform = False, which means all files are unpacked into the host directory directly, without an intervening platform-specific directory name. If asMirror is True, then the default is perPlatform = True. Note that perPlatform is also restricted by the individual package's specification. """ self.__setHostUrl(hostUrl) self.appRunner = appRunner self.rootDir = rootDir if rootDir is None and appRunner: self.rootDir = appRunner.rootDir if hostDir and not isinstance(hostDir, Filename): hostDir = Filename.fromOsSpecific(hostDir) self.hostDir = hostDir self.asMirror = asMirror self.perPlatform = perPlatform if perPlatform is None: self.perPlatform = asMirror # Initially false, this is set true when the contents file is # successfully read. self.hasContentsFile = False # This is the time value at which the current contents file is # no longer valid. self.contentsExpiration = 0 # Contains the md5 hash of the original contents.xml file. self.contentsSpec = FileSpec() # descriptiveName will be filled in later, when the # contents file is read. self.descriptiveName = None # A list of known mirrors for this host, all URL's guaranteed # to end with a slash. self.mirrors = [] # A map of keyword -> altHost URL's. An altHost is different # than a mirror; an altHost is an alternate URL to download a # different (e.g. testing) version of this host's contents. # It is rarely used. self.altHosts = {} # This is a dictionary of packages by (name, version). It # will be filled in when the contents file is read. self.packages = {} if self.appRunner and self.appRunner.verifyContents != self.appRunner.P3DVCForce: # Attempt to pre-read the existing contents.xml; maybe it # will be current enough for our purposes. self.readContentsFile() def __setHostUrl(self, hostUrl): """ Assigns self.hostUrl, and related values. """ self.hostUrl = hostUrl if not self.hostUrl: # A special case: the URL will be set later. self.hostUrlPrefix = None self.downloadUrlPrefix = None else: # hostUrlPrefix is the host URL, but it is guaranteed to end # with a slash. self.hostUrlPrefix = hostUrl if self.hostUrlPrefix[-1] != '/': self.hostUrlPrefix += '/' # downloadUrlPrefix is the URL prefix that should be used for # everything other than the contents.xml file. It might be # the same as hostUrlPrefix, but in the case of an # https-protected hostUrl, it will be the cleartext channel. self.downloadUrlPrefix = self.hostUrlPrefix def freshenFile(self, http, fileSpec, localPathname): """ Ensures that the localPathname is the most current version of the file defined by fileSpec, as offered by host. If not, it downloads a new version on-the-spot. Returns true on success, false on failure. """ if fileSpec.quickVerify(pathname = localPathname): # It's good, keep it. return True # It's stale, get a new one. doc = None if self.appRunner and self.appRunner.superMirrorUrl: # Use the "super mirror" first. url = core.URLSpec(self.appRunner.superMirrorUrl + fileSpec.filename) self.notify.info("Freshening %s" % (url)) doc = http.getDocument(url) if not doc or not doc.isValid(): # Failing the super mirror, contact the actual host. url = core.URLSpec(self.hostUrlPrefix + fileSpec.filename) self.notify.info("Freshening %s" % (url)) doc = http.getDocument(url) if not doc.isValid(): return False file = Filename.temporary('', 'p3d_') if not doc.downloadToFile(file): # Failed to download. file.unlink() return False # Successfully downloaded! localPathname.makeDir() if not file.renameTo(localPathname): # Couldn't move it into place. file.unlink() return False if not fileSpec.fullVerify(pathname = localPathname, notify = self.notify): # No good after download. self.notify.info("%s is still no good after downloading." % (url)) return False return True def downloadContentsFile(self, http, redownload = False, hashVal = None): """ Downloads the contents.xml file for this particular host, synchronously, and then reads it. Returns true on success, false on failure. If hashVal is not None, it should be a HashVal object, which will be filled with the hash from the new contents.xml file.""" if self.hasCurrentContentsFile(): # We've already got one. return True if self.appRunner and self.appRunner.verifyContents == self.appRunner.P3DVCNever: # Not allowed to. return False rf = None if http: if not redownload and self.appRunner and self.appRunner.superMirrorUrl: # We start with the "super mirror", if it's defined. url = self.appRunner.superMirrorUrl + 'contents.xml' request = DocumentSpec(url) self.notify.info("Downloading contents file %s" % (request)) rf = Ramfile() channel = http.makeChannel(False) channel.getDocument(request) if not channel.downloadToRam(rf): self.notify.warning("Unable to download %s" % (url)) rf = None if not rf: # Then go to the main host, if our super mirror let us # down. url = self.hostUrlPrefix + 'contents.xml' # Append a uniquifying query string to the URL to force the # download to go all the way through any caches. We use the # time in seconds; that's unique enough. url += '?' + str(int(time.time())) # We might as well explicitly request the cache to be disabled # too, since we have an interface for that via HTTPChannel. request = DocumentSpec(url) request.setCacheControl(DocumentSpec.CCNoCache) self.notify.info("Downloading contents file %s" % (request)) statusCode = None statusString = '' for attempt in range(int(ConfigVariableInt('contents-xml-dl-attempts', 3))): if attempt > 0: self.notify.info("Retrying (%s)..."%(attempt,)) rf = Ramfile() channel = http.makeChannel(False) channel.getDocument(request) if channel.downloadToRam(rf): self.notify.info("Successfully downloaded %s" % (url,)) break else: rf = None statusCode = channel.getStatusCode() statusString = channel.getStatusString() self.notify.warning("Could not contact download server at %s" % (url,)) self.notify.warning("Status code = %s %s" % (statusCode, statusString)) if not rf: self.notify.warning("Unable to download %s" % (url,)) try: # Something screwed up. if statusCode == HTTPChannel.SCDownloadOpenError or \ statusCode == HTTPChannel.SCDownloadWriteError: launcher.setPandaErrorCode(2) elif statusCode == 404: # 404 not found launcher.setPandaErrorCode(5) elif statusCode < 100: # statusCode < 100 implies the connection attempt itself # failed. This is usually due to firewall software # interfering. Apparently some firewall software might # allow the first connection and disallow subsequent # connections; how strange. launcher.setPandaErrorCode(4) else: # There are other kinds of failures, but these will # generally have been caught already by the first test; so # if we get here there may be some bigger problem. Just # give the generic "big problem" message. launcher.setPandaErrorCode(6) except NameError,e: # no launcher pass except AttributeError, e: self.notify.warning("%s" % (str(e),)) pass return False tempFilename = Filename.temporary('', 'p3d_', '.xml') if rf: f = open(tempFilename.toOsSpecific(), 'wb') f.write(rf.getData()) f.close() if hashVal: hashVal.hashString(rf.getData()) if not self.readContentsFile(tempFilename, freshDownload = True): self.notify.warning("Failure reading %s" % (url)) tempFilename.unlink() return False tempFilename.unlink() return True # Couldn't download the file. Maybe we should look for a # previously-downloaded copy already on disk? return False def redownloadContentsFile(self, http): """ Downloads a new contents.xml file in case it has changed. Returns true if the file has indeed changed, false if it has not. """ assert self.hasContentsFile if self.appRunner and self.appRunner.verifyContents == self.appRunner.P3DVCNever: # Not allowed to. return False url = self.hostUrlPrefix + 'contents.xml' self.notify.info("Redownloading %s" % (url)) # Get the hash of the original file. assert self.hostDir hv1 = HashVal() if self.contentsSpec.hash: hv1.setFromHex(self.contentsSpec.hash) else: filename = Filename(self.hostDir, 'contents.xml') hv1.hashFile(filename) # Now download it again. self.hasContentsFile = False hv2 = HashVal() if not self.downloadContentsFile(http, redownload = True, hashVal = hv2): return False if hv2 == HashVal(): self.notify.info("%s didn't actually redownload." % (url)) return False elif hv1 != hv2: self.notify.info("%s has changed." % (url)) return True else: self.notify.info("%s has not changed." % (url)) return False def hasCurrentContentsFile(self): """ Returns true if a contents.xml file has been successfully read for this host and is still current, false otherwise. """ if not self.appRunner \ or self.appRunner.verifyContents == self.appRunner.P3DVCNone \ or self.appRunner.verifyContents == self.appRunner.P3DVCNever: # If we're not asking to verify contents, then # contents.xml files never expires. return self.hasContentsFile now = int(time.time()) return now < self.contentsExpiration and self.hasContentsFile def readContentsFile(self, tempFilename = None, freshDownload = False): """ Reads the contents.xml file for this particular host, once it has been downloaded into the indicated temporary file. Returns true on success, false if the contents file is not already on disk or is unreadable. If tempFilename is specified, it is the filename read, and it is copied the file into the standard location if it's not there already. If tempFilename is not specified, the standard filename is read if it is known. """ if not hasattr(core, 'TiXmlDocument'): return False if not tempFilename: if self.hostDir: # If the filename is not specified, we can infer it # if we already know our hostDir hostDir = self.hostDir else: # Otherwise, we have to guess the hostDir. hostDir = self.__determineHostDir(None, self.hostUrl) tempFilename = Filename(hostDir, 'contents.xml') doc = core.TiXmlDocument(tempFilename.toOsSpecific()) if not doc.LoadFile(): return False xcontents = doc.FirstChildElement('contents') if not xcontents: return False maxAge = xcontents.Attribute('max_age') if maxAge: try: maxAge = int(maxAge) except: maxAge = None if maxAge is None: # Default max_age if unspecified (see p3d_plugin.h). from direct.p3d.AppRunner import AppRunner maxAge = AppRunner.P3D_CONTENTS_DEFAULT_MAX_AGE # Get the latest possible expiration time, based on the max_age # indication. Any expiration time later than this is in error. now = int(time.time()) self.contentsExpiration = now + maxAge if freshDownload: self.contentsSpec.readHash(tempFilename) # Update the XML with the new download information. xorig = xcontents.FirstChildElement('orig') while xorig: xcontents.RemoveChild(xorig) xorig = xcontents.FirstChildElement('orig') xorig = core.TiXmlElement('orig') self.contentsSpec.storeXml(xorig) xorig.SetAttribute('expiration', str(self.contentsExpiration)) xcontents.InsertEndChild(xorig) else: # Read the download hash and expiration time from the XML. expiration = None xorig = xcontents.FirstChildElement('orig') if xorig: self.contentsSpec.loadXml(xorig) expiration = xorig.Attribute('expiration') if expiration: try: expiration = int(expiration) except: expiration = None if not self.contentsSpec.hash: self.contentsSpec.readHash(tempFilename) if expiration is not None: self.contentsExpiration = min(self.contentsExpiration, expiration) # Look for our own entry in the hosts table. if self.hostUrl: self.__findHostXml(xcontents) else: assert self.hostDir self.__findHostXmlForHostDir(xcontents) if self.rootDir and not self.hostDir: self.hostDir = self.__determineHostDir(None, self.hostUrl) # Get the list of packages available for download and/or import. xpackage = xcontents.FirstChildElement('package') while xpackage: name = xpackage.Attribute('name') platform = xpackage.Attribute('platform') version = xpackage.Attribute('version') try: solo = int(xpackage.Attribute('solo') or '') except ValueError: solo = False try: perPlatform = int(xpackage.Attribute('per_platform') or '') except ValueError: perPlatform = False package = self.__makePackage(name, platform, version, solo, perPlatform) package.descFile = FileSpec() package.descFile.loadXml(xpackage) package.setupFilenames() package.importDescFile = None ximport = xpackage.FirstChildElement('import') if ximport: package.importDescFile = FileSpec() package.importDescFile.loadXml(ximport) xpackage = xpackage.NextSiblingElement('package') self.hasContentsFile = True # Now save the contents.xml file into the standard location. if self.appRunner and self.appRunner.verifyContents != self.appRunner.P3DVCNever: assert self.hostDir filename = Filename(self.hostDir, 'contents.xml') filename.makeDir() if freshDownload: doc.SaveFile(filename.toOsSpecific()) else: if filename != tempFilename: tempFilename.copyTo(filename) return True def __findHostXml(self, xcontents): """ Looks for the <host> or <alt_host> entry in the contents.xml that corresponds to the URL that we actually downloaded from. """ xhost = xcontents.FirstChildElement('host') while xhost: url = xhost.Attribute('url') if url == self.hostUrl: self.readHostXml(xhost) return xalthost = xhost.FirstChildElement('alt_host') while xalthost: url = xalthost.Attribute('url') if url == self.hostUrl: self.readHostXml(xalthost) return xalthost = xalthost.NextSiblingElement('alt_host') xhost = xhost.NextSiblingElement('host') def __findHostXmlForHostDir(self, xcontents): """ Looks for the <host> or <alt_host> entry in the contents.xml that corresponds to the host dir that we read the contents.xml from. This is used when reading a contents.xml file found on disk, as opposed to downloading it from a site. """ xhost = xcontents.FirstChildElement('host') while xhost: url = xhost.Attribute('url') hostDirBasename = xhost.Attribute('host_dir') hostDir = self.__determineHostDir(hostDirBasename, url) if hostDir == self.hostDir: self.__setHostUrl(url) self.readHostXml(xhost) return xalthost = xhost.FirstChildElement('alt_host') while xalthost: url = xalthost.Attribute('url') hostDirBasename = xalthost.Attribute('host_dir') hostDir = self.__determineHostDir(hostDirBasename, url) if hostDir == self.hostDir: self.__setHostUrl(url) self.readHostXml(xalthost) return xalthost = xalthost.NextSiblingElement('alt_host') xhost = xhost.NextSiblingElement('host') def readHostXml(self, xhost): """ Reads a <host> or <alt_host> entry and applies the data to this object. """ descriptiveName = xhost.Attribute('descriptive_name') if descriptiveName and not self.descriptiveName: self.descriptiveName = descriptiveName hostDirBasename = xhost.Attribute('host_dir') if self.rootDir and not self.hostDir: self.hostDir = self.__determineHostDir(hostDirBasename, self.hostUrl) # Get the "download" URL, which is the source from which we # download everything other than the contents.xml file. downloadUrl = xhost.Attribute('download_url') if downloadUrl: self.downloadUrlPrefix = downloadUrl if self.downloadUrlPrefix[-1] != '/': self.downloadUrlPrefix += '/' else: self.downloadUrlPrefix = self.hostUrlPrefix xmirror = xhost.FirstChildElement('mirror') while xmirror: url = xmirror.Attribute('url') if url: if url[-1] != '/': url += '/' if url not in self.mirrors: self.mirrors.append(url) xmirror = xmirror.NextSiblingElement('mirror') xalthost = xhost.FirstChildElement('alt_host') while xalthost: keyword = xalthost.Attribute('keyword') url = xalthost.Attribute('url') if url and keyword: self.altHosts[keyword] = url xalthost = xalthost.NextSiblingElement('alt_host') def __makePackage(self, name, platform, version, solo, perPlatform): """ Creates a new PackageInfo entry for the given name, version, and platform. If there is already a matching PackageInfo, returns it. """ if not platform: platform = None platforms = self.packages.setdefault((name, version or ""), {}) package = platforms.get("", None) if not package: package = PackageInfo(self, name, version, platform = platform, solo = solo, asMirror = self.asMirror, perPlatform = perPlatform) platforms[platform or ""] = package return package def getPackage(self, name, version, platform = None): """ Returns a PackageInfo that matches the indicated name and version and the indicated platform or the current runtime platform, if one is provided by this host, or None if not. """ assert self.hasContentsFile platforms = self.packages.get((name, version or ""), {}) if platform: # In this case, we are looking for a specific platform # only. return platforms.get(platform, None) # We are looking for one matching the current runtime # platform. First, look for a package matching the current # platform exactly. package = platforms.get(PandaSystem.getPlatform(), None) # If not found, look for one matching no particular platform. if not package: package = platforms.get("", None) return package def getPackages(self, name = None, platform = None): """ Returns a list of PackageInfo objects that match the indicated name and/or platform, with no particular regards to version. If name is None, all packages are returned. """ assert self.hasContentsFile packages = [] for (pn, version), platforms in self.packages.items(): if name and pn != name: continue if not platform: for p2 in platforms: package = self.getPackage(pn, version, platform = p2) if package: packages.append(package) else: package = self.getPackage(pn, version, platform = platform) if package: packages.append(package) return packages def getAllPackages(self, includeAllPlatforms = False): """ Returns a list of all available packages provided by this host. """ result = [] items = sorted(self.packages.items()) for key, platforms in items: if self.perPlatform or includeAllPlatforms: # If we maintain a different answer per platform, # return all of them. pitems = sorted(platforms.items()) for pkey, package in pitems: result.append(package) else: # If we maintain a host for the current platform # only (e.g. a client copy), then return only the # current platform, or no particular platform. package = platforms.get(PandaSystem.getPlatform(), None) if not package: package = platforms.get("", None) if package: result.append(package) return result def deletePackages(self, packages): """ Removes all of the indicated packages from the disk, uninstalling them and deleting all of their files. The packages parameter must be a list of one or more PackageInfo objects, for instance as returned by getPackage(). Returns the list of packages that were NOT found. """ packages = packages[:] for key, platforms in self.packages.items(): for platform, package in platforms.items(): if package in packages: self.__deletePackageFiles(package) del platforms[platform] packages.remove(package) if not platforms: # If we've removed all the platforms for a given # package, remove the key from the toplevel map. del self.packages[key] return packages def __deletePackageFiles(self, package): """ Called by deletePackage(), this actually removes the files for the indicated package. """ if self.appRunner: self.notify.info("Deleting package %s: %s" % (package.packageName, package.getPackageDir())) self.appRunner.rmtree(package.getPackageDir()) self.appRunner.sendRequest('forget_package', self.hostUrl, package.packageName, package.packageVersion or '') def __determineHostDir(self, hostDirBasename, hostUrl): """ Hashes the host URL into a (mostly) unique directory string, which will be the root of the host's install tree. Returns the resulting path, as a Filename. This code is duplicated in C++, in P3DHost::determine_host_dir(). """ if hostDirBasename: # If the contents.xml specified a host_dir parameter, use # it. hostDir = str(self.rootDir) + '/hosts' for component in hostDirBasename.split('/'): if component: if component[0] == '.': # Forbid ".foo" or "..". component = 'x' + component hostDir += '/' hostDir += component return Filename(hostDir) hostDir = 'hosts/' # Look for a server name in the URL. Including this string in the # directory name makes it friendlier for people browsing the # directory. # We could use URLSpec, but we do it by hand instead, to make # it more likely that our hash code will exactly match the # similar logic in P3DHost. p = hostUrl.find('://') hostname = '' if p != -1: start = p + 3 end = hostUrl.find('/', start) # Now start .. end is something like "username@host:port". at = hostUrl.find('@', start) if at != -1 and at < end: start = at + 1 colon = hostUrl.find(':', start) if colon != -1 and colon < end: end = colon # Now start .. end is just the hostname. hostname = hostUrl[start : end] # Now build a hash string of the whole URL. We'll use MD5 to # get a pretty good hash, with a minimum chance of collision. # Even if there is a hash collision, though, it's not the end # of the world; it just means that both hosts will dump their # packages into the same directory, and they'll fight over the # toplevel contents.xml file. Assuming they use different # version numbers (which should be safe since they have the # same hostname), there will be minimal redownloading. hashSize = 16 keepHash = hashSize if hostname: hostDir += hostname + '_' # If we successfully got a hostname, we don't really need the # full hash. We'll keep half of it. keepHash = keepHash // 2 md = HashVal() md.hashString(hostUrl) hostDir += md.asHex()[:keepHash * 2] hostDir = Filename(self.rootDir, hostDir) return hostDir
{ "repo_name": "mgracer48/panda3d", "path": "direct/src/p3d/HostInfo.py", "copies": "1", "size": "30006", "license": "bsd-3-clause", "hash": -8872493868360692000, "line_mean": 38.9547270306, "line_max": 121, "alpha_frac": 0.5731187096, "autogenerated": false, "ratio": 4.665837350334318, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.001597048349385028, "num_lines": 751 }
__all__ = ['hough'] from itertools import izip import numpy as np def _hough(img, theta=None): if img.ndim != 2: raise ValueError('The input image must be 2-D') if theta is None: theta = np.linspace(-np.pi / 2, np.pi / 2, 180) # compute the vertical bins (the distances) d = np.ceil(np.hypot(*img.shape)) nr_bins = 2 * d bins = np.linspace(-d, d, nr_bins) # allocate the output image out = np.zeros((nr_bins, len(theta)), dtype=np.uint64) # precompute the sin and cos of the angles cos_theta = np.cos(theta) sin_theta = np.sin(theta) # find the indices of the non-zero values in # the input image y, x = np.nonzero(img) # x and y can be large, so we can't just broadcast to 2D # arrays as we may run out of memory. Instead we process # one vertical slice at a time. for i, (cT, sT) in enumerate(izip(cos_theta, sin_theta)): # compute the base distances distances = x * cT + y * sT # round the distances to the nearest integer # and shift them to a nonzero bin shifted = np.round(distances) - bins[0] # cast the shifted values to ints to use as indices indices = shifted.astype(np.int) # use bin count to accumulate the coefficients bincount = np.bincount(indices) # finally assign the proper values to the out array out[:len(bincount), i] = bincount return out, theta, bins _py_hough = _hough # try to import and use the faster Cython version if it exists try: from ._hough_transform import _hough except ImportError: pass def hough(img, theta=None): """Perform a straight line Hough transform. Parameters ---------- img : (M, N) ndarray Input image with nonzero values representing edges. theta : 1D ndarray of double Angles at which to compute the transform, in radians. Defaults to -pi/2 - pi/2 Returns ------- H : 2-D ndarray of uint64 Hough transform accumulator. distances : ndarray Distance values. theta : ndarray Angles at which the transform was computed. Examples -------- Generate a test image: >>> img = np.zeros((100, 150), dtype=bool) >>> img[30, :] = 1 >>> img[:, 65] = 1 >>> img[35:45, 35:50] = 1 >>> for i in range(90): >>> img[i, i] = 1 >>> img += np.random.random(img.shape) > 0.95 Apply the Hough transform: >>> out, angles, d = hough(img) Plot the results: >>> import matplotlib.pyplot as plt >>> plt.imshow(out, cmap=plt.cm.bone) >>> plt.xlabel('Angle (degree)') >>> plt.ylabel('Distance %d (pixel)' % d[0]) >>> plt.show() .. plot:: hough_tf.py """ return _hough(img, theta)
{ "repo_name": "GaelVaroquaux/scikits.image", "path": "scikits/image/transform/hough_transform.py", "copies": "1", "size": "2790", "license": "bsd-3-clause", "hash": -4555680245915931000, "line_mean": 24.8333333333, "line_max": 62, "alpha_frac": 0.5967741935, "autogenerated": false, "ratio": 3.6139896373056994, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9706730759621993, "avg_score": 0.0008066142367412785, "num_lines": 108 }
__all__ = ['hough', 'probabilistic_hough'] from itertools import izip as zip import numpy as np from ._hough_transform import _probabilistic_hough def _hough(img, theta=None): if img.ndim != 2: raise ValueError('The input image must be 2-D') if theta is None: theta = np.linspace(-np.pi / 2, np.pi / 2, 180) # compute the vertical bins (the distances) d = np.ceil(np.hypot(*img.shape)) nr_bins = 2 * d bins = np.linspace(-d, d, nr_bins) # allocate the output image out = np.zeros((nr_bins, len(theta)), dtype=np.uint64) # precompute the sin and cos of the angles cos_theta = np.cos(theta) sin_theta = np.sin(theta) # find the indices of the non-zero values in # the input image y, x = np.nonzero(img) # x and y can be large, so we can't just broadcast to 2D # arrays as we may run out of memory. Instead we process # one vertical slice at a time. for i, (cT, sT) in enumerate(zip(cos_theta, sin_theta)): # compute the base distances distances = x * cT + y * sT # round the distances to the nearest integer # and shift them to a nonzero bin shifted = np.round(distances) - bins[0] # cast the shifted values to ints to use as indices indices = shifted.astype(np.int) # use bin count to accumulate the coefficients bincount = np.bincount(indices) # finally assign the proper values to the out array out[:len(bincount), i] = bincount return out, theta, bins _py_hough = _hough # try to import and use the faster Cython version if it exists try: from ._hough_transform import _hough except ImportError: pass def probabilistic_hough(img, threshold=10, line_length=50, line_gap=10, theta=None): """Performs a progressive probabilistic line Hough transform and returns the detected lines. Parameters ---------- img : (M, N) ndarray Input image with nonzero values representing edges. threshold : int Threshold line_length : int, optional (default 50) Minimum accepted length of detected lines. Increase the parameter to extract longer lines. line_gap : int, optional, (default 10) Maximum gap between pixels to still form a line. Increase the parameter to merge broken lines more aggresively. theta : 1D ndarray, dtype=double, optional, default (-pi/2 .. pi/2) Angles at which to compute the transform, in radians. Returns ------- lines : list List of lines identified, lines in format ((x0, y0), (x1, y0)), indicating line start and end. References ---------- .. [1] C. Galamhos, J. Matas and J. Kittler,"Progressive probabilistic Hough transform for line detection", in IEEE Computer Society Conference on Computer Vision and Pattern Recognition, 1999. """ return _probabilistic_hough(img, threshold, line_length, line_gap, theta) def hough(img, theta=None): """Perform a straight line Hough transform. Parameters ---------- img : (M, N) ndarray Input image with nonzero values representing edges. theta : 1D ndarray of double Angles at which to compute the transform, in radians. Defaults to -pi/2 .. pi/2 Returns ------- H : 2-D ndarray of uint64 Hough transform accumulator. distances : ndarray Distance values. theta : ndarray Angles at which the transform was computed. Examples -------- Generate a test image: >>> img = np.zeros((100, 150), dtype=bool) >>> img[30, :] = 1 >>> img[:, 65] = 1 >>> img[35:45, 35:50] = 1 >>> for i in range(90): >>> img[i, i] = 1 >>> img += np.random.random(img.shape) > 0.95 Apply the Hough transform: >>> out, angles, d = hough(img) Plot the results: >>> import matplotlib.pyplot as plt >>> plt.imshow(out, cmap=plt.cm.bone) >>> plt.xlabel('Angle (degree)') >>> plt.ylabel('Distance %d (pixel)' % d[0]) >>> plt.show() .. plot:: hough_tf.py """ return _hough(img, theta)
{ "repo_name": "emmanuelle/scikits.image", "path": "skimage/transform/hough_transform.py", "copies": "2", "size": "4158", "license": "bsd-3-clause", "hash": -827837782941171600, "line_mean": 27.875, "line_max": 96, "alpha_frac": 0.6195286195, "autogenerated": false, "ratio": 3.7125, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0007728788674644885, "num_lines": 144 }
__all__ = ('HoverBehavior', ) from kivy.properties import BooleanProperty, NumericProperty, ObjectProperty from kivy.weakproxy import WeakProxy from kivy.core.window import Window class HoverBehavior(object): ''' The HoverBehavior `mixin <https://en.wikipedia.org/wiki/Mixin>`_ provides Hover behavior. When combined with a widget, hovering mouse cursor above it's position will call it's on_hovering event. ''' _hover_grab_widget = None '''WeakProxy of widget which has grabbed focus or None''' _hover_widgets = [] '''List of hover widget WeakProxy references''' min_hover_height = 0 '''Numeric class attribute of minimum height where "hovering" property will be updated''' hovering = BooleanProperty(False) '''Hover state, is True when mouse enters it's position :attr:`hovering` is a :class:`~kivy.properties.BooleanProperty` and defaults to `False`. ''' hover_height = NumericProperty(0) '''Number that is compared to min_hover_height. :attr:`hover_height` is a :class:`~kivy.properties.NumericProperty` and defaults to `0`. ''' def _on_hover_mouse_move(win, pos): '''Internal method that is binded on Window.mouse_pos. Compares mouse position with widget positions, ignoring disabled widgets and widgets with hover_height below HoverBehavior.min_hover_height, then sets widget hovering property to False or True''' collided = [] # widget weak proxies that collide with mouse pos if HoverBehavior._hover_grab_widget: HoverBehavior.hover_widget_refs = [HoverBehavior._hover_grab_widget] else: HoverBehavior.hover_widget_refs = HoverBehavior._hover_widgets for ref in HoverBehavior.hover_widget_refs: if not ref.disabled and ref._collide_point_window(*pos): # Get all widgets that are at mouse pos collided.append(ref) # Remove hover from all widgets that are not at mouse pos elif ref.hovering: ref.hovering = False if collided: # Find the highest widget and set it's hover to True # Set hover to False for other widgets highest = collided[0] if len(collided) > 1: for ref in collided: if ref.hover_height > highest.hover_height: if highest.hovering: highest.hovering = False highest = ref elif ref.hovering: ref.hovering = False if HoverBehavior._hover_grab_widget: if not highest.hovering: highest.hovering = True elif highest.hover_height >= HoverBehavior.min_hover_height: if not highest.hovering: highest.hovering = True @staticmethod def force_update_hover(): '''Gets window mouse position and updates hover state for all widgets''' HoverBehavior._on_hover_mouse_move(Window, Window.mouse_pos) @staticmethod def set_min_hover_height(number): '''Sets min_hover_height for HoverBehavior class''' HoverBehavior.min_hover_height = number @staticmethod def get_min_hover_height(): '''Gets min_hover_height from HoverBehavior class''' return HoverBehavior.min_hover_height def __init__(self, **kwargs): super(HoverBehavior, self).__init__(**kwargs) self.bind(parent=self._on_parent_update_hover) def _on_parent_update_hover(self, _, parent): '''Adds self to hover system when has a parent, otherwise removes self from hover system''' if parent: self.hoverable_add() else: self.hoverable_remove() def hoverable_add(self): '''Add widget in hover system. By default, is called when widget is added to a parent''' HoverBehavior._hover_widgets.append(WeakProxy(self)) def hoverable_remove(self): '''Remove widget from hover system. By default is called when widget is removed from a parent''' HoverBehavior._hover_widgets.remove(self) def grab_hover(self): '''Prevents other widgets from receiving hover''' HoverBehavior._hover_grab_widget = WeakProxy(self) @staticmethod def get_hover_grab_widget(): '''Returns widget which has grabbed hover currently or None''' return HoverBehavior._hover_grab_widget @staticmethod def remove_hover_grab(): '''Removes widget WeakProxy from hover system''' HoverBehavior._hover_grab_widget = None def _collide_point_window(self, x, y): '''Widget collide point method that compares arguments to "self.to_window(self.x, self.y)" instead of "self.x, self.y"''' sx, sy = self.to_window(self.x, self.y) return sx <= x <= sx + self.width and sy <= y <= sy + self.height Window.bind(mouse_pos=HoverBehavior._on_hover_mouse_move)
{ "repo_name": "Bakterija/mmplayer", "path": "mmplayer/kivy_soil/hover_behavior/__init__.py", "copies": "1", "size": "5148", "license": "mit", "hash": -8676318573573915000, "line_mean": 36.035971223, "line_max": 80, "alpha_frac": 0.6182983683, "autogenerated": false, "ratio": 4.237037037037037, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00027755573319122477, "num_lines": 139 }
__all__ = ['HPX_grid_step', 'HPX_grid_size', 'FITS_to_HPPX'] import numpy as np from scipy import sparse # Kapteyn software contains tie-ins to WCS standard. try: from kapteyn import wcs except ImportError: print ("kapteyn package required: download at\n" "http://www.astro.rug.nl/software/kapteyn/") raise from .grid_interpolation import GridInterpolation from .util import regrid def HPX_grid_size(Nside): """Return the size of the pixel grid (Nx, Ny) for a given Nside""" Nx = 8 * Nside Ny = 4 * Nside + 1 return Nx, Ny def HPX_grid_step(Nside): """Return the size of the step between pixels in degrees""" return 45. / Nside def FITS_to_HPX(header, data, Nside, return_sparse=False): """Convert data from FITS format to sparse HPX grid Parameters ---------- header : dict or PyFITS header WCS header describing the coordinates of the input array data : array_like Input data array Nside : int HEALPix gridding parameter Returns ------- hpx_data : csr matrix The HPX-projected data """ # Here's what we do for this function: we're working in "IMG coords" # (i.e. the projection of the input data) and "HPX coords" (i.e. the # projection of the output data). In between, we use "WCS coords". # # These are the steps involved: # 1. Create an array of image edge-pixels in IMG coords, and project # these to HPX coords. # 2. From these bounds, create a regular grid of HPX coords that covers # the image. Project this grid to IMG coords. # 3. In IMG coords, interpolate the image data to the healpix grid. # 4. Use this data to construct a sparse array in HPX coords. if header['NAXIS'] != 2: raise ValueError("input data & header must be two dimensional") if data.shape != (header['NAXIS2'], header['NAXIS1']): raise ValueError("data shape must match header metadata") # Create wcs projection instance from the header proj_img = wcs.Projection(header) # Create wcs projection for healpix grid # Note that the "pixel" coordinates here are measured in degrees... # 0 to 360 in x/RA and -90 to 90 in y/DEC proj_hpx = wcs.Projection({'NAXIS': 2, 'CTYPE1': 'RA---HPX', 'CTYPE2': 'DEC--HPX'}) # Define the dimension of the HEALPIX SciDB grid Nx_hpx, Ny_hpx = HPX_grid_size(Nside) dx_hpx = dy_hpx = HPX_grid_step(Nside) #x_hpx = np.linspace(0, 360, Nx_hpx, endpoint=False) #y_hpx = np.linspace(-90, 90, Ny_hpx) # Find the coordinates of the pixels at the edge of the image # Projecting these onto the healpix grid will give the bounds we need. img_bounds_x = np.arange(header['NAXIS2']) zeros_x = np.zeros_like(img_bounds_x) img_bounds_y = np.arange(header['NAXIS1']) zeros_y = np.zeros_like(img_bounds_y) img_bounds_pix = np.concatenate( [img_bounds_x, img_bounds_x, zeros_y, zeros_y + img_bounds_x[-1], zeros_x, zeros_x + img_bounds_y[-1], img_bounds_y, img_bounds_y] ).reshape((2, -1)).T x_bound_hpx, y_bound_hpx =\ proj_hpx.topixel(proj_img.toworld(img_bounds_pix)).T # here we take the pixels at the edge of the boundaries of the image, # transform them to HPX coordinates, and find the required extent # of the HPX pixel grid. # [TODO: check for crossing the pole] # first we need to calculate pixel number i_bound_hpx = x_bound_hpx / dx_hpx j_bound_hpx = (y_bound_hpx + 90.) / dy_hpx i_hpx = np.arange(int(np.floor(i_bound_hpx.min())), int(np.ceil(i_bound_hpx.max()) + 1)) j_hpx = np.arange(int(np.floor(j_bound_hpx.min())), int(np.ceil(j_bound_hpx.max()) + 1)) x_hpx = i_hpx * dx_hpx y_hpx = j_hpx * dy_hpx - 90. # Create the grid of HPX pixels pixel_ind_hpx = np.vstack(map(np.ravel, np.meshgrid(i_hpx, j_hpx))).T pixel_locs_hpx = np.vstack(map(np.ravel, np.meshgrid(x_hpx, y_hpx))).T pixel_locs_img = proj_img.topixel(proj_hpx.toworld(pixel_locs_hpx)) ## DEBUG: Plot the borders & grid in the HPX projection #import matplotlib.pyplot as plt #plt.plot(i_bound_hpx, j_bound_hpx, '.k') #plt.plot(pixel_ind_hpx[:, 0], pixel_ind_hpx[:, 1], '.r') #plt.show() #exit() ## DEBUG: Plot the HPX grid in the IMG projection #import matplotlib.pyplot as plt #plt.plot(img_bounds_pix[:, 0], img_bounds_pix[:, 1], '.k') #plt.plot(pixel_locs_img[:, 0], pixel_locs_img[:, 1], '.r') #plt.show() #exit() # Interpolate from data to pixel locations I = GridInterpolation(data, [0, 0], [1, 1]) HPX_vals = I(pixel_locs_img)#.reshape(len(y_hpx), len(x_hpx)) # # DEBUG: Plot regridded input data next to the interpolated HPX data # import matplotlib.pyplot as plt # plt.figure(figsize=(8, 8)) # plt.subplot(211, aspect='equal') # plt.contourf(x_hpx, y_hpx, HPX_vals) # plt.subplot(212, aspect='equal') # plt.contourf(regrid(data, 5)) # plt.show() # exit() good_vals = ~np.isnan(HPX_vals) x, y = pixel_ind_hpx[good_vals].T HPX_vals = HPX_vals[good_vals] if return_sparse: return sparse.coo_matrix((HPX_vals, (x, y)), shape=(Nx_hpx, Ny_hpx)) else: output = np.zeros(len(HPX_vals), dtype=[('time', np.int64), ('x', np.int64), ('y', np.int64), ('val', np.float64)]) # use MJD in seconds output['time'] = int(header['TAI'] * 24 * 60 * 60) output['x'] = x output['y'] = y output['val'] = HPX_vals return output
{ "repo_name": "jakevdp/spheredb", "path": "spheredb/conversions.py", "copies": "1", "size": "5861", "license": "bsd-3-clause", "hash": 7092915956995665000, "line_mean": 34.737804878, "line_max": 76, "alpha_frac": 0.5942671899, "autogenerated": false, "ratio": 3.1732539252842447, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9219126122312413, "avg_score": 0.00967899857436641, "num_lines": 164 }
__all__ = ['HTTPView', 'TCPView'] from again.utils import unique_hex from .utils.helpers import default_preflight_response from .utils.ordered_class_member import OrderedClassMembers class BaseView: '''base class for views''' _host = None @property def host(self): return self._host @host.setter def host(self, host): self._host = host class BaseHTTPView(BaseView, metaclass=OrderedClassMembers): '''base class for HTTP views''' middlewares = [] def __init__(self): super(BaseHTTPView, self).__init__() class HTTPView(BaseHTTPView): def __init__(self, allow_cross_domain=True, preflight_response=default_preflight_response): super(HTTPView, self).__init__() self._allow_cross_domain = allow_cross_domain self._preflight_response = preflight_response @property def cross_domain_allowed(self): return self._allow_cross_domain @property def preflight_response(self): return self._preflight_response class BaseTCPView(BaseView): '''base class for TCP views''' def __init__(self): super(BaseTCPView, self).__init__() class TCPView(BaseTCPView): def __init__(self): super(TCPView, self).__init__() @staticmethod def _make_response_packet(request_id: str, from_id: str, entity: str, result: object, error: object, failed: bool, old_api=None, replacement_api=None): from .services import _Service if failed: payload = {'request_id': request_id, 'error': error, 'failed': failed} else: payload = {'request_id': request_id, 'result': result} if old_api: payload['old_api'] = old_api if replacement_api: payload['replacement_api'] = replacement_api packet = {'pid': unique_hex(), 'to': from_id, 'entity': entity, 'type': _Service._RES_PKT_STR, 'payload': payload} return packet
{ "repo_name": "technomaniac/trellio", "path": "trellio/views.py", "copies": "2", "size": "2073", "license": "mit", "hash": -8676553279200657000, "line_mean": 27.0135135135, "line_max": 104, "alpha_frac": 0.5904486252, "autogenerated": false, "ratio": 4.017441860465116, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00045834704469242625, "num_lines": 74 }
__all__ = ['HttpWhoHas'] from gevent import monkey; monkey.patch_all() # flake8: noqa import gevent from gevent.queue import Queue from random import sample import urllib2 import logging class DefaultErrorHandler(urllib2.HTTPDefaultErrorHandler): def http_error_default(self, req, fp, code, msg, headers): result = urllib2.HTTPError(req.get_full_url(), code, msg, headers, fp) result.status = code return result class HttpWhoHas(object): """Finds the HTTP server that store a specific file from a list of HTTP servers. This object allow to defines clusters of nodes, each nodes of the cluster should have the same data. The resole process will try to find a node in a cluster storing a specific file and will return the full url to the filename. """ def __init__(self, per_cluster=3, user_agent='HttpWhoHas.py', proxy=None, timeout=5): """Initializes the resolver. Args: per_cluster (int): number of node to query from the same cluster. user_agent (str): the user agent that will be used for queries. proxy (str): a proxy server with IP/HOST:PORT format (eg: '127.0.0.1:8888'). timeout (int): timeout of the queries. """ self.clusters = {} self.per_cluster = per_cluster self.user_agent = user_agent self.timeout = timeout if proxy: urllib2.install_opener( urllib2.build_opener(urllib2.ProxyHandler({'http': proxy}))) urllib2.install_opener(urllib2.build_opener(DefaultErrorHandler())) self.logger = logging.getLogger('katana.httpwhohas') def set_cluster(self, name, ips, headers=None): """Adds a new cluster in the resolver. Args: name (str): the name of the cluster. ips (list): a list of ips of nodes in this cluster. headers (dict): a dict of headers that will be passed to every queries. Returns: None """ self.clusters[name] = { 'ips': ips, 'headers': headers if headers else {}, 'per_cluster': min(self.per_cluster, len(ips)), } def _do_req(self, name, req, res): full_url = req.get_full_url() try: resp = urllib2.urlopen(req, timeout=self.timeout) status_code = resp.code if status_code in (200, 304) and not hasattr(req, 'redirect_dict'): host = req.get_header('Host') modified = status_code == 200 self.logger.debug( 'found url=%s filer=%s host=%s modified=%s', full_url, name, host, modified) res.put({ 'filer': name, 'url': full_url, 'host': host, 'modified': modified, 'headers': dict(resp.headers), }) else: self.logger.debug( '%s url=%s returned code %d', name, full_url, status_code) except (urllib2.HTTPError, urllib2.URLError) as exc: self.logger.debug('%s url=%s error: %s', name, full_url, exc) except Exception as exc: self.logger.exception('%s url=%s got an exception', name, full_url) def _do_reqs(self, reqs, res): jobs = [gevent.spawn(self._do_req, name, req, res) for name, req in reqs] gevent.joinall(jobs, timeout=self.timeout) res.put(None) gevent.killall(jobs) def resolve(self, filename, etag=None, last_modified=None): """Resolves a filename on the clusters. Args: filename (str): the filename that we are looking for on the clusters. etag (str): the etag to user for the query if any. last_modified (str): the date in the same format as returned by Last-Modified. Returns: A dict if the filename was found otherwise None. The dict has the following keys: * filer (str): the name of the cluster. * url (str): the full url of the filename. * host (str): the value of the Host header. * modified (bool): True if the file has been modified since the previous request. * headers (dict): the HTTP response headers. """ self.logger.debug('resolving %s', filename) res = Queue() reqs = [] for name, info in self.clusters.items(): headers = {'User-Agent': self.user_agent} headers.update(info['headers']) if etag: headers['If-None-Match'] = etag elif last_modified: headers['If-Modified-Since'] = last_modified for ip in sample(info['ips'], info['per_cluster']): self.logger.debug( 'looking for %s on %s with headers %s', filename, ip, headers) req = urllib2.Request( 'http://%s%s' % (ip, filename), headers=headers) req.get_method = lambda: 'HEAD' reqs.append((name, req)) gevent.spawn(self._do_reqs, reqs, res) result = res.get() if result: self.logger.debug('found %s on %s: url=%s host=%s', filename, result['filer'], result['url'], result['host']) else: self.logger.debug('%s not found', filename) return result
{ "repo_name": "ktosiu/katana", "path": "katana/httpwhohas.py", "copies": "1", "size": "5522", "license": "mpl-2.0", "hash": -1780310059016073200, "line_mean": 36.8219178082, "line_max": 96, "alpha_frac": 0.5579500181, "autogenerated": false, "ratio": 4.186504927975739, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0010777129214134167, "num_lines": 146 }
__all__ = ['HttpWhoHas'] from gevent import monkey; monkey.patch_all() # flake8: noqa import gevent from gevent.queue import Queue from random import sample import urllib.request, urllib.error, urllib.parse import logging class DefaultErrorHandler(urllib.request.HTTPDefaultErrorHandler): def http_error_default(self, req, fp, code, msg, headers): result = urllib.error.HTTPError(req.get_full_url(), code, msg, headers, fp) result.status = code return result class HttpWhoHas(object): """Finds the HTTP server that store a specific file from a list of HTTP servers. This object allow to defines clusters of nodes, each nodes of the cluster should have the same data. The resole process will try to find a node in a cluster storing a specific file and will return the full url to the filename. """ def __init__(self, per_cluster=3, user_agent='HttpWhoHas.py', proxy=None, timeout=5): """Initializes the resolver. Args: per_cluster (int): number of node to query from the same cluster. user_agent (str): the user agent that will be used for queries. proxy (str): a proxy server with IP/HOST:PORT format (eg: '127.0.0.1:8888'). timeout (int): timeout of the queries. """ self.clusters = {} self.per_cluster = per_cluster self.user_agent = user_agent self.timeout = timeout if proxy: urllib.request.install_opener( urllib.request.build_opener(urllib.request.ProxyHandler({'http': proxy}))) urllib.request.install_opener(urllib.request.build_opener(DefaultErrorHandler())) self.logger = logging.getLogger('katana.httpwhohas') def set_cluster(self, name, ips, headers=None): """Adds a new cluster in the resolver. Args: name (str): the name of the cluster. ips (list): a list of ips of nodes in this cluster. headers (dict): a dict of headers that will be passed to every queries. Returns: None """ self.clusters[name] = { 'ips': ips, 'headers': headers if headers else {}, 'per_cluster': min(self.per_cluster, len(ips)), } def _do_req(self, name, req, res): full_url = req.get_full_url() try: resp = urllib.request.urlopen(req, timeout=self.timeout) status_code = resp.code if status_code in (200, 304) and not hasattr(req, 'redirect_dict'): host = req.get_header('Host') modified = status_code == 200 self.logger.debug( 'found url=%s filer=%s host=%s modified=%s', full_url, name, host, modified) res.put({ 'filer': name, 'url': full_url, 'host': host, 'modified': modified, 'headers': dict(resp.headers), }) else: self.logger.debug( '%s url=%s returned code %d', name, full_url, status_code) except (urllib.error.HTTPError, urllib.error.URLError) as exc: self.logger.debug('%s url=%s error: %s', name, full_url, exc) except Exception as exc: self.logger.exception('%s url=%s got an exception', name, full_url) def _do_reqs(self, reqs, res): jobs = [gevent.spawn(self._do_req, name, req, res) for name, req in reqs] gevent.joinall(jobs, timeout=self.timeout) res.put(None) gevent.killall(jobs) def resolve(self, filename, etag=None, last_modified=None): """Resolves a filename on the clusters. Args: filename (str): the filename that we are looking for on the clusters. etag (str): the etag to user for the query if any. last_modified (str): the date in the same format as returned by Last-Modified. Returns: A dict if the filename was found otherwise None. The dict has the following keys: * filer (str): the name of the cluster. * url (str): the full url of the filename. * host (str): the value of the Host header. * modified (bool): True if the file has been modified since the previous request. * headers (dict): the HTTP response headers. """ self.logger.debug('resolving %s', filename) res = Queue() reqs = [] for name, info in list(self.clusters.items()): headers = {'User-Agent': self.user_agent} headers.update(info['headers']) if etag: headers['If-None-Match'] = etag elif last_modified: headers['If-Modified-Since'] = last_modified for ip in sample(info['ips'], info['per_cluster']): self.logger.debug( 'looking for %s on %s with headers %s', filename, ip, headers) req = urllib.request.Request( 'http://%s%s' % (ip, filename), headers=headers) req.get_method = lambda: 'HEAD' reqs.append((name, req)) gevent.spawn(self._do_reqs, reqs, res) result = res.get() if result: self.logger.debug('found %s on %s: url=%s host=%s', filename, result['filer'], result['url'], result['host']) else: self.logger.debug('%s not found', filename) return result
{ "repo_name": "sebest/katana", "path": "katana/httpwhohas.py", "copies": "1", "size": "5634", "license": "mpl-2.0", "hash": 4968513432039562000, "line_mean": 37.5890410959, "line_max": 96, "alpha_frac": 0.5631877884, "autogenerated": false, "ratio": 4.201342281879195, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014476093872002936, "num_lines": 146 }
__all__ = ['HyperparameterGridsearchMixin'] import logging from joblib import Parallel, delayed from sklearn.metrics import accuracy_score from sklearn.model_selection import ParameterGrid from sklearn.model_selection import train_test_split from ycml.utils import get_class_from_module_path logger = logging.getLogger(__name__) class HyperparameterGridsearchMixin(object): def __init__(self, classifier='sklearn.svm.SVC', classifier_args={}, param_grid={}, metric=accuracy_score, validation_size=0.2, **kwargs): self.classifier = classifier self.classifier_args = classifier_args self.param_grid = param_grid self.validation_size = validation_size self.metric = metric if isinstance(metric, str): if metric.startswith('lambda'): self.metric = eval(metric) else: self.metric = get_class_from_module_path(metric) #end if #end def def fit_binarized(self, X_featurized, Y_binarized, validation_data=None, **kwargs): klass = get_class_from_module_path(self.classifier) if validation_data is None: # use 0.2 for validation data X_train, X_validation, Y_train, Y_validation = train_test_split(X_featurized, Y_binarized, test_size=self.validation_size) logger.info('Using {} of training data ({} instances) for validation.'.format(self.validation_size, Y_validation.shape[0])) else: X_train, X_validation, Y_train, Y_validation = X_featurized, validation_data[0], Y_binarized, validation_data[1] #end if best_score, best_param = 0.0, None if self.n_jobs > 1: logger.info('Performing hyperparameter gridsearch in parallel using {} jobs.'.format(self.n_jobs)) else: logger.debug('Performing hyperparameter gridsearch in parallel using {} jobs.'.format(self.n_jobs)) param_scores = Parallel(n_jobs=self.n_jobs)(delayed(_fit_classifier)(klass, self.classifier_args, param, self.metric, X_train, Y_train, X_validation, Y_validation) for param in ParameterGrid(self.param_grid)) best_param, best_score = max(param_scores, key=lambda x: x[1]) logger.info('Best scoring param is {} with score {}.'.format(best_param, best_score)) classifier_args = {} classifier_args.update(self.classifier_args) classifier_args.update(best_param) self.classifier_ = klass(**classifier_args) logger.info('Fitting final model <{}> on full data with param {}.'.format(self.classifier_, best_param)) self.classifier_.fit(X_featurized, Y_binarized) return self #end def #end class def _fit_classifier(klass, classifier_args, param, metric, X_train, Y_train, X_validation, Y_validation): local_classifier_args = {} local_classifier_args.update(classifier_args) local_classifier_args.update(param) classifier = klass(**local_classifier_args).fit(X_train, Y_train) Y_predict = classifier.predict(X_validation) score = metric(Y_validation, Y_predict) logger.info('<{}> with param {} has micro F1 of {}.'.format(classifier, param, score)) return (param, score) #end def
{ "repo_name": "skylander86/ycml", "path": "ycml/classifiers/gridsearch.py", "copies": "1", "size": "3151", "license": "apache-2.0", "hash": 683475633627162000, "line_mean": 41.5810810811, "line_max": 216, "alpha_frac": 0.684544589, "autogenerated": false, "ratio": 3.668218859138533, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48527634481385334, "avg_score": null, "num_lines": null }
''' Alliance vs. Horde Game Mode, based on an idea that a friend of mine suggested to me once. Draft cards randomly from the entire set with the only restriction being that they are (1) a class card or (2) not a class card BUT of a certain faction (Horde/Alliance). Definitions of card factions have been customly patched as defined in the factions.json file (see root directory of repository). ''' from __init__ import gameMode as mode, HS_NUM_CARDS_IN_SET from random import uniform, choice import copy name = 'Alliance vs. Horde' key = 'allianceVsHorde' options = ['Alliance','Horde'] description = "Battle a friend as one of the <strong>factions</strong> of Azeroth! Pandarens, dragons, and other related creatures are <em>neutral</em>." class gameMode(mode): def __init__(self,coll,hero,info): super(gameMode,self).__init__(coll,hero,info) self.cards = list() def tooManyCards(self,card): # Quick hack; make sure the draft only has enough cards in it that you can put into a normal hearthstone deck. if card.getRarity() == 'Legendary': return (card in self.cards) else: return (self.cards.count(card) == 2) def getSet(self): coll = self.collection hero = self.hero cards = [card for card in coll.iterCards() if self.isApplicableCard(card)] set = list() for x in xrange(HS_NUM_CARDS_IN_SET): card = choice(cards) while (card in set or self.tooManyCards(card)): card = choice(cards) self.cards.append(card) set.append(copy.deepcopy(card)) return tuple(set) def isApplicableCard(self,card): return (card.getHero() and card.getHero() == self.hero.getHero() ) or (not card.getHero() and card.getFaction() == self.info['faction']) def getDraft(self,numCards): sets = [] for set in xrange(numCards): sets.append(self.getSet()) return sets
{ "repo_name": "AlexSafatli/HearthstoneDrafter", "path": "modes/allianceVsHorde.py", "copies": "1", "size": "2002", "license": "mit", "hash": -4646840250615443000, "line_mean": 44.5, "line_max": 398, "alpha_frac": 0.6448551449, "autogenerated": false, "ratio": 3.633393829401089, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4778248974301089, "avg_score": null, "num_lines": null }
__all__ = ["Image", "ImageCollection"] from typing import Any, Set from uuid import uuid4 ImageUri = str SourceUri = str class Image(object): """Describe an image `uri` The absolute URI of the image. This basically identifies the Image and makes it unique. This absolute URI must include: ``scheme``, ``host``. ``schema`` must be either 'http' or 'https' - use 'https' if possible! Optional are: ``port``, ``path``, ``query``, ``fragment``. `source` The URI where did the image is originally found? This URI can point to a ImageBoardThread, or a comment section in a Forum, or a news article... In the idea of fair use, it is encouraged to point to the source as good as possible. This absolute URI must include: ``scheme``, ``host``. ``schema`` must be either 'http' or 'https' - the last one is preferred. Optional are: ``port``, ``path``, ``query``, ``fragment``. Good examples are: * https://www.reddit.com/r/Awww/comments/e1er0c/say_hi_to_loki_hes_just_contemplating/ * https://giphy.com/gifs/10kABVanhwykJW `is_generic` If a generic image crawler is used, its common that each image URI looks exactly the same. To make this known, use this flag. `more` A dictionary of additional information an image crawler might want to deliver. This dictionary's data types are intended to the basic ones: string, int, float, list, set, dict, bool, None Good examples are: * image-dimensions * author, copyright information * valid-until """ def __init__(self, *, uri: ImageUri, source: SourceUri, is_generic: bool = False, **more: Any) -> None: # pragma: no cover self.uri = uri self.source = source self.more = more self.is_generic = is_generic self.__hash = hash(uuid4()) if self.is_generic else hash(self.uri) def __hash__(self) -> int: return self.__hash def __eq__(self, other: Any) -> bool: if type(other) is type(self): return hash(self) == hash(other) return False def __repr__(self) -> str: # pragma: no cover return '<{0.__module__}.{0.__name__} object at {1:#x} {2.uri!r}>'.format(type(self), id(self), self) class ImageCollection(Set[Image]): pass
{ "repo_name": "k4cg/nichtparasoup", "path": "nichtparasoup/core/image.py", "copies": "1", "size": "2453", "license": "mit", "hash": -6929420835666320000, "line_mean": 32.1486486486, "line_max": 116, "alpha_frac": 0.5923359152, "autogenerated": false, "ratio": 3.9185303514377, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0014040654237436009, "num_lines": 74 }
__all__ = ['Image', 'imread', 'imread_collection', 'imsave', 'imshow', 'show', 'push', 'pop'] try: from urllib.request import urlopen except ImportError: from urllib2 import urlopen import os import re import tempfile from io import BytesIO import numpy as np import six from skimage.io._plugins import call as call_plugin from skimage.color import rgb2grey # Shared image queue _image_stack = [] URL_REGEX = re.compile(r'http://|https://|ftp://|file://|file:\\') def is_url(filename): """Return True if string is an http or ftp path.""" return (isinstance(filename, six.string_types) and URL_REGEX.match(filename) is not None) class Image(np.ndarray): """Class representing Image data. These objects have tags for image metadata and IPython display protocol methods for image display. Parameters ---------- arr : ndarray Image data. kwargs : Image tags as keywords Specified in the form ``tag0=value``, ``tag1=value``. Attributes ---------- tags : dict Meta-data. """ def __new__(cls, arr, **kwargs): """Set the image data and tags according to given parameters. """ x = np.asarray(arr).view(cls) x.tags = kwargs return x def __array_finalize__(self, obj): self.tags = getattr(obj, 'tags', {}) def _repr_png_(self): return self._repr_image_format('png') def _repr_jpeg_(self): return self._repr_image_format('jpeg') def _repr_image_format(self, format_str): str_buffer = BytesIO() imsave(str_buffer, self, format_str=format_str) return_str = str_buffer.getvalue() str_buffer.close() return return_str def push(img): """Push an image onto the shared image stack. Parameters ---------- img : ndarray Image to push. """ if not isinstance(img, np.ndarray): raise ValueError("Can only push ndarrays to the image stack.") _image_stack.append(img) def pop(): """Pop an image from the shared image stack. Returns ------- img : ndarray Image popped from the stack. """ return _image_stack.pop() def imread(fname, as_grey=False, plugin=None, flatten=None, **plugin_args): """Load an image from file. Parameters ---------- fname : string Image file name, e.g. ``test.jpg`` or URL. as_grey : bool If True, convert color images to grey-scale (32-bit floats). Images that are already in grey-scale format are not converted. plugin : str Name of plugin to use (Python Imaging Library by default). Other Parameters ---------------- flatten : bool Backward compatible keyword, superseded by `as_grey`. Returns ------- img_array : ndarray The different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ # Backward compatibility if flatten is not None: as_grey = flatten if is_url(fname): _, ext = os.path.splitext(fname) with tempfile.NamedTemporaryFile(delete=False, suffix=ext) as f: u = urlopen(fname) f.write(u.read()) img = call_plugin('imread', f.name, plugin=plugin, **plugin_args) os.remove(f.name) else: img = call_plugin('imread', fname, plugin=plugin, **plugin_args) if as_grey and getattr(img, 'ndim', 0) >= 3: img = rgb2grey(img) return img def imread_collection(load_pattern, conserve_memory=True, plugin=None, **plugin_args): """ Load a collection of images. Parameters ---------- load_pattern : str or list List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for ``ImageCollection`` for the default behaviour of this parameter. conserve_memory : bool, optional If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ return call_plugin('imread_collection', load_pattern, conserve_memory, plugin=plugin, **plugin_args) def imsave(fname, arr, plugin=None, **plugin_args): """Save an image to file. Parameters ---------- fname : str Target filename. arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4) Image data. plugin : str Name of plugin to use. By default, the different plugins are tried (starting with the Python Imaging Library) until a suitable candidate is found. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args) def imshow(arr, plugin=None, **plugin_args): """Display an image. Parameters ---------- arr : ndarray or str Image data or name of image file. plugin : str Name of plugin to use. By default, the different plugins are tried (starting with the Python Imaging Library) until a suitable candidate is found. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ if isinstance(arr, six.string_types): arr = call_plugin('imread', arr, plugin=plugin) return call_plugin('imshow', arr, plugin=plugin, **plugin_args) def show(): '''Display pending images. Launch the event loop of the current gui plugin, and display all pending images, queued via `imshow`. This is required when using `imshow` from non-interactive scripts. A call to `show` will block execution of code until all windows have been closed. Examples -------- >>> import skimage.io as io >>> for i in range(4): ... io.imshow(np.random.random((50, 50))) >>> io.show() # doctest: +SKIP ''' return call_plugin('_app_show')
{ "repo_name": "almarklein/scikit-image", "path": "skimage/io/_io.py", "copies": "1", "size": "6424", "license": "bsd-3-clause", "hash": 695960431952372000, "line_mean": 24.2913385827, "line_max": 78, "alpha_frac": 0.6016500623, "autogenerated": false, "ratio": 4.078730158730159, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5180380221030159, "avg_score": null, "num_lines": null }
# all imports needed by the client from direct.showbase.DirectObject import DirectObject from direct.distributed.ClientRepository import ClientRepository from pandac.PandaModules import URLSpec class DungeonClientRepository(ClientRepository): """the main client repository class""" def __init__(self): # list of all needed .dc files dcFileNames = ['distributed/direct.dc', 'distributed/net.dc'] # initialise the client repository on this # machine with the dc filenames ClientRepository.__init__(self, dcFileNames = dcFileNames) class Client(DirectObject): """The main client class, which contains all the logic and stuff you can see in the application and handles the connection to the server""" def __init__(self, ip): """ Default constructor for the Clinet class """ # get the port number from the configuration file # if it doesn't exist, use 4400 as the default tcpPort = base.config.GetInt('server-port', 4400) # get the host name from the configuration file # which we want to connect to. If it doesn't exit # we use loopback to connect to hostname = base.config.GetString('server-host', ip) # now build the url from the data given above self.url = URLSpec('http://%s:%s' % (hostname, tcpPort)) # create the Repository for the client self.cr = DungeonClientRepository() # and finaly try to connect to the server self.cr.connect([self.url], successCallback = self.connectSuccess, failureCallback = self.connectFailure) def connectFailure(self, statusCode, statusString): """ some error occured while try to connect to the server """ # send a message, that should show the client the error message base.messenger.send( "showerror", ["Failed to connect to %s: %s." % (self.url, statusString)]) def connectSuccess(self): """ Successfully connected. But we still can't really do anything until we've got the doID range. """ print "Connection established, waiting for server." self.cr.setInterestZones([1]) self.acceptOnce('gotTimeSync', self.syncReady) def syncReady(self): """ Now we've got the TimeManager manifested, and we're in sync with the server time. Now we can enter the world. Check to see if we've received our doIdBase yet. """ if self.cr.haveCreateAuthority(): self.createReady() else: # Not yet, keep waiting a bit longer. self.acceptOnce('createReady', self.createReady) def createReady(self): """ Now we're ready to go! """ print "server connection done" self.player = self.cr.createDistributedObject( className = "DistributedPlayer", zoneId = 1) self.player.startPosHprBroadcast() # Unsure?? This maybe a good place to run a precheck to get # everything ready or something like that :P self.accept("clickPosition", self.walkTo) def walkTo(self, pos): self.player.lookAt(pos) moveInterval = self.player.posInterval(1, pos) moveInterval.start() #self.player.setPos(pos)
{ "repo_name": "grimfang/owp_dungeon_crawler", "path": "src/client/client.py", "copies": "1", "size": "3309", "license": "mit", "hash": 1157125451503840000, "line_mean": 40.3625, "line_max": 72, "alpha_frac": 0.6452100332, "autogenerated": false, "ratio": 4.325490196078431, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002422765983253022, "num_lines": 80 }
# all imports import sqlite3 from flask import Flask, request, session, g, redirect, url_for,\ abort, render_template, flash from contextlib import closing # configuration DATABASE = '/temp/bloggify.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = 'admin' PASSWORD = 'default' # create our little application app = Flask(__name__) app.config.from_envvar('BLOGGIFY_SETTINGS', silent=True) def connect_db(): """ Connects to a specific database """ return sqlite3.connect(app.config['DATABASE']) def init_db(): """ innitializes a connexion """ with closing(connect_db()) as db: with app.open_resource('schema.sql', mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): db = getattr(g, 'db', None ) if db is not None: db.close() @app.route('/') def show_entries(): cur = g.db.execute('select title, text from entries order by id desc') entries = [dict(title=row[0],text=row[1]) for row in cur.fetchall()] return render_template('show_entries.html', entries=entries) @app.route('/add', methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) g.db.execute('insert into entries (title, text) values (?,?)', [request.form['title'], request.form[text]]) g.db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) # Login and logout @app.route('/login', methods=['GET', 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: rerror = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else: session['logged_in'] = True flash('You were logged in') return redirect(url_for('show_entries')) return render_template('login.html', error=error) if __name__ == '__main__': app.run()
{ "repo_name": "ledrui/blogify", "path": "bloggify.py", "copies": "1", "size": "2105", "license": "mit", "hash": 5855447274542126000, "line_mean": 26.3376623377, "line_max": 111, "alpha_frac": 0.6332541568, "autogenerated": false, "ratio": 3.5738539898132426, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47071081466132425, "avg_score": null, "num_lines": null }
# all imports import sqlite3 import os from flask import Flask , request , session , g , redirect , url_for , \ abort , render_template , flash from contextlib import closing # Database configuration DATABASE = os.environ['OPENSHIFT_DATA_DIR'] + 'flaskr.db' DEBUG = True SECRET_KEY = 'development key' USERNAME = 'admin' PASSWORD = 'admin' # create our little application :) app = Flask(__name__) app.config.from_object(__name__) app.config.from_envvar('FLASKR_SETTINGS', silent=True) def connect_db(): return sqlite3.connect(app.config['DATABASE']) def init_db(): with closing(connect_db()) as db: with app.open_resource('schema.sql' , mode='r') as f: db.cursor().executescript(f.read()) db.commit() @app.before_request def before_request(): g.db = connect_db() @app.teardown_request def teardown_request(exception): db = getattr(g, 'db',None) if db is not None: db.close() @app.route('/') def show_entries(): cur = g.db.execute('select title , text from entries order by id desc') entries = [dict(title=row[0] , text=row[1]) for row in cur.fetchall()] return render_template('show_entries.html' , entries = entries) @app.route('/add',methods=['POST']) def add_entry(): if not session.get('logged_in'): abort(401) g.db.execute('insert into entries (title , text) values (? , ?)', [request.form['title'], request.form['text']]) g.db.commit() flash('New entry was successfully posted') return redirect(url_for('show_entries')) @app.route('/login' , methods=['GET' , 'POST']) def login(): error = None if request.method == 'POST': if request.form['username'] != app.config['USERNAME']: error = 'Invalid username' elif request.form['password'] != app.config['PASSWORD']: error = 'Invalid password' else : session['logged_in'] = True flash('You are logged in') return redirect(url_for('show_entries')) return render_template('login.html' , error = error) @app.route('/logout') def logout(): session.pop('logged_in' , None) flash('You were logged out') return redirect(url_for('show_entries')) if __name__ == '__main__': # init_db() app.run()
{ "repo_name": "coursemdetw/flaskr_on_openshift", "path": "wsgi/flaskr.py", "copies": "1", "size": "2111", "license": "apache-2.0", "hash": -4971371700237716000, "line_mean": 25.0617283951, "line_max": 72, "alpha_frac": 0.6750355282, "autogenerated": false, "ratio": 3.0998531571218795, "config_test": true, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9130882110950461, "avg_score": 0.028801314874283602, "num_lines": 81 }
__all__ = ['imread', 'imread_collection', 'imsave', 'imshow', 'show', 'push', 'pop'] from scikits.image.io._plugins import call as call_plugin from scikits.image.color import rgb2grey import numpy as np # Shared image queue _image_stack = [] def push(img): """Push an image onto the shared image stack. Parameters ---------- img : ndarray Image to push. """ if not isinstance(img, np.ndarray): raise ValueError("Can only push ndarrays to the image stack.") _image_stack.append(img) def pop(): """Pop an image from the shared image stack. Returns ------- img : ndarray Image popped from the stack. """ return _image_stack.pop() def imread(fname, as_grey=False, plugin=None, flatten=None, **plugin_args): """Load an image from file. Parameters ---------- fname : string Image file name, e.g. ``test.jpg``. as_grey : bool If True, convert color images to grey-scale (32-bit floats). Images that are already in grey-scale format are not converted. plugin : str Name of plugin to use (Python Imaging Library by default). Other Parameters ---------------- flatten : bool Backward compatible keyword, superseded by `as_grey`. Returns ------- img_array : ndarray The different colour bands/channels are stored in the third dimension, such that a grey-image is MxN, an RGB-image MxNx3 and an RGBA-image MxNx4. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ # Backward compatibility if flatten is not None: as_grey = flatten img = call_plugin('imread', fname, plugin=plugin, **plugin_args) if as_grey and getattr(img, 'ndim', 0) >= 3: img = rgb2grey(img) return img def imread_collection(load_pattern, conserve_memory=True, plugin=None, **plugin_args): """ Load a collection of images. Parameters ---------- load_pattern : str or list List of objects to load. These are usually filenames, but may vary depending on the currently active plugin. See the docstring for ``ImageCollection`` for the default behaviour of this parameter. conserve_memory : bool, optional If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ return call_plugin('imread_collection', load_pattern, conserve_memory, plugin=plugin, **plugin_args) def imsave(fname, arr, plugin=None, **plugin_args): """Save an image to file. Parameters ---------- fname : str Target filename. arr : ndarray of shape (M,N) or (M,N,3) or (M,N,4) Image data. plugin : str Name of plugin to use. By default, the different plugins are tried (starting with the Python Imaging Library) until a suitable candidate is found. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ return call_plugin('imsave', fname, arr, plugin=plugin, **plugin_args) def imshow(arr, plugin=None, **plugin_args): """Display an image. Parameters ---------- arr : ndarray Image data. plugin : str Name of plugin to use. By default, the different plugins are tried (starting with the Python Imaging Library) until a suitable candidate is found. Other parameters ---------------- plugin_args : keywords Passed to the given plugin. """ return call_plugin('imshow', arr, plugin=plugin, **plugin_args) def show(): '''Display pending images. Launch the event loop of the current gui plugin, and display all pending images, queued via `imshow`. This is required when using `imshow` from non-interactive scripts. A call to `show` will block execution of code until all windows have been closed. Examples -------- >>> import scikits.image.io as io >>> for i in range(4): ... io.imshow(np.random.random((50, 50))) >>> io.show() ''' return call_plugin('_app_show')
{ "repo_name": "GaelVaroquaux/scikits.image", "path": "scikits/image/io/io.py", "copies": "1", "size": "4461", "license": "bsd-3-clause", "hash": 6169115537938402000, "line_mean": 25.2411764706, "line_max": 76, "alpha_frac": 0.6030038108, "autogenerated": false, "ratio": 4.173058933582787, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0017472903476960272, "num_lines": 170 }
__all__ = ['imread', 'imread_collection'] import numpy as np import scikits.image.io as io try: import pyfits except ImportError: raise ImportError("PyFITS could not be found. Please refer to\n" "http://www.stsci.edu/resources/software_hardware/pyfits\n" "for further instructions.") def imread(fname, dtype=None): """Load an image from a FITS file. Parameters ---------- fname : string Image file name, e.g. ``test.fits``. dtype : dtype, optional For FITS, this argument is ignored because Stefan is planning on removing the dtype argument from imread anyway. Returns ------- img_array : ndarray Unlike plugins such as PIL, where different colour bands/channels are stored in the third dimension, FITS images are greyscale-only and can be N-dimensional, so an array of the native FITS dimensionality is returned, without colour channels. Currently if no image is found in the file, None will be returned Notes ----- Currently FITS ``imread()`` always returns the first image extension when given a Multi-Extension FITS file; use ``imread_collection()`` (which does lazy loading) to get all the extensions at once. """ hdulist = pyfits.open(fname) # Iterate over FITS image extensions, ignoring any other extension types # such as binary tables, and get the first image data array: img_array = None for hdu in hdulist: if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): if hdu.data is not None: img_array = hdu.data break hdulist.close() return img_array def imread_collection(load_pattern, conserve_memory=True): """Load a collection of images from one or more FITS files Parameters ---------- load_pattern : str or list List of extensions to load. Filename globbing is currently unsupported. converve_memory : bool If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. """ intype = type(load_pattern) if intype is not list and intype is not str: raise TypeError("Input must be a filename or list of filenames") # Ensure we have a list, otherwise we'll end up iterating over the string: if intype is not list: load_pattern = [load_pattern] # Generate a list of filename/extension pairs by opening the list of # files and finding the image extensions in each one: ext_list = [] for filename in load_pattern: hdulist = pyfits.open(filename) for n, hdu in zip(range(len(hdulist)), hdulist): if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): # Ignore (primary) header units with no data (use '.size' # rather than '.data' to avoid actually loading the image): if hdu.size() > 0: ext_list.append((filename, n)) hdulist.close() return io.ImageCollection(ext_list, load_func=FITSFactory, conserve_memory=conserve_memory) def FITSFactory(image_ext): """Load an image extension from a FITS file and return a NumPy array Parameters ---------- image_ext : tuple FITS extension to load, in the format ``(filename, ext_num)``. The FITS ``(extname, extver)`` format is unsupported, since this function is not called directly by the user and ``imread_collection()`` does the work of figuring out which extensions need loading. """ # Expect a length-2 tuple with a filename as the first element: if not isinstance(image_ext, tuple): raise TypeError("Expected a tuple") if len(image_ext) != 2: raise ValueError("Expected a tuple of length 2") filename = image_ext[0] extnum = image_ext[1] if type(filename) is not str or type(extnum) is not int: raise ValueError("Expected a (filename, extension) tuple") hdulist = pyfits.open(filename) data = hdulist[extnum].data hdulist.close() if data is None: raise RuntimeError("Extension %d of %s has no data" % (extnum, filename)) return data
{ "repo_name": "GaelVaroquaux/scikits.image", "path": "scikits/image/io/_plugins/fits_plugin.py", "copies": "1", "size": "4494", "license": "bsd-3-clause", "hash": -988224040351516900, "line_mean": 29.9931034483, "line_max": 78, "alpha_frac": 0.6279483756, "autogenerated": false, "ratio": 4.219718309859155, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5347666685459155, "avg_score": null, "num_lines": null }
__all__ = ['imread', 'imread_collection'] import numpy as np import skimage.io as io try: import pyfits except ImportError: raise ImportError("PyFITS could not be found. Please refer to\n" "http://www.stsci.edu/resources/software_hardware/pyfits\n" "for further instructions.") def imread(fname, dtype=None): """Load an image from a FITS file. Parameters ---------- fname : string Image file name, e.g. ``test.fits``. dtype : dtype, optional For FITS, this argument is ignored because Stefan is planning on removing the dtype argument from imread anyway. Returns ------- img_array : ndarray Unlike plugins such as PIL, where different colour bands/channels are stored in the third dimension, FITS images are greyscale-only and can be N-dimensional, so an array of the native FITS dimensionality is returned, without colour channels. Currently if no image is found in the file, None will be returned Notes ----- Currently FITS ``imread()`` always returns the first image extension when given a Multi-Extension FITS file; use ``imread_collection()`` (which does lazy loading) to get all the extensions at once. """ hdulist = pyfits.open(fname) # Iterate over FITS image extensions, ignoring any other extension types # such as binary tables, and get the first image data array: img_array = None for hdu in hdulist: if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): if hdu.data is not None: img_array = hdu.data break hdulist.close() return img_array def imread_collection(load_pattern, conserve_memory=True): """Load a collection of images from one or more FITS files Parameters ---------- load_pattern : str or list List of extensions to load. Filename globbing is currently unsupported. converve_memory : bool If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. """ intype = type(load_pattern) if intype is not list and intype is not str: raise TypeError("Input must be a filename or list of filenames") # Ensure we have a list, otherwise we'll end up iterating over the string: if intype is not list: load_pattern = [load_pattern] # Generate a list of filename/extension pairs by opening the list of # files and finding the image extensions in each one: ext_list = [] for filename in load_pattern: hdulist = pyfits.open(filename) for n, hdu in zip(range(len(hdulist)), hdulist): if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): # Ignore (primary) header units with no data (use '.size' # rather than '.data' to avoid actually loading the image): try: data_size = hdu.size() except TypeError: # (size changed to int in PyFITS 3.1) data_size = hdu.size if data_size > 0: ext_list.append((filename, n)) hdulist.close() return io.ImageCollection(ext_list, load_func=FITSFactory, conserve_memory=conserve_memory) def FITSFactory(image_ext): """Load an image extension from a FITS file and return a NumPy array Parameters ---------- image_ext : tuple FITS extension to load, in the format ``(filename, ext_num)``. The FITS ``(extname, extver)`` format is unsupported, since this function is not called directly by the user and ``imread_collection()`` does the work of figuring out which extensions need loading. """ # Expect a length-2 tuple with a filename as the first element: if not isinstance(image_ext, tuple): raise TypeError("Expected a tuple") if len(image_ext) != 2: raise ValueError("Expected a tuple of length 2") filename = image_ext[0] extnum = image_ext[1] if type(filename) is not str or type(extnum) is not int: raise ValueError("Expected a (filename, extension) tuple") hdulist = pyfits.open(filename) data = hdulist[extnum].data hdulist.close() if data is None: raise RuntimeError("Extension %d of %s has no data" % (extnum, filename)) return data
{ "repo_name": "emmanuelle/scikits.image", "path": "skimage/io/_plugins/fits_plugin.py", "copies": "2", "size": "4655", "license": "bsd-3-clause", "hash": 2907905309740414000, "line_mean": 30.4527027027, "line_max": 78, "alpha_frac": 0.6212674544, "autogenerated": false, "ratio": 4.2318181818181815, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.0004597885057679217, "num_lines": 148 }
__all__ = ['imread', 'imread_collection'] import skimage.io as io try: from astropy.io import fits as pyfits except ImportError: try: import pyfits except ImportError: raise ImportError("PyFITS could not be found. Please refer to\n" "http://www.stsci.edu/resources/software_hardware/pyfits\n" "for further instructions.") def imread(fname, dtype=None): """Load an image from a FITS file. Parameters ---------- fname : string Image file name, e.g. ``test.fits``. dtype : dtype, optional For FITS, this argument is ignored because Stefan is planning on removing the dtype argument from imread anyway. Returns ------- img_array : ndarray Unlike plugins such as PIL, where different colour bands/channels are stored in the third dimension, FITS images are greyscale-only and can be N-dimensional, so an array of the native FITS dimensionality is returned, without colour channels. Currently if no image is found in the file, None will be returned Notes ----- Currently FITS ``imread()`` always returns the first image extension when given a Multi-Extension FITS file; use ``imread_collection()`` (which does lazy loading) to get all the extensions at once. """ hdulist = pyfits.open(fname) # Iterate over FITS image extensions, ignoring any other extension types # such as binary tables, and get the first image data array: img_array = None for hdu in hdulist: if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): if hdu.data is not None: img_array = hdu.data break hdulist.close() return img_array def imread_collection(load_pattern, conserve_memory=True): """Load a collection of images from one or more FITS files Parameters ---------- load_pattern : str or list List of extensions to load. Filename globbing is currently unsupported. converve_memory : bool If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. """ intype = type(load_pattern) if intype is not list and intype is not str: raise TypeError("Input must be a filename or list of filenames") # Ensure we have a list, otherwise we'll end up iterating over the string: if intype is not list: load_pattern = [load_pattern] # Generate a list of filename/extension pairs by opening the list of # files and finding the image extensions in each one: ext_list = [] for filename in load_pattern: hdulist = pyfits.open(filename) for n, hdu in zip(range(len(hdulist)), hdulist): if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): # Ignore (primary) header units with no data (use '.size' # rather than '.data' to avoid actually loading the image): try: data_size = hdu.size() except TypeError: # (size changed to int in PyFITS 3.1) data_size = hdu.size if data_size > 0: ext_list.append((filename, n)) hdulist.close() return io.ImageCollection(ext_list, load_func=FITSFactory, conserve_memory=conserve_memory) def FITSFactory(image_ext): """Load an image extension from a FITS file and return a NumPy array Parameters ---------- image_ext : tuple FITS extension to load, in the format ``(filename, ext_num)``. The FITS ``(extname, extver)`` format is unsupported, since this function is not called directly by the user and ``imread_collection()`` does the work of figuring out which extensions need loading. """ # Expect a length-2 tuple with a filename as the first element: if not isinstance(image_ext, tuple): raise TypeError("Expected a tuple") if len(image_ext) != 2: raise ValueError("Expected a tuple of length 2") filename = image_ext[0] extnum = image_ext[1] if type(filename) is not str or type(extnum) is not int: raise ValueError("Expected a (filename, extension) tuple") hdulist = pyfits.open(filename) data = hdulist[extnum].data hdulist.close() if data is None: raise RuntimeError("Extension %d of %s has no data" % (extnum, filename)) return data
{ "repo_name": "SamHames/scikit-image", "path": "skimage/io/_plugins/fits_plugin.py", "copies": "9", "size": "4727", "license": "bsd-3-clause", "hash": -3250211166962519000, "line_mean": 30.5133333333, "line_max": 78, "alpha_frac": 0.6194203512, "autogenerated": false, "ratio": 4.250899280575539, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9370319631775539, "avg_score": null, "num_lines": null }
__all__ = ['imread', 'imread_collection'] import skimage.io as io try: import pyfits except ImportError: raise ImportError("PyFITS could not be found. Please refer to\n" "http://www.stsci.edu/resources/software_hardware/pyfits\n" "for further instructions.") def imread(fname, dtype=None): """Load an image from a FITS file. Parameters ---------- fname : string Image file name, e.g. ``test.fits``. dtype : dtype, optional For FITS, this argument is ignored because Stefan is planning on removing the dtype argument from imread anyway. Returns ------- img_array : ndarray Unlike plugins such as PIL, where different colour bands/channels are stored in the third dimension, FITS images are greyscale-only and can be N-dimensional, so an array of the native FITS dimensionality is returned, without colour channels. Currently if no image is found in the file, None will be returned Notes ----- Currently FITS ``imread()`` always returns the first image extension when given a Multi-Extension FITS file; use ``imread_collection()`` (which does lazy loading) to get all the extensions at once. """ hdulist = pyfits.open(fname) # Iterate over FITS image extensions, ignoring any other extension types # such as binary tables, and get the first image data array: img_array = None for hdu in hdulist: if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): if hdu.data is not None: img_array = hdu.data break hdulist.close() return img_array def imread_collection(load_pattern, conserve_memory=True): """Load a collection of images from one or more FITS files Parameters ---------- load_pattern : str or list List of extensions to load. Filename globbing is currently unsupported. converve_memory : bool If True, never keep more than one in memory at a specific time. Otherwise, images will be cached once they are loaded. Returns ------- ic : ImageCollection Collection of images. """ intype = type(load_pattern) if intype is not list and intype is not str: raise TypeError("Input must be a filename or list of filenames") # Ensure we have a list, otherwise we'll end up iterating over the string: if intype is not list: load_pattern = [load_pattern] # Generate a list of filename/extension pairs by opening the list of # files and finding the image extensions in each one: ext_list = [] for filename in load_pattern: hdulist = pyfits.open(filename) for n, hdu in zip(range(len(hdulist)), hdulist): if isinstance(hdu, pyfits.ImageHDU) or \ isinstance(hdu, pyfits.PrimaryHDU): # Ignore (primary) header units with no data (use '.size' # rather than '.data' to avoid actually loading the image): try: data_size = hdu.size() except TypeError: # (size changed to int in PyFITS 3.1) data_size = hdu.size if data_size > 0: ext_list.append((filename, n)) hdulist.close() return io.ImageCollection(ext_list, load_func=FITSFactory, conserve_memory=conserve_memory) def FITSFactory(image_ext): """Load an image extension from a FITS file and return a NumPy array Parameters ---------- image_ext : tuple FITS extension to load, in the format ``(filename, ext_num)``. The FITS ``(extname, extver)`` format is unsupported, since this function is not called directly by the user and ``imread_collection()`` does the work of figuring out which extensions need loading. """ # Expect a length-2 tuple with a filename as the first element: if not isinstance(image_ext, tuple): raise TypeError("Expected a tuple") if len(image_ext) != 2: raise ValueError("Expected a tuple of length 2") filename = image_ext[0] extnum = image_ext[1] if type(filename) is not str or type(extnum) is not int: raise ValueError("Expected a (filename, extension) tuple") hdulist = pyfits.open(filename) data = hdulist[extnum].data hdulist.close() if data is None: raise RuntimeError("Extension %d of %s has no data" % (extnum, filename)) return data
{ "repo_name": "almarklein/scikit-image", "path": "skimage/io/_plugins/fits_plugin.py", "copies": "2", "size": "4636", "license": "bsd-3-clause", "hash": -4676620609502751000, "line_mean": 30.537414966, "line_max": 78, "alpha_frac": 0.6205780846, "autogenerated": false, "ratio": 4.233789954337899, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5854368038937899, "avg_score": null, "num_lines": null }
__all__ = ['imread', 'imsave'] import numpy as np from six import string_types from PIL import Image from ...util import img_as_ubyte, img_as_uint from ...external.tifffile import imread as tif_imread, imsave as tif_imsave def imread(fname, dtype=None, img_num=None, **kwargs): """Load an image from file. Parameters ---------- fname : str File name. dtype : numpy dtype object or string specifier Specifies data type of array elements. img_num : int, optional Specifies which image to read in a file with multiple images (zero-indexed). kwargs : keyword pairs, optional Addition keyword arguments to pass through (only applicable to Tiff files for now, see `tifffile`'s `imread` function). Notes ----- Tiff files are handled by Christophe Golhke's tifffile.py [1]_, and support many advanced image types including multi-page and floating point. All other files are read using the Python Imaging Libary. See PIL docs [2]_ for a list of supported formats. References ---------- .. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ if hasattr(fname, 'lower') and dtype is None: kwargs.setdefault('key', img_num) if fname.lower().endswith(('.tiff', '.tif')): return tif_imread(fname, **kwargs) im = Image.open(fname) try: # this will raise an IOError if the file is not readable im.getdata()[0] except IOError: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" raise ValueError('Could not load "%s"\nPlease see documentation at: %s' % (fname, site)) else: return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): """Import a PIL Image object to an ndarray, in memory. Parameters ---------- Refer to ``imread``. """ frames = [] grayscale = None i = 0 while 1: try: im.seek(i) except EOFError: break frame = im if img_num is not None and img_num != i: im.getdata()[0] i += 1 continue if im.mode == 'P': if grayscale is None: grayscale = _palette_is_grayscale(im) if grayscale: frame = im.convert('L') else: frame = im.convert('RGB') elif im.mode == '1': frame = im.convert('L') elif 'A' in im.mode: frame = im.convert('RGBA') elif im.mode == 'CMYK': frame = im.convert('RGB') if im.mode.startswith('I;16'): shape = im.size dtype = '>u2' if im.mode.endswith('B') else '<u2' if 'S' in im.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1 if hasattr(im, 'fp') and im.fp: im.fp.close() if img_num is None and len(frames) > 1: return np.array(frames) elif frames: return frames[0] elif img_num: raise IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image): """Return True if PIL image in palette mode is grayscale. Parameters ---------- pil_image : PIL image PIL Image that is in Palette mode. Returns ------- is_grayscale : bool True if all colors in image palette are gray. """ assert pil_image.mode == 'P' # get palette as an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used; unused colors have junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop] # Image is grayscale if channel differences (R - G and G - B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): """Export an ndarray to a PIL object. Parameters ---------- Refer to ``imsave``. """ if arr.ndim == 3: arr = img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode = 'I;16' mode_base = 'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max() < 256 and arr.min() >= 0: arr = arr.astype(np.uint8) mode = mode_base = 'L' else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L' mode_base = 'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy < 1.9 if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs): """Save an image to disk. Parameters ---------- fname : str or file-like object Name of destination file. arr : ndarray of uint8 or float Array (image) to save. Arrays of data-type uint8 should have values in [0, 255], whereas floating-point arrays must be in [0, 1]. format_str: str Format to save as, this is defaulted to PNG if using a file-like object; this will be derived from the extension if fname is a string kwargs: dict Keyword arguments to the Pillow save function (or tifffile save function, for Tiff files). These are format dependent. For example, Pillow's JPEG save function supports an integer ``quality`` argument with values in [1, 95], while TIFFFile supports a ``compress`` integer argument with values in [0, 9]. Notes ----- Tiff files are handled by Christophe Golhke's tifffile.py [1]_, and support many advanced image types including multi-page and floating point. All other image formats use the Python Imaging Libary. See PIL docs [2]_ for a list of other supported formats. All images besides single channel PNGs are converted using `img_as_uint8`. Single Channel PNGs have the following behavior: - Integer values in [0, 255] and Boolean types -> img_as_uint8 - Floating point and other integers -> img_as_uint16 References ---------- .. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ # default to PNG if file-like object if not isinstance(fname, string_types) and format_str is None: format_str = "PNG" # Check for png in filename if (isinstance(fname, string_types) and fname.lower().endswith(".png")): format_str = "PNG" arr = np.asanyarray(arr).squeeze() if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) use_tif = False if hasattr(fname, 'lower'): if fname.lower().endswith(('.tiff', '.tif')): use_tif = True if not format_str is None: if format_str.lower() in ['tiff', 'tif']: use_tif = True if use_tif: tif_imsave(fname, arr, **kwargs) return if arr.ndim not in (2, 3): raise ValueError("Invalid shape for image array: %s" % arr.shape) if arr.ndim == 3: if arr.shape[2] not in (3, 4): raise ValueError("Invalid number of channels in image array.") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname, format=format_str, **kwargs)
{ "repo_name": "newville/scikit-image", "path": "skimage/io/_plugins/pil_plugin.py", "copies": "1", "size": "8171", "license": "bsd-3-clause", "hash": -3443627217807784000, "line_mean": 29.1512915129, "line_max": 96, "alpha_frac": 0.5841390283, "autogenerated": false, "ratio": 3.685611186287776, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9768112209598276, "avg_score": 0.00032760099789985855, "num_lines": 271 }
__all__ = ['imread', 'imsave'] import numpy as np from six import string_types from PIL import Image from ...util import img_as_ubyte, img_as_uint from .tifffile_plugin import imread as tif_imread, imsave as tif_imsave def imread(fname, dtype=None, img_num=None, **kwargs): """Load an image from file. Parameters ---------- fname : str or file File name or file-like-object. dtype : numpy dtype object or string specifier Specifies data type of array elements. img_num : int, optional Specifies which image to read in a file with multiple images (zero-indexed). kwargs : keyword pairs, optional Addition keyword arguments to pass through (only applicable to Tiff files for now, see `tifffile`'s `imread` function). Notes ----- Tiff files are handled by Christophe Golhke's tifffile.py [1]_, and support many advanced image types including multi-page and floating point. All other files are read using the Python Imaging Libary. See PIL docs [2]_ for a list of supported formats. References ---------- .. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ if hasattr(fname, 'lower') and dtype is None: kwargs.setdefault('key', img_num) if fname.lower().endswith(('.tiff', '.tif')): return tif_imread(fname, **kwargs) if isinstance(fname, string_types): with open(fname, 'rb') as f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): """Import a PIL Image object to an ndarray, in memory. Parameters ---------- Refer to ``imread``. """ try: # this will raise an IOError if the file is not readable im.getdata()[0] except IOError as e: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" pillow_error_message = str(e) error_message = ('Could not load "%s" \n' 'Reason: "%s"\n' 'Please see documentation at: %s' % (im.filename, pillow_error_message, site)) raise ValueError(error_message) frames = [] grayscale = None i = 0 while 1: try: im.seek(i) except EOFError: break frame = im if img_num is not None and img_num != i: im.getdata()[0] i += 1 continue if im.format == 'PNG' and im.mode == 'I' and dtype is None: dtype = 'uint16' if im.mode == 'P': if grayscale is None: grayscale = _palette_is_grayscale(im) if grayscale: frame = im.convert('L') else: frame = im.convert('RGB') elif im.mode == '1': frame = im.convert('L') elif 'A' in im.mode: frame = im.convert('RGBA') elif im.mode == 'CMYK': frame = im.convert('RGB') if im.mode.startswith('I;16'): shape = im.size dtype = '>u2' if im.mode.endswith('B') else '<u2' if 'S' in im.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1 if img_num is not None: break if hasattr(im, 'fp') and im.fp: im.fp.close() if img_num is None and len(frames) > 1: return np.array(frames) elif frames: return frames[0] elif img_num: raise IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image): """Return True if PIL image in palette mode is grayscale. Parameters ---------- pil_image : PIL image PIL Image that is in Palette mode. Returns ------- is_grayscale : bool True if all colors in image palette are gray. """ assert pil_image.mode == 'P' # get palette as an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used; unused colors have junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop] # Image is grayscale if channel differences (R - G and G - B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): """Export an ndarray to a PIL object. Parameters ---------- Refer to ``imsave``. """ if arr.ndim == 3: arr = img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode = 'I;16' mode_base = 'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max() < 256 and arr.min() >= 0: arr = arr.astype(np.uint8) mode = mode_base = 'L' else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L' mode_base = 'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy < 1.9 if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs): """Save an image to disk. Parameters ---------- fname : str or file-like object Name of destination file. arr : ndarray of uint8 or float Array (image) to save. Arrays of data-type uint8 should have values in [0, 255], whereas floating-point arrays must be in [0, 1]. format_str: str Format to save as, this is defaulted to PNG if using a file-like object; this will be derived from the extension if fname is a string kwargs: dict Keyword arguments to the Pillow save function (or tifffile save function, for Tiff files). These are format dependent. For example, Pillow's JPEG save function supports an integer ``quality`` argument with values in [1, 95], while TIFFFile supports a ``compress`` integer argument with values in [0, 9]. Notes ----- Tiff files are handled by Christophe Golhke's tifffile.py [1]_, and support many advanced image types including multi-page and floating point. All other image formats use the Python Imaging Libary. See PIL docs [2]_ for a list of other supported formats. All images besides single channel PNGs are converted using `img_as_uint8`. Single Channel PNGs have the following behavior: - Integer values in [0, 255] and Boolean types -> img_as_uint8 - Floating point and other integers -> img_as_uint16 References ---------- .. [1] http://www.lfd.uci.edu/~gohlke/code/tifffile.py.html .. [2] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ # default to PNG if file-like object if not isinstance(fname, string_types) and format_str is None: format_str = "PNG" # Check for png in filename if (isinstance(fname, string_types) and fname.lower().endswith(".png")): format_str = "PNG" arr = np.asanyarray(arr) if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) use_tif = False if hasattr(fname, 'lower'): if fname.lower().endswith(('.tiff', '.tif')): use_tif = True if format_str is not None: if format_str.lower() in ['tiff', 'tif']: use_tif = True if use_tif: tif_imsave(fname, arr, **kwargs) return if arr.ndim not in (2, 3): raise ValueError("Invalid shape for image array: %s" % arr.shape) if arr.ndim == 3: if arr.shape[2] not in (3, 4): raise ValueError("Invalid number of channels in image array.") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname, format=format_str, **kwargs)
{ "repo_name": "Midafi/scikit-image", "path": "skimage/io/_plugins/pil_plugin.py", "copies": "5", "size": "8721", "license": "bsd-3-clause", "hash": 6582274928026409000, "line_mean": 29.493006993, "line_max": 93, "alpha_frac": 0.5774567137, "autogenerated": false, "ratio": 3.6859678782755707, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00012044692895756726, "num_lines": 286 }
__all__ = ['imread', 'imsave'] import numpy as np from six import string_types from PIL import Image from ...util import img_as_ubyte, img_as_uint def imread(fname, dtype=None, img_num=None, **kwargs): """Load an image from file. Parameters ---------- fname : str or file File name or file-like-object. dtype : numpy dtype object or string specifier Specifies data type of array elements. img_num : int, optional Specifies which image to read in a file with multiple images (zero-indexed). kwargs : keyword pairs, optional Addition keyword arguments to pass through. Notes ----- Files are read using the Python Imaging Libary. See PIL docs [1]_ for a list of supported formats. References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ if isinstance(fname, string_types): with open(fname, 'rb') as f: im = Image.open(f) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) else: im = Image.open(fname) return pil_to_ndarray(im, dtype=dtype, img_num=img_num) def pil_to_ndarray(im, dtype=None, img_num=None): """Import a PIL Image object to an ndarray, in memory. Parameters ---------- Refer to ``imread``. """ try: # this will raise an IOError if the file is not readable im.getdata()[0] except IOError as e: site = "http://pillow.readthedocs.org/en/latest/installation.html#external-libraries" pillow_error_message = str(e) error_message = ('Could not load "%s" \n' 'Reason: "%s"\n' 'Please see documentation at: %s' % (im.filename, pillow_error_message, site)) raise ValueError(error_message) frames = [] grayscale = None i = 0 while 1: try: im.seek(i) except EOFError: break frame = im if img_num is not None and img_num != i: im.getdata()[0] i += 1 continue if im.format == 'PNG' and im.mode == 'I' and dtype is None: dtype = 'uint16' if im.mode == 'P': if grayscale is None: grayscale = _palette_is_grayscale(im) if grayscale: frame = im.convert('L') else: if im.format == 'PNG' and 'transparency' in im.info: frame = im.convert('RGBA') else: frame = im.convert('RGB') elif im.mode == '1': frame = im.convert('L') elif 'A' in im.mode: frame = im.convert('RGBA') elif im.mode == 'CMYK': frame = im.convert('RGB') if im.mode.startswith('I;16'): shape = im.size dtype = '>u2' if im.mode.endswith('B') else '<u2' if 'S' in im.mode: dtype = dtype.replace('u', 'i') frame = np.fromstring(frame.tobytes(), dtype) frame.shape = shape[::-1] else: frame = np.array(frame, dtype=dtype) frames.append(frame) i += 1 if img_num is not None: break if hasattr(im, 'fp') and im.fp: im.fp.close() if img_num is None and len(frames) > 1: return np.array(frames) elif frames: return frames[0] elif img_num: raise IndexError('Could not find image #%s' % img_num) def _palette_is_grayscale(pil_image): """Return True if PIL image in palette mode is grayscale. Parameters ---------- pil_image : PIL image PIL Image that is in Palette mode. Returns ------- is_grayscale : bool True if all colors in image palette are gray. """ assert pil_image.mode == 'P' # get palette as an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used; unused colors have junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop] # Image is grayscale if channel differences (R - G and G - B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def ndarray_to_pil(arr, format_str=None): """Export an ndarray to a PIL object. Parameters ---------- Refer to ``imsave``. """ if arr.ndim == 3: arr = img_as_ubyte(arr) mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] elif format_str in ['png', 'PNG']: mode = 'I;16' mode_base = 'I' if arr.dtype.kind == 'f': arr = img_as_uint(arr) elif arr.max() < 256 and arr.min() >= 0: arr = arr.astype(np.uint8) mode = mode_base = 'L' else: arr = img_as_uint(arr) else: arr = img_as_ubyte(arr) mode = 'L' mode_base = 'L' try: array_buffer = arr.tobytes() except AttributeError: array_buffer = arr.tostring() # Numpy < 1.9 if arr.ndim == 2: im = Image.new(mode_base, arr.T.shape) try: im.frombytes(array_buffer, 'raw', mode) except AttributeError: im.fromstring(array_buffer, 'raw', mode) # PIL 1.1.7 else: image_shape = (arr.shape[1], arr.shape[0]) try: im = Image.frombytes(mode, image_shape, array_buffer) except AttributeError: im = Image.fromstring(mode, image_shape, array_buffer) # PIL 1.1.7 return im def imsave(fname, arr, format_str=None, **kwargs): """Save an image to disk. Parameters ---------- fname : str or file-like object Name of destination file. arr : ndarray of uint8 or float Array (image) to save. Arrays of data-type uint8 should have values in [0, 255], whereas floating-point arrays must be in [0, 1]. format_str: str Format to save as, this is defaulted to PNG if using a file-like object; this will be derived from the extension if fname is a string kwargs: dict Keyword arguments to the Pillow save function (or tifffile save function, for Tiff files). These are format dependent. For example, Pillow's JPEG save function supports an integer ``quality`` argument with values in [1, 95], while TIFFFile supports a ``compress`` integer argument with values in [0, 9]. Notes ----- Use the Python Imaging Libary. See PIL docs [1]_ for a list of other supported formats. All images besides single channel PNGs are converted using `img_as_uint8`. Single Channel PNGs have the following behavior: - Integer values in [0, 255] and Boolean types -> img_as_uint8 - Floating point and other integers -> img_as_uint16 References ---------- .. [1] http://pillow.readthedocs.org/en/latest/handbook/image-file-formats.html """ # default to PNG if file-like object if not isinstance(fname, string_types) and format_str is None: format_str = "PNG" # Check for png in filename if (isinstance(fname, string_types) and fname.lower().endswith(".png")): format_str = "PNG" arr = np.asanyarray(arr) if arr.dtype.kind == 'b': arr = arr.astype(np.uint8) if arr.ndim not in (2, 3): raise ValueError("Invalid shape for image array: %s" % arr.shape) if arr.ndim == 3: if arr.shape[2] not in (3, 4): raise ValueError("Invalid number of channels in image array.") img = ndarray_to_pil(arr, format_str=format_str) img.save(fname, format=format_str, **kwargs)
{ "repo_name": "pratapvardhan/scikit-image", "path": "skimage/io/_plugins/pil_plugin.py", "copies": "15", "size": "7726", "license": "bsd-3-clause", "hash": 7467518209125070000, "line_mean": 28.7153846154, "line_max": 93, "alpha_frac": 0.56549314, "autogenerated": false, "ratio": 3.743217054263566, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": null, "num_lines": null }
__all__ = ['imread'] import numpy as np try: from PIL import Image except ImportError: raise ImportError("The Python Image Library could not be found. " "Please refer to http://pypi.python.org/pypi/PIL/ " "for further instructions.") def imread(fname, dtype=None): """Load an image from file. """ im = Image.open(fname) if im.mode == 'P': if _palette_is_grayscale(im): im = im.convert('L') else: im = im.convert('RGB') if 'A' in im.mode: im = im.convert('RGBA') return np.array(im, dtype=dtype) def _palette_is_grayscale(pil_image): """Return True if PIL image in palette mode is grayscale. Parameters ---------- pil_image : PIL image PIL Image that is in Palette mode. Returns ------- is_grayscale : bool True if all colors in image palette are gray. """ assert pil_image.mode == 'P' # get palette as an array with R, G, B columns palette = np.asarray(pil_image.getpalette()).reshape((256, 3)) # Not all palette colors are used; unused colors have junk values. start, stop = pil_image.getextrema() valid_palette = palette[start:stop] # Image is grayscale if channel differences (R - G and G - B) # are all zero. return np.allclose(np.diff(valid_palette), 0) def imsave(fname, arr): """Save an image to disk. Parameters ---------- fname : str Name of destination file. arr : ndarray of uint8 or float Array (image) to save. Arrays of data-type uint8 should have values in [0, 255], whereas floating-point arrays must be in [0, 1]. Notes ----- Currently, only 8-bit precision is supported. """ arr = np.asarray(arr).squeeze() if arr.ndim not in (2, 3): raise ValueError("Invalid shape for image array: %s" % arr.shape) if arr.ndim == 3: if arr.shape[2] not in (3, 4): raise ValueError("Invalid number of channels in image array.") # Image is floating point, assume in [0, 1] if np.issubdtype(arr.dtype, float): arr = arr * 255 arr = arr.astype(np.uint8) if arr.ndim == 2: mode = 'L' elif arr.shape[2] in (3, 4): mode = {3: 'RGB', 4: 'RGBA'}[arr.shape[2]] # Force all integers to bytes arr = arr.astype(np.uint8) img = Image.fromstring(mode, (arr.shape[1], arr.shape[0]), arr.tostring()) img.save(fname) def imshow(arr): """Display an image, using PIL's default display command. Parameters ---------- arr : ndarray Image to display. Images of dtype float are assumed to be in [0, 1]. Images of dtype uint8 are in [0, 255]. """ if np.issubdtype(arr.dtype, float): arr = (arr * 255).astype(np.uint8) Image.fromarray(arr).show()
{ "repo_name": "GaelVaroquaux/scikits.image", "path": "scikits/image/io/_plugins/pil_plugin.py", "copies": "1", "size": "2886", "license": "bsd-3-clause", "hash": -7233221457519247000, "line_mean": 25.7222222222, "line_max": 78, "alpha_frac": 0.5838530839, "autogenerated": false, "ratio": 3.5940224159402243, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9670511423448176, "avg_score": 0.0014728152784096722, "num_lines": 108 }
__all__ = ['Index'] import os import sys import mmap import struct class Index(object): def __init__(self, sstable, t, columns, path=None): self.sstable = sstable self.t = t self.columns = columns self.mm = None self.f = None def get_path(self): table = self.sstable.table filename = 'index-%s-%s.data' % (self.t, '-'.join(self.columns)) path = os.path.join(table.get_path(), filename) return path def open(self): ''' Open file for reading. ''' self.f = open(self.get_path(), 'r+b') self.mm = mmap.mmap(self.f.fileno(), 0) def close(self): ''' Open file for reading. ''' self.mm.close() self.f.close() def w_open(self): ''' Open file for writing. ''' self.f = open(self.get_path(), 'wb') def w_close(self): ''' Close file for writing. ''' self.f.close() def _write_key(self, row, sstable_pos): table = self.sstable.table key_blob_items = [] for c in self.columns: t = table.schema[c] b = t._get_column_packed(row[c]) key_blob_items.append(b) key_blob = b''.join(key_blob_items) pos_blob = struct.pack('!Q', sstable_pos) self.f.write(key_blob) self.f.write(pos_blob) def _read_key(self, pos): table = self.sstable.table key = [] p = pos for c in self.columns: t = table.schema[c] v, p = t._get_column_unpacked(self.mm, p) key.append(v) key = tuple(key) sstable_pos, = struct.unpack_from('!Q', self.mm, p) return key, sstable_pos def _get_key_size(self, key): table = self.sstable.table size = 0 for c in self.columns: t = table.schema[c] i = self.columns.index(c) s = t._get_column_size(key[i]) size += s return size def get_sstable_pos(self, key): sstable = self.sstable table = self.sstable.table step = 8 + self._get_key_size(key) # !Q + KEY # binary search low = 0 high = (self.mm.size() // step) - 1 key_pos = None offset_pos = None while low <= high: mid = (low + high) // 2 key_pos = mid * step offset_pos = mid cur_key, sstable_pos = self._read_key(key_pos) # print 'cur_key:', cur_key if cur_key > key: high = mid - 1 elif cur_key < key: low = mid + 1 else: break else: sstable_pos = None return offset_pos, sstable_pos def get_lt_sstable_pos(self, key): sstable = self.sstable table = self.sstable.table step = 8 + self._get_key_size(key) # !Q + KEY # binary search low = 0 high = (self.mm.size() // step) - 1 key_pos = None while low < high: mid = (low + high) // 2 key_pos = mid * step cur_key, sstable_pos = self._read_key(key_pos) # print 'left cur_key:', cur_key _key = tuple(x for x, y in zip(key, cur_key) if x != None) _cur_key = tuple(y for x, y in zip(key, cur_key) if x != None) if _cur_key < _key: low = mid + 1 else: high = mid offset_pos = low - 1 _, sstable_pos = self._read_key(offset_pos * step) return offset_pos, sstable_pos def get_le_sstable_pos(self, key): sstable = self.sstable table = self.sstable.table step = 8 + self._get_key_size(key) # !Q + KEY # binary search low = 0 high = (self.mm.size() // step) - 1 key_pos = None while low < high: mid = (low + high) // 2 key_pos = mid * step cur_key, sstable_pos = self._read_key(key_pos) # print 'left cur_key:', cur_key _key = tuple(x for x, y in zip(key, cur_key) if x != None) _cur_key = tuple(y for x, y in zip(key, cur_key) if x != None) if _key < _cur_key: high = mid else: low = mid + 1 offset_pos = low - 1 _, sstable_pos = self._read_key(offset_pos * step) return offset_pos, sstable_pos def get_gt_sstable_pos(self, key): sstable = self.sstable table = self.sstable.table step = 8 + self._get_key_size(key) # !Q + KEY # binary search low = 0 high = (self.mm.size() // step) - 1 key_pos = None while low < high: mid = (low + high) // 2 key_pos = mid * step cur_key, sstable_pos = self._read_key(key_pos) # print 'left cur_key:', cur_key _key = tuple(x for x, y in zip(key, cur_key) if x != None) _cur_key = tuple(y for x, y in zip(key, cur_key) if x != None) if _key < _cur_key: high = mid else: low = mid + 1 offset_pos = low _, sstable_pos = self._read_key(offset_pos * step) return offset_pos, sstable_pos def get_ge_sstable_pos(self, key): sstable = self.sstable table = self.sstable.table step = 8 + self._get_key_size(key) # !Q + KEY # binary search low = 0 high = (self.mm.size() // step) - 1 key_pos = None while low < high: mid = (low + high) // 2 key_pos = mid * step cur_key, sstable_pos = self._read_key(key_pos) # print 'left cur_key:', cur_key _key = tuple(x for x, y in zip(key, cur_key) if x != None) _cur_key = tuple(y for x, y in zip(key, cur_key) if x != None) if _cur_key < _key: low = mid + 1 else: high = mid offset_pos = low _, sstable_pos = self._read_key(offset_pos * step) return offset_pos, sstable_pos
{ "repo_name": "yadb/yadb", "path": "backup/store/index.py", "copies": "1", "size": "6298", "license": "mit", "hash": -986041783436472700, "line_mean": 26.7444933921, "line_max": 74, "alpha_frac": 0.4680851064, "autogenerated": false, "ratio": 3.530269058295964, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4498354164695964, "avg_score": null, "num_lines": null }
__all__ = ['IndraDBRestSearchProcessor', 'IndraDBRestHashProcessor'] import logging from copy import deepcopy from threading import Thread from datetime import datetime from collections import OrderedDict, defaultdict from indra.statements import stmts_from_json, get_statement_by_name, \ get_all_descendants from indra.sources.indra_db_rest.util import submit_query_request, \ submit_statement_request from indra.sources.indra_db_rest.exceptions import IndraDBRestResponseError from indra.util.statement_presentation import get_available_source_counts, \ get_available_ev_counts, standardize_counts logger = logging.getLogger(__name__) class RemoveParam(object): pass class IndraDBRestProcessor(object): """The generalized packaging for query responses. General Parameters ------------------ timeout : positive int or None If an int, block until the work is done and statements are retrieved, or until the timeout has expired, in which case the results so far will be returned in the response object, and further results will be added in a separate thread as they become available. If simple_response is True, all statements available will be returned. Otherwise (if None), block indefinitely until all statements are retrieved. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 10. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. max_stmts : int or None Select the maximum number of statements to return. When set less than 1000 the effect is much the same as setting persist to false, and will guarantee a faster response. Default is None. use_obtained_counts : Optional[bool] If set to True, the statement evidence counts and source counts are calculated based on the actual obtained statements and evidences rather than the counts provided by the DB API. Default: False. Attributes ---------- statements : list[:py:class:`indra.statements.Statement`] A list of INDRA Statements that will be filled once all queries have been completed. """ _override_default_api_params = {} def __init__(self, *args, **kwargs): self.statements = [] self.__statement_jsons = {} self.__evidence_counts = {} self.__source_counts = {} self.use_obtained_counts = kwargs.pop('use_obtained_counts', False) # Define the basic generic defaults. default_api_params = dict(timeout=None, ev_limit=10, best_first=True, tries=2, max_stmts=None) # Update with any overrides. default_api_params.update(self._override_default_api_params) # Some overrides may be RemoveParam objects, indicating the key should # be removed. Filter those out. default_api_params = {k: v for k, v in default_api_params.items() if not isinstance(v, RemoveParam)} # Update the kwargs to include these default values, if not already # specified by the user. kwargs.update((k, kwargs.get(k, default_api_params[k])) for k in default_api_params.keys()) self._run(*args, **kwargs) return def get_ev_count(self, stmt): """Get the total evidence count for a statement.""" return self.get_ev_count_by_hash(stmt.get_hash(shallow=True)) def get_ev_count_by_hash(self, stmt_hash): """Get the total evidence count for a statement hash.""" return self.__evidence_counts.get(stmt_hash, 0) def get_source_counts(self): """Get the source counts as a dict per statement hash.""" return deepcopy(self.__source_counts) def get_source_count(self, stmt): """Get the source counts for a given statement.""" return self.get_source_count_by_hash(stmt.get_hash(shallow=True)) def get_source_count_by_hash(self, stmt_hash): """Get the source counts for a given statement.""" return self.__source_counts.get(stmt_hash, {}) def get_ev_counts(self): """Get a dictionary of evidence counts.""" return self.__evidence_counts.copy() def get_hash_statements_dict(self): """Return a dict of Statements keyed by hashes.""" res = {stmt_hash: stmts_from_json([stmt])[0] for stmt_hash, stmt in self.__statement_jsons.items()} return res def merge_results(self, other_processor): """Merge the results of this processor with those of another.""" if not isinstance(other_processor, self.__class__): raise ValueError("Can only extend with another %s instance." % self.__class__.__name__) self.statements.extend(other_processor.statements) self._merge_json(other_processor.__statement_jsons, other_processor.__evidence_counts, other_processor.__source_counts) return def _merge_json(self, stmt_json, ev_counts, source_counts): """Merge these statement jsons with new jsons.""" # Where there is overlap, there _should_ be agreement. self.__evidence_counts.update(standardize_counts(ev_counts)) # We turn source counts into an int-keyed dict and update it that way self.__source_counts.update(standardize_counts(source_counts)) for k, sj in stmt_json.items(): if k not in self.__statement_jsons: self.__statement_jsons[k] = sj # This should be most of them else: # This should only happen rarely. for evj in sj['evidence']: self.__statement_jsons[k]['evidence'].append(evj) return def _compile_statements(self): """Generate statements from the jsons.""" self.statements = stmts_from_json(self.__statement_jsons.values()) if self.use_obtained_counts: self.__source_counts = get_available_source_counts(self.statements) self.__evidence_counts = get_available_ev_counts(self.statements) def _unload_and_merge_resp(self, resp): resp_dict = resp.json(object_pairs_hook=OrderedDict) stmts_json = resp_dict['statements'] ev_totals = resp_dict['evidence_totals'] source_counts = resp_dict['source_counts'] eos = resp_dict['end_of_statements'] limit = resp_dict['statement_limit'] num_returned = resp_dict['statements_returned'] # Update the result self._merge_json(stmts_json, ev_totals, source_counts) return eos, num_returned, limit def _run(self, *args, **kwargs): raise NotImplementedError("_run must be defined in subclass.") class IndraDBRestHashProcessor(IndraDBRestProcessor): """The packaging and processor for hash lookup of statements. Parameters ---------- hash_list : list[int or str] A list of the matches-key hashes for the statements you want to get. Keyword Parameters ------------------ timeout : positive int or None If an int, block until the work is done and statements are retrieved, or until the timeout has expired, in which case the results so far will be returned in the response object, and further results will be added in a separate thread as they become available. If simple_response is True, all statements available will be returned. Otherwise (if None), block indefinitely until all statements are retrieved. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 100. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. Attributes ---------- statements : list[:py:class:`indra.statements.Statement`] A list of INDRA Statements that will be filled once all queries have been completed. """ _default_api_params = {'ev_limit': 100, 'max_stmts': RemoveParam()} def _run(self, hash_list, **api_params): # Make sure the input is a list (not just a single hash). if not isinstance(hash_list, list): raise ValueError("The `hash_list` input is a list, not %s." % type(hash_list)) # If there is nothing in the list, don't waste time with a query. if not hash_list: return # Regularize and check the types of elements in the hash list. if isinstance(hash_list[0], str): hash_list = [int(h) for h in hash_list] if not all([isinstance(h, int) for h in hash_list]): raise ValueError("Hashes must be ints or strings that can be " "converted into ints.") # Execute the query and load the results. resp = submit_statement_request('post', 'from_hashes', data={'hashes': hash_list}, **api_params) self._unload_and_merge_resp(resp) self._compile_statements() return class IndraDBRestPaperProcessor(IndraDBRestProcessor): """The packaging and processor for hash lookup of statements. Parameters ---------- ids : list[(<id type>, <id value>)] A list of tuples with ids and their type. The type can be any one of 'pmid', 'pmcid', 'doi', 'pii', 'manuscript id', or 'trid', which is the primary key id of the text references in the database. Keyword Parameters ------------------ timeout : positive int or None If an int, block until the work is done and statements are retrieved, or until the timeout has expired, in which case the results so far will be returned in the response object, and further results will be added in a separate thread as they become available. If simple_response is True, all statements available will be returned. Otherwise (if None), block indefinitely until all statements are retrieved. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 100. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. max_stmts : int or None Select the maximum number of statements to return. When set less than 1000 the effect is much the same as setting persist to false, and will guarantee a faster response. Default is None. Attributes ---------- statements : list[:py:class:`indra.statements.Statement`] A list of INDRA Statements that will be filled once all queries have been completed. """ def _run(self, ids, **api_params): id_l = [{'id': id_val, 'type': id_type} for id_type, id_val in ids] resp = submit_statement_request('post', 'from_papers', data={'ids': id_l}, **api_params) self._unload_and_merge_resp(resp) self._compile_statements() return class IndraDBRestSearchProcessor(IndraDBRestProcessor): """The packaging for agent and statement type search query responses. Parameters ---------- subject/object : str Optionally specify the subject and/or object of the statements in you wish to get from the database. By default, the namespace is assumed to be HGNC gene names, however you may specify another namespace by including `@<namespace>` at the end of the name string. For example, if you want to specify an agent by chebi, you could use `CHEBI:6801@CHEBI`, or if you wanted to use the HGNC id, you could use `6871@HGNC`. agents : list[str] A list of agents, specified in the same manner as subject and object, but without specifying their grammatical position. stmt_type : str Specify the types of interactions you are interested in, as indicated by the sub-classes of INDRA's Statements. This argument is *not* case sensitive. If the statement class given has sub-classes (e.g. RegulateAmount has IncreaseAmount and DecreaseAmount), then both the class itself, and its subclasses, will be queried, by default. If you do not want this behavior, set use_exact_type=True. Note that if max_stmts is set, it is possible only the exact statement type will be returned, as this is the first searched. The processor then cycles through the types, getting a page of results for each type and adding it to the quota, until the max number of statements is reached. use_exact_type : bool If stmt_type is given, and you only want to search for that specific statement type, set this to True. Default is False. persist : bool Default is True. When False, if a query comes back limited (not all results returned), just give up and pass along what was returned. Otherwise, make further queries to get the rest of the data (which may take some time). Keyword Parameters ------------------ timeout : positive int or None If an int, block until the work is done and statements are retrieved, or until the timeout has expired, in which case the results so far will be returned in the response object, and further results will be added in a separate thread as they become available. If simple_response is True, all statements available will be returned. Otherwise (if None), block indefinitely until all statements are retrieved. Default is None. ev_limit : int or None Limit the amount of evidence returned per Statement. Default is 10. best_first : bool If True, the preassembled statements will be sorted by the amount of evidence they have, and those with the most evidence will be prioritized. When using `max_stmts`, this means you will get the "best" statements. If False, statements will be queried in arbitrary order. tries : int > 0 Set the number of times to try the query. The database often caches results, so if a query times out the first time, trying again after a timeout will often succeed fast enough to avoid a timeout. This can also help gracefully handle an unreliable connection, if you're willing to wait. Default is 2. max_stmts : int or None Select the maximum number of statements to return. When set less than 1000 the effect is much the same as setting persist to false, and will guarantee a faster response. Default is None. Attributes ---------- statements : list[:py:class:`indra.statements.Statement`] A list of INDRA Statements that will be filled once all queries have been completed. statements_sample : list[:py:class:`indra.statements.Statement`] A list of the INDRA Statements received from the first query. In general these will be the "best" (currently this means they have the most evidence) Statements available. """ def __init__(self, *args, **kwargs): self.statements_sample = None super(self.__class__, self).__init__(*args, **kwargs) return def is_working(self): """Check if the thread is running.""" if not self.__th: return False return self.__th.is_alive() def wait_until_done(self, timeout=None): """Wait for the background load to complete.""" start = datetime.now() if not self.__th: raise IndraDBRestResponseError("There is no thread waiting to " "complete.") self.__th.join(timeout) now = datetime.now() dt = now - start if self.__th.is_alive(): logger.warning("Timed out after %0.3f seconds waiting for " "statement load to complete." % dt.total_seconds()) ret = False else: logger.info("Waited %0.3f seconds for statements to finish" "loading." % dt.total_seconds()) ret = True return ret def _all_done(self): every_type_done = (len(self.__done_dict) > 0 and all(self.__done_dict.values())) quota_done = (self.__quota is not None and self.__quota <= 0) return every_type_done or quota_done def _query_and_extract(self, agent_strs, params, stmt_type=None): assert not self._all_done(), "Tried to run query but I'm done!" params['offset'] = self.__page_dict[stmt_type] params['max_stmts'] = self.__quota if stmt_type is not None: params['type'] = stmt_type resp = submit_query_request('from_agents', *agent_strs, **params) eos, num_returned, page_step = self._unload_and_merge_resp(resp) # NOTE: this is technically not a direct conclusion, and could be # wrong, resulting in a single unnecessary extra query, but that # should almost never happen, and if it does, it isn't the end of # the world. self.__done_dict[stmt_type] = eos # Update the quota if self.__quota is not None: self.__quota -= num_returned # Increment the page self.__page_dict[stmt_type] += page_step return def _query_over_statement_types(self, agent_strs, stmt_types, params): if not stmt_types: self._query_and_extract(agent_strs, params.copy()) else: for stmt_type in stmt_types: if self.__done_dict[stmt_type]: continue self._query_and_extract(agent_strs, params.copy(), stmt_type) # Check the quota if self.__quota is not None and self.__quota <= 0: break return def _run_queries(self, agent_strs, stmt_types, params, persist): """Use paging to get all statements requested.""" self._query_over_statement_types(agent_strs, stmt_types, params) assert len(self.__done_dict) == len(stmt_types) \ or None in self.__done_dict.keys(), \ "Done dict was not initiated for all stmt_type's." # Check if we want to keep going. if not persist: self._compile_statements() return # Get the rest of the content. while not self._all_done(): self._query_over_statement_types(agent_strs, stmt_types, params) # Create the actual statements. self._compile_statements() return def merge_results(self, other_processor): super(self.__class__, self).merge_results(other_processor) if other_processor.statements_sample is not None: if self.statements_sample is None: self.statements_sample = other_processor.statements_sample else: self.statements_sample.extend(other_processor.statements_sample) def _merge_json(self, stmt_json, ev_counts, source_counts): super(self.__class__, self)._merge_json(stmt_json, ev_counts, source_counts) if not self.__started: self.statements_sample = stmts_from_json(stmt_json.values()) self.__started = True return def _run(self, subject=None, object=None, agents=None, stmt_type=None, use_exact_type=False, persist=True, strict_stop=False, **api_params): self.__started = False self.__done_dict = defaultdict(lambda: False) self.__page_dict = defaultdict(lambda: 0) self.__th = None self.__quota = api_params['max_stmts'] # Make sure we got at least SOME agents (the remote API will error if # we proceed with no arguments). if subject is None and object is None and not agents: raise ValueError("At least one agent must be specified, or else " "the scope will be too large.") # Make timeouts apply differently in this case if not strict_stop: timeout = api_params.pop('timeout', None) else: timeout = api_params.get('timeout', None) # Formulate inputs for the agents.. key_val_list = [('subject', subject), ('object', object)] params = {param_key: param_val for param_key, param_val in key_val_list if param_val is not None} params.update(api_params) agent_strs = [] if agents is None else ['agent%d=%s' % (i, ag) for i, ag in enumerate(agents)] # Handle the type(s). stmt_types = [stmt_type] if stmt_type else [] if stmt_type is not None and not use_exact_type: stmt_class = get_statement_by_name(stmt_type) descendant_classes = get_all_descendants(stmt_class) stmt_types += [cls.__name__ for cls in descendant_classes] # Handle the content if we were limited. args = [agent_strs, stmt_types, params, persist] logger.debug("The remainder of the query will be performed in a " "thread...") self.__th = Thread(target=self._run_queries, args=args) self.__th.start() if timeout is None: logger.debug("Waiting for thread to complete...") self.__th.join() elif timeout: # is not 0 logger.debug("Waiting at most %d seconds for thread to complete..." % timeout) self.__th.join(timeout) return
{ "repo_name": "johnbachman/belpy", "path": "indra/sources/indra_db_rest/processor.py", "copies": "1", "size": "23664", "license": "mit", "hash": -2581718736399459300, "line_mean": 43.3977485929, "line_max": 80, "alpha_frac": 0.6271974307, "autogenerated": false, "ratio": 4.341221794166208, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5468419224866208, "avg_score": null, "num_lines": null }
__all__ = ["infantry_bot", "heavy_bot", "rocket_bot"] from .tools import create_unit INFANTRY_BOT_BASIS = { 'c_size': 1, 'firing_range': 4, 'rate_of_fire': 1, 'speed': 5, 'type': 'infantryBot' } INFANTRY_BOTS = { 1: dict(damage_per_shot=50, hit_points=120, **INFANTRY_BOT_BASIS), 2: dict(damage_per_shot=60, hit_points=150, **INFANTRY_BOT_BASIS), 3: dict(damage_per_shot=75, hit_points=200, **INFANTRY_BOT_BASIS), } HEAVY_BOT_BASIS = { 'c_size': 4, 'firing_range': 2.5, 'rate_of_fire': 10, 'speed': 3, 'type': 'heavyBot' } HEAVY_BOTS = { 1: dict(damage_per_shot=10, hit_points=1000, **HEAVY_BOT_BASIS), 2: dict(damage_per_shot=13, hit_points=1200, **HEAVY_BOT_BASIS), 3: dict(damage_per_shot=16, hit_points=1400, **HEAVY_BOT_BASIS), } ROCKET_BOT_BASIS = { 'c_size': 2, 'firing_range': 8, 'rate_of_fire': 0.5, 'speed': 4, 'type': 'rocketBot' } ROCKET_BOTS = { 1: dict(damage_per_shot=150, hit_points=50, **ROCKET_BOT_BASIS), 2: dict(damage_per_shot=200, hit_points=60, **ROCKET_BOT_BASIS), 3: dict(damage_per_shot=300, hit_points=80, **ROCKET_BOT_BASIS), } def infantry_bot(level: int) -> dict: return create_unit(INFANTRY_BOTS, level) def heavy_bot(level: int) -> dict: return create_unit(HEAVY_BOTS, level) def rocket_bot(level: int) -> dict: return create_unit(ROCKET_BOTS, level)
{ "repo_name": "CheckiO/EoC-battle-mocks", "path": "battle_mocks/units.py", "copies": "1", "size": "1404", "license": "mit", "hash": -2247354539715590000, "line_mean": 23.6315789474, "line_max": 70, "alpha_frac": 0.6160968661, "autogenerated": false, "ratio": 2.3837011884550083, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.34997980545550084, "avg_score": null, "num_lines": null }
__all__ = ["InitLogging", \ "VLOG", \ "DEBUG", \ "INFO", \ "WARNING", \ "ERROR", \ "CRITICAL"] import time import sys import logging import copy DEFAULT_LOGGER_NAME = "\033[1;42m" + "Log" + "\033[1;0m" DEBUG = 0 INFO = 1 WARNING = 2 ERROR = 3 CRITICAL = 4 """ InitLogging should only be invoked on main thread, aka before the http handler, and we only use one true logger whose name is set by "DEFAULT_LOGGER_NAME", wherever need a log you just call VLOG(), the only logger is global scoped """ def InitLogging(opts): logging.addLevelName(logging.DEBUG, "\033[1;44m%s\033[1;0m" % logging.getLevelName(logging.DEBUG)) logging.addLevelName(logging.INFO, "\033[1;45m%s\033[1;0m" % logging.getLevelName(logging.INFO)) logging.addLevelName(logging.WARNING, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.WARNING)) logging.addLevelName(logging.ERROR, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.ERROR)) logging.addLevelName(logging.CRITICAL, "\033[1;41m%s\033[1;0m" % logging.getLevelName(logging.CRITICAL)) g_level = logging.DEBUG if '--verbose' in sys.argv: g_level = logging.DEBUG if '--silent' in sys.argv: g_level = logging.NOTSET logger = logging.getLogger(DEFAULT_LOGGER_NAME) logger.setLevel(g_level) g_start_time = time.asctime() g_formatter = logging.Formatter('\033[1;33m%(asctime)s\033[1;0m %(name)s %(levelname)s %(message)s') if opts.log_path: try: log_file = open(opts.log_path, "w") except: print "Failed to redirect stderr to log file" return False sys.stderr = log_file # create a handler to write the log to a given file fh = logging.FileHandler(log_path) fh.setLevel(g_level) fh.setFormatter(g_formatter) logger.addHandler(fh) # we direct the log information to stdout ch = logging.StreamHandler(sys.__stdout__) ch.setLevel(g_level) ch.setFormatter(g_formatter) logger.addHandler(ch) return True # dispatch difference level to logger created by InitLogging() def VLOG(level, msg): logger = logging.getLogger(DEFAULT_LOGGER_NAME) if level == DEBUG: logger.debug('\033[1;34m' + msg + '\033[1;0m') elif level == INFO: logger.info('\033[1;35m' + msg + '\033[1;0m') elif level == WARNING: logger.warning('\033[1;31m' + msg + '\033[1;0m') elif level == ERROR: logger.error('\033[1;31m' + msg + '\033[1;0m') elif level == CRITICAL: logger.critical('\033[1;31m' + msg + '\033[1;0m') else: logger.debug('\033[1;34m' + msg + '\033[1;0m') return
{ "repo_name": "PeterWangIntel/crosswalk-webdriver-python", "path": "base/log.py", "copies": "1", "size": "2586", "license": "bsd-3-clause", "hash": -5982681547423919000, "line_mean": 31.325, "line_max": 106, "alpha_frac": 0.6573859242, "autogenerated": false, "ratio": 3.0822407628128725, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9066670373381962, "avg_score": 0.03459126272618212, "num_lines": 80 }
__all__ = ['inject', 'signature'] import os import sys def _ensure_path(p): p = os.path.realpath(p) if isinstance(p, unicode): p = p.encode(sys.getfilesystemencoding()) return p def inject(pid, bundle, useMainThread=True): """Loads the given MH_BUNDLE in the target process identified by pid""" try: from _objc import _inject from _dyld import dyld_find except ImportError: raise NotImplementedError("objc.inject is only supported on Mac OS X 10.3 and later") bundlePath = bundle systemPath = dyld_find('/usr/lib/libSystem.dylib') carbonPath = dyld_find('/System/Library/Frameworks/Carbon.framework/Carbon') paths = map(_ensure_path, (bundlePath, systemPath, carbonPath)) return _inject( pid, useMainThread, *paths ) def signature(signature, **kw): """ A Python method decorator that allows easy specification of Objective-C selectors. Usage:: @objc.signature('i@:if') def methodWithX_andY_(self, x, y): return 0 """ from _objc import selector kw['signature'] = signature def makeSignature(func): return selector(func, **kw) return makeSignature
{ "repo_name": "rays/ipodderx-core", "path": "objc/_functions.py", "copies": "1", "size": "1236", "license": "mit", "hash": -1470164344321094100, "line_mean": 27.0909090909, "line_max": 93, "alpha_frac": 0.6359223301, "autogenerated": false, "ratio": 3.850467289719626, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4986389619819626, "avg_score": null, "num_lines": null }
"""All in one NTM. Encapsulation of all components.""" import torch from torch import nn from .ntm import NTM from .controller import LSTMController from .head import NTMReadHead, NTMWriteHead from .memory import NTMMemory class EncapsulatedNTM(nn.Module): def __init__(self, num_inputs, num_outputs, controller_size, controller_layers, num_heads, N, M): """Initialize an EncapsulatedNTM. :param num_inputs: External number of inputs. :param num_outputs: External number of outputs. :param controller_size: The size of the internal representation. :param controller_layers: Controller number of layers. :param num_heads: Number of heads. :param N: Number of rows in the memory bank. :param M: Number of cols/features in the memory bank. """ super(EncapsulatedNTM, self).__init__() # Save args self.num_inputs = num_inputs self.num_outputs = num_outputs self.controller_size = controller_size self.controller_layers = controller_layers self.num_heads = num_heads self.N = N self.M = M # Create the NTM components memory = NTMMemory(N, M) controller = LSTMController(num_inputs + M*num_heads, controller_size, controller_layers) heads = nn.ModuleList([]) for i in range(num_heads): heads += [ NTMReadHead(memory, controller_size), NTMWriteHead(memory, controller_size) ] self.ntm = NTM(num_inputs, num_outputs, controller, memory, heads) self.memory = memory def init_sequence(self, batch_size): """Initializing the state.""" self.batch_size = batch_size self.memory.reset(batch_size) self.previous_state = self.ntm.create_new_state(batch_size) def forward(self, x=None): if x is None: x = torch.zeros(self.batch_size, self.num_inputs) o, self.previous_state = self.ntm(x, self.previous_state) return o, self.previous_state def calculate_num_params(self): """Returns the total number of parameters.""" num_params = 0 for p in self.parameters(): num_params += p.data.view(-1).size(0) return num_params
{ "repo_name": "loudinthecloud/pytorch-ntm", "path": "ntm/aio.py", "copies": "1", "size": "2311", "license": "bsd-3-clause", "hash": -637902669801121200, "line_mean": 34.0151515152, "line_max": 97, "alpha_frac": 0.622674167, "autogenerated": false, "ratio": 3.923599320882852, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5046273487882852, "avg_score": null, "num_lines": null }
__all__ = ['input', 'middleware'] ''' a middleware to build http params ''' '''#makingitpossible no file uploads handled yet ''' import io, cgi, collections def middleware(app): def process_fieldstorage(fieldstorage): ''' not processing file uploads ''' return isinstance(fieldstorage, list) and [process_fieldstorage(fs) for fs in fieldstorage] or fieldstorage.value def input_app(environ): if environ['REQUEST_METHOD'] in ('POST', 'PUT'): length = int(environ.get('CONTENT_LENGTH', '0')) environ['data'] = data = environ['wsgi.input'].read(length) data_input = cgi.FieldStorage(fp=io.BytesIO(data), environ=environ, keep_blank_values=True, encoding='utf8') environ['input'] = {key: process_fieldstorage(data_input[key]) for key in data_input.keys()} else: query_input = cgi.FieldStorage(environ=environ, keep_blank_values=True) environ['input'] = {key: process_fieldstorage(query_input[key]) for key in query_input.keys()} return app(environ) return input_app def input(): return middleware
{ "repo_name": "web-i/ripplet", "path": "ripple/middlewares/input.py", "copies": "1", "size": "1064", "license": "mit", "hash": -9081010112236003000, "line_mean": 37, "line_max": 117, "alpha_frac": 0.6898496241, "autogenerated": false, "ratio": 3.668965517241379, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48588151413413794, "avg_score": null, "num_lines": null }
__all__ = ['INPUT', 'OUTPUT', 'INOUT'] __all__ += ['flip'] __all__ += ['Port'] INPUT = 'input' OUTPUT = 'output' INOUT = 'inout' def flip(direction): assert direction in [INPUT, OUTPUT, INOUT] if direction == INPUT: return OUTPUT elif direction == OUTPUT: return INPUT elif direction == INOUT: return INOUT def mergewires(new, old): for i in old.inputs: if i not in new.inputs: new.inputs.append(i) i.wires = new for o in old.outputs: if o not in new.outputs: if len(new.outputs) > 0: print("Error: connecting more than one output to an input", o) new.outputs.append(o) o.wires = new # # A Wire has a list of input and output Ports. # class Wire: def __init__(self): self.inputs = [] self.outputs = [] def connect( self, o, i ): # anon Ports are added to the input or output list of this wire # # connecting to a non-anonymous port to an anonymous port # add the non-anonymous port to the wire associated with the # anonymous port #print str(o), o.anon(), o.bit.isinput(), o.bit.isoutput() #print str(i), i.anon(), i.bit.isinput(), i.bit.isoutput() if not o.anon(): #assert o.bit.direction is not None if o.bit.isinput(): print("Error: using an input as an output", str(o)) return if o not in self.outputs: if len(self.outputs) != 0: print("Warning: adding an output to a wire with an output", str(o)) #print('adding output', o) self.outputs.append(o) if not i.anon(): #assert i.bit.direction is not None if i.bit.isoutput(): print("Error: using an output as an input", str(i)) return if i not in self.inputs: #print('adding input', i) self.inputs.append(i) # print(o.wires,i.wires,self,self.outputs,self.inputs) # always update wires o.wires = self i.wires = self def check(self): for o in self.inputs: if o.isoutput(): print("Error: output in the wire inputs:",) for o in self.outputs: if o.isinput(): print("Error: input in the wire outputs:",) return False # check that this wire is only driven by a single output if len(self.outputs) > 1: print("Error: Multiple outputs on a wire:",) return False return True # # Port implements wiring # # Each port is represented by a Bit() # class Port: def __init__(self, bit): self.bit = bit self.wires = Wire() def __str__(self): return str(self.bit) def anon(self): return self.bit.anon() # wire a port to a port def wire(i, o): #if o.bit.direction is None: # o.bit.direction = OUTPUT #if i.bit.direction is None: # i.bit.direction = INPUT #print("Wiring", o.bit.direction, str(o), "->", i.bit.direction, str(i)) if i.wires and o.wires and i.wires is not o.wires: # print('merging', i.wires.inputs, i.wires.outputs) # print('merging', o.wires.inputs, o.wires.outputs) w = Wire() mergewires(w, i.wires) mergewires(w, o.wires) # print('after merge', w.inputs, w.outputs) elif o.wires: w = o.wires elif i.wires: w = i.wires else: w = Wire() w.connect(o, i) #print("after",o,"->",i, w) # if the port is an input or inout, return the output # if the port is an output, return the first input def trace(self): if not self.wires: return None if self in self.wires.inputs: if len(self.wires.outputs) < 1: # print('Warning:', str(self), 'is not connected to an output') return None assert len(self.wires.outputs) == 1 return self.wires.outputs[0] if self in self.wires.outputs: if len(self.wires.inputs) < 1: # print('Warning:', str(self), 'is not connected to an input') return None assert len(self.wires.inputs) == 1 return self.wires.inputs[0] return None # if the port is in the inputs, return the output def value(self): if not self.wires: return None if self in self.wires.inputs: if len(self.wires.outputs) < 1: # print('Warning:', str(self), 'is not connected to an output') return None #assert len(self.wires.outputs) == 1 return self.wires.outputs[0] return None def driven(self): return self.value() is not None def wired(self): return self.trace() is not None
{ "repo_name": "bjmnbraun/icestick_fastio", "path": "thirdparty/magma/magma/port.py", "copies": "1", "size": "5066", "license": "mit", "hash": 5612266653857670000, "line_mean": 27.1444444444, "line_max": 87, "alpha_frac": 0.5276352152, "autogenerated": false, "ratio": 3.7721518987341773, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47997871139341775, "avg_score": null, "num_lines": null }
__all__ = ["install"] from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import fastRepr import sys import traceback notify = directNotify.newCategory("ExceptionVarDump") reentry = 0 def _varDump__init__(self, *args, **kArgs): global reentry if reentry > 0: return reentry += 1 # frame zero is this frame f = 1 self._savedExcString = None self._savedStackFrames = [] while True: try: frame = sys._getframe(f) except ValueError as e: break else: f += 1 self._savedStackFrames.append(frame) self._moved__init__(*args, **kArgs) reentry -= 1 sReentry = 0 def _varDump__print(exc): global sReentry global notify if sReentry > 0: return sReentry += 1 if not exc._savedExcString: s = '' foundRun = False for frame in reversed(exc._savedStackFrames): filename = frame.f_code.co_filename codename = frame.f_code.co_name if not foundRun and codename != 'run': # don't print stack frames before run(), # they contain builtins and are huge continue foundRun = True s += '\nlocals for %s:%s\n' % (filename, codename) locals = frame.f_locals for var in locals: obj = locals[var] rep = fastRepr(obj) s += '::%s = %s\n' % (var, rep) exc._savedExcString = s exc._savedStackFrames = None notify.info(exc._savedExcString) sReentry -= 1 oldExcepthook = None # store these values here so that Task.py can always reliably access them # from its main exception handler wantStackDumpLog = False wantStackDumpUpload = False variableDumpReasons = [] dumpOnExceptionInit = False class _AttrNotFound: pass def _excepthookDumpVars(eType, eValue, tb): origTb = tb excStrs = traceback.format_exception(eType, eValue, origTb) s = 'printing traceback in case variable repr crashes the process...\n' for excStr in excStrs: s += excStr notify.info(s) s = 'DUMPING STACK FRAME VARIABLES' #import pdb;pdb.set_trace() #foundRun = False foundRun = True while tb is not None: frame = tb.tb_frame code = frame.f_code # this is a list of every string identifier used in this stack frame's code codeNames = set(code.co_names) # skip everything before the 'run' method, those frames have lots of # not-useful information if not foundRun: if code.co_name == 'run': foundRun = True else: tb = tb.tb_next continue s += '\n File "%s", line %s, in %s' % ( code.co_filename, frame.f_lineno, code.co_name) stateStack = Stack() # prime the stack with the variables we should visit from the frame's data structures # grab all of the local, builtin and global variables that appear in the code's name list name2obj = {} for name, obj in frame.f_builtins.items(): if name in codeNames: name2obj[name] = obj for name, obj in frame.f_globals.items(): if name in codeNames: name2obj[name] = obj for name, obj in frame.f_locals.items(): if name in codeNames: name2obj[name] = obj # show them in alphabetical order names = list(name2obj.keys()) names.sort() # push them in reverse order so they'll be popped in the correct order names.reverse() traversedIds = set() for name in names: stateStack.push([name, name2obj[name], traversedIds]) while len(stateStack) > 0: name, obj, traversedIds = stateStack.pop() #notify.info('%s, %s, %s' % (name, fastRepr(obj), traversedIds)) r = fastRepr(obj, maxLen=10) if type(r) is str: r = r.replace('\n', '\\n') s += '\n %s = %s' % (name, r) # if we've already traversed through this object, don't traverse through it again if id(obj) not in traversedIds: attrName2obj = {} for attrName in codeNames: attr = getattr(obj, attrName, _AttrNotFound) if (attr is not _AttrNotFound): # prevent infinite recursion on method wrappers (__init__.__init__.__init__...) try: className = attr.__class__.__name__ except: pass else: if className == 'method-wrapper': continue attrName2obj[attrName] = attr if len(attrName2obj): # show them in alphabetical order attrNames = list(attrName2obj.keys()) attrNames.sort() # push them in reverse order so they'll be popped in the correct order attrNames.reverse() ids = set(traversedIds) ids.add(id(obj)) for attrName in attrNames: obj = attrName2obj[attrName] stateStack.push(['%s.%s' % (name, attrName), obj, ids]) tb = tb.tb_next if foundRun: s += '\n' if wantStackDumpLog: notify.info(s) if wantStackDumpUpload: excStrs = traceback.format_exception(eType, eValue, origTb) for excStr in excStrs: s += excStr timeMgr = None try: timeMgr = base.cr.timeManager except: try: timeMgr = simbase.air.timeManager except: pass if timeMgr: timeMgr.setStackDump(s) oldExcepthook(eType, eValue, origTb) def install(log, upload): global oldExcepthook global wantStackDumpLog global wantStackDumpUpload global dumpOnExceptionInit wantStackDumpLog = log wantStackDumpUpload = upload dumpOnExceptionInit = ConfigVariableBool('variable-dump-on-exception-init', False) if dumpOnExceptionInit: # this mode doesn't completely work because exception objects # thrown by the interpreter don't get created until the # stack has been unwound and an except block has been reached if not hasattr(Exception, '_moved__init__'): Exception._moved__init__ = Exception.__init__ Exception.__init__ = _varDump__init__ else: if sys.excepthook is not _excepthookDumpVars: oldExcepthook = sys.excepthook sys.excepthook = _excepthookDumpVars
{ "repo_name": "brakhane/panda3d", "path": "direct/src/showbase/ExceptionVarDump.py", "copies": "1", "size": "6972", "license": "bsd-3-clause", "hash": 1340529052280700000, "line_mean": 33.86, "line_max": 103, "alpha_frac": 0.5499139415, "autogenerated": false, "ratio": 4.184873949579832, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5234787891079832, "avg_score": null, "num_lines": null }
__all__ = ["install"] from panda3d.core import * from direct.directnotify.DirectNotifyGlobal import directNotify from direct.showbase.PythonUtil import fastRepr import sys import traceback notify = directNotify.newCategory("ExceptionVarDump") reentry = 0 def _varDump__init__(self, *args, **kArgs): global reentry if reentry > 0: return reentry += 1 # frame zero is this frame f = 1 self._savedExcString = None self._savedStackFrames = [] while True: try: frame = sys._getframe(f) except ValueError as e: break else: f += 1 self._savedStackFrames.append(frame) self._moved__init__(*args, **kArgs) reentry -= 1 sReentry = 0 def _varDump__print(exc): global sReentry global notify if sReentry > 0: return sReentry += 1 if not exc._savedExcString: s = '' foundRun = False for frame in reversed(exc._savedStackFrames): filename = frame.f_code.co_filename codename = frame.f_code.co_name if not foundRun and codename != 'run': # don't print stack frames before run(), # they contain builtins and are huge continue foundRun = True s += '\nlocals for %s:%s\n' % (filename, codename) locals = frame.f_locals for var in locals: obj = locals[var] rep = fastRepr(obj) s += '::%s = %s\n' % (var, rep) exc._savedExcString = s exc._savedStackFrames = None notify.info(exc._savedExcString) sReentry -= 1 oldExcepthook = None # store these values here so that Task.py can always reliably access them # from its main exception handler wantStackDumpLog = False wantStackDumpUpload = False variableDumpReasons = [] dumpOnExceptionInit = False class _AttrNotFound: pass def _excepthookDumpVars(eType, eValue, tb): origTb = tb excStrs = traceback.format_exception(eType, eValue, origTb) s = 'printing traceback in case variable repr crashes the process...\n' for excStr in excStrs: s += excStr notify.info(s) s = 'DUMPING STACK FRAME VARIABLES' #import pdb;pdb.set_trace() #foundRun = False foundRun = True while tb is not None: frame = tb.tb_frame code = frame.f_code # this is a list of every string identifier used in this stack frame's code codeNames = set(code.co_names) # skip everything before the 'run' method, those frames have lots of # not-useful information if not foundRun: if code.co_name == 'run': foundRun = True else: tb = tb.tb_next continue s += '\n File "%s", line %s, in %s' % ( code.co_filename, frame.f_lineno, code.co_name) stateStack = Stack() # prime the stack with the variables we should visit from the frame's data structures # grab all of the local, builtin and global variables that appear in the code's name list name2obj = {} for name, obj in frame.f_builtins.items(): if name in codeNames: name2obj[name] = obj for name, obj in frame.f_globals.items(): if name in codeNames: name2obj[name] = obj for name, obj in frame.f_locals.items(): if name in codeNames: name2obj[name] = obj # show them in alphabetical order names = list(name2obj.keys()) names.sort() # push them in reverse order so they'll be popped in the correct order names.reverse() traversedIds = set() for name in names: stateStack.push([name, name2obj[name], traversedIds]) while len(stateStack) > 0: name, obj, traversedIds = stateStack.pop() #notify.info('%s, %s, %s' % (name, fastRepr(obj), traversedIds)) r = fastRepr(obj, maxLen=10) if type(r) is str: r = r.replace('\n', '\\n') s += '\n %s = %s' % (name, r) # if we've already traversed through this object, don't traverse through it again if id(obj) not in traversedIds: attrName2obj = {} for attrName in codeNames: attr = getattr(obj, attrName, _AttrNotFound) if (attr is not _AttrNotFound): # prevent infinite recursion on method wrappers (__init__.__init__.__init__...) try: className = attr.__class__.__name__ except: pass else: if className == 'method-wrapper': continue attrName2obj[attrName] = attr if len(attrName2obj): # show them in alphabetical order attrNames = list(attrName2obj.keys()) attrNames.sort() # push them in reverse order so they'll be popped in the correct order attrNames.reverse() ids = set(traversedIds) ids.add(id(obj)) for attrName in attrNames: obj = attrName2obj[attrName] stateStack.push(['%s.%s' % (name, attrName), obj, ids]) tb = tb.tb_next if foundRun: s += '\n' if wantStackDumpLog: notify.info(s) if wantStackDumpUpload: excStrs = traceback.format_exception(eType, eValue, origTb) for excStr in excStrs: s += excStr timeMgr = None try: timeMgr = base.cr.timeManager except: try: timeMgr = simbase.air.timeManager except: pass if timeMgr: timeMgr.setStackDump(s) oldExcepthook(eType, eValue, origTb) def install(log, upload): global oldExcepthook global wantStackDumpLog global wantStackDumpUpload global dumpOnExceptionInit wantStackDumpLog = log wantStackDumpUpload = upload dumpOnExceptionInit = ConfigVariableBool('variable-dump-on-exception-init', False) if dumpOnExceptionInit: # this mode doesn't completely work because exception objects # thrown by the interpreter don't get created until the # stack has been unwound and an except block has been reached if not hasattr(Exception, '_moved__init__'): Exception._moved__init__ = Exception.__init__ Exception.__init__ = _varDump__init__ else: if sys.excepthook is not _excepthookDumpVars: oldExcepthook = sys.excepthook sys.excepthook = _excepthookDumpVars
{ "repo_name": "tobspr/panda3d", "path": "direct/src/showbase/ExceptionVarDump.py", "copies": "10", "size": "6999", "license": "bsd-3-clause", "hash": -2859432944781279700, "line_mean": 33.8208955224, "line_max": 103, "alpha_frac": 0.5507929704, "autogenerated": false, "ratio": 4.176014319809069, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.002898662225905842, "num_lines": 201 }
__all__ = ['intAllen'] from scipy.interpolate import interp1d import numpy as np def intAllen(wavelength, mu): """ Return the intensity at a given wavelength and mu as tabulated by Allen """ CLight = 2.99792458e10 HPlanck = 6.62606876e-27 l = 1e4 * np.asarray([0.20,0.22,0.24,0.26,0.28,0.30,0.32,0.34,0.36,0.37,0.38,0.39,0.40,0.41,0.42,0.43,0.44,0.45,\ 0.46,0.48,0.50,0.55,0.60,0.65,0.70,0.75,0.80,0.90,1.00,1.10,1.20,1.40,1.60,1.80,2.00,2.50,\ 3.00,4.00,5.00,6.00,8.00,10.0,12.0]) i0 = 1e14 * (l*1e-8)**2 / CLight * np.asarray([0.06,0.21,0.29,0.60,1.30,2.45,3.25,3.77,4.13,4.23,4.63,4.95,5.15,5.26,5.28,5.24,5.19,5.10,5.00,\ 4.79,4.55,4.02,3.52,3.06,2.69,2.28,2.03,1.57,1.26,1.01,0.81,0.53,0.36,0.238,0.160,0.078,0.041,0.0142,0.0062,0.0032,0.00095,0.00035,0.00018]) cl0 = 1e4 * np.asarray([0.20, 0.22, 0.245,0.265,0.28,0.30,0.32,0.35,0.37,0.38,0.40,0.45,0.50,0.55,0.60,0.80,1.0,1.5,2.0,3.0,5.0,10.0]) cl1 = np.asarray([0.12,-1.3 ,-0.1 ,-0.1 , 0.38, 0.74, 0.88, 0.98, 1.03, 0.92, 0.91, 0.99, 0.97, 0.93, 0.88, 0.73, 0.64, 0.57, 0.48, 0.35, 0.22, 0.15]) cl2 = np.asarray([0.33, 1.6, 0.85, 0.90, 0.57, 0.20, 0.03,-0.1,-0.16,-0.05,-0.05,-0.17,-0.22,-0.23,-0.23,-0.22,-0.20,-0.21,-0.18,-0.12,-0.07,-0.07]) u = interp1d(cl0, cl1)(wavelength) v = interp1d(cl0, cl2)(wavelength) i0 = interp1d(l, i0)(wavelength) return (1.0 - u - v + u * mu + v * mu**2)*i0
{ "repo_name": "aasensio/pyiacsun", "path": "pyiacsun/util/intAllen.py", "copies": "2", "size": "1381", "license": "mit", "hash": -1789956382318096000, "line_mean": 48.3571428571, "line_max": 151, "alpha_frac": 0.5908761767, "autogenerated": false, "ratio": 1.6227967097532314, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.6978898683879018, "avg_score": 0.24695484051484276, "num_lines": 28 }
__all__ = ["integrate_velocity_field"] from .process_args import _int_antsProcessArguments from .. import utils def integrate_velocity_field( reference_image, velocity_field_filename, deformation_field_filename, time_0=0, time_1=1, delta_time=0.01, ): """ Integrate a velocityfield ANTsR function: `integrateVelocityField` Arguments --------- reference_image : ANTsImage Reference image domain, same as velocity field space velocity_field_filename : string Filename to velocity field, output from ants.registration deformation_field_filename : string Filename to output deformation field time_0 : scalar Typically one or zero but can take intermediate values time_1 : scalar Typically one or zero but can take intermediate values delta_time : scalar Time step value in zero to one; typically 0.01 Returns ------- None Example ------- >>> import ants >>> fi = ants.image_read( ants.get_data( "r16" ) ) >>> mi = ants.image_read( ants.get_data( "r27" ) ) >>> mytx2 = ants.registration( fi, mi, "TV[2]" ) >>> ants.integrate_velocity_field( fi, mytx2['velocityfield'][0], "/tmp/def.nii.gz", 0, 1, 0.01 ) >>> mydef = ants.apply_transforms( fi, mi, ["/tmp/def.nii.gz", mytx2['fwdtransforms'][1]] ) >>> ants.image_mutual_information(fi,mi) >>> ants.image_mutual_information(fi,mytx2['warpedmovout']) >>> ants.image_mutual_information(fi,mydef) >>> ants.integrate_velocity_field( fi, mytx2['velocityfield'][0], "/tmp/defi.nii.gz", 1, 0, 0.5 ) >>> mydefi = ants.apply_transforms( mi, fi, [ mytx2['fwdtransforms'][1], "/tmp/defi.nii.gz" ] ) >>> ants.image_mutual_information(mi,mydefi) >>> ants.image_mutual_information(mi,mytx2['warpedfixout']) """ libfn = utils.get_lib_fn("integrateVelocityField") if reference_image.dimension == 2: libfn.integrateVelocityField2D( reference_image.pointer, velocity_field_filename, deformation_field_filename, time_0, time_1, delta_time, ) if reference_image.dimension == 3: libfn.integrateVelocityField3D( reference_image.pointer, velocity_field_filename, deformation_field_filename, time_0, time_1, delta_time, )
{ "repo_name": "ANTsX/ANTsPy", "path": "ants/utils/ants_integrate_velocity_field.py", "copies": "1", "size": "2435", "license": "apache-2.0", "hash": 7797265809526752000, "line_mean": 29.8227848101, "line_max": 102, "alpha_frac": 0.6135523614, "autogenerated": false, "ratio": 3.4985632183908044, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4612115579790804, "avg_score": null, "num_lines": null }
__all__ = ["interact"] import jnupy import sys def input(prompt=None): if prompt is not None: print(prompt, end="") result = jnupy.input() if result is None: raise EOFError return result def mp_repl_continue_with_input(line): # check for blank input if not line: return False # check for escape char in terminal if "\x1b" in line: return False # check if input starts with a certain keyword starts_with_compound_keyword = False for keyword in "@", "if", "while", "for", "try", "with", "def", "class": starts_with_compound_keyword = starts_with_compound_keyword or line.startswith(keyword) # check for unmatched open bracket or triple quote # TODO don't look at triple quotes inside single quotes n_paren = n_brack = n_brace = 0 in_triple_quote = 0 passed = 0 for charno, char in enumerate(line): if passed: passed -= 1 continue elif char == '(': n_paren += 1 elif char == ')': n_paren -= 1 elif char == '[': n_brack += 1 elif char == ']': n_brack -= 1 elif char == '{': n_brace += 1 elif char == '}': n_brace -= 1 elif char == "'": if chr(in_triple_quote) != '"' and line[charno+1:charno+2] == line[charno+2:charno+3] == "'": passed += 2; in_triple_quote = ord("'") - in_triple_quote elif char == '"': if chr(in_triple_quote) != "'" and line[charno+1:charno+2] == line[charno+2:charno+3] == '"': passed += 2; in_triple_quote = ord('"') - in_triple_quote # continue if unmatched brackets or quotes if n_paren > 0 or n_brack > 0 or n_brace > 0 or in_triple_quote != 0: return True # continue if last character was backslash (for line continuation) if line.endswith('\\'): return True # continue if compound keyword and last line was not empty if starts_with_compound_keyword and not line.endswith('\n'): return True # otherwise, don't continue return False def interact(banner=None, readfunc=None, local=None): if readfunc is None: readfunc = input if banner is None: banner = "Micro Python {} on {}; {} version".format(jnupy.get_version("MICROPY_GIT_TAG"), jnupy.get_version("MICROPY_BUILD_DATE"), sys.platform) if local is None: local = dict() print(banner) while True: try: code = readfunc(">>> ") except EOFError: print() continue while mp_repl_continue_with_input(code): try: code += "\n" + readfunc("... ") except EOFError: print() continue try: fun = compile(code, "<stdin>", "single") except SyntaxError: sys.print_exception(sys.exc_info()[1]) continue try: exec(fun, local, local) except SystemExit: raise except: sys.print_exception(sys.exc_info()[1])
{ "repo_name": "EcmaXp/micropython", "path": "opencom/lib/code.py", "copies": "1", "size": "3157", "license": "mit", "hash": -7980299781826150000, "line_mean": 28.7830188679, "line_max": 152, "alpha_frac": 0.5388026608, "autogenerated": false, "ratio": 3.9760705289672544, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5014873189767254, "avg_score": null, "num_lines": null }
"""All internal ansible-lint rules.""" import glob import importlib.util import logging import os import re from collections import defaultdict from importlib.abc import Loader from time import sleep from typing import List import ansiblelint.utils from ansiblelint.errors import MatchError from ansiblelint.skip_utils import append_skipped_rules, get_rule_skips_from_line _logger = logging.getLogger(__name__) class AnsibleLintRule(object): def __repr__(self) -> str: """Return a AnsibleLintRule instance representation.""" return self.id + ": " + self.shortdesc def verbose(self) -> str: return self.id + ": " + self.shortdesc + "\n " + self.description id: str = "" tags: List[str] = [] shortdesc: str = "" description: str = "" version_added: str = "" severity: str = "" match = None matchtask = None matchplay = None @staticmethod def unjinja(text): text = re.sub(r"{{.+?}}", "JINJA_EXPRESSION", text) text = re.sub(r"{%.+?%}", "JINJA_STATEMENT", text) text = re.sub(r"{#.+?#}", "JINJA_COMMENT", text) return text def create_matcherror( self, message: str = None, linenumber: int = 0, details: str = "", filename: str = None) -> MatchError: return MatchError( message=message, linenumber=linenumber, details=details, filename=filename, rule=self ) def matchlines(self, file, text) -> List[MatchError]: matches: List[MatchError] = [] if not self.match: return matches # arrays are 0-based, line numbers are 1-based # so use prev_line_no as the counter for (prev_line_no, line) in enumerate(text.split("\n")): if line.lstrip().startswith('#'): continue rule_id_list = get_rule_skips_from_line(line) if self.id in rule_id_list: continue result = self.match(file, line) if not result: continue message = None if isinstance(result, str): message = result m = self.create_matcherror( message=message, linenumber=prev_line_no + 1, details=line, filename=file['path']) matches.append(m) return matches # TODO(ssbarnea): Reduce mccabe complexity # https://github.com/ansible/ansible-lint/issues/744 def matchtasks(self, file: str, text: str) -> List[MatchError]: # noqa: C901 matches: List[MatchError] = [] if not self.matchtask: return matches if file['type'] == 'meta': return matches yaml = ansiblelint.utils.parse_yaml_linenumbers(text, file['path']) if not yaml: return matches yaml = append_skipped_rules(yaml, text, file['type']) try: tasks = ansiblelint.utils.get_normalized_tasks(yaml, file) except MatchError as e: return [e] for task in tasks: if self.id in task.get('skipped_rules', ()): continue if 'action' not in task: continue result = self.matchtask(file, task) if not result: continue message = None if isinstance(result, str): message = result task_msg = "Task/Handler: " + ansiblelint.utils.task_to_str(task) m = self.create_matcherror( message=message, linenumber=task[ansiblelint.utils.LINE_NUMBER_KEY], details=task_msg, filename=file['path']) matches.append(m) return matches @staticmethod def _matchplay_linenumber(play, optional_linenumber): try: linenumber, = optional_linenumber except ValueError: linenumber = play[ansiblelint.utils.LINE_NUMBER_KEY] return linenumber def matchyaml(self, file: str, text: str) -> List[MatchError]: matches: List[MatchError] = [] if not self.matchplay: return matches yaml = ansiblelint.utils.parse_yaml_linenumbers(text, file['path']) if not yaml: return matches if isinstance(yaml, dict): yaml = [yaml] yaml = ansiblelint.skip_utils.append_skipped_rules(yaml, text, file['type']) for play in yaml: if self.id in play.get('skipped_rules', ()): continue result = self.matchplay(file, play) if not result: continue if isinstance(result, tuple): result = [result] if not isinstance(result, list): raise TypeError("{} is not a list".format(result)) for section, message, *optional_linenumber in result: linenumber = self._matchplay_linenumber(play, optional_linenumber) matches.append(self.create_matcherror( message=message, linenumber=linenumber, details=str(section), filename=file['path'] )) return matches def load_plugins(directory: str) -> List[AnsibleLintRule]: """Return a list of rule classes.""" result = [] for pluginfile in glob.glob(os.path.join(directory, '[A-Za-z]*.py')): pluginname = os.path.basename(pluginfile.replace('.py', '')) spec = importlib.util.spec_from_file_location(pluginname, pluginfile) # https://github.com/python/typeshed/issues/2793 if spec and isinstance(spec.loader, Loader): module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) obj = getattr(module, pluginname)() result.append(obj) return result class RulesCollection(object): def __init__(self, rulesdirs=None) -> None: """Initialize a RulesCollection instance.""" if rulesdirs is None: rulesdirs = [] self.rulesdirs = ansiblelint.utils.expand_paths_vars(rulesdirs) self.rules: List[AnsibleLintRule] = [] for rulesdir in self.rulesdirs: _logger.debug("Loading rules from %s", rulesdir) self.extend(load_plugins(rulesdir)) self.rules = sorted(self.rules, key=lambda r: r.id) def register(self, obj: AnsibleLintRule): self.rules.append(obj) def __iter__(self): """Return the iterator over the rules in the RulesCollection.""" return iter(self.rules) def __len__(self): """Return the length of the RulesCollection data.""" return len(self.rules) def extend(self, more: List[AnsibleLintRule]) -> None: self.rules.extend(more) def run(self, playbookfile, tags=set(), skip_list=frozenset()) -> List: text = "" matches: List = list() for i in range(3): try: with open(playbookfile['path'], mode='r', encoding='utf-8') as f: text = f.read() break except IOError as e: _logger.warning( "Couldn't open %s - %s [try:%s]", playbookfile['path'], e.strerror, i) sleep(1) continue if i and not text: return matches for rule in self.rules: if not tags or not set(rule.tags).union([rule.id]).isdisjoint(tags): rule_definition = set(rule.tags) rule_definition.add(rule.id) if set(rule_definition).isdisjoint(skip_list): matches.extend(rule.matchlines(playbookfile, text)) matches.extend(rule.matchtasks(playbookfile, text)) matches.extend(rule.matchyaml(playbookfile, text)) return matches def __repr__(self) -> str: """Return a RulesCollection instance representation.""" return "\n".join([rule.verbose() for rule in sorted(self.rules, key=lambda x: x.id)]) def listtags(self) -> str: tags = defaultdict(list) for rule in self.rules: for tag in rule.tags: tags[tag].append("[{0}]".format(rule.id)) results = [] for tag in sorted(tags): results.append("{0} {1}".format(tag, tags[tag])) return "\n".join(results)
{ "repo_name": "ansible/ansible-lint", "path": "lib/ansiblelint/rules/__init__.py", "copies": "1", "size": "8648", "license": "mit", "hash": -2846238959904863000, "line_mean": 31.6339622642, "line_max": 84, "alpha_frac": 0.5513413506, "autogenerated": false, "ratio": 4.23921568627451, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00022848611912536598, "num_lines": 265 }
__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly', 'RegularGridInterpolator', 'interpn'] import itertools import warnings import functools import operator import numpy as np from numpy import (array, transpose, searchsorted, atleast_1d, atleast_2d, ravel, poly1d, asarray, intp) import scipy.special as spec from scipy.special import comb from scipy._lib._util import prod from . import fitpack from . import dfitpack from . import _fitpack from .polyint import _Interpolator1D from . import _ppoly from .fitpack2 import RectBivariateSpline from .interpnd import _ndim_coords_from_arrays from ._bsplines import make_interp_spline, BSpline def lagrange(x, w): r""" Return a Lagrange interpolating polynomial. Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating polynomial through the points ``(x, w)``. Warning: This implementation is numerically unstable. Do not expect to be able to use more than about 20 points even if they are chosen optimally. Parameters ---------- x : array_like `x` represents the x-coordinates of a set of datapoints. w : array_like `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`). Returns ------- lagrange : `numpy.poly1d` instance The Lagrange interpolating polynomial. Examples -------- Interpolate :math:`f(x) = x^3` by 3 points. >>> from scipy.interpolate import lagrange >>> x = np.array([0, 1, 2]) >>> y = x**3 >>> poly = lagrange(x, y) Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly, it is given by .. math:: \begin{aligned} L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\ &= x (-2 + 3x) \end{aligned} >>> from numpy.polynomial.polynomial import Polynomial >>> Polynomial(poly).coef array([ 3., -2., 0.]) """ M = len(x) p = poly1d(0.0) for j in range(M): pt = poly1d(w[j]) for k in range(M): if k == j: continue fac = x[j]-x[k] pt *= poly1d([1.0, -x[k]])/fac p += pt return p # !! Need to find argument for keeping initialize. If it isn't # !! found, get rid of it! class interp2d(object): """ interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None) Interpolate over a 2-D grid. `x`, `y` and `z` are arrays of values used to approximate some function f: ``z = f(x, y)``. This class returns a function whose call method uses spline interpolation to find the value of new points. If `x` and `y` represent a regular grid, consider using RectBivariateSpline. Note that calling `interp2d` with NaNs present in input values results in undefined behaviour. Methods ------- __call__ Parameters ---------- x, y : array_like Arrays defining the data point coordinates. If the points lie on a regular grid, `x` can specify the column coordinates and `y` the row coordinates, for example:: >>> x = [0,1,2]; y = [0,3]; z = [[1,2,3], [4,5,6]] Otherwise, `x` and `y` must specify the full coordinates for each point, for example:: >>> x = [0,1,2,0,1,2]; y = [0,0,0,3,3,3]; z = [1,2,3,4,5,6] If `x` and `y` are multidimensional, they are flattened before use. z : array_like The values of the function to interpolate at the data points. If `z` is a multidimensional array, it is flattened before use. The length of a flattened `z` array is either len(`x`)*len(`y`) if `x` and `y` specify the column and row coordinates or ``len(z) == len(x) == len(y)`` if `x` and `y` specify coordinates for each point. kind : {'linear', 'cubic', 'quintic'}, optional The kind of spline interpolation to use. Default is 'linear'. copy : bool, optional If True, the class makes internal copies of x, y and z. If False, references may be used. The default is to copy. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data (x,y), a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If omitted (None), values outside the domain are extrapolated via nearest-neighbor extrapolation. See Also -------- RectBivariateSpline : Much faster 2-D interpolation if your input data is on a grid bisplrep, bisplev : Spline interpolation based on FITPACK BivariateSpline : a more recent wrapper of the FITPACK routines interp1d : 1-D version of this function Notes ----- The minimum number of data points required along the interpolation axis is ``(k+1)**2``, with k=1 for linear, k=3 for cubic and k=5 for quintic interpolation. The interpolator is constructed by `bisplrep`, with a smoothing factor of 0. If more control over smoothing is needed, `bisplrep` should be used directly. Examples -------- Construct a 2-D grid and interpolate on it: >>> from scipy import interpolate >>> x = np.arange(-5.01, 5.01, 0.25) >>> y = np.arange(-5.01, 5.01, 0.25) >>> xx, yy = np.meshgrid(x, y) >>> z = np.sin(xx**2+yy**2) >>> f = interpolate.interp2d(x, y, z, kind='cubic') Now use the obtained interpolation function and plot the result: >>> import matplotlib.pyplot as plt >>> xnew = np.arange(-5.01, 5.01, 1e-2) >>> ynew = np.arange(-5.01, 5.01, 1e-2) >>> znew = f(xnew, ynew) >>> plt.plot(x, z[0, :], 'ro-', xnew, znew[0, :], 'b-') >>> plt.show() """ def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None): x = ravel(x) y = ravel(y) z = asarray(z) rectangular_grid = (z.size == len(x) * len(y)) if rectangular_grid: if z.ndim == 2: if z.shape != (len(y), len(x)): raise ValueError("When on a regular grid with x.size = m " "and y.size = n, if z.ndim == 2, then z " "must have shape (n, m)") if not np.all(x[1:] >= x[:-1]): j = np.argsort(x) x = x[j] z = z[:, j] if not np.all(y[1:] >= y[:-1]): j = np.argsort(y) y = y[j] z = z[j, :] z = ravel(z.T) else: z = ravel(z) if len(x) != len(y): raise ValueError( "x and y must have equal lengths for non rectangular grid") if len(z) != len(x): raise ValueError( "Invalid length for input z for non rectangular grid") try: kx = ky = {'linear': 1, 'cubic': 3, 'quintic': 5}[kind] except KeyError: raise ValueError("Unsupported interpolation type.") if not rectangular_grid: # TODO: surfit is really not meant for interpolation! self.tck = fitpack.bisplrep(x, y, z, kx=kx, ky=ky, s=0.0) else: nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth( x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0) self.tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky) self.bounds_error = bounds_error self.fill_value = fill_value self.x, self.y, self.z = [array(a, copy=copy) for a in (x, y, z)] self.x_min, self.x_max = np.amin(x), np.amax(x) self.y_min, self.y_max = np.amin(y), np.amax(y) def __call__(self, x, y, dx=0, dy=0, assume_sorted=False): """Interpolate the function. Parameters ---------- x : 1-D array x-coordinates of the mesh on which to interpolate. y : 1-D array y-coordinates of the mesh on which to interpolate. dx : int >= 0, < kx Order of partial derivatives in x. dy : int >= 0, < ky Order of partial derivatives in y. assume_sorted : bool, optional If False, values of `x` and `y` can be in any order and they are sorted first. If True, `x` and `y` have to be arrays of monotonically increasing values. Returns ------- z : 2-D array with shape (len(y), len(x)) The interpolated values. """ x = atleast_1d(x) y = atleast_1d(y) if x.ndim != 1 or y.ndim != 1: raise ValueError("x and y should both be 1-D arrays") if not assume_sorted: x = np.sort(x) y = np.sort(y) if self.bounds_error or self.fill_value is not None: out_of_bounds_x = (x < self.x_min) | (x > self.x_max) out_of_bounds_y = (y < self.y_min) | (y > self.y_max) any_out_of_bounds_x = np.any(out_of_bounds_x) any_out_of_bounds_y = np.any(out_of_bounds_y) if self.bounds_error and (any_out_of_bounds_x or any_out_of_bounds_y): raise ValueError("Values out of range; x must be in %r, y in %r" % ((self.x_min, self.x_max), (self.y_min, self.y_max))) z = fitpack.bisplev(x, y, self.tck, dx, dy) z = atleast_2d(z) z = transpose(z) if self.fill_value is not None: if any_out_of_bounds_x: z[:, out_of_bounds_x] = self.fill_value if any_out_of_bounds_y: z[out_of_bounds_y, :] = self.fill_value if len(z) == 1: z = z[0] return array(z) def _check_broadcast_up_to(arr_from, shape_to, name): """Helper to check that arr_from broadcasts up to shape_to""" shape_from = arr_from.shape if len(shape_to) >= len(shape_from): for t, f in zip(shape_to[::-1], shape_from[::-1]): if f != 1 and f != t: break else: # all checks pass, do the upcasting that we need later if arr_from.size != 1 and arr_from.shape != shape_to: arr_from = np.ones(shape_to, arr_from.dtype) * arr_from return arr_from.ravel() # at least one check failed raise ValueError('%s argument must be able to broadcast up ' 'to shape %s but had shape %s' % (name, shape_to, shape_from)) def _do_extrapolate(fill_value): """Helper to check if fill_value == "extrapolate" without warnings""" return (isinstance(fill_value, str) and fill_value == 'extrapolate') class interp1d(_Interpolator1D): """ Interpolate a 1-D function. `x` and `y` are arrays of values used to approximate some function f: ``y = f(x)``. This class returns a function whose call method uses interpolation to find the value of new points. Note that calling `interp1d` with NaNs present in input values results in undefined behaviour. Parameters ---------- x : (N,) array_like A 1-D array of real values. y : (...,N,...) array_like A N-D array of real values. The length of `y` along the interpolation axis must be equal to the length of `x`. kind : str or int, optional Specifies the kind of interpolation as a string ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of zeroth, first, second or third order; 'previous' and 'next' simply return the previous or next value of the point) or as an integer specifying the order of the spline interpolator to use. Default is 'linear'. axis : int, optional Specifies the axis of `y` along which to interpolate. Interpolation defaults to the last axis of `y`. copy : bool, optional If True, the class makes internal copies of x and y. If False, references to `x` and `y` are used. The default is to copy. bounds_error : bool, optional If True, a ValueError is raised any time interpolation is attempted on a value outside of the range of x (where extrapolation is necessary). If False, out of bounds values are assigned `fill_value`. By default, an error is raised unless ``fill_value="extrapolate"``. fill_value : array-like or (array-like, array_like) or "extrapolate", optional - if a ndarray (or float), this value will be used to fill in for requested points outside of the data range. If not provided, then the default is NaN. The array-like must broadcast properly to the dimensions of the non-interpolation axes. - If a two-element tuple, then the first element is used as a fill value for ``x_new < x[0]`` and the second element is used for ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g., list or ndarray, regardless of shape) is taken to be a single array-like argument meant to be used for both bounds as ``below, above = fill_value, fill_value``. .. versionadded:: 0.17.0 - If "extrapolate", then points outside the data range will be extrapolated. .. versionadded:: 0.17.0 assume_sorted : bool, optional If False, values of `x` can be in any order and they are sorted first. If True, `x` has to be an array of monotonically increasing values. Attributes ---------- fill_value Methods ------- __call__ See Also -------- splrep, splev Spline interpolation/smoothing based on FITPACK. UnivariateSpline : An object-oriented wrapper of the FITPACK routines. interp2d : 2-D interpolation Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy import interpolate >>> x = np.arange(0, 10) >>> y = np.exp(-x/3.0) >>> f = interpolate.interp1d(x, y) >>> xnew = np.arange(0, 9, 0.1) >>> ynew = f(xnew) # use interpolation function returned by `interp1d` >>> plt.plot(x, y, 'o', xnew, ynew, '-') >>> plt.show() """ def __init__(self, x, y, kind='linear', axis=-1, copy=True, bounds_error=None, fill_value=np.nan, assume_sorted=False): """ Initialize a 1-D linear interpolation class.""" _Interpolator1D.__init__(self, x, y, axis=axis) self.bounds_error = bounds_error # used by fill_value setter self.copy = copy if kind in ['zero', 'slinear', 'quadratic', 'cubic']: order = {'zero': 0, 'slinear': 1, 'quadratic': 2, 'cubic': 3}[kind] kind = 'spline' elif isinstance(kind, int): order = kind kind = 'spline' elif kind not in ('linear', 'nearest', 'previous', 'next'): raise NotImplementedError("%s is unsupported: Use fitpack " "routines for other types." % kind) x = array(x, copy=self.copy) y = array(y, copy=self.copy) if not assume_sorted: ind = np.argsort(x) x = x[ind] y = np.take(y, ind, axis=axis) if x.ndim != 1: raise ValueError("the x array must have exactly one dimension.") if y.ndim == 0: raise ValueError("the y array must have at least one dimension.") # Force-cast y to a floating-point type, if it's not yet one if not issubclass(y.dtype.type, np.inexact): y = y.astype(np.float_) # Backward compatibility self.axis = axis % y.ndim # Interpolation goes internally along the first axis self.y = y self._y = self._reshape_yi(self.y) self.x = x del y, x # clean up namespace to prevent misuse; use attributes self._kind = kind self.fill_value = fill_value # calls the setter, can modify bounds_err # Adjust to interpolation kind; store reference to *unbound* # interpolation methods, in order to avoid circular references to self # stored in the bound instance methods, and therefore delayed garbage # collection. See: https://docs.python.org/reference/datamodel.html if kind in ('linear', 'nearest', 'previous', 'next'): # Make a "view" of the y array that is rotated to the interpolation # axis. minval = 2 if kind == 'nearest': # Do division before addition to prevent possible integer # overflow self.x_bds = self.x / 2.0 self.x_bds = self.x_bds[1:] + self.x_bds[:-1] self._call = self.__class__._call_nearest elif kind == 'previous': # Side for np.searchsorted and index for clipping self._side = 'left' self._ind = 0 # Move x by one floating point value to the left self._x_shift = np.nextafter(self.x, -np.inf) self._call = self.__class__._call_previousnext elif kind == 'next': self._side = 'right' self._ind = 1 # Move x by one floating point value to the right self._x_shift = np.nextafter(self.x, np.inf) self._call = self.__class__._call_previousnext else: # Check if we can delegate to numpy.interp (2x-10x faster). cond = self.x.dtype == np.float_ and self.y.dtype == np.float_ cond = cond and self.y.ndim == 1 cond = cond and not _do_extrapolate(fill_value) if cond: self._call = self.__class__._call_linear_np else: self._call = self.__class__._call_linear else: minval = order + 1 rewrite_nan = False xx, yy = self.x, self._y if order > 1: # Quadratic or cubic spline. If input contains even a single # nan, then the output is all nans. We cannot just feed data # with nans to make_interp_spline because it calls LAPACK. # So, we make up a bogus x and y with no nans and use it # to get the correct shape of the output, which we then fill # with nans. # For slinear or zero order spline, we just pass nans through. mask = np.isnan(self.x) if mask.any(): sx = self.x[~mask] if sx.size == 0: raise ValueError("`x` array is all-nan") xx = np.linspace(np.nanmin(self.x), np.nanmax(self.x), len(self.x)) rewrite_nan = True if np.isnan(self._y).any(): yy = np.ones_like(self._y) rewrite_nan = True self._spline = make_interp_spline(xx, yy, k=order, check_finite=False) if rewrite_nan: self._call = self.__class__._call_nan_spline else: self._call = self.__class__._call_spline if len(self.x) < minval: raise ValueError("x and y arrays must have at " "least %d entries" % minval) @property def fill_value(self): """The fill value.""" # backwards compat: mimic a public attribute return self._fill_value_orig @fill_value.setter def fill_value(self, fill_value): # extrapolation only works for nearest neighbor and linear methods if _do_extrapolate(fill_value): if self.bounds_error: raise ValueError("Cannot extrapolate and raise " "at the same time.") self.bounds_error = False self._extrapolate = True else: broadcast_shape = (self.y.shape[:self.axis] + self.y.shape[self.axis + 1:]) if len(broadcast_shape) == 0: broadcast_shape = (1,) # it's either a pair (_below_range, _above_range) or a single value # for both above and below range if isinstance(fill_value, tuple) and len(fill_value) == 2: below_above = [np.asarray(fill_value[0]), np.asarray(fill_value[1])] names = ('fill_value (below)', 'fill_value (above)') for ii in range(2): below_above[ii] = _check_broadcast_up_to( below_above[ii], broadcast_shape, names[ii]) else: fill_value = np.asarray(fill_value) below_above = [_check_broadcast_up_to( fill_value, broadcast_shape, 'fill_value')] * 2 self._fill_value_below, self._fill_value_above = below_above self._extrapolate = False if self.bounds_error is None: self.bounds_error = True # backwards compat: fill_value was a public attr; make it writeable self._fill_value_orig = fill_value def _call_linear_np(self, x_new): # Note that out-of-bounds values are taken care of in self._evaluate return np.interp(x_new, self.x, self.y) def _call_linear(self, x_new): # 2. Find where in the original data, the values to interpolate # would be inserted. # Note: If x_new[n] == x[m], then m is returned by searchsorted. x_new_indices = searchsorted(self.x, x_new) # 3. Clip x_new_indices so that they are within the range of # self.x indices and at least 1. Removes mis-interpolation # of x_new[n] = x[0] x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int) # 4. Calculate the slope of regions that each x_new value falls in. lo = x_new_indices - 1 hi = x_new_indices x_lo = self.x[lo] x_hi = self.x[hi] y_lo = self._y[lo] y_hi = self._y[hi] # Note that the following two expressions rely on the specifics of the # broadcasting semantics. slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None] # 5. Calculate the actual value for each entry in x_new. y_new = slope*(x_new - x_lo)[:, None] + y_lo return y_new def _call_nearest(self, x_new): """ Find nearest neighbor interpolated y_new = f(x_new).""" # 2. Find where in the averaged data the values to interpolate # would be inserted. # Note: use side='left' (right) to searchsorted() to define the # halfway point to be nearest to the left (right) neighbor x_new_indices = searchsorted(self.x_bds, x_new, side='left') # 3. Clip x_new_indices so that they are within the range of x indices. x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) # 4. Calculate the actual value for each entry in x_new. y_new = self._y[x_new_indices] return y_new def _call_previousnext(self, x_new): """Use previous/next neighbor of x_new, y_new = f(x_new).""" # 1. Get index of left/right value x_new_indices = searchsorted(self._x_shift, x_new, side=self._side) # 2. Clip x_new_indices so that they are within the range of x indices. x_new_indices = x_new_indices.clip(1-self._ind, len(self.x)-self._ind).astype(intp) # 3. Calculate the actual value for each entry in x_new. y_new = self._y[x_new_indices+self._ind-1] return y_new def _call_spline(self, x_new): return self._spline(x_new) def _call_nan_spline(self, x_new): out = self._spline(x_new) out[...] = np.nan return out def _evaluate(self, x_new): # 1. Handle values in x_new that are outside of x. Throw error, # or return a list of mask array indicating the outofbounds values. # The behavior is set by the bounds_error variable. x_new = asarray(x_new) y_new = self._call(self, x_new) if not self._extrapolate: below_bounds, above_bounds = self._check_bounds(x_new) if len(y_new) > 0: # Note fill_value must be broadcast up to the proper size # and flattened to work here y_new[below_bounds] = self._fill_value_below y_new[above_bounds] = self._fill_value_above return y_new def _check_bounds(self, x_new): """Check the inputs for being in the bounds of the interpolated data. Parameters ---------- x_new : array Returns ------- out_of_bounds : bool array The mask on x_new of values that are out of the bounds. """ # If self.bounds_error is True, we raise an error if any x_new values # fall outside the range of x. Otherwise, we return an array indicating # which values are outside the boundary region. below_bounds = x_new < self.x[0] above_bounds = x_new > self.x[-1] # !! Could provide more information about which values are out of bounds if self.bounds_error and below_bounds.any(): raise ValueError("A value in x_new is below the interpolation " "range.") if self.bounds_error and above_bounds.any(): raise ValueError("A value in x_new is above the interpolation " "range.") # !! Should we emit a warning if some values are out of bounds? # !! matlab does not. return below_bounds, above_bounds class _PPolyBase(object): """Base class for piecewise polynomials.""" __slots__ = ('c', 'x', 'extrapolate', 'axis') def __init__(self, c, x, extrapolate=None, axis=0): self.c = np.asarray(c) self.x = np.ascontiguousarray(x, dtype=np.float64) if extrapolate is None: extrapolate = True elif extrapolate != 'periodic': extrapolate = bool(extrapolate) self.extrapolate = extrapolate if self.c.ndim < 2: raise ValueError("Coefficients array must be at least " "2-dimensional.") if not (0 <= axis < self.c.ndim - 1): raise ValueError("axis=%s must be between 0 and %s" % (axis, self.c.ndim-1)) self.axis = axis if axis != 0: # roll the interpolation axis to be the first one in self.c # More specifically, the target shape for self.c is (k, m, ...), # and axis !=0 means that we have c.shape (..., k, m, ...) # ^ # axis # So we roll two of them. self.c = np.rollaxis(self.c, axis+1) self.c = np.rollaxis(self.c, axis+1) if self.x.ndim != 1: raise ValueError("x must be 1-dimensional") if self.x.size < 2: raise ValueError("at least 2 breakpoints are needed") if self.c.ndim < 2: raise ValueError("c must have at least 2 dimensions") if self.c.shape[0] == 0: raise ValueError("polynomial must be at least of order 0") if self.c.shape[1] != self.x.size-1: raise ValueError("number of coefficients != len(x)-1") dx = np.diff(self.x) if not (np.all(dx >= 0) or np.all(dx <= 0)): raise ValueError("`x` must be strictly increasing or decreasing.") dtype = self._get_dtype(self.c.dtype) self.c = np.ascontiguousarray(self.c, dtype=dtype) def _get_dtype(self, dtype): if np.issubdtype(dtype, np.complexfloating) \ or np.issubdtype(self.c.dtype, np.complexfloating): return np.complex_ else: return np.float_ @classmethod def construct_fast(cls, c, x, extrapolate=None, axis=0): """ Construct the piecewise polynomial without making checks. Takes the same parameters as the constructor. Input arguments ``c`` and ``x`` must be arrays of the correct shape and type. The ``c`` array can only be of dtypes float and complex, and ``x`` array must have dtype float. """ self = object.__new__(cls) self.c = c self.x = x self.axis = axis if extrapolate is None: extrapolate = True self.extrapolate = extrapolate return self def _ensure_c_contiguous(self): """ c and x may be modified by the user. The Cython code expects that they are C contiguous. """ if not self.x.flags.c_contiguous: self.x = self.x.copy() if not self.c.flags.c_contiguous: self.c = self.c.copy() def extend(self, c, x, right=None): """ Add additional breakpoints and coefficients to the polynomial. Parameters ---------- c : ndarray, size (k, m, ...) Additional coefficients for polynomials in intervals. Note that the first additional interval will be formed using one of the ``self.x`` end points. x : ndarray, size (m,) Additional breakpoints. Must be sorted in the same order as ``self.x`` and either to the right or to the left of the current breakpoints. right Deprecated argument. Has no effect. .. deprecated:: 0.19 """ if right is not None: warnings.warn("`right` is deprecated and will be removed.") c = np.asarray(c) x = np.asarray(x) if c.ndim < 2: raise ValueError("invalid dimensions for c") if x.ndim != 1: raise ValueError("invalid dimensions for x") if x.shape[0] != c.shape[1]: raise ValueError("Shapes of x {} and c {} are incompatible" .format(x.shape, c.shape)) if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim: raise ValueError("Shapes of c {} and self.c {} are incompatible" .format(c.shape, self.c.shape)) if c.size == 0: return dx = np.diff(x) if not (np.all(dx >= 0) or np.all(dx <= 0)): raise ValueError("`x` is not sorted.") if self.x[-1] >= self.x[0]: if not x[-1] >= x[0]: raise ValueError("`x` is in the different order " "than `self.x`.") if x[0] >= self.x[-1]: action = 'append' elif x[-1] <= self.x[0]: action = 'prepend' else: raise ValueError("`x` is neither on the left or on the right " "from `self.x`.") else: if not x[-1] <= x[0]: raise ValueError("`x` is in the different order " "than `self.x`.") if x[0] <= self.x[-1]: action = 'append' elif x[-1] >= self.x[0]: action = 'prepend' else: raise ValueError("`x` is neither on the left or on the right " "from `self.x`.") dtype = self._get_dtype(c.dtype) k2 = max(c.shape[0], self.c.shape[0]) c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:], dtype=dtype) if action == 'append': c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c c2[k2-c.shape[0]:, self.c.shape[1]:] = c self.x = np.r_[self.x, x] elif action == 'prepend': c2[k2-self.c.shape[0]:, :c.shape[1]] = c c2[k2-c.shape[0]:, c.shape[1]:] = self.c self.x = np.r_[x, self.x] self.c = c2 def __call__(self, x, nu=0, extrapolate=None): """ Evaluate the piecewise polynomial or its derivative. Parameters ---------- x : array_like Points to evaluate the interpolant at. nu : int, optional Order of derivative to evaluate. Must be non-negative. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- y : array_like Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if extrapolate is None: extrapolate = self.extrapolate x = np.asarray(x) x_shape, x_ndim = x.shape, x.ndim x = np.ascontiguousarray(x.ravel(), dtype=np.float_) # With periodic extrapolation we map x to the segment # [self.x[0], self.x[-1]]. if extrapolate == 'periodic': x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0]) extrapolate = False out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype) self._ensure_c_contiguous() self._evaluate(x, nu, extrapolate, out) out = out.reshape(x_shape + self.c.shape[2:]) if self.axis != 0: # transpose to move the calculated values to the interpolation axis l = list(range(out.ndim)) l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] out = out.transpose(l) return out class PPoly(_PPolyBase): """ Piecewise polynomial in terms of coefficients and breakpoints The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the local power basis:: S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1)) where ``k`` is the degree of the polynomial. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals. x : ndarray, shape (m+1,) Polynomial breakpoints. Must be sorted in either increasing or decreasing order. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-D array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ derivative antiderivative integrate solve roots extend from_spline from_bernstein_basis construct_fast See also -------- BPoly : piecewise polynomials in the Bernstein basis Notes ----- High-order polynomials in the power basis can be numerically unstable. Precision problems can start to appear for orders larger than 20-30. """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. Default is 1, i.e., compute the first derivative. If negative, the antiderivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k - n representing the derivative of this polynomial. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if nu < 0: return self.antiderivative(-nu) # reduce order if nu == 0: c2 = self.c.copy() else: c2 = self.c[:-nu, :].copy() if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # multiply by the correct rising factorials factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu) c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)] # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Antiderivative is also the indefinite integral of the function, and derivative is its inverse operation. Parameters ---------- nu : int, optional Order of antiderivative to evaluate. Default is 1, i.e., compute the first integral. If negative, the derivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k + n representing the antiderivative of this polynomial. Notes ----- The antiderivative returned by this function is continuous and continuously differentiable to order n-1, up to floating point rounding error. If antiderivative is computed and ``self.extrapolate='periodic'``, it will be set to False for the returned instance. This is done because the antiderivative is no longer periodic and its correct evaluation outside of the initially given x interval is difficult. """ if nu <= 0: return self.derivative(-nu) c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:], dtype=self.c.dtype) c[:-nu] = self.c # divide by the correct rising factorials factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu) c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] # fix continuity of added degrees of freedom self._ensure_c_contiguous() _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1), self.x, nu - 1) if self.extrapolate == 'periodic': extrapolate = False else: extrapolate = self.extrapolate # construct a compatible polynomial return self.construct_fast(c, self.x, extrapolate, self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- ig : array_like Definite integral of the piecewise polynomial over [a, b] """ if extrapolate is None: extrapolate = self.extrapolate # Swap integration bounds if needed sign = 1 if b < a: a, b = b, a sign = -1 range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype) self._ensure_c_contiguous() # Compute the integral. if extrapolate == 'periodic': # Split the integral into the part over period (can be several # of them) and the remaining part. xs, xe = self.x[0], self.x[-1] period = xe - xs interval = b - a n_periods, left = divmod(interval, period) if n_periods > 0: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, xs, xe, False, out=range_int) range_int *= n_periods else: range_int.fill(0) # Map a to [xs, xe], b is always a + left. a = xs + (a - xs) % period b = a + left # If b <= xe then we need to integrate over [a, b], otherwise # over [a, xe] and from xs to what is remained. remainder_int = np.empty_like(range_int) if b <= xe: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, b, False, out=remainder_int) range_int += remainder_int else: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, xe, False, out=remainder_int) range_int += remainder_int _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, xs, xs + left + a - xe, False, out=remainder_int) range_int += remainder_int else: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, b, bool(extrapolate), out=range_int) # Return range_int *= sign return range_int.reshape(self.c.shape[2:]) def solve(self, y=0., discontinuity=True, extrapolate=None): """ Find real solutions of the the equation ``pp(x) == y``. Parameters ---------- y : float, optional Right-hand side. Default is zero. discontinuity : bool, optional Whether to report sign changes across discontinuities at breakpoints as roots. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to return roots from the polynomial extrapolated based on first and last intervals, 'periodic' works the same as False. If None (default), use `self.extrapolate`. Returns ------- roots : ndarray Roots of the polynomial(s). If the PPoly object describes multiple polynomials, the return value is an object array whose each element is an ndarray containing the roots. Notes ----- This routine works only on real-valued polynomials. If the piecewise polynomial contains sections that are identically zero, the root list will contain the start point of the corresponding interval, followed by a ``nan`` value. If the polynomial is discontinuous across a breakpoint, and there is a sign change across the breakpoint, this is reported if the `discont` parameter is True. Examples -------- Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals ``[-2, 1], [1, 2]``: >>> from scipy.interpolate import PPoly >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2]) >>> pp.solve() array([-1., 1.]) """ if extrapolate is None: extrapolate = self.extrapolate self._ensure_c_contiguous() if np.issubdtype(self.c.dtype, np.complexfloating): raise ValueError("Root finding is only for " "real-valued polynomials") y = float(y) r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, y, bool(discontinuity), bool(extrapolate)) if self.c.ndim == 2: return r[0] else: r2 = np.empty(prod(self.c.shape[2:]), dtype=object) # this for-loop is equivalent to ``r2[...] = r``, but that's broken # in NumPy 1.6.0 for ii, root in enumerate(r): r2[ii] = root return r2.reshape(self.c.shape[2:]) def roots(self, discontinuity=True, extrapolate=None): """ Find real roots of the the piecewise polynomial. Parameters ---------- discontinuity : bool, optional Whether to report sign changes across discontinuities at breakpoints as roots. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to return roots from the polynomial extrapolated based on first and last intervals, 'periodic' works the same as False. If None (default), use `self.extrapolate`. Returns ------- roots : ndarray Roots of the polynomial(s). If the PPoly object describes multiple polynomials, the return value is an object array whose each element is an ndarray containing the roots. See Also -------- PPoly.solve """ return self.solve(0, discontinuity, extrapolate) @classmethod def from_spline(cls, tck, extrapolate=None): """ Construct a piecewise polynomial from a spline Parameters ---------- tck A spline, as returned by `splrep` or a BSpline object. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if isinstance(tck, BSpline): t, c, k = tck.tck if extrapolate is None: extrapolate = tck.extrapolate else: t, c, k = tck cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype) for m in range(k, -1, -1): y = fitpack.splev(t[:-1], tck, der=m) cvals[k - m, :] = y/spec.gamma(m+1) return cls.construct_fast(cvals, t, extrapolate) @classmethod def from_bernstein_basis(cls, bp, extrapolate=None): """ Construct a piecewise polynomial in the power basis from a polynomial in Bernstein basis. Parameters ---------- bp : BPoly A Bernstein basis polynomial, as created by BPoly extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if not isinstance(bp, BPoly): raise TypeError(".from_bernstein_basis only accepts BPoly instances. " "Got %s instead." % type(bp)) dx = np.diff(bp.x) k = bp.c.shape[0] - 1 # polynomial order rest = (None,)*(bp.c.ndim-2) c = np.zeros_like(bp.c) for a in range(k+1): factor = (-1)**a * comb(k, a) * bp.c[a] for s in range(a, k+1): val = comb(k-a, s-a) * (-1)**s c[k-s] += factor * val / dx[(slice(None),)+rest]**s if extrapolate is None: extrapolate = bp.extrapolate return cls.construct_fast(c, bp.x, extrapolate, bp.axis) class BPoly(_PPolyBase): """Piecewise polynomial in terms of coefficients and breakpoints. The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the Bernstein polynomial basis:: S = sum(c[a, i] * b(a, k; x) for a in range(k+1)), where ``k`` is the degree of the polynomial, and:: b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a), with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial coefficient. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals x : ndarray, shape (m+1,) Polynomial breakpoints. Must be sorted in either increasing or decreasing order. extrapolate : bool, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-D array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ extend derivative antiderivative integrate construct_fast from_power_basis from_derivatives See also -------- PPoly : piecewise polynomials in the power basis Notes ----- Properties of Bernstein polynomials are well documented in the literature, see for example [1]_ [2]_ [3]_. References ---------- .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial .. [2] Kenneth I. Joy, Bernstein polynomials, http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems, vol 2011, article ID 829546, :doi:`10.1155/2011/829543`. Examples -------- >>> from scipy.interpolate import BPoly >>> x = [0, 1] >>> c = [[1], [2], [3]] >>> bp = BPoly(c, x) This creates a 2nd order polynomial .. math:: B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3 \\times b_{2, 2}(x) \\\\ = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2 """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate_bernstein( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. Default is 1, i.e., compute the first derivative. If negative, the antiderivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k - nu representing the derivative of this polynomial. """ if nu < 0: return self.antiderivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.derivative() return bp # reduce order if nu == 0: c2 = self.c.copy() else: # For a polynomial # B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x), # we use the fact that # b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ), # which leads to # B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1} # # finally, for an interval [y, y + dy] with dy != 1, # we need to correct for an extra power of dy rest = (None,)*(self.c.ndim-2) k = self.c.shape[0] - 1 dx = np.diff(self.x)[(None, slice(None))+rest] c2 = k * np.diff(self.c, axis=0) / dx if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Parameters ---------- nu : int, optional Order of antiderivative to evaluate. Default is 1, i.e., compute the first integral. If negative, the derivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k + nu representing the antiderivative of this polynomial. Notes ----- If antiderivative is computed and ``self.extrapolate='periodic'``, it will be set to False for the returned instance. This is done because the antiderivative is no longer periodic and its correct evaluation outside of the initially given x interval is difficult. """ if nu <= 0: return self.derivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.antiderivative() return bp # Construct the indefinite integrals on individual intervals c, x = self.c, self.x k = c.shape[0] c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype) c2[1:, ...] = np.cumsum(c, axis=0) / k delta = x[1:] - x[:-1] c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)] # Now fix continuity: on the very first interval, take the integration # constant to be zero; on an interval [x_j, x_{j+1}) with j>0, # the integration constant is then equal to the jump of the `bp` at x_j. # The latter is given by the coefficient of B_{n+1, n+1} # *on the previous interval* (other B. polynomials are zero at the # breakpoint). Finally, use the fact that BPs form a partition of unity. c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1] if self.extrapolate == 'periodic': extrapolate = False else: extrapolate = self.extrapolate return self.construct_fast(c2, x, extrapolate, axis=self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : {bool, 'periodic', None}, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- array_like Definite integral of the piecewise polynomial over [a, b] """ # XXX: can probably use instead the fact that # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1) ib = self.antiderivative() if extrapolate is None: extrapolate = self.extrapolate # ib.extrapolate shouldn't be 'periodic', it is converted to # False for 'periodic. in antiderivative() call. if extrapolate != 'periodic': ib.extrapolate = extrapolate if extrapolate == 'periodic': # Split the integral into the part over period (can be several # of them) and the remaining part. # For simplicity and clarity convert to a <= b case. if a <= b: sign = 1 else: a, b = b, a sign = -1 xs, xe = self.x[0], self.x[-1] period = xe - xs interval = b - a n_periods, left = divmod(interval, period) res = n_periods * (ib(xe) - ib(xs)) # Map a and b to [xs, xe]. a = xs + (a - xs) % period b = a + left # If b <= xe then we need to integrate over [a, b], otherwise # over [a, xe] and from xs to what is remained. if b <= xe: res += ib(b) - ib(a) else: res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs) return sign * res else: return ib(b) - ib(a) def extend(self, c, x, right=None): k = max(self.c.shape[0], c.shape[0]) self.c = self._raise_degree(self.c, k - self.c.shape[0]) c = self._raise_degree(c, k - c.shape[0]) return _PPolyBase.extend(self, c, x, right) extend.__doc__ = _PPolyBase.extend.__doc__ @classmethod def from_power_basis(cls, pp, extrapolate=None): """ Construct a piecewise polynomial in Bernstein basis from a power basis polynomial. Parameters ---------- pp : PPoly A piecewise polynomial in the power basis extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if not isinstance(pp, PPoly): raise TypeError(".from_power_basis only accepts PPoly instances. " "Got %s instead." % type(pp)) dx = np.diff(pp.x) k = pp.c.shape[0] - 1 # polynomial order rest = (None,)*(pp.c.ndim-2) c = np.zeros_like(pp.c) for a in range(k+1): factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a) for j in range(k-a, k+1): c[j] += factor * comb(j, k-a) if extrapolate is None: extrapolate = pp.extrapolate return cls.construct_fast(c, pp.x, extrapolate, pp.axis) @classmethod def from_derivatives(cls, xi, yi, orders=None, extrapolate=None): """Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1-D array of x-coordinates yi : array_like or list of array_likes ``yi[i][j]`` is the ``j``th derivative known at ``xi[i]`` orders : None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. Notes ----- If ``k`` derivatives are specified at a breakpoint ``x``, the constructed polynomial is exactly ``k`` times continuously differentiable at ``x``, unless the ``order`` is provided explicitly. In the latter case, the smoothness of the polynomial at the breakpoint is controlled by the ``order``. Deduces the number of derivatives to match at each end from ``order`` and the number of derivatives available. If possible it uses the same number of derivatives from each end; if the number is odd it tries to take the extra one from y2. In any case if not enough derivatives are available at one end or another it draws enough to make up the total from the other end. If the order is too high and not enough derivatives are available, an exception is raised. Examples -------- >>> from scipy.interpolate import BPoly >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]]) Creates a polynomial `f(x)` of degree 3, defined on `[0, 1]` such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4` >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]]) Creates a piecewise polynomial `f(x)`, such that `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`. Based on the number of derivatives provided, the order of the local polynomials is 2 on `[0, 1]` and 1 on `[1, 2]`. Notice that no restriction is imposed on the derivatives at ``x = 1`` and ``x = 2``. Indeed, the explicit form of the polynomial is:: f(x) = | x * (1 - x), 0 <= x < 1 | 2 * (x - 1), 1 <= x <= 2 So that f'(1-0) = -1 and f'(1+0) = 2 """ xi = np.asarray(xi) if len(xi) != len(yi): raise ValueError("xi and yi need to have the same length") if np.any(xi[1:] - xi[:1] <= 0): raise ValueError("x coordinates are not in increasing order") # number of intervals m = len(xi) - 1 # global poly order is k-1, local orders are <=k and can vary try: k = max(len(yi[i]) + len(yi[i+1]) for i in range(m)) except TypeError: raise ValueError("Using a 1-D array for y? Please .reshape(-1, 1).") if orders is None: orders = [None] * m else: if isinstance(orders, (int, np.integer)): orders = [orders] * m k = max(k, max(orders)) if any(o <= 0 for o in orders): raise ValueError("Orders must be positive.") c = [] for i in range(m): y1, y2 = yi[i], yi[i+1] if orders[i] is None: n1, n2 = len(y1), len(y2) else: n = orders[i]+1 n1 = min(n//2, len(y1)) n2 = min(n - n1, len(y2)) n1 = min(n - n2, len(y2)) if n1+n2 != n: mesg = ("Point %g has %d derivatives, point %g" " has %d derivatives, but order %d requested" % ( xi[i], len(y1), xi[i+1], len(y2), orders[i])) raise ValueError(mesg) if not (n1 <= len(y1) and n2 <= len(y2)): raise ValueError("`order` input incompatible with" " length y1 or y2.") b = BPoly._construct_from_derivatives(xi[i], xi[i+1], y1[:n1], y2[:n2]) if len(b) < k: b = BPoly._raise_degree(b, k - len(b)) c.append(b) c = np.asarray(c) return cls(c.swapaxes(0, 1), xi, extrapolate) @staticmethod def _construct_from_derivatives(xa, xb, ya, yb): r"""Compute the coefficients of a polynomial in the Bernstein basis given the values and derivatives at the edges. Return the coefficients of a polynomial in the Bernstein basis defined on ``[xa, xb]`` and having the values and derivatives at the endpoints `xa` and `xb` as specified by `ya`` and `yb`. The polynomial constructed is of the minimal possible degree, i.e., if the lengths of `ya` and `yb` are `na` and `nb`, the degree of the polynomial is ``na + nb - 1``. Parameters ---------- xa : float Left-hand end point of the interval xb : float Right-hand end point of the interval ya : array_like Derivatives at `xa`. `ya[0]` is the value of the function, and `ya[i]` for ``i > 0`` is the value of the ``i``th derivative. yb : array_like Derivatives at `xb`. Returns ------- array coefficient array of a polynomial having specified derivatives Notes ----- This uses several facts from life of Bernstein basis functions. First of all, .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1}) If B(x) is a linear combination of the form .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n}, then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}. Iterating the latter one, one finds for the q-th derivative .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q}, with .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a} This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and `c_q` are found one by one by iterating `q = 0, ..., na`. At ``x = xb`` it's the same with ``a = n - q``. """ ya, yb = np.asarray(ya), np.asarray(yb) if ya.shape[1:] != yb.shape[1:]: raise ValueError('Shapes of ya {} and yb {} are incompatible' .format(ya.shape, yb.shape)) dta, dtb = ya.dtype, yb.dtype if (np.issubdtype(dta, np.complexfloating) or np.issubdtype(dtb, np.complexfloating)): dt = np.complex_ else: dt = np.float_ na, nb = len(ya), len(yb) n = na + nb c = np.empty((na+nb,) + ya.shape[1:], dtype=dt) # compute coefficients of a polynomial degree na+nb-1 # walk left-to-right for q in range(0, na): c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q for j in range(0, q): c[q] -= (-1)**(j+q) * comb(q, j) * c[j] # now walk right-to-left for q in range(0, nb): c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q for j in range(0, q): c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j] return c @staticmethod def _raise_degree(c, d): r"""Raise a degree of a polynomial in the Bernstein basis. Given the coefficients of a polynomial degree `k`, return (the coefficients of) the equivalent polynomial of degree `k+d`. Parameters ---------- c : array_like coefficient array, 1-D d : integer Returns ------- array coefficient array, 1-D array of length `c.shape[0] + d` Notes ----- This uses the fact that a Bernstein polynomial `b_{a, k}` can be identically represented as a linear combination of polynomials of a higher degree `k+d`: .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \ comb(d, j) / comb(k+d, a+j) """ if d == 0: return c k = c.shape[0] - 1 out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype) for a in range(c.shape[0]): f = c[a] * comb(k, a) for j in range(d+1): out[a+j] += f * comb(d, j) / comb(k+d, a+j) return out class NdPPoly(object): """ Piecewise tensor product polynomial The value at point ``xp = (x', y', z', ...)`` is evaluated by first computing the interval indices `i` such that:: x[0][i[0]] <= x' < x[0][i[0]+1] x[1][i[1]] <= y' < x[1][i[1]+1] ... and then computing:: S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]] * (xp[0] - x[0][i[0]])**m0 * ... * (xp[n] - x[n][i[n]])**mn for m0 in range(k[0]+1) ... for mn in range(k[n]+1)) where ``k[j]`` is the degree of the polynomial in dimension j. This representation is the piecewise multivariate power basis. Parameters ---------- c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...) Polynomial coefficients, with polynomial order `kj` and `mj+1` intervals for each dimension `j`. x : ndim-tuple of ndarrays, shapes (mj+1,) Polynomial breakpoints for each dimension. These must be sorted in increasing order. extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Default: True. Attributes ---------- x : tuple of ndarrays Breakpoints. c : ndarray Coefficients of the polynomials. Methods ------- __call__ construct_fast See also -------- PPoly : piecewise polynomials in 1D Notes ----- High-order polynomials in the power basis can be numerically unstable. """ def __init__(self, c, x, extrapolate=None): self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x) self.c = np.asarray(c) if extrapolate is None: extrapolate = True self.extrapolate = bool(extrapolate) ndim = len(self.x) if any(v.ndim != 1 for v in self.x): raise ValueError("x arrays must all be 1-dimensional") if any(v.size < 2 for v in self.x): raise ValueError("x arrays must all contain at least 2 points") if c.ndim < 2*ndim: raise ValueError("c must have at least 2*len(x) dimensions") if any(np.any(v[1:] - v[:-1] < 0) for v in self.x): raise ValueError("x-coordinates are not in increasing order") if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)): raise ValueError("x and c do not agree on the number of intervals") dtype = self._get_dtype(self.c.dtype) self.c = np.ascontiguousarray(self.c, dtype=dtype) @classmethod def construct_fast(cls, c, x, extrapolate=None): """ Construct the piecewise polynomial without making checks. Takes the same parameters as the constructor. Input arguments ``c`` and ``x`` must be arrays of the correct shape and type. The ``c`` array can only be of dtypes float and complex, and ``x`` array must have dtype float. """ self = object.__new__(cls) self.c = c self.x = x if extrapolate is None: extrapolate = True self.extrapolate = extrapolate return self def _get_dtype(self, dtype): if np.issubdtype(dtype, np.complexfloating) \ or np.issubdtype(self.c.dtype, np.complexfloating): return np.complex_ else: return np.float_ def _ensure_c_contiguous(self): if not self.c.flags.c_contiguous: self.c = self.c.copy() if not isinstance(self.x, tuple): self.x = tuple(self.x) def __call__(self, x, nu=None, extrapolate=None): """ Evaluate the piecewise polynomial or its derivative Parameters ---------- x : array-like Points to evaluate the interpolant at. nu : tuple, optional Orders of derivatives to evaluate. Each must be non-negative. extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- y : array-like Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) ndim = len(self.x) x = _ndim_coords_from_arrays(x) x_shape = x.shape x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float_) if nu is None: nu = np.zeros((ndim,), dtype=np.intc) else: nu = np.asarray(nu, dtype=np.intc) if nu.ndim != 1 or nu.shape[0] != ndim: raise ValueError("invalid number of derivative orders nu") dim1 = prod(self.c.shape[:ndim]) dim2 = prod(self.c.shape[ndim:2*ndim]) dim3 = prod(self.c.shape[2*ndim:]) ks = np.array(self.c.shape[:ndim], dtype=np.intc) out = np.empty((x.shape[0], dim3), dtype=self.c.dtype) self._ensure_c_contiguous() _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3), self.x, ks, x, nu, bool(extrapolate), out) return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:]) def _derivative_inplace(self, nu, axis): """ Compute 1-D derivative along a selected dimension in-place May result to non-contiguous c array. """ if nu < 0: return self._antiderivative_inplace(-nu, axis) ndim = len(self.x) axis = axis % ndim # reduce order if nu == 0: # noop return else: sl = [slice(None)]*ndim sl[axis] = slice(None, -nu, None) c2 = self.c[tuple(sl)] if c2.shape[axis] == 0: # derivative of order 0 is zero shp = list(c2.shape) shp[axis] = 1 c2 = np.zeros(shp, dtype=c2.dtype) # multiply by the correct rising factorials factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu) sl = [None]*c2.ndim sl[axis] = slice(None) c2 *= factor[tuple(sl)] self.c = c2 def _antiderivative_inplace(self, nu, axis): """ Compute 1-D antiderivative along a selected dimension May result to non-contiguous c array. """ if nu <= 0: return self._derivative_inplace(-nu, axis) ndim = len(self.x) axis = axis % ndim perm = list(range(ndim)) perm[0], perm[axis] = perm[axis], perm[0] perm = perm + list(range(ndim, self.c.ndim)) c = self.c.transpose(perm) c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:], dtype=c.dtype) c2[:-nu] = c # divide by the correct rising factorials factor = spec.poch(np.arange(c.shape[0], 0, -1), nu) c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] # fix continuity of added degrees of freedom perm2 = list(range(c2.ndim)) perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1] c2 = c2.transpose(perm2) c2 = c2.copy() _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1), self.x[axis], nu-1) c2 = c2.transpose(perm2) c2 = c2.transpose(perm) # Done self.c = c2 def derivative(self, nu): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : ndim-tuple of int Order of derivatives to evaluate for each dimension. If negative, the antiderivative is returned. Returns ------- pp : NdPPoly Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n]) representing the derivative of this polynomial. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals in each dimension are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) for axis, n in enumerate(nu): p._derivative_inplace(n, axis) p._ensure_c_contiguous() return p def antiderivative(self, nu): """ Construct a new piecewise polynomial representing the antiderivative. Antiderivative is also the indefinite integral of the function, and derivative is its inverse operation. Parameters ---------- nu : ndim-tuple of int Order of derivatives to evaluate for each dimension. If negative, the derivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k + n representing the antiderivative of this polynomial. Notes ----- The antiderivative returned by this function is continuous and continuously differentiable to order n-1, up to floating point rounding error. """ p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) for axis, n in enumerate(nu): p._antiderivative_inplace(n, axis) p._ensure_c_contiguous() return p def integrate_1d(self, a, b, axis, extrapolate=None): r""" Compute NdPPoly representation for one dimensional definite integral The result is a piecewise polynomial representing the integral: .. math:: p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...) where the dimension integrated over is specified with the `axis` parameter. Parameters ---------- a, b : float Lower and upper bound for integration. axis : int Dimension over which to compute the 1-D integrals extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- ig : NdPPoly or array-like Definite integral of the piecewise polynomial over [a, b]. If the polynomial was 1D, an array is returned, otherwise, an NdPPoly object. """ if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) ndim = len(self.x) axis = int(axis) % ndim # reuse 1-D integration routines c = self.c swap = list(range(c.ndim)) swap.insert(0, swap[axis]) del swap[axis + 1] swap.insert(1, swap[ndim + axis]) del swap[ndim + axis + 1] c = c.transpose(swap) p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1), self.x[axis], extrapolate=extrapolate) out = p.integrate(a, b, extrapolate=extrapolate) # Construct result if ndim == 1: return out.reshape(c.shape[2:]) else: c = out.reshape(c.shape[2:]) x = self.x[:axis] + self.x[axis+1:] return self.construct_fast(c, x, extrapolate=extrapolate) def integrate(self, ranges, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- ranges : ndim-tuple of 2-tuples float Sequence of lower and upper bounds for each dimension, ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]`` extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- ig : array_like Definite integral of the piecewise polynomial over [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]] """ ndim = len(self.x) if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) if not hasattr(ranges, '__len__') or len(ranges) != ndim: raise ValueError("Range not a sequence of correct length") self._ensure_c_contiguous() # Reuse 1D integration routine c = self.c for n, (a, b) in enumerate(ranges): swap = list(range(c.ndim)) swap.insert(1, swap[ndim - n]) del swap[ndim - n + 1] c = c.transpose(swap) p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate) out = p.integrate(a, b, extrapolate=extrapolate) c = out.reshape(c.shape[2:]) return c class RegularGridInterpolator(object): """ Interpolation on a regular grid in arbitrary dimensions The data must be defined on a regular grid; the grid spacing however may be uneven. Linear and nearest-neighbor interpolation are supported. After setting up the interpolator object, the interpolation method (*linear* or *nearest*) may be chosen at each evaluation. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest". This parameter will become the default for the object's ``__call__`` method. Default is "linear". bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Methods ------- __call__ Notes ----- Contrary to LinearNDInterpolator and NearestNDInterpolator, this class avoids expensive triangulation of the input data by taking advantage of the regular grid structure. If any of `points` have a dimension of size 1, linear interpolation will return an array of `nan` values. Nearest-neighbor interpolation will work as usual in this case. .. versionadded:: 0.14 Examples -------- Evaluate a simple example function on the points of a 3-D grid: >>> from scipy.interpolate import RegularGridInterpolator >>> def f(x, y, z): ... return 2 * x**3 + 3 * y**2 - z >>> x = np.linspace(1, 4, 11) >>> y = np.linspace(4, 7, 22) >>> z = np.linspace(7, 9, 33) >>> data = f(*np.meshgrid(x, y, z, indexing='ij', sparse=True)) ``data`` is now a 3-D array with ``data[i,j,k] = f(x[i], y[j], z[k])``. Next, define an interpolating function from this data: >>> my_interpolating_function = RegularGridInterpolator((x, y, z), data) Evaluate the interpolating function at the two points ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``: >>> pts = np.array([[2.1, 6.2, 8.3], [3.3, 5.2, 7.1]]) >>> my_interpolating_function(pts) array([ 125.80469388, 146.30069388]) which is indeed a close approximation to ``[f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)]``. See also -------- NearestNDInterpolator : Nearest neighbor interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions References ---------- .. [1] Python package *regulargrid* by Johannes Buchner, see https://pypi.python.org/pypi/regulargrid/ .. [2] Wikipedia, "Trilinear interpolation", https://en.wikipedia.org/wiki/Trilinear_interpolation .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear and multilinear table interpolation in many dimensions." MATH. COMPUT. 50.181 (1988): 189-196. https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf """ # this class is based on code originally programmed by Johannes Buchner, # see https://github.com/JohannesBuchner/regulargrid def __init__(self, points, values, method="linear", bounds_error=True, fill_value=np.nan): if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) self.method = method self.bounds_error = bounds_error if not hasattr(values, 'ndim'): # allow reasonable duck-typed values values = np.asarray(values) if len(points) > values.ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), values.ndim)) if hasattr(values, 'dtype') and hasattr(values, 'astype'): if not np.issubdtype(values.dtype, np.inexact): values = values.astype(float) self.fill_value = fill_value if fill_value is not None: fill_value_dtype = np.asarray(fill_value).dtype if (hasattr(values, 'dtype') and not np.can_cast(fill_value_dtype, values.dtype, casting='same_kind')): raise ValueError("fill_value must be either 'None' or " "of a type compatible with values") for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) self.grid = tuple([np.asarray(p) for p in points]) self.values = values def __call__(self, xi, method=None): """ Interpolation at coordinates Parameters ---------- xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str The method of interpolation to perform. Supported are "linear" and "nearest". """ method = self.method if method is None else method if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) ndim = len(self.grid) xi = _ndim_coords_from_arrays(xi, ndim=ndim) if xi.shape[-1] != len(self.grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], ndim)) xi_shape = xi.shape xi = xi.reshape(-1, xi_shape[-1]) if self.bounds_error: for i, p in enumerate(xi.T): if not np.logical_and(np.all(self.grid[i][0] <= p), np.all(p <= self.grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) indices, norm_distances, out_of_bounds = self._find_indices(xi.T) if method == "linear": result = self._evaluate_linear(indices, norm_distances, out_of_bounds) elif method == "nearest": result = self._evaluate_nearest(indices, norm_distances, out_of_bounds) if not self.bounds_error and self.fill_value is not None: result[out_of_bounds] = self.fill_value return result.reshape(xi_shape[:-1] + self.values.shape[ndim:]) def _evaluate_linear(self, indices, norm_distances, out_of_bounds): # slice for broadcasting over trailing dimensions in self.values vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices)) # find relevant values # each i and i+1 represents a edge edges = itertools.product(*[[i, i + 1] for i in indices]) values = 0. for edge_indices in edges: weight = 1. for ei, i, yi in zip(edge_indices, indices, norm_distances): weight *= np.where(ei == i, 1 - yi, yi) values += np.asarray(self.values[edge_indices]) * weight[vslice] return values def _evaluate_nearest(self, indices, norm_distances, out_of_bounds): idx_res = [np.where(yi <= .5, i, i + 1) for i, yi in zip(indices, norm_distances)] return self.values[tuple(idx_res)] def _find_indices(self, xi): # find relevant edges between which xi are situated indices = [] # compute distance to lower edge in unity units norm_distances = [] # check for out of bounds xi out_of_bounds = np.zeros((xi.shape[1]), dtype=bool) # iterate through dimensions for x, grid in zip(xi, self.grid): i = np.searchsorted(grid, x) - 1 i[i < 0] = 0 i[i > grid.size - 2] = grid.size - 2 indices.append(i) norm_distances.append((x - grid[i]) / (grid[i + 1] - grid[i])) if not self.bounds_error: out_of_bounds += x < grid[0] out_of_bounds += x > grid[-1] return indices, norm_distances, out_of_bounds def interpn(points, values, xi, method="linear", bounds_error=True, fill_value=np.nan): """ Multidimensional interpolation on regular grids. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest", and "splinef2d". "splinef2d" is only supported for 2-dimensional data. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Extrapolation is not supported by method "splinef2d". Returns ------- values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] Interpolated values at input coordinates. Notes ----- .. versionadded:: 0.14 Examples -------- Evaluate a simple example function on the points of a regular 3-D grid: >>> from scipy.interpolate import interpn >>> def value_func_3d(x, y, z): ... return 2 * x + 3 * y - z >>> x = np.linspace(0, 5) >>> y = np.linspace(0, 5) >>> z = np.linspace(0, 5) >>> points = (x, y, z) >>> values = value_func_3d(*np.meshgrid(*points)) Evaluate the interpolating function at a point >>> point = np.array([2.21, 3.12, 1.15]) >>> print(interpn(points, values, point)) [11.72] See also -------- NearestNDInterpolator : Nearest neighbor interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions RegularGridInterpolator : Linear and nearest-neighbor Interpolation on a regular grid in arbitrary dimensions RectBivariateSpline : Bivariate spline approximation over a rectangular mesh """ # sanity check 'method' kwarg if method not in ["linear", "nearest", "splinef2d"]: raise ValueError("interpn only understands the methods 'linear', " "'nearest', and 'splinef2d'. You provided %s." % method) if not hasattr(values, 'ndim'): values = np.asarray(values) ndim = values.ndim if ndim > 2 and method == "splinef2d": raise ValueError("The method splinef2d can only be used for " "2-dimensional input data") if not bounds_error and fill_value is None and method == "splinef2d": raise ValueError("The method splinef2d does not support extrapolation.") # sanity check consistency of input dimensions if len(points) > ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), ndim)) if len(points) != ndim and method == 'splinef2d': raise ValueError("The method splinef2d can only be used for " "scalar data with one point per coordinate") # sanity check input grid for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) grid = tuple([np.asarray(p) for p in points]) # sanity check requested xi xi = _ndim_coords_from_arrays(xi, ndim=len(grid)) if xi.shape[-1] != len(grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], len(grid))) for i, p in enumerate(xi.T): if bounds_error and not np.logical_and(np.all(grid[i][0] <= p), np.all(p <= grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) # perform interpolation if method == "linear": interp = RegularGridInterpolator(points, values, method="linear", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "nearest": interp = RegularGridInterpolator(points, values, method="nearest", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "splinef2d": xi_shape = xi.shape xi = xi.reshape(-1, xi.shape[-1]) # RectBivariateSpline doesn't support fill_value; we need to wrap here idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1], grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]), axis=0) result = np.empty_like(xi[:, 0]) # make a copy of values for RectBivariateSpline interp = RectBivariateSpline(points[0], points[1], values[:]) result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1]) result[np.logical_not(idx_valid)] = fill_value return result.reshape(xi_shape[:-1]) # backward compatibility wrapper class _ppform(PPoly): """ Deprecated piecewise polynomial class. New code should use the `PPoly` class instead. """ def __init__(self, coeffs, breaks, fill=0.0, sort=False): warnings.warn("_ppform is deprecated -- use PPoly instead", category=DeprecationWarning) if sort: breaks = np.sort(breaks) else: breaks = np.asarray(breaks) PPoly.__init__(self, coeffs, breaks) self.coeffs = self.c self.breaks = self.x self.K = self.coeffs.shape[0] self.fill = fill self.a = self.breaks[0] self.b = self.breaks[-1] def __call__(self, x): return PPoly.__call__(self, x, 0, False) def _evaluate(self, x, nu, extrapolate, out): PPoly._evaluate(self, x, nu, extrapolate, out) out[~((x >= self.a) & (x <= self.b))] = self.fill return out @classmethod def fromspline(cls, xk, cvals, order, fill=0.0): # Note: this spline representation is incompatible with FITPACK N = len(xk)-1 sivals = np.empty((order+1, N), dtype=float) for m in range(order, -1, -1): fact = spec.gamma(m+1) res = _fitpack._bspleval(xk[:-1], xk, cvals, order, m) res /= fact sivals[order-m, :] = res return cls(sivals, xk, fill=fill)
{ "repo_name": "pizzathief/scipy", "path": "scipy/interpolate/interpolate.py", "copies": "2", "size": "98262", "license": "bsd-3-clause", "hash": 5529917065104486000, "line_mean": 34.8358862144, "line_max": 112, "alpha_frac": 0.5433840142, "autogenerated": false, "ratio": 3.9134174997013025, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.00010444624003605113, "num_lines": 2742 }
__all__ = ['interp1d', 'interp2d', 'lagrange', 'PPoly', 'BPoly', 'NdPPoly', 'RegularGridInterpolator', 'interpn'] import itertools import warnings import numpy as np from numpy import (array, transpose, searchsorted, atleast_1d, atleast_2d, ravel, poly1d, asarray, intp) import scipy.special as spec from scipy.special import comb from scipy._lib._util import prod from . import fitpack from . import dfitpack from . import _fitpack from .polyint import _Interpolator1D from . import _ppoly from .fitpack2 import RectBivariateSpline from .interpnd import _ndim_coords_from_arrays from ._bsplines import make_interp_spline, BSpline def lagrange(x, w): r""" Return a Lagrange interpolating polynomial. Given two 1-D arrays `x` and `w,` returns the Lagrange interpolating polynomial through the points ``(x, w)``. Warning: This implementation is numerically unstable. Do not expect to be able to use more than about 20 points even if they are chosen optimally. Parameters ---------- x : array_like `x` represents the x-coordinates of a set of datapoints. w : array_like `w` represents the y-coordinates of a set of datapoints, i.e., f(`x`). Returns ------- lagrange : `numpy.poly1d` instance The Lagrange interpolating polynomial. Examples -------- Interpolate :math:`f(x) = x^3` by 3 points. >>> from scipy.interpolate import lagrange >>> x = np.array([0, 1, 2]) >>> y = x**3 >>> poly = lagrange(x, y) Since there are only 3 points, Lagrange polynomial has degree 2. Explicitly, it is given by .. math:: \begin{aligned} L(x) &= 1\times \frac{x (x - 2)}{-1} + 8\times \frac{x (x-1)}{2} \\ &= x (-2 + 3x) \end{aligned} >>> from numpy.polynomial.polynomial import Polynomial >>> Polynomial(poly).coef array([ 3., -2., 0.]) """ M = len(x) p = poly1d(0.0) for j in range(M): pt = poly1d(w[j]) for k in range(M): if k == j: continue fac = x[j]-x[k] pt *= poly1d([1.0, -x[k]])/fac p += pt return p # !! Need to find argument for keeping initialize. If it isn't # !! found, get rid of it! class interp2d(object): """ interp2d(x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None) Interpolate over a 2-D grid. `x`, `y` and `z` are arrays of values used to approximate some function f: ``z = f(x, y)``. This class returns a function whose call method uses spline interpolation to find the value of new points. If `x` and `y` represent a regular grid, consider using RectBivariateSpline. Note that calling `interp2d` with NaNs present in input values results in undefined behaviour. Methods ------- __call__ Parameters ---------- x, y : array_like Arrays defining the data point coordinates. If the points lie on a regular grid, `x` can specify the column coordinates and `y` the row coordinates, for example:: >>> x = [0,1,2]; y = [0,3]; z = [[1,2,3], [4,5,6]] Otherwise, `x` and `y` must specify the full coordinates for each point, for example:: >>> x = [0,1,2,0,1,2]; y = [0,0,0,3,3,3]; z = [1,2,3,4,5,6] If `x` and `y` are multidimensional, they are flattened before use. z : array_like The values of the function to interpolate at the data points. If `z` is a multidimensional array, it is flattened before use. The length of a flattened `z` array is either len(`x`)*len(`y`) if `x` and `y` specify the column and row coordinates or ``len(z) == len(x) == len(y)`` if `x` and `y` specify coordinates for each point. kind : {'linear', 'cubic', 'quintic'}, optional The kind of spline interpolation to use. Default is 'linear'. copy : bool, optional If True, the class makes internal copies of x, y and z. If False, references may be used. The default is to copy. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data (x,y), a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If omitted (None), values outside the domain are extrapolated via nearest-neighbor extrapolation. See Also -------- RectBivariateSpline : Much faster 2-D interpolation if your input data is on a grid bisplrep, bisplev : Spline interpolation based on FITPACK BivariateSpline : a more recent wrapper of the FITPACK routines interp1d : 1-D version of this function Notes ----- The minimum number of data points required along the interpolation axis is ``(k+1)**2``, with k=1 for linear, k=3 for cubic and k=5 for quintic interpolation. The interpolator is constructed by `bisplrep`, with a smoothing factor of 0. If more control over smoothing is needed, `bisplrep` should be used directly. Examples -------- Construct a 2-D grid and interpolate on it: >>> from scipy import interpolate >>> x = np.arange(-5.01, 5.01, 0.25) >>> y = np.arange(-5.01, 5.01, 0.25) >>> xx, yy = np.meshgrid(x, y) >>> z = np.sin(xx**2+yy**2) >>> f = interpolate.interp2d(x, y, z, kind='cubic') Now use the obtained interpolation function and plot the result: >>> import matplotlib.pyplot as plt >>> xnew = np.arange(-5.01, 5.01, 1e-2) >>> ynew = np.arange(-5.01, 5.01, 1e-2) >>> znew = f(xnew, ynew) >>> plt.plot(x, z[0, :], 'ro-', xnew, znew[0, :], 'b-') >>> plt.show() """ def __init__(self, x, y, z, kind='linear', copy=True, bounds_error=False, fill_value=None): x = ravel(x) y = ravel(y) z = asarray(z) rectangular_grid = (z.size == len(x) * len(y)) if rectangular_grid: if z.ndim == 2: if z.shape != (len(y), len(x)): raise ValueError("When on a regular grid with x.size = m " "and y.size = n, if z.ndim == 2, then z " "must have shape (n, m)") if not np.all(x[1:] >= x[:-1]): j = np.argsort(x) x = x[j] z = z[:, j] if not np.all(y[1:] >= y[:-1]): j = np.argsort(y) y = y[j] z = z[j, :] z = ravel(z.T) else: z = ravel(z) if len(x) != len(y): raise ValueError( "x and y must have equal lengths for non rectangular grid") if len(z) != len(x): raise ValueError( "Invalid length for input z for non rectangular grid") interpolation_types = {'linear': 1, 'cubic': 3, 'quintic': 5} try: kx = ky = interpolation_types[kind] except KeyError as e: raise ValueError( f"Unsupported interpolation type {repr(kind)}, must be " f"either of {', '.join(map(repr, interpolation_types))}." ) from e if not rectangular_grid: # TODO: surfit is really not meant for interpolation! self.tck = fitpack.bisplrep(x, y, z, kx=kx, ky=ky, s=0.0) else: nx, tx, ny, ty, c, fp, ier = dfitpack.regrid_smth( x, y, z, None, None, None, None, kx=kx, ky=ky, s=0.0) self.tck = (tx[:nx], ty[:ny], c[:(nx - kx - 1) * (ny - ky - 1)], kx, ky) self.bounds_error = bounds_error self.fill_value = fill_value self.x, self.y, self.z = [array(a, copy=copy) for a in (x, y, z)] self.x_min, self.x_max = np.amin(x), np.amax(x) self.y_min, self.y_max = np.amin(y), np.amax(y) def __call__(self, x, y, dx=0, dy=0, assume_sorted=False): """Interpolate the function. Parameters ---------- x : 1-D array x-coordinates of the mesh on which to interpolate. y : 1-D array y-coordinates of the mesh on which to interpolate. dx : int >= 0, < kx Order of partial derivatives in x. dy : int >= 0, < ky Order of partial derivatives in y. assume_sorted : bool, optional If False, values of `x` and `y` can be in any order and they are sorted first. If True, `x` and `y` have to be arrays of monotonically increasing values. Returns ------- z : 2-D array with shape (len(y), len(x)) The interpolated values. """ x = atleast_1d(x) y = atleast_1d(y) if x.ndim != 1 or y.ndim != 1: raise ValueError("x and y should both be 1-D arrays") if not assume_sorted: x = np.sort(x, kind="mergesort") y = np.sort(y, kind="mergesort") if self.bounds_error or self.fill_value is not None: out_of_bounds_x = (x < self.x_min) | (x > self.x_max) out_of_bounds_y = (y < self.y_min) | (y > self.y_max) any_out_of_bounds_x = np.any(out_of_bounds_x) any_out_of_bounds_y = np.any(out_of_bounds_y) if self.bounds_error and (any_out_of_bounds_x or any_out_of_bounds_y): raise ValueError("Values out of range; x must be in %r, y in %r" % ((self.x_min, self.x_max), (self.y_min, self.y_max))) z = fitpack.bisplev(x, y, self.tck, dx, dy) z = atleast_2d(z) z = transpose(z) if self.fill_value is not None: if any_out_of_bounds_x: z[:, out_of_bounds_x] = self.fill_value if any_out_of_bounds_y: z[out_of_bounds_y, :] = self.fill_value if len(z) == 1: z = z[0] return array(z) def _check_broadcast_up_to(arr_from, shape_to, name): """Helper to check that arr_from broadcasts up to shape_to""" shape_from = arr_from.shape if len(shape_to) >= len(shape_from): for t, f in zip(shape_to[::-1], shape_from[::-1]): if f != 1 and f != t: break else: # all checks pass, do the upcasting that we need later if arr_from.size != 1 and arr_from.shape != shape_to: arr_from = np.ones(shape_to, arr_from.dtype) * arr_from return arr_from.ravel() # at least one check failed raise ValueError('%s argument must be able to broadcast up ' 'to shape %s but had shape %s' % (name, shape_to, shape_from)) def _do_extrapolate(fill_value): """Helper to check if fill_value == "extrapolate" without warnings""" return (isinstance(fill_value, str) and fill_value == 'extrapolate') class interp1d(_Interpolator1D): """ Interpolate a 1-D function. `x` and `y` are arrays of values used to approximate some function f: ``y = f(x)``. This class returns a function whose call method uses interpolation to find the value of new points. Parameters ---------- x : (N,) array_like A 1-D array of real values. y : (...,N,...) array_like A N-D array of real values. The length of `y` along the interpolation axis must be equal to the length of `x`. kind : str or int, optional Specifies the kind of interpolation as a string ('linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic', 'previous', 'next', where 'zero', 'slinear', 'quadratic' and 'cubic' refer to a spline interpolation of zeroth, first, second or third order; 'previous' and 'next' simply return the previous or next value of the point) or as an integer specifying the order of the spline interpolator to use. Default is 'linear'. axis : int, optional Specifies the axis of `y` along which to interpolate. Interpolation defaults to the last axis of `y`. copy : bool, optional If True, the class makes internal copies of x and y. If False, references to `x` and `y` are used. The default is to copy. bounds_error : bool, optional If True, a ValueError is raised any time interpolation is attempted on a value outside of the range of x (where extrapolation is necessary). If False, out of bounds values are assigned `fill_value`. By default, an error is raised unless ``fill_value="extrapolate"``. fill_value : array-like or (array-like, array_like) or "extrapolate", optional - if a ndarray (or float), this value will be used to fill in for requested points outside of the data range. If not provided, then the default is NaN. The array-like must broadcast properly to the dimensions of the non-interpolation axes. - If a two-element tuple, then the first element is used as a fill value for ``x_new < x[0]`` and the second element is used for ``x_new > x[-1]``. Anything that is not a 2-element tuple (e.g., list or ndarray, regardless of shape) is taken to be a single array-like argument meant to be used for both bounds as ``below, above = fill_value, fill_value``. .. versionadded:: 0.17.0 - If "extrapolate", then points outside the data range will be extrapolated. .. versionadded:: 0.17.0 assume_sorted : bool, optional If False, values of `x` can be in any order and they are sorted first. If True, `x` has to be an array of monotonically increasing values. Attributes ---------- fill_value Methods ------- __call__ See Also -------- splrep, splev Spline interpolation/smoothing based on FITPACK. UnivariateSpline : An object-oriented wrapper of the FITPACK routines. interp2d : 2-D interpolation Notes ----- Calling `interp1d` with NaNs present in input values results in undefined behaviour. Input values `x` and `y` must be convertible to `float` values like `int` or `float`. Examples -------- >>> import matplotlib.pyplot as plt >>> from scipy import interpolate >>> x = np.arange(0, 10) >>> y = np.exp(-x/3.0) >>> f = interpolate.interp1d(x, y) >>> xnew = np.arange(0, 9, 0.1) >>> ynew = f(xnew) # use interpolation function returned by `interp1d` >>> plt.plot(x, y, 'o', xnew, ynew, '-') >>> plt.show() """ def __init__(self, x, y, kind='linear', axis=-1, copy=True, bounds_error=None, fill_value=np.nan, assume_sorted=False): """ Initialize a 1-D linear interpolation class.""" _Interpolator1D.__init__(self, x, y, axis=axis) self.bounds_error = bounds_error # used by fill_value setter self.copy = copy if kind in ['zero', 'slinear', 'quadratic', 'cubic']: order = {'zero': 0, 'slinear': 1, 'quadratic': 2, 'cubic': 3}[kind] kind = 'spline' elif isinstance(kind, int): order = kind kind = 'spline' elif kind not in ('linear', 'nearest', 'previous', 'next'): raise NotImplementedError("%s is unsupported: Use fitpack " "routines for other types." % kind) x = array(x, copy=self.copy) y = array(y, copy=self.copy) if not assume_sorted: ind = np.argsort(x, kind="mergesort") x = x[ind] y = np.take(y, ind, axis=axis) if x.ndim != 1: raise ValueError("the x array must have exactly one dimension.") if y.ndim == 0: raise ValueError("the y array must have at least one dimension.") # Force-cast y to a floating-point type, if it's not yet one if not issubclass(y.dtype.type, np.inexact): y = y.astype(np.float_) # Backward compatibility self.axis = axis % y.ndim # Interpolation goes internally along the first axis self.y = y self._y = self._reshape_yi(self.y) self.x = x del y, x # clean up namespace to prevent misuse; use attributes self._kind = kind self.fill_value = fill_value # calls the setter, can modify bounds_err # Adjust to interpolation kind; store reference to *unbound* # interpolation methods, in order to avoid circular references to self # stored in the bound instance methods, and therefore delayed garbage # collection. See: https://docs.python.org/reference/datamodel.html if kind in ('linear', 'nearest', 'previous', 'next'): # Make a "view" of the y array that is rotated to the interpolation # axis. minval = 2 if kind == 'nearest': # Do division before addition to prevent possible integer # overflow self.x_bds = self.x / 2.0 self.x_bds = self.x_bds[1:] + self.x_bds[:-1] self._call = self.__class__._call_nearest elif kind == 'previous': # Side for np.searchsorted and index for clipping self._side = 'left' self._ind = 0 # Move x by one floating point value to the left self._x_shift = np.nextafter(self.x, -np.inf) self._call = self.__class__._call_previousnext elif kind == 'next': self._side = 'right' self._ind = 1 # Move x by one floating point value to the right self._x_shift = np.nextafter(self.x, np.inf) self._call = self.__class__._call_previousnext else: # Check if we can delegate to numpy.interp (2x-10x faster). cond = self.x.dtype == np.float_ and self.y.dtype == np.float_ cond = cond and self.y.ndim == 1 cond = cond and not _do_extrapolate(fill_value) if cond: self._call = self.__class__._call_linear_np else: self._call = self.__class__._call_linear else: minval = order + 1 rewrite_nan = False xx, yy = self.x, self._y if order > 1: # Quadratic or cubic spline. If input contains even a single # nan, then the output is all nans. We cannot just feed data # with nans to make_interp_spline because it calls LAPACK. # So, we make up a bogus x and y with no nans and use it # to get the correct shape of the output, which we then fill # with nans. # For slinear or zero order spline, we just pass nans through. mask = np.isnan(self.x) if mask.any(): sx = self.x[~mask] if sx.size == 0: raise ValueError("`x` array is all-nan") xx = np.linspace(np.nanmin(self.x), np.nanmax(self.x), len(self.x)) rewrite_nan = True if np.isnan(self._y).any(): yy = np.ones_like(self._y) rewrite_nan = True self._spline = make_interp_spline(xx, yy, k=order, check_finite=False) if rewrite_nan: self._call = self.__class__._call_nan_spline else: self._call = self.__class__._call_spline if len(self.x) < minval: raise ValueError("x and y arrays must have at " "least %d entries" % minval) @property def fill_value(self): """The fill value.""" # backwards compat: mimic a public attribute return self._fill_value_orig @fill_value.setter def fill_value(self, fill_value): # extrapolation only works for nearest neighbor and linear methods if _do_extrapolate(fill_value): if self.bounds_error: raise ValueError("Cannot extrapolate and raise " "at the same time.") self.bounds_error = False self._extrapolate = True else: broadcast_shape = (self.y.shape[:self.axis] + self.y.shape[self.axis + 1:]) if len(broadcast_shape) == 0: broadcast_shape = (1,) # it's either a pair (_below_range, _above_range) or a single value # for both above and below range if isinstance(fill_value, tuple) and len(fill_value) == 2: below_above = [np.asarray(fill_value[0]), np.asarray(fill_value[1])] names = ('fill_value (below)', 'fill_value (above)') for ii in range(2): below_above[ii] = _check_broadcast_up_to( below_above[ii], broadcast_shape, names[ii]) else: fill_value = np.asarray(fill_value) below_above = [_check_broadcast_up_to( fill_value, broadcast_shape, 'fill_value')] * 2 self._fill_value_below, self._fill_value_above = below_above self._extrapolate = False if self.bounds_error is None: self.bounds_error = True # backwards compat: fill_value was a public attr; make it writeable self._fill_value_orig = fill_value def _call_linear_np(self, x_new): # Note that out-of-bounds values are taken care of in self._evaluate return np.interp(x_new, self.x, self.y) def _call_linear(self, x_new): # 2. Find where in the original data, the values to interpolate # would be inserted. # Note: If x_new[n] == x[m], then m is returned by searchsorted. x_new_indices = searchsorted(self.x, x_new) # 3. Clip x_new_indices so that they are within the range of # self.x indices and at least 1. Removes mis-interpolation # of x_new[n] = x[0] x_new_indices = x_new_indices.clip(1, len(self.x)-1).astype(int) # 4. Calculate the slope of regions that each x_new value falls in. lo = x_new_indices - 1 hi = x_new_indices x_lo = self.x[lo] x_hi = self.x[hi] y_lo = self._y[lo] y_hi = self._y[hi] # Note that the following two expressions rely on the specifics of the # broadcasting semantics. slope = (y_hi - y_lo) / (x_hi - x_lo)[:, None] # 5. Calculate the actual value for each entry in x_new. y_new = slope*(x_new - x_lo)[:, None] + y_lo return y_new def _call_nearest(self, x_new): """ Find nearest neighbor interpolated y_new = f(x_new).""" # 2. Find where in the averaged data the values to interpolate # would be inserted. # Note: use side='left' (right) to searchsorted() to define the # halfway point to be nearest to the left (right) neighbor x_new_indices = searchsorted(self.x_bds, x_new, side='left') # 3. Clip x_new_indices so that they are within the range of x indices. x_new_indices = x_new_indices.clip(0, len(self.x)-1).astype(intp) # 4. Calculate the actual value for each entry in x_new. y_new = self._y[x_new_indices] return y_new def _call_previousnext(self, x_new): """Use previous/next neighbor of x_new, y_new = f(x_new).""" # 1. Get index of left/right value x_new_indices = searchsorted(self._x_shift, x_new, side=self._side) # 2. Clip x_new_indices so that they are within the range of x indices. x_new_indices = x_new_indices.clip(1-self._ind, len(self.x)-self._ind).astype(intp) # 3. Calculate the actual value for each entry in x_new. y_new = self._y[x_new_indices+self._ind-1] return y_new def _call_spline(self, x_new): return self._spline(x_new) def _call_nan_spline(self, x_new): out = self._spline(x_new) out[...] = np.nan return out def _evaluate(self, x_new): # 1. Handle values in x_new that are outside of x. Throw error, # or return a list of mask array indicating the outofbounds values. # The behavior is set by the bounds_error variable. x_new = asarray(x_new) y_new = self._call(self, x_new) if not self._extrapolate: below_bounds, above_bounds = self._check_bounds(x_new) if len(y_new) > 0: # Note fill_value must be broadcast up to the proper size # and flattened to work here y_new[below_bounds] = self._fill_value_below y_new[above_bounds] = self._fill_value_above return y_new def _check_bounds(self, x_new): """Check the inputs for being in the bounds of the interpolated data. Parameters ---------- x_new : array Returns ------- out_of_bounds : bool array The mask on x_new of values that are out of the bounds. """ # If self.bounds_error is True, we raise an error if any x_new values # fall outside the range of x. Otherwise, we return an array indicating # which values are outside the boundary region. below_bounds = x_new < self.x[0] above_bounds = x_new > self.x[-1] # !! Could provide more information about which values are out of bounds if self.bounds_error and below_bounds.any(): raise ValueError("A value in x_new is below the interpolation " "range.") if self.bounds_error and above_bounds.any(): raise ValueError("A value in x_new is above the interpolation " "range.") # !! Should we emit a warning if some values are out of bounds? # !! matlab does not. return below_bounds, above_bounds class _PPolyBase(object): """Base class for piecewise polynomials.""" __slots__ = ('c', 'x', 'extrapolate', 'axis') def __init__(self, c, x, extrapolate=None, axis=0): self.c = np.asarray(c) self.x = np.ascontiguousarray(x, dtype=np.float64) if extrapolate is None: extrapolate = True elif extrapolate != 'periodic': extrapolate = bool(extrapolate) self.extrapolate = extrapolate if self.c.ndim < 2: raise ValueError("Coefficients array must be at least " "2-dimensional.") if not (0 <= axis < self.c.ndim - 1): raise ValueError("axis=%s must be between 0 and %s" % (axis, self.c.ndim-1)) self.axis = axis if axis != 0: # roll the interpolation axis to be the first one in self.c # More specifically, the target shape for self.c is (k, m, ...), # and axis !=0 means that we have c.shape (..., k, m, ...) # ^ # axis # So we roll two of them. self.c = np.rollaxis(self.c, axis+1) self.c = np.rollaxis(self.c, axis+1) if self.x.ndim != 1: raise ValueError("x must be 1-dimensional") if self.x.size < 2: raise ValueError("at least 2 breakpoints are needed") if self.c.ndim < 2: raise ValueError("c must have at least 2 dimensions") if self.c.shape[0] == 0: raise ValueError("polynomial must be at least of order 0") if self.c.shape[1] != self.x.size-1: raise ValueError("number of coefficients != len(x)-1") dx = np.diff(self.x) if not (np.all(dx >= 0) or np.all(dx <= 0)): raise ValueError("`x` must be strictly increasing or decreasing.") dtype = self._get_dtype(self.c.dtype) self.c = np.ascontiguousarray(self.c, dtype=dtype) def _get_dtype(self, dtype): if np.issubdtype(dtype, np.complexfloating) \ or np.issubdtype(self.c.dtype, np.complexfloating): return np.complex_ else: return np.float_ @classmethod def construct_fast(cls, c, x, extrapolate=None, axis=0): """ Construct the piecewise polynomial without making checks. Takes the same parameters as the constructor. Input arguments ``c`` and ``x`` must be arrays of the correct shape and type. The ``c`` array can only be of dtypes float and complex, and ``x`` array must have dtype float. """ self = object.__new__(cls) self.c = c self.x = x self.axis = axis if extrapolate is None: extrapolate = True self.extrapolate = extrapolate return self def _ensure_c_contiguous(self): """ c and x may be modified by the user. The Cython code expects that they are C contiguous. """ if not self.x.flags.c_contiguous: self.x = self.x.copy() if not self.c.flags.c_contiguous: self.c = self.c.copy() def extend(self, c, x, right=None): """ Add additional breakpoints and coefficients to the polynomial. Parameters ---------- c : ndarray, size (k, m, ...) Additional coefficients for polynomials in intervals. Note that the first additional interval will be formed using one of the ``self.x`` end points. x : ndarray, size (m,) Additional breakpoints. Must be sorted in the same order as ``self.x`` and either to the right or to the left of the current breakpoints. right Deprecated argument. Has no effect. .. deprecated:: 0.19 """ if right is not None: warnings.warn("`right` is deprecated and will be removed.") c = np.asarray(c) x = np.asarray(x) if c.ndim < 2: raise ValueError("invalid dimensions for c") if x.ndim != 1: raise ValueError("invalid dimensions for x") if x.shape[0] != c.shape[1]: raise ValueError("Shapes of x {} and c {} are incompatible" .format(x.shape, c.shape)) if c.shape[2:] != self.c.shape[2:] or c.ndim != self.c.ndim: raise ValueError("Shapes of c {} and self.c {} are incompatible" .format(c.shape, self.c.shape)) if c.size == 0: return dx = np.diff(x) if not (np.all(dx >= 0) or np.all(dx <= 0)): raise ValueError("`x` is not sorted.") if self.x[-1] >= self.x[0]: if not x[-1] >= x[0]: raise ValueError("`x` is in the different order " "than `self.x`.") if x[0] >= self.x[-1]: action = 'append' elif x[-1] <= self.x[0]: action = 'prepend' else: raise ValueError("`x` is neither on the left or on the right " "from `self.x`.") else: if not x[-1] <= x[0]: raise ValueError("`x` is in the different order " "than `self.x`.") if x[0] <= self.x[-1]: action = 'append' elif x[-1] >= self.x[0]: action = 'prepend' else: raise ValueError("`x` is neither on the left or on the right " "from `self.x`.") dtype = self._get_dtype(c.dtype) k2 = max(c.shape[0], self.c.shape[0]) c2 = np.zeros((k2, self.c.shape[1] + c.shape[1]) + self.c.shape[2:], dtype=dtype) if action == 'append': c2[k2-self.c.shape[0]:, :self.c.shape[1]] = self.c c2[k2-c.shape[0]:, self.c.shape[1]:] = c self.x = np.r_[self.x, x] elif action == 'prepend': c2[k2-self.c.shape[0]:, :c.shape[1]] = c c2[k2-c.shape[0]:, c.shape[1]:] = self.c self.x = np.r_[x, self.x] self.c = c2 def __call__(self, x, nu=0, extrapolate=None): """ Evaluate the piecewise polynomial or its derivative. Parameters ---------- x : array_like Points to evaluate the interpolant at. nu : int, optional Order of derivative to evaluate. Must be non-negative. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- y : array_like Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if extrapolate is None: extrapolate = self.extrapolate x = np.asarray(x) x_shape, x_ndim = x.shape, x.ndim x = np.ascontiguousarray(x.ravel(), dtype=np.float_) # With periodic extrapolation we map x to the segment # [self.x[0], self.x[-1]]. if extrapolate == 'periodic': x = self.x[0] + (x - self.x[0]) % (self.x[-1] - self.x[0]) extrapolate = False out = np.empty((len(x), prod(self.c.shape[2:])), dtype=self.c.dtype) self._ensure_c_contiguous() self._evaluate(x, nu, extrapolate, out) out = out.reshape(x_shape + self.c.shape[2:]) if self.axis != 0: # transpose to move the calculated values to the interpolation axis l = list(range(out.ndim)) l = l[x_ndim:x_ndim+self.axis] + l[:x_ndim] + l[x_ndim+self.axis:] out = out.transpose(l) return out class PPoly(_PPolyBase): """ Piecewise polynomial in terms of coefficients and breakpoints The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the local power basis:: S = sum(c[m, i] * (xp - x[i])**(k-m) for m in range(k+1)) where ``k`` is the degree of the polynomial. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals. x : ndarray, shape (m+1,) Polynomial breakpoints. Must be sorted in either increasing or decreasing order. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-D array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ derivative antiderivative integrate solve roots extend from_spline from_bernstein_basis construct_fast See also -------- BPoly : piecewise polynomials in the Bernstein basis Notes ----- High-order polynomials in the power basis can be numerically unstable. Precision problems can start to appear for orders larger than 20-30. """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. Default is 1, i.e., compute the first derivative. If negative, the antiderivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k - n representing the derivative of this polynomial. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if nu < 0: return self.antiderivative(-nu) # reduce order if nu == 0: c2 = self.c.copy() else: c2 = self.c[:-nu, :].copy() if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # multiply by the correct rising factorials factor = spec.poch(np.arange(c2.shape[0], 0, -1), nu) c2 *= factor[(slice(None),) + (None,)*(c2.ndim-1)] # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Antiderivative is also the indefinite integral of the function, and derivative is its inverse operation. Parameters ---------- nu : int, optional Order of antiderivative to evaluate. Default is 1, i.e., compute the first integral. If negative, the derivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k + n representing the antiderivative of this polynomial. Notes ----- The antiderivative returned by this function is continuous and continuously differentiable to order n-1, up to floating point rounding error. If antiderivative is computed and ``self.extrapolate='periodic'``, it will be set to False for the returned instance. This is done because the antiderivative is no longer periodic and its correct evaluation outside of the initially given x interval is difficult. """ if nu <= 0: return self.derivative(-nu) c = np.zeros((self.c.shape[0] + nu, self.c.shape[1]) + self.c.shape[2:], dtype=self.c.dtype) c[:-nu] = self.c # divide by the correct rising factorials factor = spec.poch(np.arange(self.c.shape[0], 0, -1), nu) c[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] # fix continuity of added degrees of freedom self._ensure_c_contiguous() _ppoly.fix_continuity(c.reshape(c.shape[0], c.shape[1], -1), self.x, nu - 1) if self.extrapolate == 'periodic': extrapolate = False else: extrapolate = self.extrapolate # construct a compatible polynomial return self.construct_fast(c, self.x, extrapolate, self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- ig : array_like Definite integral of the piecewise polynomial over [a, b] """ if extrapolate is None: extrapolate = self.extrapolate # Swap integration bounds if needed sign = 1 if b < a: a, b = b, a sign = -1 range_int = np.empty((prod(self.c.shape[2:]),), dtype=self.c.dtype) self._ensure_c_contiguous() # Compute the integral. if extrapolate == 'periodic': # Split the integral into the part over period (can be several # of them) and the remaining part. xs, xe = self.x[0], self.x[-1] period = xe - xs interval = b - a n_periods, left = divmod(interval, period) if n_periods > 0: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, xs, xe, False, out=range_int) range_int *= n_periods else: range_int.fill(0) # Map a to [xs, xe], b is always a + left. a = xs + (a - xs) % period b = a + left # If b <= xe then we need to integrate over [a, b], otherwise # over [a, xe] and from xs to what is remained. remainder_int = np.empty_like(range_int) if b <= xe: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, b, False, out=remainder_int) range_int += remainder_int else: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, xe, False, out=remainder_int) range_int += remainder_int _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, xs, xs + left + a - xe, False, out=remainder_int) range_int += remainder_int else: _ppoly.integrate( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, a, b, bool(extrapolate), out=range_int) # Return range_int *= sign return range_int.reshape(self.c.shape[2:]) def solve(self, y=0., discontinuity=True, extrapolate=None): """ Find real solutions of the the equation ``pp(x) == y``. Parameters ---------- y : float, optional Right-hand side. Default is zero. discontinuity : bool, optional Whether to report sign changes across discontinuities at breakpoints as roots. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to return roots from the polynomial extrapolated based on first and last intervals, 'periodic' works the same as False. If None (default), use `self.extrapolate`. Returns ------- roots : ndarray Roots of the polynomial(s). If the PPoly object describes multiple polynomials, the return value is an object array whose each element is an ndarray containing the roots. Notes ----- This routine works only on real-valued polynomials. If the piecewise polynomial contains sections that are identically zero, the root list will contain the start point of the corresponding interval, followed by a ``nan`` value. If the polynomial is discontinuous across a breakpoint, and there is a sign change across the breakpoint, this is reported if the `discont` parameter is True. Examples -------- Finding roots of ``[x**2 - 1, (x - 1)**2]`` defined on intervals ``[-2, 1], [1, 2]``: >>> from scipy.interpolate import PPoly >>> pp = PPoly(np.array([[1, -4, 3], [1, 0, 0]]).T, [-2, 1, 2]) >>> pp.solve() array([-1., 1.]) """ if extrapolate is None: extrapolate = self.extrapolate self._ensure_c_contiguous() if np.issubdtype(self.c.dtype, np.complexfloating): raise ValueError("Root finding is only for " "real-valued polynomials") y = float(y) r = _ppoly.real_roots(self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, y, bool(discontinuity), bool(extrapolate)) if self.c.ndim == 2: return r[0] else: r2 = np.empty(prod(self.c.shape[2:]), dtype=object) # this for-loop is equivalent to ``r2[...] = r``, but that's broken # in NumPy 1.6.0 for ii, root in enumerate(r): r2[ii] = root return r2.reshape(self.c.shape[2:]) def roots(self, discontinuity=True, extrapolate=None): """ Find real roots of the the piecewise polynomial. Parameters ---------- discontinuity : bool, optional Whether to report sign changes across discontinuities at breakpoints as roots. extrapolate : {bool, 'periodic', None}, optional If bool, determines whether to return roots from the polynomial extrapolated based on first and last intervals, 'periodic' works the same as False. If None (default), use `self.extrapolate`. Returns ------- roots : ndarray Roots of the polynomial(s). If the PPoly object describes multiple polynomials, the return value is an object array whose each element is an ndarray containing the roots. See Also -------- PPoly.solve """ return self.solve(0, discontinuity, extrapolate) @classmethod def from_spline(cls, tck, extrapolate=None): """ Construct a piecewise polynomial from a spline Parameters ---------- tck A spline, as returned by `splrep` or a BSpline object. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if isinstance(tck, BSpline): t, c, k = tck.tck if extrapolate is None: extrapolate = tck.extrapolate else: t, c, k = tck cvals = np.empty((k + 1, len(t)-1), dtype=c.dtype) for m in range(k, -1, -1): y = fitpack.splev(t[:-1], tck, der=m) cvals[k - m, :] = y/spec.gamma(m+1) return cls.construct_fast(cvals, t, extrapolate) @classmethod def from_bernstein_basis(cls, bp, extrapolate=None): """ Construct a piecewise polynomial in the power basis from a polynomial in Bernstein basis. Parameters ---------- bp : BPoly A Bernstein basis polynomial, as created by BPoly extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if not isinstance(bp, BPoly): raise TypeError(".from_bernstein_basis only accepts BPoly instances. " "Got %s instead." % type(bp)) dx = np.diff(bp.x) k = bp.c.shape[0] - 1 # polynomial order rest = (None,)*(bp.c.ndim-2) c = np.zeros_like(bp.c) for a in range(k+1): factor = (-1)**a * comb(k, a) * bp.c[a] for s in range(a, k+1): val = comb(k-a, s-a) * (-1)**s c[k-s] += factor * val / dx[(slice(None),)+rest]**s if extrapolate is None: extrapolate = bp.extrapolate return cls.construct_fast(c, bp.x, extrapolate, bp.axis) class BPoly(_PPolyBase): """Piecewise polynomial in terms of coefficients and breakpoints. The polynomial between ``x[i]`` and ``x[i + 1]`` is written in the Bernstein polynomial basis:: S = sum(c[a, i] * b(a, k; x) for a in range(k+1)), where ``k`` is the degree of the polynomial, and:: b(a, k; x) = binom(k, a) * t**a * (1 - t)**(k - a), with ``t = (x - x[i]) / (x[i+1] - x[i])`` and ``binom`` is the binomial coefficient. Parameters ---------- c : ndarray, shape (k, m, ...) Polynomial coefficients, order `k` and `m` intervals x : ndarray, shape (m+1,) Polynomial breakpoints. Must be sorted in either increasing or decreasing order. extrapolate : bool, optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. axis : int, optional Interpolation axis. Default is zero. Attributes ---------- x : ndarray Breakpoints. c : ndarray Coefficients of the polynomials. They are reshaped to a 3-D array with the last dimension representing the trailing dimensions of the original coefficient array. axis : int Interpolation axis. Methods ------- __call__ extend derivative antiderivative integrate construct_fast from_power_basis from_derivatives See also -------- PPoly : piecewise polynomials in the power basis Notes ----- Properties of Bernstein polynomials are well documented in the literature, see for example [1]_ [2]_ [3]_. References ---------- .. [1] https://en.wikipedia.org/wiki/Bernstein_polynomial .. [2] Kenneth I. Joy, Bernstein polynomials, http://www.idav.ucdavis.edu/education/CAGDNotes/Bernstein-Polynomials.pdf .. [3] E. H. Doha, A. H. Bhrawy, and M. A. Saker, Boundary Value Problems, vol 2011, article ID 829546, :doi:`10.1155/2011/829543`. Examples -------- >>> from scipy.interpolate import BPoly >>> x = [0, 1] >>> c = [[1], [2], [3]] >>> bp = BPoly(c, x) This creates a 2nd order polynomial .. math:: B(x) = 1 \\times b_{0, 2}(x) + 2 \\times b_{1, 2}(x) + 3 \\times b_{2, 2}(x) \\\\ = 1 \\times (1-x)^2 + 2 \\times 2 x (1 - x) + 3 \\times x^2 """ def _evaluate(self, x, nu, extrapolate, out): _ppoly.evaluate_bernstein( self.c.reshape(self.c.shape[0], self.c.shape[1], -1), self.x, x, nu, bool(extrapolate), out) def derivative(self, nu=1): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : int, optional Order of derivative to evaluate. Default is 1, i.e., compute the first derivative. If negative, the antiderivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k - nu representing the derivative of this polynomial. """ if nu < 0: return self.antiderivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.derivative() return bp # reduce order if nu == 0: c2 = self.c.copy() else: # For a polynomial # B(x) = \sum_{a=0}^{k} c_a b_{a, k}(x), # we use the fact that # b'_{a, k} = k ( b_{a-1, k-1} - b_{a, k-1} ), # which leads to # B'(x) = \sum_{a=0}^{k-1} (c_{a+1} - c_a) b_{a, k-1} # # finally, for an interval [y, y + dy] with dy != 1, # we need to correct for an extra power of dy rest = (None,)*(self.c.ndim-2) k = self.c.shape[0] - 1 dx = np.diff(self.x)[(None, slice(None))+rest] c2 = k * np.diff(self.c, axis=0) / dx if c2.shape[0] == 0: # derivative of order 0 is zero c2 = np.zeros((1,) + c2.shape[1:], dtype=c2.dtype) # construct a compatible polynomial return self.construct_fast(c2, self.x, self.extrapolate, self.axis) def antiderivative(self, nu=1): """ Construct a new piecewise polynomial representing the antiderivative. Parameters ---------- nu : int, optional Order of antiderivative to evaluate. Default is 1, i.e., compute the first integral. If negative, the derivative is returned. Returns ------- bp : BPoly Piecewise polynomial of order k + nu representing the antiderivative of this polynomial. Notes ----- If antiderivative is computed and ``self.extrapolate='periodic'``, it will be set to False for the returned instance. This is done because the antiderivative is no longer periodic and its correct evaluation outside of the initially given x interval is difficult. """ if nu <= 0: return self.derivative(-nu) if nu > 1: bp = self for k in range(nu): bp = bp.antiderivative() return bp # Construct the indefinite integrals on individual intervals c, x = self.c, self.x k = c.shape[0] c2 = np.zeros((k+1,) + c.shape[1:], dtype=c.dtype) c2[1:, ...] = np.cumsum(c, axis=0) / k delta = x[1:] - x[:-1] c2 *= delta[(None, slice(None)) + (None,)*(c.ndim-2)] # Now fix continuity: on the very first interval, take the integration # constant to be zero; on an interval [x_j, x_{j+1}) with j>0, # the integration constant is then equal to the jump of the `bp` at x_j. # The latter is given by the coefficient of B_{n+1, n+1} # *on the previous interval* (other B. polynomials are zero at the # breakpoint). Finally, use the fact that BPs form a partition of unity. c2[:,1:] += np.cumsum(c2[k, :], axis=0)[:-1] if self.extrapolate == 'periodic': extrapolate = False else: extrapolate = self.extrapolate return self.construct_fast(c2, x, extrapolate, axis=self.axis) def integrate(self, a, b, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- a : float Lower integration bound b : float Upper integration bound extrapolate : {bool, 'periodic', None}, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. If None (default), use `self.extrapolate`. Returns ------- array_like Definite integral of the piecewise polynomial over [a, b] """ # XXX: can probably use instead the fact that # \int_0^{1} B_{j, n}(x) \dx = 1/(n+1) ib = self.antiderivative() if extrapolate is None: extrapolate = self.extrapolate # ib.extrapolate shouldn't be 'periodic', it is converted to # False for 'periodic. in antiderivative() call. if extrapolate != 'periodic': ib.extrapolate = extrapolate if extrapolate == 'periodic': # Split the integral into the part over period (can be several # of them) and the remaining part. # For simplicity and clarity convert to a <= b case. if a <= b: sign = 1 else: a, b = b, a sign = -1 xs, xe = self.x[0], self.x[-1] period = xe - xs interval = b - a n_periods, left = divmod(interval, period) res = n_periods * (ib(xe) - ib(xs)) # Map a and b to [xs, xe]. a = xs + (a - xs) % period b = a + left # If b <= xe then we need to integrate over [a, b], otherwise # over [a, xe] and from xs to what is remained. if b <= xe: res += ib(b) - ib(a) else: res += ib(xe) - ib(a) + ib(xs + left + a - xe) - ib(xs) return sign * res else: return ib(b) - ib(a) def extend(self, c, x, right=None): k = max(self.c.shape[0], c.shape[0]) self.c = self._raise_degree(self.c, k - self.c.shape[0]) c = self._raise_degree(c, k - c.shape[0]) return _PPolyBase.extend(self, c, x, right) extend.__doc__ = _PPolyBase.extend.__doc__ @classmethod def from_power_basis(cls, pp, extrapolate=None): """ Construct a piecewise polynomial in Bernstein basis from a power basis polynomial. Parameters ---------- pp : PPoly A piecewise polynomial in the power basis extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. """ if not isinstance(pp, PPoly): raise TypeError(".from_power_basis only accepts PPoly instances. " "Got %s instead." % type(pp)) dx = np.diff(pp.x) k = pp.c.shape[0] - 1 # polynomial order rest = (None,)*(pp.c.ndim-2) c = np.zeros_like(pp.c) for a in range(k+1): factor = pp.c[a] / comb(k, k-a) * dx[(slice(None),)+rest]**(k-a) for j in range(k-a, k+1): c[j] += factor * comb(j, k-a) if extrapolate is None: extrapolate = pp.extrapolate return cls.construct_fast(c, pp.x, extrapolate, pp.axis) @classmethod def from_derivatives(cls, xi, yi, orders=None, extrapolate=None): """Construct a piecewise polynomial in the Bernstein basis, compatible with the specified values and derivatives at breakpoints. Parameters ---------- xi : array_like sorted 1-D array of x-coordinates yi : array_like or list of array_likes ``yi[i][j]`` is the ``j``th derivative known at ``xi[i]`` orders : None or int or array_like of ints. Default: None. Specifies the degree of local polynomials. If not None, some derivatives are ignored. extrapolate : bool or 'periodic', optional If bool, determines whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. If 'periodic', periodic extrapolation is used. Default is True. Notes ----- If ``k`` derivatives are specified at a breakpoint ``x``, the constructed polynomial is exactly ``k`` times continuously differentiable at ``x``, unless the ``order`` is provided explicitly. In the latter case, the smoothness of the polynomial at the breakpoint is controlled by the ``order``. Deduces the number of derivatives to match at each end from ``order`` and the number of derivatives available. If possible it uses the same number of derivatives from each end; if the number is odd it tries to take the extra one from y2. In any case if not enough derivatives are available at one end or another it draws enough to make up the total from the other end. If the order is too high and not enough derivatives are available, an exception is raised. Examples -------- >>> from scipy.interpolate import BPoly >>> BPoly.from_derivatives([0, 1], [[1, 2], [3, 4]]) Creates a polynomial `f(x)` of degree 3, defined on `[0, 1]` such that `f(0) = 1, df/dx(0) = 2, f(1) = 3, df/dx(1) = 4` >>> BPoly.from_derivatives([0, 1, 2], [[0, 1], [0], [2]]) Creates a piecewise polynomial `f(x)`, such that `f(0) = f(1) = 0`, `f(2) = 2`, and `df/dx(0) = 1`. Based on the number of derivatives provided, the order of the local polynomials is 2 on `[0, 1]` and 1 on `[1, 2]`. Notice that no restriction is imposed on the derivatives at ``x = 1`` and ``x = 2``. Indeed, the explicit form of the polynomial is:: f(x) = | x * (1 - x), 0 <= x < 1 | 2 * (x - 1), 1 <= x <= 2 So that f'(1-0) = -1 and f'(1+0) = 2 """ xi = np.asarray(xi) if len(xi) != len(yi): raise ValueError("xi and yi need to have the same length") if np.any(xi[1:] - xi[:1] <= 0): raise ValueError("x coordinates are not in increasing order") # number of intervals m = len(xi) - 1 # global poly order is k-1, local orders are <=k and can vary try: k = max(len(yi[i]) + len(yi[i+1]) for i in range(m)) except TypeError as e: raise ValueError( "Using a 1-D array for y? Please .reshape(-1, 1)." ) from e if orders is None: orders = [None] * m else: if isinstance(orders, (int, np.integer)): orders = [orders] * m k = max(k, max(orders)) if any(o <= 0 for o in orders): raise ValueError("Orders must be positive.") c = [] for i in range(m): y1, y2 = yi[i], yi[i+1] if orders[i] is None: n1, n2 = len(y1), len(y2) else: n = orders[i]+1 n1 = min(n//2, len(y1)) n2 = min(n - n1, len(y2)) n1 = min(n - n2, len(y2)) if n1+n2 != n: mesg = ("Point %g has %d derivatives, point %g" " has %d derivatives, but order %d requested" % ( xi[i], len(y1), xi[i+1], len(y2), orders[i])) raise ValueError(mesg) if not (n1 <= len(y1) and n2 <= len(y2)): raise ValueError("`order` input incompatible with" " length y1 or y2.") b = BPoly._construct_from_derivatives(xi[i], xi[i+1], y1[:n1], y2[:n2]) if len(b) < k: b = BPoly._raise_degree(b, k - len(b)) c.append(b) c = np.asarray(c) return cls(c.swapaxes(0, 1), xi, extrapolate) @staticmethod def _construct_from_derivatives(xa, xb, ya, yb): r"""Compute the coefficients of a polynomial in the Bernstein basis given the values and derivatives at the edges. Return the coefficients of a polynomial in the Bernstein basis defined on ``[xa, xb]`` and having the values and derivatives at the endpoints `xa` and `xb` as specified by `ya`` and `yb`. The polynomial constructed is of the minimal possible degree, i.e., if the lengths of `ya` and `yb` are `na` and `nb`, the degree of the polynomial is ``na + nb - 1``. Parameters ---------- xa : float Left-hand end point of the interval xb : float Right-hand end point of the interval ya : array_like Derivatives at `xa`. `ya[0]` is the value of the function, and `ya[i]` for ``i > 0`` is the value of the ``i``th derivative. yb : array_like Derivatives at `xb`. Returns ------- array coefficient array of a polynomial having specified derivatives Notes ----- This uses several facts from life of Bernstein basis functions. First of all, .. math:: b'_{a, n} = n (b_{a-1, n-1} - b_{a, n-1}) If B(x) is a linear combination of the form .. math:: B(x) = \sum_{a=0}^{n} c_a b_{a, n}, then :math: B'(x) = n \sum_{a=0}^{n-1} (c_{a+1} - c_{a}) b_{a, n-1}. Iterating the latter one, one finds for the q-th derivative .. math:: B^{q}(x) = n!/(n-q)! \sum_{a=0}^{n-q} Q_a b_{a, n-q}, with .. math:: Q_a = \sum_{j=0}^{q} (-)^{j+q} comb(q, j) c_{j+a} This way, only `a=0` contributes to :math: `B^{q}(x = xa)`, and `c_q` are found one by one by iterating `q = 0, ..., na`. At ``x = xb`` it's the same with ``a = n - q``. """ ya, yb = np.asarray(ya), np.asarray(yb) if ya.shape[1:] != yb.shape[1:]: raise ValueError('Shapes of ya {} and yb {} are incompatible' .format(ya.shape, yb.shape)) dta, dtb = ya.dtype, yb.dtype if (np.issubdtype(dta, np.complexfloating) or np.issubdtype(dtb, np.complexfloating)): dt = np.complex_ else: dt = np.float_ na, nb = len(ya), len(yb) n = na + nb c = np.empty((na+nb,) + ya.shape[1:], dtype=dt) # compute coefficients of a polynomial degree na+nb-1 # walk left-to-right for q in range(0, na): c[q] = ya[q] / spec.poch(n - q, q) * (xb - xa)**q for j in range(0, q): c[q] -= (-1)**(j+q) * comb(q, j) * c[j] # now walk right-to-left for q in range(0, nb): c[-q-1] = yb[q] / spec.poch(n - q, q) * (-1)**q * (xb - xa)**q for j in range(0, q): c[-q-1] -= (-1)**(j+1) * comb(q, j+1) * c[-q+j] return c @staticmethod def _raise_degree(c, d): r"""Raise a degree of a polynomial in the Bernstein basis. Given the coefficients of a polynomial degree `k`, return (the coefficients of) the equivalent polynomial of degree `k+d`. Parameters ---------- c : array_like coefficient array, 1-D d : integer Returns ------- array coefficient array, 1-D array of length `c.shape[0] + d` Notes ----- This uses the fact that a Bernstein polynomial `b_{a, k}` can be identically represented as a linear combination of polynomials of a higher degree `k+d`: .. math:: b_{a, k} = comb(k, a) \sum_{j=0}^{d} b_{a+j, k+d} \ comb(d, j) / comb(k+d, a+j) """ if d == 0: return c k = c.shape[0] - 1 out = np.zeros((c.shape[0] + d,) + c.shape[1:], dtype=c.dtype) for a in range(c.shape[0]): f = c[a] * comb(k, a) for j in range(d+1): out[a+j] += f * comb(d, j) / comb(k+d, a+j) return out class NdPPoly(object): """ Piecewise tensor product polynomial The value at point ``xp = (x', y', z', ...)`` is evaluated by first computing the interval indices `i` such that:: x[0][i[0]] <= x' < x[0][i[0]+1] x[1][i[1]] <= y' < x[1][i[1]+1] ... and then computing:: S = sum(c[k0-m0-1,...,kn-mn-1,i[0],...,i[n]] * (xp[0] - x[0][i[0]])**m0 * ... * (xp[n] - x[n][i[n]])**mn for m0 in range(k[0]+1) ... for mn in range(k[n]+1)) where ``k[j]`` is the degree of the polynomial in dimension j. This representation is the piecewise multivariate power basis. Parameters ---------- c : ndarray, shape (k0, ..., kn, m0, ..., mn, ...) Polynomial coefficients, with polynomial order `kj` and `mj+1` intervals for each dimension `j`. x : ndim-tuple of ndarrays, shapes (mj+1,) Polynomial breakpoints for each dimension. These must be sorted in increasing order. extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Default: True. Attributes ---------- x : tuple of ndarrays Breakpoints. c : ndarray Coefficients of the polynomials. Methods ------- __call__ derivative antiderivative integrate integrate_1d construct_fast See also -------- PPoly : piecewise polynomials in 1D Notes ----- High-order polynomials in the power basis can be numerically unstable. """ def __init__(self, c, x, extrapolate=None): self.x = tuple(np.ascontiguousarray(v, dtype=np.float64) for v in x) self.c = np.asarray(c) if extrapolate is None: extrapolate = True self.extrapolate = bool(extrapolate) ndim = len(self.x) if any(v.ndim != 1 for v in self.x): raise ValueError("x arrays must all be 1-dimensional") if any(v.size < 2 for v in self.x): raise ValueError("x arrays must all contain at least 2 points") if c.ndim < 2*ndim: raise ValueError("c must have at least 2*len(x) dimensions") if any(np.any(v[1:] - v[:-1] < 0) for v in self.x): raise ValueError("x-coordinates are not in increasing order") if any(a != b.size - 1 for a, b in zip(c.shape[ndim:2*ndim], self.x)): raise ValueError("x and c do not agree on the number of intervals") dtype = self._get_dtype(self.c.dtype) self.c = np.ascontiguousarray(self.c, dtype=dtype) @classmethod def construct_fast(cls, c, x, extrapolate=None): """ Construct the piecewise polynomial without making checks. Takes the same parameters as the constructor. Input arguments ``c`` and ``x`` must be arrays of the correct shape and type. The ``c`` array can only be of dtypes float and complex, and ``x`` array must have dtype float. """ self = object.__new__(cls) self.c = c self.x = x if extrapolate is None: extrapolate = True self.extrapolate = extrapolate return self def _get_dtype(self, dtype): if np.issubdtype(dtype, np.complexfloating) \ or np.issubdtype(self.c.dtype, np.complexfloating): return np.complex_ else: return np.float_ def _ensure_c_contiguous(self): if not self.c.flags.c_contiguous: self.c = self.c.copy() if not isinstance(self.x, tuple): self.x = tuple(self.x) def __call__(self, x, nu=None, extrapolate=None): """ Evaluate the piecewise polynomial or its derivative Parameters ---------- x : array-like Points to evaluate the interpolant at. nu : tuple, optional Orders of derivatives to evaluate. Each must be non-negative. extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- y : array-like Interpolated values. Shape is determined by replacing the interpolation axis in the original array with the shape of x. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) ndim = len(self.x) x = _ndim_coords_from_arrays(x) x_shape = x.shape x = np.ascontiguousarray(x.reshape(-1, x.shape[-1]), dtype=np.float_) if nu is None: nu = np.zeros((ndim,), dtype=np.intc) else: nu = np.asarray(nu, dtype=np.intc) if nu.ndim != 1 or nu.shape[0] != ndim: raise ValueError("invalid number of derivative orders nu") dim1 = prod(self.c.shape[:ndim]) dim2 = prod(self.c.shape[ndim:2*ndim]) dim3 = prod(self.c.shape[2*ndim:]) ks = np.array(self.c.shape[:ndim], dtype=np.intc) out = np.empty((x.shape[0], dim3), dtype=self.c.dtype) self._ensure_c_contiguous() _ppoly.evaluate_nd(self.c.reshape(dim1, dim2, dim3), self.x, ks, x, nu, bool(extrapolate), out) return out.reshape(x_shape[:-1] + self.c.shape[2*ndim:]) def _derivative_inplace(self, nu, axis): """ Compute 1-D derivative along a selected dimension in-place May result to non-contiguous c array. """ if nu < 0: return self._antiderivative_inplace(-nu, axis) ndim = len(self.x) axis = axis % ndim # reduce order if nu == 0: # noop return else: sl = [slice(None)]*ndim sl[axis] = slice(None, -nu, None) c2 = self.c[tuple(sl)] if c2.shape[axis] == 0: # derivative of order 0 is zero shp = list(c2.shape) shp[axis] = 1 c2 = np.zeros(shp, dtype=c2.dtype) # multiply by the correct rising factorials factor = spec.poch(np.arange(c2.shape[axis], 0, -1), nu) sl = [None]*c2.ndim sl[axis] = slice(None) c2 *= factor[tuple(sl)] self.c = c2 def _antiderivative_inplace(self, nu, axis): """ Compute 1-D antiderivative along a selected dimension May result to non-contiguous c array. """ if nu <= 0: return self._derivative_inplace(-nu, axis) ndim = len(self.x) axis = axis % ndim perm = list(range(ndim)) perm[0], perm[axis] = perm[axis], perm[0] perm = perm + list(range(ndim, self.c.ndim)) c = self.c.transpose(perm) c2 = np.zeros((c.shape[0] + nu,) + c.shape[1:], dtype=c.dtype) c2[:-nu] = c # divide by the correct rising factorials factor = spec.poch(np.arange(c.shape[0], 0, -1), nu) c2[:-nu] /= factor[(slice(None),) + (None,)*(c.ndim-1)] # fix continuity of added degrees of freedom perm2 = list(range(c2.ndim)) perm2[1], perm2[ndim+axis] = perm2[ndim+axis], perm2[1] c2 = c2.transpose(perm2) c2 = c2.copy() _ppoly.fix_continuity(c2.reshape(c2.shape[0], c2.shape[1], -1), self.x[axis], nu-1) c2 = c2.transpose(perm2) c2 = c2.transpose(perm) # Done self.c = c2 def derivative(self, nu): """ Construct a new piecewise polynomial representing the derivative. Parameters ---------- nu : ndim-tuple of int Order of derivatives to evaluate for each dimension. If negative, the antiderivative is returned. Returns ------- pp : NdPPoly Piecewise polynomial of orders (k[0] - nu[0], ..., k[n] - nu[n]) representing the derivative of this polynomial. Notes ----- Derivatives are evaluated piecewise for each polynomial segment, even if the polynomial is not differentiable at the breakpoints. The polynomial intervals in each dimension are considered half-open, ``[a, b)``, except for the last interval which is closed ``[a, b]``. """ p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) for axis, n in enumerate(nu): p._derivative_inplace(n, axis) p._ensure_c_contiguous() return p def antiderivative(self, nu): """ Construct a new piecewise polynomial representing the antiderivative. Antiderivative is also the indefinite integral of the function, and derivative is its inverse operation. Parameters ---------- nu : ndim-tuple of int Order of derivatives to evaluate for each dimension. If negative, the derivative is returned. Returns ------- pp : PPoly Piecewise polynomial of order k2 = k + n representing the antiderivative of this polynomial. Notes ----- The antiderivative returned by this function is continuous and continuously differentiable to order n-1, up to floating point rounding error. """ p = self.construct_fast(self.c.copy(), self.x, self.extrapolate) for axis, n in enumerate(nu): p._antiderivative_inplace(n, axis) p._ensure_c_contiguous() return p def integrate_1d(self, a, b, axis, extrapolate=None): r""" Compute NdPPoly representation for one dimensional definite integral The result is a piecewise polynomial representing the integral: .. math:: p(y, z, ...) = \int_a^b dx\, p(x, y, z, ...) where the dimension integrated over is specified with the `axis` parameter. Parameters ---------- a, b : float Lower and upper bound for integration. axis : int Dimension over which to compute the 1-D integrals extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- ig : NdPPoly or array-like Definite integral of the piecewise polynomial over [a, b]. If the polynomial was 1D, an array is returned, otherwise, an NdPPoly object. """ if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) ndim = len(self.x) axis = int(axis) % ndim # reuse 1-D integration routines c = self.c swap = list(range(c.ndim)) swap.insert(0, swap[axis]) del swap[axis + 1] swap.insert(1, swap[ndim + axis]) del swap[ndim + axis + 1] c = c.transpose(swap) p = PPoly.construct_fast(c.reshape(c.shape[0], c.shape[1], -1), self.x[axis], extrapolate=extrapolate) out = p.integrate(a, b, extrapolate=extrapolate) # Construct result if ndim == 1: return out.reshape(c.shape[2:]) else: c = out.reshape(c.shape[2:]) x = self.x[:axis] + self.x[axis+1:] return self.construct_fast(c, x, extrapolate=extrapolate) def integrate(self, ranges, extrapolate=None): """ Compute a definite integral over a piecewise polynomial. Parameters ---------- ranges : ndim-tuple of 2-tuples float Sequence of lower and upper bounds for each dimension, ``[(a[0], b[0]), ..., (a[ndim-1], b[ndim-1])]`` extrapolate : bool, optional Whether to extrapolate to out-of-bounds points based on first and last intervals, or to return NaNs. Returns ------- ig : array_like Definite integral of the piecewise polynomial over [a[0], b[0]] x ... x [a[ndim-1], b[ndim-1]] """ ndim = len(self.x) if extrapolate is None: extrapolate = self.extrapolate else: extrapolate = bool(extrapolate) if not hasattr(ranges, '__len__') or len(ranges) != ndim: raise ValueError("Range not a sequence of correct length") self._ensure_c_contiguous() # Reuse 1D integration routine c = self.c for n, (a, b) in enumerate(ranges): swap = list(range(c.ndim)) swap.insert(1, swap[ndim - n]) del swap[ndim - n + 1] c = c.transpose(swap) p = PPoly.construct_fast(c, self.x[n], extrapolate=extrapolate) out = p.integrate(a, b, extrapolate=extrapolate) c = out.reshape(c.shape[2:]) return c class RegularGridInterpolator(object): """ Interpolation on a regular grid in arbitrary dimensions The data must be defined on a regular grid; the grid spacing however may be uneven. Linear and nearest-neighbor interpolation are supported. After setting up the interpolator object, the interpolation method (*linear* or *nearest*) may be chosen at each evaluation. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest". This parameter will become the default for the object's ``__call__`` method. Default is "linear". bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Methods ------- __call__ Notes ----- Contrary to LinearNDInterpolator and NearestNDInterpolator, this class avoids expensive triangulation of the input data by taking advantage of the regular grid structure. If any of `points` have a dimension of size 1, linear interpolation will return an array of `nan` values. Nearest-neighbor interpolation will work as usual in this case. .. versionadded:: 0.14 Examples -------- Evaluate a simple example function on the points of a 3-D grid: >>> from scipy.interpolate import RegularGridInterpolator >>> def f(x, y, z): ... return 2 * x**3 + 3 * y**2 - z >>> x = np.linspace(1, 4, 11) >>> y = np.linspace(4, 7, 22) >>> z = np.linspace(7, 9, 33) >>> data = f(*np.meshgrid(x, y, z, indexing='ij', sparse=True)) ``data`` is now a 3-D array with ``data[i,j,k] = f(x[i], y[j], z[k])``. Next, define an interpolating function from this data: >>> my_interpolating_function = RegularGridInterpolator((x, y, z), data) Evaluate the interpolating function at the two points ``(x,y,z) = (2.1, 6.2, 8.3)`` and ``(3.3, 5.2, 7.1)``: >>> pts = np.array([[2.1, 6.2, 8.3], [3.3, 5.2, 7.1]]) >>> my_interpolating_function(pts) array([ 125.80469388, 146.30069388]) which is indeed a close approximation to ``[f(2.1, 6.2, 8.3), f(3.3, 5.2, 7.1)]``. See also -------- NearestNDInterpolator : Nearest neighbor interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions References ---------- .. [1] Python package *regulargrid* by Johannes Buchner, see https://pypi.python.org/pypi/regulargrid/ .. [2] Wikipedia, "Trilinear interpolation", https://en.wikipedia.org/wiki/Trilinear_interpolation .. [3] Weiser, Alan, and Sergio E. Zarantonello. "A note on piecewise linear and multilinear table interpolation in many dimensions." MATH. COMPUT. 50.181 (1988): 189-196. https://www.ams.org/journals/mcom/1988-50-181/S0025-5718-1988-0917826-0/S0025-5718-1988-0917826-0.pdf """ # this class is based on code originally programmed by Johannes Buchner, # see https://github.com/JohannesBuchner/regulargrid def __init__(self, points, values, method="linear", bounds_error=True, fill_value=np.nan): if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) self.method = method self.bounds_error = bounds_error if not hasattr(values, 'ndim'): # allow reasonable duck-typed values values = np.asarray(values) if len(points) > values.ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), values.ndim)) if hasattr(values, 'dtype') and hasattr(values, 'astype'): if not np.issubdtype(values.dtype, np.inexact): values = values.astype(float) self.fill_value = fill_value if fill_value is not None: fill_value_dtype = np.asarray(fill_value).dtype if (hasattr(values, 'dtype') and not np.can_cast(fill_value_dtype, values.dtype, casting='same_kind')): raise ValueError("fill_value must be either 'None' or " "of a type compatible with values") for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) self.grid = tuple([np.asarray(p) for p in points]) self.values = values def __call__(self, xi, method=None): """ Interpolation at coordinates Parameters ---------- xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str The method of interpolation to perform. Supported are "linear" and "nearest". """ method = self.method if method is None else method if method not in ["linear", "nearest"]: raise ValueError("Method '%s' is not defined" % method) ndim = len(self.grid) xi = _ndim_coords_from_arrays(xi, ndim=ndim) if xi.shape[-1] != len(self.grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], ndim)) xi_shape = xi.shape xi = xi.reshape(-1, xi_shape[-1]) if self.bounds_error: for i, p in enumerate(xi.T): if not np.logical_and(np.all(self.grid[i][0] <= p), np.all(p <= self.grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) indices, norm_distances, out_of_bounds = self._find_indices(xi.T) if method == "linear": result = self._evaluate_linear(indices, norm_distances, out_of_bounds) elif method == "nearest": result = self._evaluate_nearest(indices, norm_distances, out_of_bounds) if not self.bounds_error and self.fill_value is not None: result[out_of_bounds] = self.fill_value return result.reshape(xi_shape[:-1] + self.values.shape[ndim:]) def _evaluate_linear(self, indices, norm_distances, out_of_bounds): # slice for broadcasting over trailing dimensions in self.values vslice = (slice(None),) + (None,)*(self.values.ndim - len(indices)) # find relevant values # each i and i+1 represents a edge edges = itertools.product(*[[i, i + 1] for i in indices]) values = 0. for edge_indices in edges: weight = 1. for ei, i, yi in zip(edge_indices, indices, norm_distances): weight *= np.where(ei == i, 1 - yi, yi) values += np.asarray(self.values[edge_indices]) * weight[vslice] return values def _evaluate_nearest(self, indices, norm_distances, out_of_bounds): idx_res = [np.where(yi <= .5, i, i + 1) for i, yi in zip(indices, norm_distances)] return self.values[tuple(idx_res)] def _find_indices(self, xi): # find relevant edges between which xi are situated indices = [] # compute distance to lower edge in unity units norm_distances = [] # check for out of bounds xi out_of_bounds = np.zeros((xi.shape[1]), dtype=bool) # iterate through dimensions for x, grid in zip(xi, self.grid): i = np.searchsorted(grid, x) - 1 i[i < 0] = 0 i[i > grid.size - 2] = grid.size - 2 indices.append(i) norm_distances.append((x - grid[i]) / (grid[i + 1] - grid[i])) if not self.bounds_error: out_of_bounds += x < grid[0] out_of_bounds += x > grid[-1] return indices, norm_distances, out_of_bounds def interpn(points, values, xi, method="linear", bounds_error=True, fill_value=np.nan): """ Multidimensional interpolation on regular grids. Parameters ---------- points : tuple of ndarray of float, with shapes (m1, ), ..., (mn, ) The points defining the regular grid in n dimensions. values : array_like, shape (m1, ..., mn, ...) The data on the regular grid in n dimensions. xi : ndarray of shape (..., ndim) The coordinates to sample the gridded data at method : str, optional The method of interpolation to perform. Supported are "linear" and "nearest", and "splinef2d". "splinef2d" is only supported for 2-dimensional data. bounds_error : bool, optional If True, when interpolated values are requested outside of the domain of the input data, a ValueError is raised. If False, then `fill_value` is used. fill_value : number, optional If provided, the value to use for points outside of the interpolation domain. If None, values outside the domain are extrapolated. Extrapolation is not supported by method "splinef2d". Returns ------- values_x : ndarray, shape xi.shape[:-1] + values.shape[ndim:] Interpolated values at input coordinates. Notes ----- .. versionadded:: 0.14 Examples -------- Evaluate a simple example function on the points of a regular 3-D grid: >>> from scipy.interpolate import interpn >>> def value_func_3d(x, y, z): ... return 2 * x + 3 * y - z >>> x = np.linspace(0, 5) >>> y = np.linspace(0, 5) >>> z = np.linspace(0, 5) >>> points = (x, y, z) >>> values = value_func_3d(*np.meshgrid(*points)) Evaluate the interpolating function at a point >>> point = np.array([2.21, 3.12, 1.15]) >>> print(interpn(points, values, point)) [11.72] See also -------- NearestNDInterpolator : Nearest neighbor interpolation on unstructured data in N dimensions LinearNDInterpolator : Piecewise linear interpolant on unstructured data in N dimensions RegularGridInterpolator : Linear and nearest-neighbor Interpolation on a regular grid in arbitrary dimensions RectBivariateSpline : Bivariate spline approximation over a rectangular mesh """ # sanity check 'method' kwarg if method not in ["linear", "nearest", "splinef2d"]: raise ValueError("interpn only understands the methods 'linear', " "'nearest', and 'splinef2d'. You provided %s." % method) if not hasattr(values, 'ndim'): values = np.asarray(values) ndim = values.ndim if ndim > 2 and method == "splinef2d": raise ValueError("The method splinef2d can only be used for " "2-dimensional input data") if not bounds_error and fill_value is None and method == "splinef2d": raise ValueError("The method splinef2d does not support extrapolation.") # sanity check consistency of input dimensions if len(points) > ndim: raise ValueError("There are %d point arrays, but values has %d " "dimensions" % (len(points), ndim)) if len(points) != ndim and method == 'splinef2d': raise ValueError("The method splinef2d can only be used for " "scalar data with one point per coordinate") # sanity check input grid for i, p in enumerate(points): if not np.all(np.diff(p) > 0.): raise ValueError("The points in dimension %d must be strictly " "ascending" % i) if not np.asarray(p).ndim == 1: raise ValueError("The points in dimension %d must be " "1-dimensional" % i) if not values.shape[i] == len(p): raise ValueError("There are %d points and %d values in " "dimension %d" % (len(p), values.shape[i], i)) grid = tuple([np.asarray(p) for p in points]) # sanity check requested xi xi = _ndim_coords_from_arrays(xi, ndim=len(grid)) if xi.shape[-1] != len(grid): raise ValueError("The requested sample points xi have dimension " "%d, but this RegularGridInterpolator has " "dimension %d" % (xi.shape[1], len(grid))) if bounds_error: for i, p in enumerate(xi.T): if not np.logical_and(np.all(grid[i][0] <= p), np.all(p <= grid[i][-1])): raise ValueError("One of the requested xi is out of bounds " "in dimension %d" % i) # perform interpolation if method == "linear": interp = RegularGridInterpolator(points, values, method="linear", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "nearest": interp = RegularGridInterpolator(points, values, method="nearest", bounds_error=bounds_error, fill_value=fill_value) return interp(xi) elif method == "splinef2d": xi_shape = xi.shape xi = xi.reshape(-1, xi.shape[-1]) # RectBivariateSpline doesn't support fill_value; we need to wrap here idx_valid = np.all((grid[0][0] <= xi[:, 0], xi[:, 0] <= grid[0][-1], grid[1][0] <= xi[:, 1], xi[:, 1] <= grid[1][-1]), axis=0) result = np.empty_like(xi[:, 0]) # make a copy of values for RectBivariateSpline interp = RectBivariateSpline(points[0], points[1], values[:]) result[idx_valid] = interp.ev(xi[idx_valid, 0], xi[idx_valid, 1]) result[np.logical_not(idx_valid)] = fill_value return result.reshape(xi_shape[:-1]) # backward compatibility wrapper class _ppform(PPoly): """ Deprecated piecewise polynomial class. New code should use the `PPoly` class instead. """ def __init__(self, coeffs, breaks, fill=0.0, sort=False): warnings.warn("_ppform is deprecated -- use PPoly instead", category=DeprecationWarning) if sort: breaks = np.sort(breaks) else: breaks = np.asarray(breaks) PPoly.__init__(self, coeffs, breaks) self.coeffs = self.c self.breaks = self.x self.K = self.coeffs.shape[0] self.fill = fill self.a = self.breaks[0] self.b = self.breaks[-1] def __call__(self, x): return PPoly.__call__(self, x, 0, False) def _evaluate(self, x, nu, extrapolate, out): PPoly._evaluate(self, x, nu, extrapolate, out) out[~((x >= self.a) & (x <= self.b))] = self.fill return out @classmethod def fromspline(cls, xk, cvals, order, fill=0.0): # Note: this spline representation is incompatible with FITPACK N = len(xk)-1 sivals = np.empty((order+1, N), dtype=float) for m in range(order, -1, -1): fact = spec.gamma(m+1) res = _fitpack._bspleval(xk[:-1], xk, cvals, order, m) res /= fact sivals[order-m, :] = res return cls(sivals, xk, fill=fill)
{ "repo_name": "e-q/scipy", "path": "scipy/interpolate/interpolate.py", "copies": "3", "size": "98660", "license": "bsd-3-clause", "hash": 7530266625394910000, "line_mean": 34.8112522686, "line_max": 112, "alpha_frac": 0.5433711737, "autogenerated": false, "ratio": 3.913060722643081, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5956431896343082, "avg_score": null, "num_lines": null }
__all__ = ["interrogator", "editor", "plotter", "conc", "save_result", "quickview", "load_result", "load_all_results", "as_regex", "new_project", "download_large_file", "extract_cnlp", "get_corpus_filepaths", "check_jdk", "parse_corpus", "move_parsed_files", "corenlp_exists"] __version__ = "1.58" __author__ = "Daniel McDonald" __license__ = "MIT" import sys import os import inspect # probably not needed, but adds corpkit to path for tregex.sh corpath = inspect.getfile(inspect.currentframe()) baspat = os.path.dirname(corpath) dicpath = os.path.join(baspat, 'dictionaries') for p in [corpath, baspat, dicpath]: if p not in sys.path: sys.path.append(p) if p not in os.environ["PATH"].split(':'): os.environ["PATH"] += os.pathsep + p from interrogator import interrogator from editor import editor from plotter import plotter from conc import conc from other import save_result from other import load_result from other import load_all_results from other import quickview from other import as_regex from other import new_project from build import download_large_file from build import extract_cnlp from build import get_corpus_filepaths from build import check_jdk from build import parse_corpus from build import move_parsed_files from build import corenlp_exists
{ "repo_name": "SigridK/corpkit", "path": "corpkit/__init__.py", "copies": "1", "size": "1479", "license": "mit", "hash": 7947299037182606000, "line_mean": 26.3888888889, "line_max": 61, "alpha_frac": 0.645030426, "autogenerated": false, "ratio": 3.563855421686747, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4708885847686747, "avg_score": null, "num_lines": null }
__all__ = [ 'Interval' ] class Interval(object): '''Interval - Arbitrary half-closed interval of the form [start, end)''' def __init__(self, start, end): self.start = start self.end = end def __call__(self, value): return (1. - value) * self.start + value * self.end def __str__(self): return 'Interval({self.start}, {self.end})'.format(self=self) def __repr__(self): return 'Interval({self.start}, {self.end})'.format(self=self) def __eq__(self, right): return self.start == right.start and self.end == right.end def contains(self, value): return self.start <= value < self.end def __intersection(self, right): return ( max(self.start, right.start), min(self.end, right.end) ) def overlaps(self, other): start, end = self.__intersection(other) return start < end def intersection(self, other): start, end = self.__intersection(other) if start < end: return Interval(start, end) else: return None
{ "repo_name": "bracket/handsome", "path": "handsome/Interval.py", "copies": "2", "size": "1108", "license": "bsd-2-clause", "hash": 2796126675688250400, "line_mean": 26.0243902439, "line_max": 76, "alpha_frac": 0.5586642599, "autogenerated": false, "ratio": 3.9014084507042255, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5460072710604226, "avg_score": null, "num_lines": null }
__all__ = ['InvalidData', 'Step', 'ProcessManager'] class InvalidData(Exception): """ Raised for by step validation process """ pass class Step(object): """ A single step in a multistep process """ def __str__(self): raise NotImplementedError() # pragma: no cover def validate(self): raise NotImplementedError() # pragma: no cover class ProcessManager(object): """ A multistep process handler """ def __iter__(self): raise NotImplementedError() # pragma: no cover def __getitem__(self, step_id): for step in self: if str(step) == step_id: return step raise KeyError('%r is not a valid step' % (step_id,)) def validate_step(self, step): try: step.validate() except InvalidData: return False return True def get_next_step(self): for step in self: if not self.validate_step(step): return step def get_errors(self): errors = {} for step in self: try: step.validate() except InvalidData as error: errors[str(step)] = error return errors def is_complete(self): return self.get_next_step() is None
{ "repo_name": "taedori81/satchless", "path": "satchless/process/__init__.py", "copies": "1", "size": "1318", "license": "bsd-3-clause", "hash": 6791970173784787000, "line_mean": 22.1228070175, "line_max": 61, "alpha_frac": 0.5440060698, "autogenerated": false, "ratio": 4.437710437710438, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0, "num_lines": 57 }
__all__ = [ "isbinary", "isiterable" ] def _inttobyte(i): """Takes an integer in the 8-bit range and returns a single-character byte object. """ return bytes((i,)) _text_characters = (b''.join(_inttobyte(i) for i in range(32, 127)) + b'\n\r\t\f\b') def isbinary(fileobj, blocksize=512): """Uses heuristics to guess whether the given file is a text or a binary file, by reading a single block of bytes from the file. If more than 30% of the bytes in the block are non-text, or there are NUL ('\x00') bytes in the block, assume this is a binary file. """ block = fileobj.read(blocksize) if b'\x00' in block: # Files with null bytes are binary. return True elif not block: # An empty file is considered a valid text file. return True # Uses translate's 'deletechars' to argument to efficiently remove all # occurrences of _text_characters from the block. nontext = block.translate(None, _text_characters) return float(len(nontext)) / len(block) > 30.0 def isiterable(obj): """Returns whether an object allows iteration. True if obj provides __iter__, False otherwise. Note that this function returns False when obj is of type str in Python 2. """ return getattr(obj, '__iter__', False)
{ "repo_name": "dnkbln/pyfea", "path": "pyfea/util/lang.py", "copies": "1", "size": "1318", "license": "bsd-2-clause", "hash": -4400307424770789400, "line_mean": 30.380952381, "line_max": 78, "alpha_frac": 0.6517450683, "autogenerated": false, "ratio": 3.7443181818181817, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9868014149823249, "avg_score": 0.005609820058986453, "num_lines": 42 }
# all is object def hi(name = 'yasoob'): return "hi " + name print(hi()) greet = hi print(greet()) del hi # print(hi()) print(greet()) def hi2(name = 'yasoob'): print("now you are inside the hi2() function") def greet2(): return "now you are in the greet2() function" def welcome2(): return "now you are in the welcome2() function" print(greet2()) print(welcome2()) print("now you are back in the hi2() function") hi2() # greet2() def hi3(name = 'yasoob'): def greet3(): return "now you are in the greet3() function" def welcome3(): return "now you are in the welcome3() function" if name == 'yasoob': return greet3 else: return welcome3 a = hi3() print(a) print(a()) b = hi3('abc') print(b) print(b()) print(hi3()()) def hi4(): return "hi yasoob!" def doSomethingBeforeHi(func): print("I am doing some boring work before executing hi()") print(func()) doSomethingBeforeHi(hi4) def a_new_decorator(a_func): def wrapTheFunction(): print("I am doing some boring work before executing a_func") a_func() print("I am doing some boring work after executing a_func") return wrapTheFunction def a_function_requiring_decoration(): print("I am the function which needs some decoration to remove my foul smell") a_function_requiring_decoration() a_function_requiring_decoration = a_new_decorator(a_function_requiring_decoration) a_function_requiring_decoration() @a_new_decorator def a_function_requiring_decoration2(): '''hey you! decorate me''' print("I am the function2") a_function_requiring_decoration2() print(a_function_requiring_decoration2.__name__) from functools import wraps def a_new_decorator2(a_func): @wraps(a_func) def wrapTheFunction(): print("I am doing some boring work before executing a_func") a_func() print("I am doing some boring work after executing a_func") return wrapTheFunction @a_new_decorator2 def a_function_requiring_decoration3(): """he""" print("I am the function3") print(type(a_function_requiring_decoration3)) a_function_requiring_decoration3() print(a_function_requiring_decoration3.__name__) def decorator_name(f): @wraps(f) def decorated(*args, **kwargs): if not can_run: return "Function will not run" return f(*args, **kwargs) return decorated @decorator_name def func(): return ("Function is running") can_run = True print(func()) can_run = False print(func()) def logit(func): @wraps(func) def with_logging(*args, **kwargs): print(func.__name__ + " was called") return func(*args, **kwargs) return with_logging @logit def addition_func(x): """Do some math.""" return x + x result = addition_func(5) def logit2(logfile='out.log'): def logging_decorator(func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called." print(log_string) with open(logfile, 'a') as opened_file: opened_file.write(log_string + '\n') return func(*args, **kwargs) return wrapped_function return logging_decorator @logit2() def myfunc1(): pass myfunc1() @logit2(logfile='func2.log') def myfunc2(): pass myfunc2() class logit3(object): def __init__(self, logfile='out.log'): self.logfile = logfile def __call__(self, func): @wraps(func) def wrapped_function(*args, **kwargs): log_string = func.__name__ + " was called" print(log_string) with open(self.logfile, 'a') as opened_file: opened_file.write(log_string + '\n') self.notify() return func(*args, **kwargs) return wrapped_function def notify(self): pass @logit3() def myfunc3(): pass # myfunc3 = logit3(myfunc3) myfunc3() class email_logit(logit3): ''' a subclass''' def __init__(self, email='admin@myproject.com', *args, **kwargs): self.email = email super(logit3,self).__init__(*args, **kwargs) def notify(self): pass @email_logit() def myfunc4(): pass myfunc4()
{ "repo_name": "cragwen/hello-world", "path": "py/interpy/7_decorator.py", "copies": "1", "size": "4372", "license": "unlicense", "hash": 3596551916420476400, "line_mean": 19.2407407407, "line_max": 82, "alpha_frac": 0.6045288198, "autogenerated": false, "ratio": 3.3630769230769233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.4467605742876923, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 5/21/2013 # Last Updated: 6/13/2013 # For JCAP from PyQt4 import QtGui, QtCore from datareader import DATA_HEADINGS import graph import profilecreator import date_helpers import time """ window that displays a single graph area and various customization options """ class GraphWindow(QtGui.QWidget): def __init__(self): super(GraphWindow, self).__init__() self.updating = False self.initUI() """ draws the user interface of the window """ def initUI(self): # set window size and position on screen self.setGeometry(300, 200, 1000, 600) # get variables from spreadsheet global DATA_HEADINGS self.vars = [] for index in range(3, len(DATA_HEADINGS)): self.vars += [DATA_HEADINGS.get(index)] # initialize default graph self.graph = graph.Graph(self, xvarname="Time", yvarname=self.vars[0]) self.toolbar = graph.NavigationToolbar(self.graph, self) self.updating = True self.setWindowTitle(self.vars[0]) self.plotOptionMenu = QtGui.QComboBox() self.plotOptionMenu.addItem('Switch graph') self.plotOptionMenu.addItem('Add to left axis') # make drop-down menu for selecting graphs self.selectVar = QtGui.QComboBox() for var in self.vars: self.selectVar.addItem(var) self.selectVar.activated[str].connect(self.selectGraph) # set up layout and sub-layouts self.layout = QtGui.QVBoxLayout(self) self.optionslayout = QtGui.QGridLayout() self.gridlayout = QtGui.QGridLayout() self.axeslayout = QtGui.QGridLayout() self.timelayout = QtGui.QGridLayout() # this exists so auto axis buttons can move if necessary self.autowidget = QtGui.QWidget(self) self.autolayout = QtGui.QGridLayout() # first column holds graph, second column holds graph options # set the column stretches - 0 is the default # set minimum column widths self.gridlayout.setColumnStretch(0, 4) self.gridlayout.setColumnStretch(1, 0) self.gridlayout.setColumnMinimumWidth(0,300) self.gridlayout.setRowMinimumHeight(0,375) # add drop-down menus and MPL toolbar to top of window self.layout.addLayout(self.optionslayout) self.optionslayout.addWidget(self.plotOptionMenu, 0, 0) self.optionslayout.addWidget(self.selectVar, 0, 1, 1, 3) self.optionslayout.addWidget(self.toolbar, 1, 0, 1, 4) # initialize checkbox that acts as pause button self.hold_cb = QtGui.QCheckBox('Hold', self) self.hold_cb.stateChanged.connect(self.hold) # initialize input boxes for axis limits self.minutes = QtGui.QLineEdit(self) self.minutes.setFixedWidth(40) self.hours = QtGui.QLineEdit(self) self.hours.setFixedWidth(40) self.days = QtGui.QLineEdit(self) self.days.setFixedWidth(40) self.Ymin = QtGui.QLineEdit(self) self.Ymax = QtGui.QLineEdit(self) self.YminR = QtGui.QLineEdit(self) self.YmaxR = QtGui.QLineEdit(self) # create labels for the input boxes self.label_time = QtGui.QLabel('Show data from the last:') self.label_minutes = QtGui.QLabel('minutes') self.label_hours = QtGui.QLabel('hours') self.label_days = QtGui.QLabel('days') self.label_Ymin = QtGui.QLabel('Y Min (left):') self.label_Ymax = QtGui.QLabel('Y Max (left):') self.label_YminR = QtGui.QLabel('Y Min (right):') self.label_YmaxR = QtGui.QLabel('Y Max (right):') # initialize buttons and their connections self.set_axes = QtGui.QPushButton('Enter') self.auto_xaxes = QtGui.QPushButton('Auto X') self.auto_yaxes = QtGui.QPushButton('Auto Y (left)') self.auto_yraxes = QtGui.QPushButton('Auto Y (right)') self.set_axes.clicked.connect(self.setAxes) self.auto_xaxes.clicked.connect(self.autoXAxes) self.auto_yaxes.clicked.connect(self.autoYAxes) self.auto_yraxes.clicked.connect(self.autoYRAxes) # set the possible streches of input boxes self.Ymin.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) self.Ymax.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) self.YminR.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) self.YmaxR.setSizePolicy(QtGui.QSizePolicy.Maximum, QtGui.QSizePolicy.Preferred) # initialize menu to choose variable for right-hand axis self.label_raxis = QtGui.QLabel('Choose a variable to plot on the right-hand axis:') self.choose_var = QtGui.QComboBox() for var in self.vars: self.choose_var.addItem(var) self.set_raxis = QtGui.QPushButton('Plot') self.set_raxis.clicked.connect(self.addRAxis) # place the main grid layout inside layout for window self.layout.addLayout(self.gridlayout) # add graph and options to main grid layout self.gridlayout.addWidget(self.graph, 0, 0) self.gridlayout.addLayout(self.axeslayout, 0, 1) # set alignment for the widgets self.axeslayout.setAlignment(QtCore.Qt.AlignTop) # create spacers to separate fields in graph options layout self.spacer1 = QtGui.QSpacerItem(1, 20) self.spacer2 = QtGui.QSpacerItem(1, 20) self.spacer3 = QtGui.QSpacerItem(1, 20) self.spacer4 = QtGui.QSpacerItem(1, 20) # add items to the graph options layout self.axeslayout.addItem(self.spacer1, 0, 0) self.axeslayout.addWidget(self.hold_cb, 1, 0) self.axeslayout.addItem(self.spacer2, 2, 0) self.axeslayout.addItem(self.spacer3, 3, 0) self.axeslayout.addWidget(self.label_raxis, 4, 0) self.axeslayout.addWidget(self.choose_var, 5, 0) self.axeslayout.addWidget(self.set_raxis, 6, 0) self.axeslayout.addItem(self.spacer4, 7, 0) self.axeslayout.addWidget(self.label_time, 8, 0) self.axeslayout.addLayout(self.timelayout, 9, 0) # add options for time axis to a sub-grid self.timelayout.addWidget(self.minutes, 0, 0) self.timelayout.addWidget(self.label_minutes, 0, 1) self.timelayout.addWidget(self.hours, 1, 0) self.timelayout.addWidget(self.label_hours, 1, 1) self.timelayout.addWidget(self.days, 2, 0) self.timelayout.addWidget(self.label_days, 2, 1) # add more items to graph options layout self.axeslayout.addWidget(self.label_Ymin, 13, 0) self.axeslayout.addWidget(self.Ymin, 14, 0) self.axeslayout.addWidget(self.label_Ymax, 15, 0) self.axeslayout.addWidget(self.Ymax, 16, 0) self.axeslayout.addWidget(self.label_YminR, 17, 0) self.axeslayout.addWidget(self.YminR, 18, 0) self.axeslayout.addWidget(self.label_YmaxR, 19, 0) self.axeslayout.addWidget(self.YmaxR, 20, 0) self.axeslayout.addWidget(self.set_axes, 21, 0) # hide options for second axis initially self.label_YminR.hide() self.YminR.hide() self.label_YmaxR.hide() self.YmaxR.hide() # add widget that holds auto axis buttons self.axeslayout.addWidget(self.autowidget, 22, 0, 1, 2) self.autowidget.setLayout(self.autolayout) # add auto axis buttons self.autolayout.addWidget(self.auto_xaxes, 0 , 0) self.autolayout.addWidget(self.auto_yaxes, 0 , 1) self.autolayout.addWidget(self.auto_yraxes, 0 , 2) # hide option for auto right axis initially self.auto_yraxes.hide() self.show() """ called when variable to plot is selected """ def selectGraph(self, varName): # convert QString to string varString = str(varName) if self.plotOptionMenu.currentText() == 'Switch graph': # clear previous plot and set parent to None so it can be deleted self.graph.clearPlot() self.graph.setParent(None) self.gridlayout.removeWidget(self.graph) self.graph =None self.graph = graph.Graph(self, xvarname = "Time", yvarname = varString) self.gridlayout.addWidget(self.graph, 0, 0) self.setWindowTitle(varString) # remove all options for right-hand axis because plot is initialized # without it self.label_YminR.hide() self.YminR.hide() self.label_YmaxR.hide() self.YmaxR.hide() self.auto_yraxes.hide() # remove the "add to right axis" option from plotOptionMenu if # it is currently displayed self.plotOptionMenu.removeItem(2) # clear axis label fields self.minutes.clear() self.hours.clear() self.days.clear() self.Ymin.clear() self.Ymax.clear() self.YminR.clear() self.YmaxR.clear() elif self.plotOptionMenu.currentText() == 'Add to left axis': self.graph.addVarToAxis(varString) return else: self.graph.addVarToAxis(varString, "right") return """ called when request to add plot to right-hand axis is made """ def addRAxis(self): # get name of variable from selection menu varName = self.choose_var.currentText() # convert QString to string varString = str(varName) self.graph.addRightAxis(varString) # reset right y-axis limit fields self.YminR.clear() self.YmaxR.clear() # remove the "add to right axis" option from plotOptionMenu if # it is currently displayed self.plotOptionMenu.removeItem(2) # show all options for right-hand axis self.plotOptionMenu.addItem('Add to right axis') self.label_YminR.show() self.YminR.show() self.label_YmaxR.show() self.YmaxR.show() self.auto_yraxes.show() """ called whenever new data is ready to be plotted """ def updateWindow(self, newRow): self.graph.updatePlot(newRow) """ called by MainMenu every second """ def redrawWindow(self): if self.updating: self.graph.timeFrame() self.graph.draw() """ toggles auto-updating property of graphs in window """ def hold(self): if self.updating == True: self.updating = False else: self.updating = True """ called when user gives input for axis limits """ def setAxes(self): # [Are axes changing?, new min, new max] setXAxes = [False, None, None] setYAxes = [False, None, None] # dealing with the current time and the time that we have to # go back for x-axis limits currTime = time.time() # measured in seconds timeBack = 0 # x-axis maximum is current time setXAxes[2] = date_helpers.dateObj(currTime) # get and save input from all fields min_input = self.minutes.text() hour_input = self.hours.text() day_input = self.days.text() Ymin_input = self.Ymin.text() Ymax_input = self.Ymax.text() axes_input = [('min', min_input), ('hour', hour_input), ('day', day_input), ('Ymin', Ymin_input), ('Ymax', Ymax_input)] for axis_tuple in axes_input: try: value = float(axis_tuple[1]) if axis_tuple[0] == 'Ymin': setYAxes[0] = True setYAxes[1] = value elif axis_tuple[0] == 'Ymax': setYAxes[0] = True setYAxes[2] = value elif axis_tuple[0] == 'min': setXAxes[0] = True timeBack += value*60 elif axis_tuple[0] == 'hour': setXAxes[0] = True timeBack += value*60*60 elif axis_tuple[0] == 'day': setXAxes[0] = True timeBack += value*60*60*24 # if no input was given to field, ignore it except ValueError: pass # set x-axis minimum to current time minus specified time window setXAxes[1] = date_helpers.dateObj(currTime - timeBack) # if y-axis limits have been changed if setYAxes[0]: self.graph.setYlim(amin=setYAxes[1], amax=setYAxes[2]) # if x-axis limits have been changed if setXAxes[0]: self.graph.auto = False self.graph.timeWindow = timeBack self.graph.setXlim(amin=setXAxes[1], amax=setXAxes[2]) if self.graph.hasRightAxis: self.setRAxis() """ called when user gives input for right-hand axis limits """ def setRAxis(self): # [Are axes changing?, new min, new max] setAxes = [False, None, None] YminR_input = self.YminR.text() YmaxR_input = self.YmaxR.text() try: setAxes[0] = True setAxes[1] = float(YminR_input) except ValueError: pass try: setAxes[0] = True setAxes[2] = float(YmaxR_input) except ValueError: pass if setAxes: self.graph.setRYlim(amin=setAxes[1], amax=setAxes[2]) """ called when 'Auto X' button is clicked sets x axis limits automatically to fit all data """ def autoXAxes(self): self.graph.auto = True self.graph.axes.autoscale(axis ='x') self.minutes.clear() self.hours.clear() self.days.clear() """ called when 'Auto Y (left)' button is clicked sets y axis limits automatically to fit all data """ def autoYAxes(self): self.graph.axes.autoscale(axis ='y') self.Ymin.clear() self.Ymax.clear() """ called when 'Auto Y (right)' button is clicked sets right-hand y axis limits automatically to fit all data """ def autoYRAxes(self): self.graph.rightAxes.autoscale(axis ='y') self.YminR.clear() self.YmaxR.clear()
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "graphwindow_data.py", "copies": "1", "size": "14461", "license": "bsd-3-clause", "hash": -3953909299645438000, "line_mean": 38.4032697548, "line_max": 92, "alpha_frac": 0.6059746905, "autogenerated": false, "ratio": 3.7905635648754914, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.48965382553754916, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 5/23/2013 # Last Updated: 6/12/2013 # For JCAP from PyQt4 import QtGui from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from navigation_toolbar import NavigationToolbar from matplotlib.figure import Figure from pylab import matplotlib import sys import date_helpers import yvariable import copy import itertools import time from dictionary_helpers import * """ widget to represent an auto-updating graph """ class Graph(FigureCanvas): """ sets up Figure object and plot """ def __init__(self, parent="None", width=3, height=2, dpi=80, xvarname="None", yvarname="None"): self.auto = True self.timeWindow = 0 self.hasRightAxis = False self.legendL = None self.xvar = xvarname # keeps track of label for coordinates on graph self.xyLabel = None # holds matplotlib keywords for color of plots self.colors = itertools.cycle(["b","r","g","c","m","y","k"]) # put first y-var into list of y-vars on left axis self.yvarsL = [yvariable.YVariable(varName = yvarname, columnNumber = getCol(yvarname), color = self.colors.next())] self.yvarsR = [] # used to access date/time data for formatting # and displaying on the x-axis self.colNums = [getCol("Date"),getCol(self.xvar)] self.figure = Figure(figsize=(width, height), dpi=dpi, tight_layout=True) FigureCanvas.__init__(self, self.figure) # Graph will have a parent widget if contained in a layout self.setParent(parent) FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) self.initPlot() # ---- this is deprecated as of adding the toolbar ---- # clicking on graph gives x and y coordinates # (not enabled when right y axis is present) #self.figure.canvas.mpl_connect('button_press_event', self.onclick) """ draws and labels axes """ def initPlot(self): self.axes = self.figure.add_subplot(111) self.axes.set_xlabel(self.xvar) self.axes.set_ylabel(self.yvarsL[0].varName) self.axes.xaxis_date() self.figure.autofmt_xdate() self.time_format = matplotlib.dates.DateFormatter('%m/%d/%y %H:%M:%S') self.axes.xaxis.set_major_formatter(self.time_format) self.axes.set_ylabel(self.yvarsL[0].varName) # Assign first y-variable to left-hand axis self.yvarsL[0].axis = self.axes self.firstPlot(self.yvarsL[0]) """ plots initial data for a given y-var on the graph """ def firstPlot(self, yvarIns): list_of_times = [] theAxes = yvarIns.axis theYvar = yvarIns.varName ydata = copy.deepcopy(DATA_DICT.get(theYvar)) time_array = copy.deepcopy(DATA_DICT.get(self.xvar)) date_array = copy.deepcopy(DATA_DICT.get("Date")) for index in range(len(time_array)): full_time = date_array[index] + " " + time_array[index] formatted_time = date_helpers.dateObjFloat(full_time) list_of_times += [formatted_time] timeToPlot = matplotlib.dates.date2num(list_of_times) # If reader is still reading, DATA_DICT is changing, # and it is possible for timeToPlot to be a different # length than ydata. In that case, we can wait for # DATA_DICT to update and try again. try: theAxes.plot_date(timeToPlot, ydata, markerfacecolor=yvarIns.color, label = theYvar, markeredgecolor=yvarIns.color) self.timeFrame() except ValueError: time.sleep(0.5) firstPlot(self, yvarIns) """ adds new data to graph whenever reader sends new row """ def updatePlot(self, row): # turn date/time strings into time objects time_value = date_helpers.dateObjFloat(row[self.colNums[0]] + " " + row[self.colNums[1]]) # plot new point for all y-vars no matter which of the two axis for axis in (self.yvarsL, self.yvarsR): for graphPlots in axis: graphPlots.axis.plot_date(time_value,row[graphPlots.columnNumber], markerfacecolor=graphPlots.color, markeredgecolor=graphPlots.color) """ resets the x-axis limits when specific time window is selected """ def timeFrame(self): if not self.auto: currTime = time.time() rightLim = date_helpers.dateObj(currTime) leftLim = date_helpers.dateObj(currTime - self.timeWindow) self.setXlim(amin=leftLim, amax=rightLim) """ initializes the right-hand y-axis and adds the first variable """ def addRightAxis(self, rightvar): # replace old right-hand axis if self.hasRightAxis: self.figure.delaxes(self.rightAxes) self.hasRightAxis = True # share x-axis with left-hand y-axis self.rightAxes = self.axes.twinx() self.rightAxes.yaxis.tick_right() self.rightAxes.yaxis.set_label_position("right") self.rightAxes.set_ylabel(rightvar) self.rightAxes.xaxis.set_major_formatter(self.time_format) self.rightAxes.get_xaxis().set_visible(False) # save the right-hand axis information self.yvarsR = [yvariable.YVariable(varName = rightvar, axis = self.rightAxes, columnNumber = getCol(rightvar), color = self.colors.next())] self.firstPlot(self.yvarsR[0]) # add legend if 2 or more variables on the same axis if len(self.yvarsL) > 1: self.addLegends() """ adds another variable to the specified y-axis """ def addVarToAxis(self, varString, axis="left"): newVar = yvariable.YVariable(varName = varString, axis = self.axes, columnNumber = getCol(varString), color = self.colors.next()) if axis == "left": self.axes.get_yaxis().get_label().set_visible(False) self.yvarsL += [newVar] elif axis == "right": newVar.axis = self.rightAxes self.rightAxes.get_yaxis().get_label().set_visible(False) self.yvarsR += [newVar] self.firstPlot(newVar) self.addLegends() """ adds left-hand and right-hand axis legends """ def addLegends(self): # remove old legend if there is already one in place if self.legendL: self.legendL.set_visible(False) linesL, labelsL = self.axes.get_legend_handles_labels() if self.hasRightAxis: linesR, labelsR = self.rightAxes.get_legend_handles_labels() # place left-hand legend in upper left corner self.legendL = self.rightAxes.legend(linesL, labelsL, loc=2, title="Left", prop={"size":"small"}) # place right-hand legend in upper right corner self.legendR = self.rightAxes.legend(linesR, labelsR, loc=1, title = "Right", prop={"size":"small"}) # add left-hand legend to upper Axes object so # it can be manipulated self.rightAxes.add_artist(self.legendL) self.legendR.draggable(state = True) else: self.legendL = self.axes.legend(linesL, labelsL, loc=2, title="Left", prop={"size":"small"}) self.legendL.draggable(state = True) """ called when user specifies a time window to display """ def setXlim(self, amin=None, amax=None): self.axes.set_xlim(left=amin, right=amax) """ called when user specifies left-hand y-axis limits """ def setYlim(self, amin=None, amax=None): self.axes.set_ylim(bottom=amin, top=amax) """ called when user specifies right-hand y-axis limits """ def setRYlim(self, amin=None, amax=None): self.rightAxes.set_ylim(bottom=amin, top=amax) """ called when new graph is selected for window """ def clearPlot(self): self.figure.clf() ## ---- the function below is deprecated as of adding the toolbar ---- ## """ called when user clicks on graph to display (x, y) data """ ## def onclick(self,event): ## if not self.hasRightAxis: ## try: ## datetime_date = matplotlib.dates.num2date(event.xdata) ## formatted_xdate = datetime_date.strftime("%m/%d/%Y %H:%M:%S") ## if self.xyLabel: ## self.xyLabel.set_visible(False) ## # textcoords is the coordinate system used to place the ## # text on the axes; 0.55 is horizontal placement, ## # 1.05 is vertical placement (where 1,1 is upper right corner) ## self.xyLabel = self.axes.annotate('x = %s, y = %f' ## %(formatted_xdate, event.ydata), ## xy=(event.xdata, event.ydata), ## textcoords='axes fraction', ## xytext=(0.55,1.05)) ## self.draw() ## except TypeError: ## if self.xyLabel: ## self.xyLabel.set_visible(False)
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "graph.py", "copies": "1", "size": "9703", "license": "bsd-3-clause", "hash": -7857562158026725000, "line_mean": 42.9049773756, "line_max": 99, "alpha_frac": 0.5814696486, "autogenerated": false, "ratio": 3.89991961414791, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.49813892627479095, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 5/23/2013 # Last Updated: 6/13/2013 # For JCAP import csv from PyQt4 import QtCore DATA_DICT = {} DATA_HEADINGS = {} """ thread that reads data from file """ class DataReader(QtCore.QThread): # initialize signal to data processor when a full line has been read lineRead = QtCore.pyqtSignal(list) def __init__(self, parent=None, filename='default.csv'): super(DataReader, self).__init__() self.initData(filename) self.running = True def initData(self, filename): global DATA_DICT global DATA_HEADINGS self.datafile = open(filename, 'rb') # read column headings and create lists to hold data headings = self.datafile.readline().split(',') # clear dictionary in case it has already been used for a different file DATA_DICT.clear() DATA_HEADINGS.clear() # manually add time and date headings because they aren't in file DATA_HEADINGS[0] = 'Time' DATA_DICT['Time'] = [] DATA_HEADINGS[1] = 'Date' DATA_DICT['Date'] = [] # initialize each heading with an array to store the column data for col in range(3, len(headings)): # strip extra " characters that may have been added to # spreadsheet cells by Excel colName = headings[col].strip('"') # ignore empty columns at end of spreadsheet if colName == '': break DATA_HEADINGS[col] = colName DATA_DICT[colName] = [] self.numColumns = len(DATA_HEADINGS) self.lastEOFpos = self.datafile.tell() def run(self): global DATA_DICT global DATA_HEADINGS # get column numbers that hold data in spreadsheet dataColNums = DATA_HEADINGS.keys() while self.running: self.datafile.seek(self.lastEOFpos) data = self.datafile.readline() row = data.split(',') strippedRow = [] # ignore empty third column in spreadsheet for col in (row[:2] + row[3:]): col = col.strip('"') if col != '': strippedRow += [col] # ignore empty columns at end of spreadsheet else: break # check if we have all data from row and have read # up to the end of line character if len(strippedRow) == self.numColumns and row[len(row)-1].endswith('\r\n'): # re-insert empty third column to keep indices # in strippedRow consistent with DATA_HEADINGS strippedRow.insert(2, '') # add the new info to the respective column for col in dataColNums: heading = DATA_HEADINGS.get(col) DATA_DICT[heading].append(strippedRow[col]) # send signal self.lineRead.emit(strippedRow) # move the reader cursor only if we read in a full line self.lastEOFpos = self.datafile.tell() # close file after end() has been called self.datafile.close() """ called when application exits, experiment, ends or new file is loaded to terminate thread """ def end(self): self.running = False
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "datareader.py", "copies": "1", "size": "3396", "license": "bsd-3-clause", "hash": 4845752237751468000, "line_mean": 35.1276595745, "line_max": 88, "alpha_frac": 0.5683156655, "autogenerated": false, "ratio": 4.445026178010472, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.015693783202091808, "num_lines": 94 }
# Allison Schubauer and Daisy Hernandez # Created: 5/23/2013 # Last Updated: 6/14/2013 # For JCAP from PyQt4 import QtGui, QtCore import datareader import cPickle as pickle """ widget to make profiles """ class ProfileCreator(QtGui.QWidget): """ sets up the Widget """ def __init__(self): super(ProfileCreator, self).__init__() self.initUI() """ creates all graphics in the Widget """ def initUI(self): self.setGeometry(400, 200, 400, 300) self.setWindowTitle('Create a New Profile') # top-level vertical layout vBox = QtGui.QVBoxLayout(self) instructions = QtGui.QLabel() instructions.setText("Choose up to 8 variables to graph.") instructions.setMaximumHeight(20) vBox.addWidget(instructions) # make widget and layout to hold checkboxes checkField = QtGui.QWidget() hBox = QtGui.QHBoxLayout(checkField) vBox.addWidget(checkField) # checkboxes displayed in 2 columns self.col1 = QtGui.QVBoxLayout() self.col2 = QtGui.QVBoxLayout() hBox.addLayout(self.col1) hBox.addLayout(self.col2) self.col1.setAlignment(QtCore.Qt.AlignTop) self.col2.setAlignment(QtCore.Qt.AlignTop) # add all checkboxes to col1 and col2 self.getVars() # create OK and Cancel buttons buttons = QtGui.QDialogButtonBox() buttons.setStandardButtons(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) buttons.accepted.connect(self.saveProfile) buttons.rejected.connect(self.close) vBox.addWidget(buttons) """ makes checkboxes for each variable in data set """ def getVars(self): global DATA_HEADINGS self.checkboxes = [] # this ignores first date and time columns in spreadsheet varNames = datareader.DATA_HEADINGS.values() varNames.remove('Time') varNames.remove('Date') for index in range(len(varNames)): self.checkboxes += [QtGui.QCheckBox(varNames[index], self)] # first half of variables added to first column if index <= len(varNames)/2: self.col1.addWidget(self.checkboxes[index]) # second half of variables added to second column else: self.col2.addWidget(self.checkboxes[index]) """ uses cPickle to save profile for future use """ def saveProfile(self): varsList = [] # get varsList from checked boxes for box in self.checkboxes: if box.isChecked(): varsList += [str(box.text())] # error if more than 8 variables checked if len(varsList) > 8: self.tooManyVars() return # error if no variables selected elif len(varsList) < 1: self.tooFewVars() return # asks for name of profile name, ok = QtGui.QInputDialog.getText(self, 'Create a New Profile', 'Please enter a name for this profile.') # saves profile if name is entered and OK is clicked if name and ok: try: # open file for reading savefile = open('saved_profiles.txt', 'rb') savedProfiles = pickle.load(savefile) savefile.close() except IOError: savedProfiles = [] # save tuple of profile name and list of variables in profile savedProfiles.append((str(name), varsList)) savefile = open('saved_profiles.txt', 'wb') pickle.dump(savedProfiles, savefile) savefile.close() self.close() """ sends error message if more than 8 variables selected """ def tooManyVars(self): error = QtGui.QMessageBox.question(None, 'Error', 'You can only put 8 graphs in a profile.', QtGui.QMessageBox.Ok) """ sends error message if no variables selected """ def tooFewVars(self): error = QtGui.QMessageBox.question(None, 'Error', 'Please select at least one graph for this profile.', QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel) # exits profile creator if Cancel is clicked if (error == QtGui.QMessageBox.Cancel): self.close() """function called on all windows by MainMenu""" def redrawWindow(self): # no figures to draw pass
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "profilecreator.py", "copies": "1", "size": "4657", "license": "bsd-3-clause", "hash": 4864857003453955000, "line_mean": 38.1344537815, "line_max": 96, "alpha_frac": 0.5819196908, "autogenerated": false, "ratio": 4.534566699123661, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5616486389923662, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 5/28/2013 # Last Updated: 6/12/2013 # For JCAP from PyQt4 import QtCore, QtGui import sys import graph """ window that displays profile after loading """ class ProfileWindow(QtGui.QMainWindow): """ takes in name that profile was saved under and list of variables to be graphed """ def __init__(self, name = "None", varsList = []): super(ProfileWindow, self).__init__() self.name = name self.varsList = varsList self.graphs = [] self.initUI() """ creates graphics in window """ def initUI(self): # window width is based on number of graphs in profile self.setGeometry(0, 50, 200*(len(self.varsList)+1)+50, 800) self.setWindowTitle(self.name) # displays graphs in a grid format self.main_widget = QtGui.QWidget(self) self.setCentralWidget(self.main_widget) grid = QtGui.QGridLayout(self.main_widget) # creates and adds graphs to appropriate row num_graphs = len(self.varsList) midpoint = (num_graphs+1)/2 for index in range(num_graphs): graphLayout = QtGui.QVBoxLayout() newGraph = graph.Graph(parent=None, xvarname="Time", yvarname=self.varsList[index]) toolbar = graph.NavigationToolbar(newGraph, self) self.graphs += [newGraph] column = 0 if index < midpoint else 1 grid.addLayout(graphLayout, column, index%midpoint) graphLayout.addWidget(toolbar) graphLayout.addWidget(newGraph) """ called whenever new data is ready to be plotted """ def updateWindow(self, newRow): for graph in self.graphs: graph.updatePlot(newRow) """ called by MainMenu every second """ def redrawWindow(self): for graph in self.graphs: graph.draw() """ menu that shows avaiable profiles and loads user's selection """ class LoadMenu(QtGui.QDialog): # these signals will be sent to MainMenu profileChosen = QtCore.pyqtSignal(str) profileToDelete = QtCore.pyqtSignal(str) """ takes in a list of profiles saved for the current data file """ def __init__(self, menuList = []): super(LoadMenu, self).__init__() self.setWindowTitle('Load Profile') # create the main layout and add the list of profiles self.layout = QtGui.QVBoxLayout(self) self.list = QtGui.QListWidget(self) self.list.addItems(menuList) self.layout.addWidget(self.list) # create and activate OK and Cancel buttons buttons = QtGui.QDialogButtonBox() buttons.setStandardButtons(QtGui.QDialogButtonBox.Ok | QtGui.QDialogButtonBox.Cancel) deleteButton = QtGui.QPushButton('Delete') buttons.addButton(deleteButton, QtGui.QDialogButtonBox.DestructiveRole) buttons.accepted.connect(self.sendName) buttons.rejected.connect(self.close) deleteButton.clicked.connect(self.deleteName) self.layout.addWidget(buttons) """ sends name of selected profile to MainMenu, which will then load the profile in a new window """ def sendName(self): name = str(self.list.currentItem().text()) self.profileChosen.emit(name) self.close() def deleteName(self): name = str(self.list.currentItem().text()) confirm = QtGui.QMessageBox.question(None, 'Delete Profile', 'Are you sure you want to delete this profile?', QtGui.QMessageBox.Yes | QtGui.QMessageBox.No) if (confirm == QtGui.QMessageBox.Yes): self.profileToDelete.emit(name) self.close() """ called by MainMenu every second; nothing for this widget to do """ def redrawWindow(self): pass
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "profilewindow.py", "copies": "1", "size": "4022", "license": "bsd-3-clause", "hash": -5871331414505426000, "line_mean": 36.2407407407, "line_max": 93, "alpha_frac": 0.6111387369, "autogenerated": false, "ratio": 4.329386437029063, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.004666542003149145, "num_lines": 108 }
# Allison Schubauer and Daisy Hernandez # Created: 5/28/2013 # Last Updated: 6/13/2013 # For JCAP from PyQt4 import QtGui from dictionary_helpers import getCol import datareader import depositionwindow_data import graphwindow_data import profilewindow import profilecreator import os import filename_handler import process_deposition_data as pdd import sys import cPickle as pickle DATA_FILE_DIR = '' """ window that pops up when application launches """ class MainMenu(QtGui.QWidget): def __init__(self): super(MainMenu, self).__init__() # holds all active windows self.graphWindows = [] self.depWindows = [] self.miscWindows = [] # holds all profiles associated with current file self.profiles = {} # data processor is not initialized until FILE_INFO is complete self.processor = None # save name of file from which application will read self.file = self.initReader() # if there are no .csv files in working folder, have user # choose file to load if not self.file: self.loadDataFile(1) # check if filename is in valid format filenameError = filename_handler.parseFilename(self.file) # if not, ask user for experiment parameters if filenameError: self.requestFileInfo(1) # otherwise, finish setting up program else: self.initData() self.initUI() """ automatically loads last modified data file when application launches """ def initReader(self): lastModifiedFile = '' lastModifiedTime = 0 allFiles = os.listdir(DATA_FILE_DIR) data = filter(lambda filename: filename.endswith('.csv'), allFiles) for filename in data: statbuf = os.stat(os.path.join(DATA_FILE_DIR, filename)) if statbuf.st_mtime > lastModifiedTime: lastModifiedTime = statbuf.st_mtime lastModifiedFile = filename return lastModifiedFile """ draws graphical user interface """ def initUI(self): self.setGeometry(50, 150, 300, 400) self.setWindowTitle('Deposition Monitor') self.layout = QtGui.QVBoxLayout(self) # load data file loadFileButton = QtGui.QPushButton('Choose Data File') self.layout.addWidget(loadFileButton) loadFileButton.clicked.connect(self.loadDataFile) # show single graph makeGraphButton = QtGui.QPushButton('Show Graph') self.layout.addWidget(makeGraphButton) makeGraphButton.clicked.connect(self.makeGraph) # create a profile makeProfileButton = QtGui.QPushButton('Create a New Profile') self.layout.addWidget(makeProfileButton) makeProfileButton.clicked.connect(self.makeProfile) # show a saved profile loadProfileButton = QtGui.QPushButton('Load a Saved Profile') self.layout.addWidget(loadProfileButton) loadProfileButton.clicked.connect(self.selectProfile) # show a deposition graph makeDepositionButton = QtGui.QPushButton('Create Deposition Graph') self.layout.addWidget(makeDepositionButton) makeDepositionButton.clicked.connect(self.makeDeposition) # end data collection session endButton = QtGui.QPushButton('End Experiment') self.layout.addWidget(endButton) endButton.clicked.connect(self.endExperiment) # initialize the timer that updates all graphs in application timer = pdd.QtCore.QTimer(self) timer.timeout.connect(self.redrawAll) # update graph every 1000 milliseconds timer.start(1000) self.show() """ initializes all elements of program that require experiment information (FILE_INFO must be complete) """ def initData(self): filepath = os.path.join(DATA_FILE_DIR, self.file) # if application has just been opened if not self.processor: # initialize data processor (includes reader) self.processor = pdd.ProcessorThread(parent=self, filename=filepath) self.processor.lineRead.connect(self.newLineRead) self.processor.newData.connect(self.depUpdate) self.processor.srcError.connect(self.sourceError) self.processor.start() # if loading a new file else: self.processor.newFile(filepath) self.initSupplyVars() """Initializes any variables that are useful for error checking""" def initSupplyVars(self): self.errors =[] # number of rows read by checkValidity self.rowsReadCV = 0 self.supply = int(filename_handler.FILE_INFO.get("Supply")) try: if self.supply % 2 == 0: self.rfl = getCol("Power Supply" + str(self.supply) + " Rfl Power") self.fwd = getCol("Power Supply" + str(self.supply) + " Fwd Power") self.dcbias = getCol("Power Supply" + str(self.supply) + " DC Bias") if self.supply % 2 == 1: self.output_power = getCol("Power Supply" + str(self.supply) + \ " Output Power") self.output_voltage = getCol("Power Supply" + str(self.supply) + \ " Output Voltage") except IndexError: self.processor.end() message = "This is not a valid data file. Please load a new file." invalidFileError = QtGui.QMessageBox.warning(None, "Invalid File", message) self.loadDataFile(1) """ if filename is not in correct format, ask user to enter experiment parameters manually (mode is 1 if called when the application is first opened, 0 if called when the user loads a new file) """ def requestFileInfo(self, mode): fileErrorDialog = FileInfoDialog(mode) self.miscWindows.append(fileErrorDialog) fileErrorDialog.fileInfoComplete.connect(self.initData) fileErrorDialog.fileAborted.connect(self.loadDataFile) """ allows user to choose another data file (mode is 1 if called to replace default file, 0 if the user loads a new file through main menu) """ def loadDataFile(self, mode=0): global DATA_FILE_DIR global FILE_INFO dirname = QtGui.QFileDialog.getOpenFileName(self, 'Open data file', DATA_FILE_DIR, 'CSV files (*.csv)') # if cancel is clicked, dirname will be empty string if dirname != '': filename_handler.FILE_INFO = {'Element':'', 'Source':'', 'Supply':'', 'TiltDeg':[], 'Z_mm':[]} # converts Qstring to string dirString = str(dirname) # gets filename from current directory (will be changed eventually) dirList = dirString.split('/') DATA_FILE_DIR = '/'.join(dirList[:len(dirList)-1]) self.file = dirList[len(dirList)-1] # hides all windows so they can be removed later for window in (self.graphWindows + self.depWindows + self.miscWindows): window.hide() # check filename for correct format filenameError = filename_handler.parseFilename(self.file) if filenameError: self.requestFileInfo(mode) # set everything up for the new file being read else: self.initData() # if user declines to use default file and declines to open a # new file, quit the application else: if mode == 1: self.close() """ creates window for single graph """ def makeGraph(self): graph = graphwindow_data.GraphWindow() self.graphWindows.append(graph) graph.show() """ shows profile creator window """ def makeProfile(self): profileCreator = profilecreator.ProfileCreator() self.miscWindows.append(profileCreator) profileCreator.show() """ shows load profile window """ def selectProfile(self): try: # open file for reading savefile = open('saved_profiles.txt', 'rb') savedProfiles = pickle.load(savefile) savefile.close() # this will occur if profiles have never been saved before # and saved_profiles.txt does not exist except IOError: savedProfiles = [] menuList = [] if not savedProfiles: error = QtGui.QMessageBox.information(None, "Load Profile Error", "There are no saved profiles.") return # only show profiles with headings that correspond to this file for name, varsList in savedProfiles: if all(var in datareader.DATA_HEADINGS.values() for var in varsList): self.profiles[name] = varsList menuList += [name] loadMenu = profilewindow.LoadMenu(menuList) self.miscWindows.append(loadMenu) loadMenu.show() loadMenu.profileChosen.connect(self.loadProfile) loadMenu.profileToDelete.connect(self.deleteProfile) """ shows deposition graph window """ def makeDeposition(self): depWindow = depositionwindow_data.DepositionWindow() self.depWindows.append(depWindow) """ once profile is chosen, loads profile in new window """ def loadProfile(self, name): varsList = self.profiles.get(str(name)) profileWindow = profilewindow.ProfileWindow(name, varsList) self.graphWindows.append(profileWindow) profileWindow.show() """ deletes a chosen profile from the LoadMenu """ def deleteProfile(self, name): # savefile holds list of all profiles savefile = open('saved_profiles.txt', 'rb') savedProfiles = pickle.load(savefile) savefile.close() for profile in savedProfiles: if profile[0] == name: savedProfiles.remove(profile) # save updated list of profiles savefile = open('saved_profiles.txt', 'wb') pickle.dump(savedProfiles, savefile) savefile.close() """ sends new data received by reader to active graph windows """ def updateGraphs(self, newRow): for window in self.graphWindows: window.updateWindow(newRow) """ sends new processed data to active deposition graph windows """ def depUpdate(self, newDepRates): for window in self.depWindows: window.updateWindow(newDepRates) """ updates all active graph windows every second """ def redrawAll(self): for windowType in (self.graphWindows,self.depWindows,self.miscWindows): for window in windowType: # release memory resources for all closed windows if window.isHidden(): windowType.remove(window) # graph windows will redraw; all other windows # ignore this command else: window.redrawWindow() """ processes final data set and terminates reader at end of experiment """ def endExperiment(self): self.processor.onEndExperiment() """ terminates reader (if still active) when main window is closed """ def closeEvent(self, event): if self.processor: self.processor.end() event.accept() """ handles signal from reader when new line has been read """ def newLineRead(self, newRow): self.updateGraphs(newRow) self.checkValidity(newRow) # This can be changed to check for errors. Currently it checks one # row at a time but it could be changed to use averages """ shows an error message if data indicates experiment failure """ def checkValidity(self, row): errors_list = [] # change the number so that it ignores the errors for the first # calibratingNumber of lines we read in case we're callibrating calibratingNumber = 30 if self.supply % 2 == 0: fwdValue = float(row[self.fwd]) dcBiasValue = float(row[self.dcbias]) rflValue = float(row[self.rfl]) if fwdValue < 5: errors_list.append("FWD power is below 5.") if dcBiasValue < 50: errors_list.append("DC bias is below 50.") if .10*fwdValue < rflValue: errors_list.append("RFL power is greater than 10% of FWD.") if self.supply % 2 == 1: opValue = float(row[self.output_power]) if opValue < 5: errors_list.append("Output power is below 5.") newErrors = [error for error in errors_list if error not in self.errors] # rows read by the checkValidity increased self.rowsReadCV +=1 # do not consider these errors if it's for the first bufferNumber lines # as it could be callibrating if self.rowsReadCV < calibratingNumber: newErrors = [] self.errors += newErrors # show error warnings if necessary if newErrors: message = "You have the following errors: " + " ".join(newErrors) self.validityError = QtGui.QErrorMessage() self.validityError.setWindowTitle("Power Supply Warning") self.validityError.showMessage(message) """ kills data processor and prompts user to load new file if invalid source number was provided """ def sourceError(self, srcNum): self.processor.end() message = "Source %d is not a valid source. Please load a new file." % srcNum srcError = QtGui.QMessageBox.warning(None, "Source Error", message) self.loadDataFile(1) """ custom dialog box to request necessary file info from user """ class FileInfoDialog(QtGui.QWidget): #sends signal and mode to MainMenu once all information # has been entered fileInfoComplete = pdd.QtCore.pyqtSignal(int) # sends signal and mode to MainMenu if user closes dialog fileAborted = pdd.QtCore.pyqtSignal(int) """ mode is 1 if called when the application is first opened, 0 if called when the user loads a new file """ def __init__(self, mode): super(FileInfoDialog, self).__init__() self.mode = mode self.setWindowModality(pdd.QtCore.Qt.ApplicationModal) self.initUI() """ draws user interface of window """ def initUI(self): self.setWindowTitle('Experiment Information') self.layout = QtGui.QVBoxLayout(self) self.gridlayout = QtGui.QGridLayout(self) self.setLayout(self.layout) self.labels = [] self.lineEdits = [] # get necessary parameters from FILE_INFO and sort in alphabetical order self.tagsList = [tag for tag in filename_handler.FILE_INFO.iteritems()] self.tagsList.sort(key = lambda x: x[0]) self.layout.addWidget(QtGui.QLabel('Please enter values for the following parameters:')) # make sub-layout to hold labels and text fields self.layout.addLayout(self.gridlayout) for i, (tag, val) in enumerate(self.tagsList): # allow comma-separated lists for z and t values if type(val) == list: val = ','.join([str(x) for x in val]) # add label for this parameter self.labels.append(QtGui.QLabel(tag+':')) # if a value was obtained from the filename, fill it in the # text input field self.lineEdits.append(QtGui.QLineEdit(str(val))) self.gridlayout.addWidget(self.labels[i], i, 0) self.gridlayout.addWidget(self.lineEdits[i], i, 1) self.enter = QtGui.QPushButton('Enter') self.enter.setDefault(True) self.enter.clicked.connect(self.sendInfo) self.layout.addWidget(self.enter, alignment=pdd.QtCore.Qt.AlignRight) self.show() """ populates FILE_INFO dictionary and sends signal to MainMenu """ def sendInfo(self): global FILE_INFO for i, (tag, val) in enumerate(self.tagsList): # convert Qstring to string newValStr = str(self.lineEdits[i].text()) # if text input field is blank, bring up an error message if not newValStr: self.completionError() return # convert comma-separated entries into list if type(filename_handler.FILE_INFO.get(tag)) == list: newValStrList = newValStr.split(',') try: newValList = [float(x) for x in newValStrList] filename_handler.FILE_INFO[tag] = newValList # raise error if z and t aren't decimal values except ValueError: self.formatError() return # add user input values to FILE_INFO else: filename_handler.FILE_INFO[tag] = newValStr # notify MainMenu that FILE_INFO is complete and close window self.fileInfoComplete.emit(self.mode) self.hide() """ NOTE: We don't check the validity of any of the actual entries here because we trust the user to know the parameters of his/her own experiment. Our program doesn't use the element name anywhere, but you could easily check if the element name given is an actual element by checking if it's a key in the ELEMENTS dictionary. An invalid power supply will raise an error in initSupplyVars in this file; an invalid source number will raise an error in process_ deposition_data, which will be handled by MainMenu (see SourceError). If the input t and z values are incorrect, the deposition graph will simply be blank. """ """ brings up an error message if not all fields are filled in """ def completionError(self): message = "Please enter values for all parameters." error = QtGui.QMessageBox.warning(self, "Error", message, QtGui.QMessageBox.Ok) """ brings up an error message if z and t entries are invalid """ def formatError(self): message = "Please enter comma-separated decimal values for Z and tilt." error = QtGui.QMessageBox.warning(self, "Error", message, QtGui.QMessageBox.Ok) # clear text input fields for z and t if error == QtGui.QMessageBox.Ok: for i, (tag, val) in enumerate(self.tagsList): if type(filename_handler.FILE_INFO.get(tag)) == list: self.lineEdits[i].clear() """ nothing to redraw every second """ def redrawWindow(self): pass """ confirms that user doesn't want to load data file if user tries to close dialog """ def closeEvent(self, event): message = "If you close this window, you will be prompted to open another file." response = QtGui.QMessageBox.information(self, "Note", message, QtGui.QMessageBox.Ok | QtGui.QMessageBox.Cancel) if response == QtGui.QMessageBox.Ok: self.fileAborted.emit(self.mode) event.accept() else: event.ignore() """ main event loop """ def main(): global DATA_FILE_DIR dirfile = open('DefaultDirectory.txt', 'rb') DATA_FILE_DIR = dirfile.readline() dirfile.close() app = QtGui.QApplication(sys.argv) menu = MainMenu() sys.exit(app.exec_()) if __name__ == '__main__': main()
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "mainmenu.py", "copies": "1", "size": "19949", "license": "bsd-3-clause", "hash": 9168197558977492000, "line_mean": 40.7343096234, "line_max": 96, "alpha_frac": 0.6107574315, "autogenerated": false, "ratio": 4.431141714793426, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5541899146293425, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 6/05/2013 # Last Updated: 6/14/2013 # For JCAP from elements import ELEMENTS # holds important information associated with data file FILE_INFO = {'Element':'', 'Source':'', 'Supply':'', 'TiltDeg':[], 'Z_mm':[]} """ gets information for FILE_INFO from name of data file """ def parseFilename(filename): global FILE_INFO # ignore '.csv' at end of filename if filename.endswith('.csv'): filename = filename[:-4] # experiment parameters should be separated with underscores rawFileInfo = filename.split('_') # keys: keywords in filename; values: corresponding keys in FILE_INFO tagsDict = {'Source': 'Source', 'Src': 'Source', 'SRC': 'Source', 'src': 'Source', 't': 'TiltDeg', 'tilt': 'TiltDeg', 'z': 'Z_mm', 'Z': 'Z_mm', 'Supply': 'Supply', 'Sup': 'Supply', 'sup': 'Supply'} for tag in rawFileInfo: # strippedTag is the keyword strippedTag = filter(str.isalpha, tag) # tagVal is the numerical value attached to the keyword tagVal = filter(lambda x: not x.isalpha(), tag) if strippedTag in tagsDict: stdName = tagsDict.get(strippedTag) # multiple z-values can be listed in filename if (stdName == 'Z_mm' and stdName in FILE_INFO): FILE_INFO[stdName] += [float(tagVal)] # z and t values should be stored in a list (used in # data processing) elif (stdName == 'Z_mm' or stdName == 'TiltDeg'): FILE_INFO[stdName] = [float(tagVal)] # all other values can be saved as string else: FILE_INFO[stdName] = tagVal elif tag in ELEMENTS: FILE_INFO['Element'] = tag # keep track of any parameters that were not found in filename invalidTags = [] for tag in FILE_INFO: if not FILE_INFO.get(tag): invalidTags.append(tag) # existence of invalidTags will be checked by MainMenu return invalidTags
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "filename_handler.py", "copies": "1", "size": "2059", "license": "bsd-3-clause", "hash": -3334506848038253000, "line_mean": 39.3725490196, "line_max": 78, "alpha_frac": 0.5998057309, "autogenerated": false, "ratio": 3.7988929889298895, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9863257919961284, "avg_score": 0.007088159973721256, "num_lines": 51 }
# Allison Schubauer and Daisy Hernandez # Created: 6/05/2013 # Last Updated: 6/14/2013 # For JCAP import numpy as np from PyQt4 import QtCore from dictionary_helpers import * import date_helpers import filename_handler import datareader # global dictionary holds all processed (z, x, y, rate) data for the experiment DEP_DATA = [] zndec = 1 tndec = 0 radius1 = 28. radius2 = 45. """ does all of the data processing necessary for deposition plots """ class ProcessorThread(QtCore.QThread): # transfers new line from reader to MainMenu lineRead = QtCore.pyqtSignal(list) # transfers new processed data to deposition graph newData = QtCore.pyqtSignal(tuple) srcError = QtCore.pyqtSignal(int) def __init__(self, parent=None, filename='default.csv'): super(ProcessorThread, self).__init__() self.file = filename self.rowBuffer = [] self.changeZ = False self.running = True self.reader = datareader.DataReader(parent=self, filename=self.file) self.reader.lineRead.connect(self.newLineRead) def run(self): self.reader.start() # initialize DATA_DICT column numbers used for data processing try: self.tcolnum = getCol('Src%d Motor Tilt Position' %int(filename_handler.FILE_INFO['Source'])) except IndexError: self.srcError.emit(int(filename_handler.FILE_INFO['Source'])) self.zcolnum = getCol('Platen Zshift Motor 1 Position') self.anglecolnum = getCol('Platen Motor Position') while self.running: pass """ called whenever the reader sends a full line """ def newLineRead(self, newRow): self.lineRead.emit(newRow) self.processRow(newRow) """ adds a new row to its own row buffer and processes the data in the row buffer if the azimuth or z-value of the instrument has changed """ def processRow(self, row): if self.rowBuffer == []: self.rowBuffer += [row] else: angle = round(float(row[self.anglecolnum])) zval = round(float(row[self.zcolnum]), 2) prevangle = round(float(self.rowBuffer[-1][self.anglecolnum]), 0) prevz = round(float(self.rowBuffer[-1][self.zcolnum]), 2) if (angle == prevangle and zval == prevz): self.rowBuffer += [row] elif (angle == prevangle): self.processData(prevz, prevangle, radius1) self.processData(prevz, prevangle, radius2) # indicates that center point will need to be # computed in next round of processing self.changeZ = True # reset row buffer self.rowBuffer = [row] else: self.processData(zval, prevangle, radius1) self.processData(zval, prevangle, radius2) self.rowBuffer = [row] """ processes all rates at the same angle and z-value to produce a single (z, x, y, rate) data point """ def processData(self, z, angle, radius): global DEP_DATA rowRange = self.getRowRange() # only one or two data points indicates a transitional angle # that can be ignored - Savitzky Golay can be used in the future if rowRange[1] - rowRange[0] <= 2: pass else: # get only valid rows from buffer dataArray = self.rowBuffer[rowRange[0]:(rowRange[1]+1)] # transpose matrix so that each column in the # spreadsheet becomes a row dataArrayT = np.array(dataArray).T timespan = self.getTimeSpan(dataArrayT) depRates = self.getDepRates(timespan, dataArrayT) # normalize based on drifting center point rate0 = self.getXtalRate(3, dataArrayT).mean() rate = rate0 if radius == radius1: if angle == 0 or self.changeZ: # plot center point along with first set # of data for this z-value DEP_DATA.append((z, 0.0, 0.0, rate)) self.newData.emit((z, 0.0, 0.0, rate)) self.changeZ = False x = radius * np.cos(angle * np.pi/180.) y = radius * np.sin(angle * np.pi/180.) # rate1 corresponds to Xtal4 Rate rate = rate0 * depRates[2]/depRates[1] else: x = radius * np.cos(angle * np.pi/180. + np.pi) y = radius * np.sin(angle * np.pi/180. + np.pi) # rate2 corresponds to Xtal2 Rate rate = rate0 * depRates[0]/depRates[1] # store data points for initializing new graph DEP_DATA.append((z, x, y, rate)) # indicate to exisiting graphs that there is # new data to display self.newData.emit((z, x, y, rate)) """ helper function to correct for instrument noise in measuring z-value """ def roundZ(self, zcol): zrnd=np.round(zcol, decimals=zndec) for i, zval in enumerate(zrnd): if zval not in filename_handler.FILE_INFO['Z_mm']: zrnd[i] = -1 return zrnd """ helper function to correct for instrument noise in measuring tilt """ def roundT(self, tcol): trnd=np.round(tcol, decimals=tndec) for i, tval in enumerate(trnd): if tval not in filename_handler.FILE_INFO['TiltDeg']: trnd[i] = -1 return trnd """ gets range of valid rows in row buffer based on whether z and t values match experimental parameters """ def getRowRange(self): data = np.array(self.rowBuffer) datacols = data.T zcol = map(float, datacols[self.zcolnum]) tcol = map(float, datacols[self.tcolnum]) inds_useful=np.where((self.roundZ(zcol)>=0)&(self.roundT(tcol)>=0))[0] # if rowRange is nonzero, send it if inds_useful.size: return (inds_useful[0], inds_useful[-1]) # otherwise, send dummy rowRange to processData return (0, 0) """ gets time span of valid data set for given angle and z-value """ def getTimeSpan(self, dataArrayT): datecol = getCol('Date') timecol = getCol('Time') datetimeTup = zip(dataArrayT[datecol], dataArrayT[timecol]) startStr = datetimeTup[0][0] + ' ' + datetimeTup[0][1] endStr = datetimeTup[-1][0] + ' ' + datetimeTup[-1][1] durationObj = date_helpers.dateObjFloat(endStr) - date_helpers.dateObjFloat(startStr) return durationObj.total_seconds() """ helper function to return column of Xtal rates from valid data set """ def getXtalRate(self, ratenum, dataArrayT): rcolnum = getCol('Xtal%d Rate' % ratenum) return np.array(map(float, dataArrayT[rcolnum])) """ helper function to compute all deposition rates as time-averaged Xtal rates """ def getDepRates(self, timespan, dataArrayT): depRates = [] for x in range(2,5): rateData = self.getXtalRate(x, dataArrayT) rateDiff = rateData[-1] - rateData[0] depRates += [rateDiff/timespan] return depRates """ re-initializes data sets and reader when a new spreadsheet file is loaded """ def newFile(self, newfile): global DEP_DATA DEP_DATA = [] self.rowBuffer = [] if self.reader: self.reader.end() self.reader = datareader.DataReader(parent=self, filename=newfile) self.reader.lineRead.connect(self.newLineRead) self.reader.start() # re-initialize DATA_DICT column numbers used for data processing try: self.tcolnum = getCol('Src%d Motor Tilt Position' %int(filename_handler.FILE_INFO['Source'])) except IndexError: self.srcError.emit(int(filename_handler.FILE_INFO['Source'])) self.zcolnum = getCol('Platen Zshift Motor 1 Position') self.anglecolnum = getCol('Platen Motor Position') """ empties row buffer and kills reader when experiment has ended """ def onEndExperiment(self): if self.rowBuffer: angle = round(float(self.rowBuffer[0][self.anglecolnum])) zval = round(float(self.rowBuffer[0][self.zcolnum]), 1) self.processData(zval, angle, radius1) self.processData(zval, angle, radius2) self.rowBuffer = [] if self.reader: self.reader.end() self.reader = None """ kills both the reader and data processor threads; called when application exits """ def end(self): if self.reader: self.reader.end() self.running = False
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "process_deposition_data.py", "copies": "1", "size": "8789", "license": "bsd-3-clause", "hash": 6554170663608306000, "line_mean": 39.8790697674, "line_max": 105, "alpha_frac": 0.5967686881, "autogenerated": false, "ratio": 3.816326530612245, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.9903399147385502, "avg_score": 0.001939214265348631, "num_lines": 215 }
# Allison Schubauer and Daisy Hernandez # Created: 6/06/2013 # Last Updated: 6/14/2013 # For JCAP from PyQt4 import QtGui from matplotlib.backends.backend_qt4agg import FigureCanvasQTAgg as FigureCanvas from matplotlib.figure import Figure import matplotlib.colors as colors import matplotlib.cm as cm import process_deposition_data as pdd import numpy as np """ the deposition graph, its axes, and its data """ class DepositionGraph(FigureCanvas): def __init__(self, parent="None", width=2, height=2, dpi=120): # initialize matplotlib figure self.figure = Figure(figsize=(width, height), dpi=dpi) FigureCanvas.__init__(self, self.figure) # let graph expand when window expands FigureCanvas.setSizePolicy(self, QtGui.QSizePolicy.Expanding, QtGui.QSizePolicy.Expanding) FigureCanvas.updateGeometry(self) # set up the axes and their properties self.initPlotArea() # conversion factor is scalar used for changing units # maxRate is used for resetting the color scale self.convFactor, self.maxRate = 1, 0 # currentZ is the z-position for which the graph # is displaying deposition rate data # zvars holds all z-values for this experiment self.currentZ, self.zvars = None, [] # formatted string that represents the units of the data # (defaults to 10^-8 g/(s cm^2)) self.units = r'$10^{-8}$'+'g/s cm'+r'$^2$' """ initializes the graph's data and axes """ def initPlotArea(self): self.xdata, self.ydata, self.ratedata = [], [], [] self.plot = self.figure.add_subplot(1, 1, 1, adjustable='box', aspect=1) self.plot.set_xlim(-50, 50) self.plot.set_ylim(-50, 50) # keep x and y limits fixed because radius values are fixed self.plot.autoscale(enable=False, tight=False) """ plots all available data when window is opened """ def firstPlot(self, zval = None): self.currentZ = zval # default to first z-value in data file if not zval: self.currentZ = pdd.DEP_DATA[0][0] # keep track of all valid z-values for experiment if self.currentZ not in self.zvars: self.zvars.append(self.currentZ) for z, x, y, rate in pdd.DEP_DATA: # save other z-values for user to access later if z != self.currentZ: if z not in self.zvars: self.zvars.append(z) continue # otherwise, plot rate on this graph self.xdata.append(x) self.ydata.append(y) modified_rate = rate*self.convFactor self.ratedata.append(modified_rate) # keep maxRate updated if we need to reset the scale if modified_rate > self.maxRate: self.maxRate = modified_rate # holds information about the scale of the colorbar self.scalarMap = cm.ScalarMappable(norm=colors.Normalize(vmin=0, vmax=self.maxRate)) self.scalarMap.set_array(np.array(self.ratedata)) # plot all available data and save scatter object for later deletion self.datavis = self.plot.scatter(self.xdata, self.ydata, c = self.ratedata, cmap=self.scalarMap.get_cmap(), marker='o', edgecolor='none', s=60) # initialize colorbar and set its properties self.colorbar = self.figure.colorbar(self.scalarMap, ax = self.plot) self.colorbar.set_array(np.array(self.ratedata)) self.colorbar.autoscale() self.colorbar.set_label(self.units) self.scalarMap.set_clim(0, self.maxRate) self.scalarMap.changed() self.draw() """ plots newly-processed data on preexisting graph """ def updatePlot(self, newData): # only plot data corresponding to current z-position for z, x, y, rate in [newData]: if z!= self.currentZ: break self.xdata.append(x) self.ydata.append(y) modified_rate = rate*self.convFactor self.ratedata.append(modified_rate) # reset colorbar scale if necessary if modified_rate > self.maxRate: self.maxRate = modified_rate # redraw plot with new point self.rescale() self.draw() """ NOTE: We redraw the entire plot every time a new point comes in rather than simply adding the point to the preexisting plot because matplotlib was often unable to associate the new point with the existing colormap, resulting in a lot of dark blue dots (representing 0 on the scale, as far as we could tell) on the graph, which the user would have to correct manually by clicking 'Reset Colors.' We decided that it was worth a negligible amount of extra memory to provide the user with a less frustrating experience. """ """ redraws the graph with new data and new color scale (if maxRate has changed) """ def rescale(self): # clear old color values from plot self.datavis.remove() # reset limits of color scale self.scalarMap.set_clim(0, self.maxRate) # plot entire set of data according to new scale self.datavis = self.plot.scatter(self.xdata, self.ydata, c = self.ratedata, cmap=self.scalarMap.get_cmap(), marker='o', edgecolor='none', s=60) # rescale the colorbar self.colorbar.draw_all() """ reset figure prior to switching z-values """ def clearPlot(self): self.figure.clear() self.initPlotArea() self.convFactor, self.maxRate = 1, 0 self.currentZ, self.zvars = None, [] self.units = r'$10^{-8}$'+'g/s cm'+r'$^2$' """ convert rate data and change label on colorbar when converting units """ def convertPlot(self): # used to make sure we got all the data values for the given z lenOfRateData = len(self.ratedata) currLocation = 0 for z, x, y, rate in pdd.DEP_DATA: # convert only those rate with the desired z if currLocation < lenOfRateData and z == self.currentZ: self.ratedata[currLocation] = rate*self.convFactor currLocation +=1 elif currLocation >= lenOfRateData: break # get new maxRate with max function to prevent errors due to precision self.maxRate = max(self.ratedata) self.scalarMap.set_clim(0, self.maxRate) self.scalarMap.changed() self.colorbar.draw_all() self.draw() """ called when user clicks on graph to display (x, y) data """ def onclick(self,event): try: xcorr = event.xdata ycorr = event.ydata except TypeError: pass
{ "repo_name": "johnmgregoire/JCAPdepositionmonitor", "path": "depgraph.py", "copies": "1", "size": "7104", "license": "bsd-3-clause", "hash": 1233300438427275300, "line_mean": 42.5828220859, "line_max": 92, "alpha_frac": 0.6013513514, "autogenerated": false, "ratio": 4.094524495677233, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5195875847077233, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 6/24/2013 # Last Updated: 6/25/2013 # For JCAP import logging, logging.handlers class ErrorHandler(): def __init__(self, name, loggingfile, loglevel = logging.DEBUG): # setting up the logger and the messages allowed to be logged self.logger = logging.getLogger(name) self.logger.setLevel(loglevel) # assures that the messages from the logger are propogated upward self.logger.propagate self.loggingfile = loggingfile """ Initializes the file handler. If we are using a child logger then we don't have to do this. That is, if we will be relying on the root logger and it's file handler. """ def initHandler(self,formatforhandler=None, logginglevel = logging.DEBUG): self.errorFileHandler = self.fileHandlerCreator(self.loggingfile,logginglevel) self.initFormat(self.errorFileHandler,formatforhandler) self.addHandler(self.errorFileHandler) """ Creates a fileHandler and sets its level. This does not have to be done more than once if one is planning to rely on a root logger. """ def fileHandlerCreator(self, filename, logginglevel): handler = logging.FileHandler(filename) handler.setLevel(logginglevel) return handler """ Sets the format of the handler it is passed.""" def initFormat(self,hdlr,formattouse ='%(asctime)s - %(name)s - %(levelname)s - %(message)s'): formatter = logging.Formatter(formattouse) hdlr.setFormatter(formatter) """ Adds the handler to the logger created. """ def addHandler(self,hdlr): self.logger.addHandler(hdlr) """ Logs the message using different levels. It defaults to DEBUG if there is no level given or its not one of the other choices. """ def logMessage(self,message,level=logging.DEBUG,traceback=False): if level == "INFO": level = logging.INFO elif level == "WARNING": level = logging.WARNING elif level == "ERROR": level = logging.ERROR elif level == "CRITICAL": level = logging.CRITICAL else: level = logging.DEBUG self.logger.log(level,message,exc_info=traceback) """ Closes the file handler. If there is more handler those need to be closed as well. """ def close(self): self.errorFileHandler.close() # example of a way to use it def example(path = 'C:\Users\Public\Documents\errors.log'): testingLog = ErrorHandler('TestingLog', path) testingLog.initHandler('%(asctime)s - %(name)s - %(levelname)s - %(message)s') a = [1,2,3,4,5] while True: try: a.pop() except: testingLog.logMessage("Failed doing a.pop()") break testingLog.close() # comment out to see a demstration of the sample # example()
{ "repo_name": "johnmgregoire/2013JCAPDataProcess", "path": "error_handling.py", "copies": "1", "size": "2861", "license": "bsd-3-clause", "hash": 3142959647258650000, "line_mean": 37.6621621622, "line_max": 98, "alpha_frac": 0.6620062915, "autogenerated": false, "ratio": 4.023909985935302, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.5185916277435302, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 6/24/2013 # Last Updated: 6/27/2013 # For JCAP # functions for converting our formatted data dictionaries to # and from JSON files import os import csv import json import numpy import datetime #SAVEPATH = os.path.expanduser("~/Desktop/Working Folder/AutoAnalysisJSON") ##def toJSON(filename, fomdict, intermeddict, inputdict): ## savepath = os.path.join(SAVEPATH, filename+'.json') ## with open(savepath, 'w') as fileObj: ## dataTup = (fomdict, intermeddict, inputdict) ## listOfObjs = [] ## for dataDict in dataTup: ## listOfObjs.append(convertNpTypes(dataDict)) ## json.dump(listOfObjs, fileObj) ## return savepath def toJSON(savepath, version, dataTup): with open(savepath, 'w') as fileObj: ObjDict['version']=version for k, dataDict in zip(["measurement_info", "fom", "raw_arrays", "intermediate_arrays", "function_parameters"], dataTup): ObjDict[k]=convertNpTypes(dataDict) json.dump(ObjDict, fileObj) return ObjDict ##def fromJSON(filepath): ## with open(filepath, 'r') as fileObj: ## dataTup = json.load(fileObj, object_hook=unicodeToString) ## print dataTup ## return dataTup def getDataFromJSON(filepath): with open(filepath, 'r') as fileObj: jsonDict = json.load(fileObj, object_hook=unicodeToString) return jsonDict def convertNpTypes(container): if isinstance(container, dict): pydict = {} for key, val in container.iteritems(): if isinstance(val, numpy.generic): val = numpy.asscalar(val) elif isinstance(val, numpy.ndarray): val = convertNpTypes(list(val)) elif isinstance(val, datetime.datetime): val=str(val) pydict[key] = val return pydict elif isinstance(container, list): for i, val in enumerate(container): if isinstance(val, numpy.generic): container[i] = numpy.asscalar(val) elif isinstance(val, numpy.ndarray): container[i] = convertNpTypes(list(val)) return container elif isinstance(container, numpy.ndarray): return convertNpTypes(list(container)) def unicodeToString(container): if isinstance(container, dict): strdict = {} for key, val in container.iteritems(): if isinstance(key, unicode): key = str(key) if isinstance(val, unicode): val = str(val) elif isinstance(val, list): val = unicodeToString(val) elif isinstance(val, dict): val = unicodeToString(val) strdict[key] = val return strdict elif isinstance(container, list): for i, val in enumerate(container): if isinstance(val, unicode): container[i] = str(val) elif isinstance(val, list): container[i] = unicodeToString(val) elif isinstance(val, dict): container[i] = unicodeToString(val) return container #def getFOMs(filename): # dataTup = fromJSON(filename) # fomdict = dataTup[0] # idval = filename.split('_')[0] # with open(filename+'.txt', 'wb') as fileToDB: # fomwriter = csv.writer(fileToDB) # rowToWrite = [idval] # for fom in fomdict: # rowToWrite.append(str(fom)+': '+str(fomdict.get(fom))) # fomwriter.writerow(rowToWrite) # print rowToWrite
{ "repo_name": "johnmgregoire/2013JCAPDataProcess", "path": "jsontranslator.py", "copies": "1", "size": "3547", "license": "bsd-3-clause", "hash": 7143248503535186000, "line_mean": 33.7745098039, "line_max": 129, "alpha_frac": 0.6123484635, "autogenerated": false, "ratio": 3.683281412253375, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 0.47956298757533755, "avg_score": null, "num_lines": null }
# Allison Schubauer and Daisy Hernandez # Created: 6/25/2013 # Last Updated: 6/26/2013 # For JCAP import sys, os from PyQt4 import QtCore, QtGui from time import strftime, localtime import re class MainMenu(QtGui.QMainWindow): def __init__(self): super(MainMenu, self).__init__() self.versionName = None self.verifiedName = None self.initUI() """ initializes the user interface for this commit menu """ def initUI(self): self.setGeometry(500, 200, 600, 100) self.setWindowTitle('Data Analysis File Committer') self.mainWidget = QtGui.QWidget(self) self.setCentralWidget(self.mainWidget) self.secondaryWidget = QtGui.QWidget(self) self.mainLayout= QtGui.QGridLayout() self.secondaryLayout= QtGui.QGridLayout() self.mainWidget.setLayout(self.mainLayout) self.secondaryWidget.setLayout(self.secondaryLayout) self.directions = QtGui.QLabel('Please select the folder you wish to.', self) self.mainLayout.addWidget(self.directions, 0,0) self.mainLayout.addWidget(self.secondaryWidget) selectFolder = QtGui.QPushButton('Select Folder', self) selectFolder.clicked.connect(self.selectProgram) self.secondaryLayout.addWidget(selectFolder, 0, 0) self.fileSelected = QtGui.QLineEdit(self) self.fileSelected.setReadOnly(True) self.secondaryLayout.addWidget(self.fileSelected, 0, 1) self.status = QtGui.QLabel('', self) self.mainLayout.addWidget(self.status) self.show() """ textFileTuple is signal received from file dialog; 0th item is string of file/folder names to display in line edit, 1st item is list of filepaths (basenames) to load """ def loadData(self, textFileTuple): self.fileSelected.setText(textFileTuple[0]) self.files = textFileTuple[1] print len(self.files) """ deals with getting relevent information for the file ones wishes to commit """ def selectProgram(self): self.programDialog = QtGui.QFileDialog(self, caption = "Select a version folder containing data analysis scripts") self.programDialog.setFileMode(QtGui.QFileDialog.Directory) # if user clicks 'Choose' if self.programDialog.exec_(): self.status.setText('') # list of QStrings (only one folder is allowed to be selected) dirList = self.programDialog.selectedFiles() targetDir = os.path.normpath(str(dirList[0])) pyFiles = filter(lambda f: f.endswith('.py'), os.listdir(targetDir)) # set the line edit and get save the location of the pyFiles self.loadData(tuple((targetDir,pyFiles))) print pyFiles # is the name valid with our version naming standards nameValidity = self.versionNameVerifier(targetDir) # if a file's name was invalid to commit if nameValidity[0] == False: # deals with renaming the program newTargetDir = self.renameProgram(targetDir,nameValidity[1]) pyFiles = filter(lambda f: f.endswith('.py'), os.listdir(newTargetDir)) self.loadData(tuple((newTargetDir,pyFiles))) if nameValidity[0] is not None: self.status.setText('Your file has been committed.') """ verifies that the name of the new version folder matches the standard naming """ def versionNameVerifier(self,directory): plainDirectory = os.path.dirname(directory) self.versionName = os.path.basename(directory) dateExpected = strftime("%Y%m%d", localtime()) pattern = '^v(' + dateExpected + ')([0-9])$' result = re.match(pattern, self.versionName) # go through all the valid names to check if either we have a match or we must # renaming the name of the folder for x in range(0,10): pathToTest = os.path.join(plainDirectory, 'v' + dateExpected + str(x)) try: if os.path.exists(pathToTest): if directory == pathToTest and result: return (True,None) else: pass else: return (False,pathToTest) except: print "TODO Something must have really gone wrong - put a logger maybe?" print "It appears you might have done more than 10 commits in one day. \ We thus cannot commit your file. Please refrain from doing this in the future." return (None,None) """ deals with renaming the program with a valid name """ def renameProgram(self, oldpath, newpath): newPath = os.path.normpath(newpath) oldPath = os.path.normpath(oldpath) os.rename(oldPath,newPath) return newPath """ TODO - A possible function to create """ def buildCompiled(self): pass # TODO: when it is already ready to go, perhaps call compiler.compileFile # so that there is a .pyc file to make it faster. This only handles # the startup being faster -- also make sure it doesn't get done everytime # once a file gets compiled def main(): app = QtGui.QApplication(sys.argv) menu = MainMenu() sys.exit(app.exec_()) if __name__ == '__main__': main()
{ "repo_name": "johnmgregoire/2013JCAPDataProcess", "path": "commitmenu.py", "copies": "1", "size": "5474", "license": "bsd-3-clause", "hash": 6886603468258203000, "line_mean": 40.1578947368, "line_max": 116, "alpha_frac": 0.6251370113, "autogenerated": false, "ratio": 4.233565351894819, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008489787004688212, "num_lines": 133 }
# Allison Schubauer and Daisy Hernandez # Created: 6/26/2013 # Last Updated: 7/25/2013 # For JCAP """ runs functions to produce figures of merit automatically, and replaces dictionaries of data produced by old versions with updated data """ import sys, os import argparse import cPickle as pickle from multiprocessing import Process, Pool, Manager from inspect import * from rawdataparser import RAW_DATA_PATH from qhtest import * # this also imports queue import jsontranslator import xmltranslator import importlib import distutils.util import path_helpers import fomautomator_helpers import filerunner import time import datetime from infodbcomm import infoDictfromDB # the directory where the versions of the fomfunctions are FUNC_DIR = os.path.normpath(os.path.expanduser("~/Desktop/Working Folder/AutoAnalysisFunctions")) MOD_NAME = 'fomfunctions' UPDATE_MOD_NAME = 'fomfunctions_update' """ The FOMAutomator class provides the framework for processing data files automatically. Its main method, defined in fom_commandline, can be accessed through the command line. Alternatively, the FOMAutomator can be started with the user interface in fomautomator_menu. The automator can either process files in sequence on a single process or use Python's multiprocessing framework to process files on an optimal number of processes for your system (determined by Python). Both options are available through the command line and user interface, but the command line defaults to running sequentially. In both implementations, status messages and errors are logged to a file in the output directory, and the FileRunner class (defined in filerunner.py) is used to process each individual file. """ class FOMAutomator(object): """ initializes the automator with all necessary information """ def __init__(self, rawDataFiles, versionName, prevVersion,funcModule, updateModule, technique_names, srcDir, dstDir, rawDataDir,errorNum,jobname): # initializing all the basic info self.version = versionName self.lastVersion = prevVersion # the os.path.insert in the gui or in main is what makes # we select the correct function module self.funcMod = __import__(funcModule) self.modname = funcModule self.updatemod = updateModule self.technique_names = technique_names self.srcDir = srcDir self.dstDir = dstDir self.rawDataDir = rawDataDir # the max number of errors allowed by the user self.errorNum = errorNum self.jobname = jobname self.files = rawDataFiles self.infoDicts=infoDictfromDB(self.files) # required to have keys 'reference_Eo' and 'technique_name' self.processFuncs() """ returns a dictionary with all of the parameters and batch variables for the fom functions that will be run """ def processFuncs(self): self.params = {} self.funcDicts = {} self.allFuncs = [] # if we have the type of experiment, we can just get the specific functions if self.technique_names: for tech in self.technique_names: techDict = self.funcMod.EXPERIMENT_FUNCTIONS.get(tech) if techDict: [self.allFuncs.append(func) for func in techDict if func not in self.allFuncs] # if not we just get them all else: self.allFuncs = [f[0] for f in getmembers(self.funcMod, isfunction)] # now that we have all the functions, we get all the parameters for fname in self.allFuncs: funcObj = [f[1] for f in getmembers(self.funcMod, isfunction) if f[0] == fname][0] funcdict = {'batchvars': [], 'params': []} try: dictargs = funcObj.func_code.co_argcount - len(funcObj.func_defaults) funcdict['numdictargs'] = dictargs arglist = zip(funcObj.func_code.co_varnames[dictargs:], funcObj.func_defaults) except TypeError: # if there are no keyword arguments dictargs = funcObj.func_code.co_argcount funcdict['numdictargs'] = dictargs arglist = [] # note: we're assuming any string argument to the functions that the user wrote is data # for example t = 't(s)' in the function would mean t is equal to the raw data column t(s) for arg, val in arglist: if isinstance(val, list): funcdict['batchvars'].append(arg) funcdict['~'+arg] = val elif isinstance(val, str): funcdict[arg] = val ## ---- VSHIFT ------------------------------------------------------- ## elif arg == 'vshift': ## pass ## ------------------------------------------------------------------- else: self.params[fname+'_'+arg] = val funcdict['params'].append(arg) funcdict['#'+arg] = val self.funcDicts[fname] = funcdict """ Returns a list of functions and their parameters, which can be changed by the user if running fomautomator_menu. This function is only called by fomautomator_menu. If 'default' is true, the default parameters defined in the fom functions file are used; otherwise, the parameters are requested from the user. """ def requestParams(self,default=True): funcNames = self.funcDicts.keys() funcNames.sort() params_full = [[ fname, [(pname,type(pval),pval) for pname in self.funcDicts[fname]['params'] for pval in [self.funcDicts[fname]['#'+pname]]]] for fname in funcNames if self.funcDicts[fname]['params'] != []] if not default: return params_full else: funcs_names = [func[0] for func in params_full for num in range(len(func[1]))] params_and_answers = [[pname,pval] for func in params_full for (pname,ptype,pval) in func[1]] return funcs_names, params_and_answers """ If the parameter values were changed by fomautomator_menu, save the changed values in the automator's parameter dictionary and function dictionary. """ def setParams(self, funcNames, paramsList): for fname, params in zip(funcNames, paramsList): fdict = self.funcDicts[fname] param,val = params fdict['#'+param] = val self.params[fname+'_'+param] = val """ processes the files in parallel, logs status messages and errors """ def runParallel(self): # the path to which to log - will change depending on the way # processing ends and if a statusFile with the same # name already exists statusFileName = path_helpers.createPathWExtention(self.dstDir,self.jobname,".run") # set up the manager and objects required for logging due to multiprocessing pmanager = Manager() # this queue takes messages from individual processes and passes them # to the QueueListener loggingQueue = pmanager.Queue() processPool = Pool() # handler for the logging file fileHandler = logging.FileHandler(statusFileName) logFormat = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fileHandler.setFormatter(logFormat) # the QueueListener takes messages from the logging queue and passes # them through another queue to the fileHandler (logs safely because # only this main process writes to the fileHandler) fileLogger = QueueListener(loggingQueue, fileHandler) fileLogger.start() # keep track of when processing started bTime = time.time() # the jobs to process each of the files # jobs = [(loggingQueue, filename, self.version, self.lastVersion, # self.modname, self.updatemod,self.params, self.funcDicts, # self.srcDir, self.dstDir, self.rawDataDir) # for filename in self.files] jobs = [(loggingQueue, filename, self.version, self.lastVersion, self.modname, self.updatemod, self.params, self.funcDicts, self.srcDir, self.dstDir, self.rawDataDir, infodict['reference_Eo'], infodict['technique_name']) \ for (filename, infodict) in zip(self.files, self.infoDicts)] processPool.map(makeFileRunner, jobs) # keep track of when processing ended eTime = time.time() timeStamp = time.strftime('%Y%m%d%H%M%S',time.gmtime()) # clean up the pool processPool.close() processPool.join() root = logging.getLogger() if fileLogger.errorCount > self.errorNum: root.info("The job encountered %d errors and the max number of them allowed is %d" %(fileLogger.errorCount,self.errorNum)) root.info("Processed for %s H:M:S" %(str(datetime.timedelta(seconds=eTime-bTime)),)) fileLogger.stop() fileHandler.close() if fileLogger.errorCount > self.errorNum: try: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname,".error")) except: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname+timeStamp,".error")) else: try: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname,".done")) except: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname+timeStamp,".done")) """ runs the files in order on a single process and logs errors """ def runSequentially(self): # set up everything needed for logging the errors root = logging.getLogger() root.setLevel(logging.INFO) statusFileName = path_helpers.createPathWExtention(self.dstDir,self.jobname,".run") fileHandler = logging.FileHandler(statusFileName) logFormat = logging.Formatter('%(asctime)s - %(levelname)s - %(message)s') fileHandler.setFormatter(logFormat) root.addHandler(fileHandler) numberOfFiles = len(self.files) numberOfErrors = 0 bTime= time.time() # The file processing occurs here logQueue = None for i, (filename, infodict) in enumerate(zip(self.files, self.infoDicts)): if numberOfErrors > self.errorNum: root.info("The job encountered %d errors and the max number of them allowed is %d" %(numberOfErrors,self.errorNum)) break try: # returns 1 if file was processed and 0 if file was skipped exitcode = filerunner.FileRunner(logQueue,filename, self.version, self.lastVersion, self.modname, self.updatemod, self.params, self.funcDicts,self.srcDir, self.dstDir, self.rawDataDir, infodict['reference_Eo'], infodict['technique_name']) if exitcode.exitSuccess: root.info('File %s completed %d/%d' %(os.path.basename(filename),i+1,numberOfFiles)) except Exception as someException: # root.exception will log an ERROR with printed traceback; # root.error will log an ERROR without traceback # root.exception(someException) root.error('Exception raised in file %s:\n' %filename +repr(someException)) numberOfErrors +=1 exitcode = -1 eTime= time.time() root.info("Processed for %s H:M:S" %(str(datetime.timedelta(seconds=eTime-bTime)),)) timeStamp = time.strftime('%Y%m%d%H%M%S',time.gmtime()) # closing the fileHandler is important or else we cannot rename the file root.removeHandler(fileHandler) fileHandler.close() # the renaming of the run file based on the way the file processing ended if numberOfErrors > self.errorNum: try: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname,".error")) except: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname+timeStamp,".error")) else: try: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname,".done")) except: os.rename(statusFileName, path_helpers.createPathWExtention(self.dstDir,self.jobname+timeStamp,".done")) """ This function is started in a separate process by ProcessPool.map. Here, a FileRunner is created and a processHandler is added temporarily to log status or error messages from the FileRunner. The argument to makeFileRunner is the list of arguments to the FileRunner, but this function is only allowed a single argument because of ProcessPool.map. """ def makeFileRunner(args): # the multiprocessing queue queue = args[0] filename = os.path.basename(args[1]) root = logging.getLogger() root.setLevel(logging.INFO) # a logging handler which sends messages to the multiprocessing queue processHandler = QueueHandler(queue) root.addHandler(processHandler) try: # exitSuccess is 1 if file was processed or 0 if file was too short exitcode = filerunner.FileRunner(*args) # if file was processed, write logging message if exitcode.exitSuccess: root.info('File %s completed' %filename) except Exception as someException: # root.exception will log an ERROR with printed traceback; # root.error will log an ERROR without traceback root.error('Exception raised in file %s:\n' %filename +repr(someException)) #root.exception(someException) exitcode = -1 finally: # remove handler for this file (because a new handler is created # for every file) root.removeHandler(processHandler) return exitcode
{ "repo_name": "johnmgregoire/2013JCAPDataProcess", "path": "fomautomator.py", "copies": "1", "size": "14469", "license": "bsd-3-clause", "hash": -6962008753702540000, "line_mean": 46.2843137255, "line_max": 134, "alpha_frac": 0.628516138, "autogenerated": false, "ratio": 4.3011296076099885, "config_test": false, "has_no_keywords": false, "few_assignments": false, "quality_score": 1, "avg_score": 0.008522673552634322, "num_lines": 306 }