text
stringlengths
3
1.05M
// @flow weak const path = require('path'); const webpack = require('webpack'); const packageJson = require('./package.json'); const packageJsonSrc = require('../package.json'); const excludedDeps = [ 'lodash', 'recompose', 'object-assign', 'material-ui-icons', 'babel-runtime', 'autosuggest-highlight', ]; const deps = [ 'react-hot-loader/index', 'react-hot-loader/patch', 'eventsource-polyfill', 'webpack-dev-server/client', 'webpack/hot/log-apply-result', 'webpack-dev-server/client/index', ] .concat(Object.keys(packageJson.dependencies)) .concat(Object.keys(packageJsonSrc.dependencies)) .concat(Object.keys(packageJsonSrc.peerDependencies)) .filter(dep => { return excludedDeps.indexOf(dep) === -1; }); module.exports = { devtool: 'inline-source-map', entry: { lib: deps, }, output: { filename: 'dll.bundle.js', path: path.join(__dirname, 'build'), library: 'dll', }, plugins: [ new webpack.DllPlugin({ name: 'dll', path: 'build/dll.manifest.json', }), ], };
from abc import abstractmethod import copy import re from sqlalchemy import Float, Integer, text, exists, select, or_ from sqlalchemy.dialects.postgresql import JSONB from sqlalchemy.sql import column from sqlalchemy.sql.operators import is_ from dart.context.locator import injectable from dart.model.exception import DartValidationException from dart.model.query import Operator, Filter @injectable class FilterService(object): def __init__(self): self._operator_handlers = { Operator.EQ: OperatorEquals(), Operator.NE: OperatorNotEquals(), Operator.LT: OperatorLessThan(), Operator.LE: OperatorLessThanOrEquals(), Operator.GT: OperatorGreaterThan(), Operator.GE: OperatorGreaterThanOrEquals(), Operator.IN: OperatorIn(), Operator.NOT_LIKE: OperatorNotLike(), Operator.LIKE: OperatorLike(), Operator.SEARCH: OperatorSearch(), } def from_string(self, f_string): pattern = re.compile(r'\s*(\S+?)\s*(' + '|'.join(self._operator_handlers.keys()) + ')\s*(\S+)\s*') m = pattern.match(f_string) try: return Filter(m.group(1), m.group(2), m.group(3)) except: raise DartValidationException('could not parse filter: %s' % f_string) def apply_filter(self, f, query, dao, schemas): """ :type f: dart.model.query.Filter """ op = self._operator_handlers[f.operator] if f.key in ['id', 'created', 'updated']: return query.filter(op.evaluate(lambda v: v, getattr(dao, f.key), str, f.value)) # at this point, assume we are dealing with a data/JSONB filter path_keys = f.key.split('.') filters = [] visited = {} for schema in schemas: type_, array_indexes = self._get_type(path_keys, schema) identifier = type_ + '@' + str(array_indexes) if identifier in visited: continue visited[identifier] = 1 key_groups = self.get_key_groups(array_indexes, path_keys) last_is_array = array_indexes[-1] == len(path_keys) - 1 if len(array_indexes) > 0 else False filters.append(self.expr(0, 'data', dao.data, key_groups, type_, f.value, op, last_is_array)) return query.filter(filters[0]) if len(filters) == 1 else query.filter(or_(*filters)) def expr(self, i, alias, col, key_groups, t, v, op, last_is_array): if i < len(key_groups) - 1: subq, c = self.get_subquery(alias, i, key_groups) subq = subq.where(self.expr(i + 1, 'dart_a_%s.value' % i, c, key_groups, t, v, op, last_is_array)) return exists(subq) if last_is_array: subq, c = self.get_subquery(alias, i, key_groups, True) subq = subq.where(op.evaluate(lambda x: x, c, _python_cast(t), v)) return exists(subq) return op.evaluate(_pg_cast(t), col[key_groups[i]], _python_cast(t), v) @staticmethod def get_subquery(alias, i, key_groups, as_text=False): c = column('value', JSONB) bindvars = {'dart_var_%s' % i: '{' + ','.join(key_groups[i]) + '}'} suffix = '_text' if as_text else '' from_expr = text('jsonb_array_elements%s(%s #> :dart_var_%s) as dart_a_%s' % (suffix, alias, i, i)) from_expr = from_expr.bindparams(**bindvars) subq = select([c]).select_from(from_expr) return subq, c @staticmethod def get_key_groups(array_indexes, path_keys): if len(array_indexes) <= 0 or len(path_keys) == 1: return [path_keys] array_groups = [] prev = 0 for i in array_indexes: array_groups.append(path_keys[prev:i + 1]) prev = i + 1 array_groups.append(path_keys[prev:]) return array_groups @staticmethod def _get_type(path_keys, schema): array_indexes = [] s = schema['properties']['data'] for i, key in enumerate(path_keys): if not s: break if 'object' in s['type']: s = s['properties'].get(key) continue if 'array' in s['type']: array_indexes.append(i - 1) s = s['items'].get('properties', {}).get(key) continue if not s: return 'string', array_indexes type_ = s['type'] if isinstance(type_, list): pt_copy = copy.copy(type_) pt_copy.remove('null') type_ = pt_copy[0] if type_ == 'array': array_indexes.append(len(path_keys) - 1) return type_, array_indexes class OperatorEvaluator(object): @abstractmethod def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): raise NotImplementedError class OperatorEquals(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs) == rhs_cast(rhs) class OperatorNotEquals(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return or_(lhs_cast(lhs) != rhs_cast(rhs), is_(lhs_cast(lhs), None)) class OperatorLessThan(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs) < rhs_cast(rhs) class OperatorLessThanOrEquals(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs) <= rhs_cast(rhs) class OperatorGreaterThan(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs) > rhs_cast(rhs) class OperatorGreaterThanOrEquals(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs) >= rhs_cast(rhs) class OperatorIn(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs).in_([rhs_cast(v) for v in rhs.split(',')]) class OperatorNotLike(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs).notilike(rhs_cast(rhs)) class OperatorLike(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): return lhs_cast(lhs).ilike(rhs_cast(rhs)) class OperatorSearch(OperatorEvaluator): def evaluate(self, lhs_cast, lhs, rhs_cast, rhs): only_alphanum = re.sub(r'\W+', '', rhs) search_string = '%' + '%'.join(only_alphanum) + '%' return lhs_cast(lhs).ilike(search_string) def _pg_cast(js_type): if js_type == 'integer': return lambda v: v.cast(Integer) if js_type == 'number': return lambda v: v.cast(Float) return lambda v: v.astext def _python_cast(js_type): if js_type == 'integer': return int if js_type == 'number': return float return str
// Deal the nodes that needn't transfrom to custom component export default function dealWithLeafAndSimple(childNodes, onChildNodesUpdate) { if (childNodes && childNodes.length) { childNodes = childNodes.map(originChildNode => { const childNode = Object.assign({}, originChildNode); if (childNode.isImage || childNode.isLeaf || childNode.isSimple || childNode.useTemplate) { childNode.domNode.$$clearEvent('$$childNodesUpdate'); childNode.domNode.addEventListener('$$childNodesUpdate', onChildNodesUpdate); } delete childNode.domNode; childNode.childNodes = dealWithLeafAndSimple(childNode.childNodes, onChildNodesUpdate); return childNode; }); } return childNodes; }
# -*- coding: utf-8 -*- import os import re import sys def abort(msg): print('Error!: {0}'.format(msg)) exit(1) def get_filename(path): return os.path.basename(path) def get_basename(path): return os.path.splitext(get_filename(path))[0] def get_extension(path): return os.path.splitext(get_filename(path))[1] def file2list(filepath): ret = [] with open(filepath, encoding='utf8', mode='r') as f: ret = [line.rstrip('\n') for line in f.readlines()] return ret def list2file(filepath, ls): with open(filepath, encoding='utf8', mode='w') as f: f.writelines(['{:}\n'.format(line) for line in ls] ) def parse_arguments(): import argparse parser = argparse.ArgumentParser( formatter_class=argparse.ArgumentDefaultsHelpFormatter, ) parser.add_argument('-i', '--input', default=None, required=True, help='A input filename.') parser.add_argument('--indent-depth', default=2, type=int, help='The number of spaces per a nest in TOC.') parser.add_argument('--parse-depth', default=-1, type=int, help='The depth of the TOC list nesting. If minus then no limit depth.') parser.add_argument('--use-asterisk', default=False, action='store_true', help='Use an asterisk `*` as a list grammer.') parser.add_argument('--use-plain-enum', default=False, action='store_true', help='Not use Markdown grammer, but use simple plain section name listing.') parser.add_argument('--edit', default=False, action='store_true', help='If given then insert TOC to the file from "--input".') parser.add_argument('--edit-target', default='<!-- TOC', help='A insertion destination label when --edit given. NOT CASE-SENSITIVE.') parser.add_argument('--md-guard-break', default=False, action='store_true', help=argparse.SUPPRESS) parser.add_argument('--edit-debug', default=False, action='store_true', help=argparse.SUPPRESS) parser.add_argument('--debug', default=False, action='store_true', help=argparse.SUPPRESS) args = parser.parse_args() return args def line2sectioninfo(line): sectionlevel = 0 body = '' # # level1 # ## level2 # ### level3 # ###... level... # # ## level2 # ^^^^^^^ # body while True: cnt = sectionlevel+1 comparer = '#'*cnt if line[0:cnt]==comparer: sectionlevel += 1 body = line[sectionlevel:] continue break return sectionlevel, body def sectionname2anchor(sectionname, duplicator): ret = sectionname ret = ret.lower() ret = ret.replace(' ', '-') # remove ascii marks excxept hypen and underscore. remove_targets = '[!"#$%&\'\\(\\)\\*\\+,\\./:;<=>?@\\[\\\\\\]\\^`\\{\\|\\}~]' ret = re.sub(remove_targets, '', ret) # remove Japanese marks remove_targets = '[、。,.・:;?!゛゜´`¨^ ̄_ヽヾゝゞ〃仝々〆〇‐/\~∥|…‥‘’“”()〔〕[]{}〈〉《》「」『』【】+-±×÷=≠<>≦≧∞∴♂♀°′″℃¥$¢£%#&*@§☆★○●◎◇◆□■△▲▽▼※〒→←↑↓〓∈∋⊆⊇⊂⊃∪∩∧∨¬⇒⇔∀∃∠⊥⌒∂∇≡≒≪≫√∽∝∵∫∬ʼn♯♭♪ΑΒΓΔΕΖΗΘΙΚΛΜΝΞΟΠΡΣΤΥΦΧΨΩαβγδεζηθικλμνξοπρστυφχψωАБВГДЕЁЖЗИЙКЛМНОПРСТУФХЦЧШЩЪЫЬЭЮЯабвгдеёжзийклмнопрстуфхцчшщъыьэюя─│┌┐┘└├┬┤┴┼━┃┏┓┛┗┣┳┫┻╋┠┯┨┷┿┝┰┥┸╂。「」、・ヲァィゥェォャュョッーアイウエオカキクケコサシスセソタチツテトナニヌネノハヒフヘホマミムメモヤユヨラリルレロワン゙゚①②③④⑤⑥⑦⑧⑨⑩⑪⑫⑬⑭⑮⑯⑰⑱⑲⑳ⅠⅡⅢⅣⅤⅥⅦⅧⅨⅩ㍉㌔㌢㍍㌘㌧㌃㌶㍑㍗㌍㌦㌣㌫㍊㌻㎜㎝㎞㎎㎏㏄㎡ ㍻〝〟№㏍℡㊤㊥㊦㊧㊨㈱㈲㈹㍾㍽㍼≒≡∫∮∑√⊥∠∟⊿∵∩∪]' ret = re.sub(remove_targets, '', ret) # In GFM, do numbering if there is a duplicated anchor name. # # Ex. # # section1 # # section1 # # section1 # VVV # href="#section1" # href="#section1-1" # href="#section1-2" dup_count = duplicator.add(ret) if dup_count>0: ret = ret + '-{0}'.format(dup_count) return ret def is_edit_target_line(line, edit_target): return line.strip().lower().startswith(edit_target.lower()) def get_toc_range(lines, edit_target): """ @return (p_start, p_end) If no toc exists then p_end returns None. """ p_start = None p_end = None for i,line in enumerate(lines): if p_start==None: if is_edit_target_line(line, edit_target): p_start = i+1 continue if line.lstrip()[0:1]=='-': p_end = i continue else: if p_end!=None: p_end += 1 break return p_start, p_end class Duplicator: def __init__(self): self._d = {} def add(self, k): try: self._d[k] except KeyError: self._d[k] = 1 return 0 ret = self._d[k] self._d[k] += 1 return ret class SectionLine: def __init__(self, level, body, duplicator, listmark): self._lv = level self._body = body self._duplicator = duplicator self._listmark = listmark def set_indent_depth(self, num): self._indent_depth = num @property def tocline(self): normed_body = self._body.strip() indent = ' '*((self._lv-1)*self._indent_depth) mark = self._listmark text = normed_body anchor = sectionname2anchor(normed_body, self._duplicator) ret = '{0}{1} [{2}](#{3})'.format( indent, mark, text, anchor ) return ret @property def plainline(self): normed_body = self._body.strip() return normed_body def __str__(self): return 'LV{0} [{1}]'.format(self._lv, self._body) if __name__ == "__main__": MYDIR = os.path.abspath(os.path.dirname(__file__)) args = parse_arguments() infile = os.path.join(MYDIR, args.input) # infile check if not(os.path.exists(infile)): abort('The input file "{0}" does not exists.'.format(infile)) if not(args.md_guard_break) and get_extension(infile)!='.md': abort('The input file is not .md file') indent_depth = args.indent_depth parse_depth = args.parse_depth use_asterisk = args.use_asterisk use_plain_enum = args.use_plain_enum use_edit = args.edit edit_target = args.edit_target duplicator = Duplicator() listmark = '-' if use_asterisk: listmark = '*' lines = file2list(infile) toclines = [] edit_target_pos = None is_in_hilight_area = False for i,line in enumerate(lines): if len(line)==0: continue if line[:3]=='```': if is_in_hilight_area==False: is_in_hilight_area = True continue is_in_hilight_area = False continue if is_in_hilight_area==True: continue if use_edit and edit_target_pos==None and is_edit_target_line(line, edit_target): edit_target_pos = i if args.debug: print('edit target pos: {0}'.format(edit_target_pos)) continue sectionlevel, body = line2sectioninfo(line) if sectionlevel==0: continue if parse_depth>=0 and sectionlevel>=parse_depth+1: continue sl = SectionLine(sectionlevel, body, duplicator, listmark) sl.set_indent_depth(indent_depth) appendee_line = sl.tocline if use_plain_enum: appendee_line = sl.plainline toclines.append(appendee_line) if edit_target_pos==None: for i,line in enumerate(toclines): print(line) exit(0) if args.edit_debug: print('Edit Target : {0}'.format(edit_target)) print('Edit Target Pos: {0}'.format(edit_target_pos)) print('dup elems') print(dup) outlines = lines[:edit_target_pos+1] outlines.extend(toclines) # If old TOC exists, must skip it. # Then, old one is not merged. startpos, endpos = get_toc_range(lines, edit_target) skippos = 0 if startpos and endpos: if args.debug: print('start, end:({0}, {1})'.format(startpos, endpos)) skippos = endpos - startpos outlines.extend(lines[edit_target_pos+1+skippos:]) writee_filename = infile if args.edit_debug: writee_filename += '.debug' list2file(writee_filename, outlines)
class Game { constructor() { this.resetTitle = createElement("h2"); this.resetButton = createButton(""); this.leadeboardTitle = createElement("h2"); this.leader1 = createElement("h2"); this.leader2 = createElement("h2"); this.playerMoving = false; this.leftKeyActive = false; this.blast = false; } getState() { var gameStateRef = database.ref("gameState"); gameStateRef.on("value", function(data) { gameState = data.val(); }); } update(state) { database.ref("/").update({ gameState: state }); } start() { player = new Player(); playerCount = player.getCount(); form = new Form(); form.display(); car1 = createSprite(width / 2 - 50, height - 100); car1.addImage("car1", car1_img); car1.scale = 0.07; car1.addImage("blast", blastImage); car2 = createSprite(width / 2 + 100, height - 100); car2.addImage("car2", car2_img); car2.scale = 0.07; car2.addImage("blast", blastImage); cars = [car1, car2]; fuels = new Group(); powerCoins = new Group(); obstacles = new Group(); var obstaclesPositions = [ { x: width / 2 + 250, y: height - 800, image: obstacle2Image }, { x: width / 2 - 150, y: height - 1300, image: obstacle1Image }, { x: width / 2 + 250, y: height - 1800, image: obstacle1Image }, { x: width / 2 - 180, y: height - 2300, image: obstacle2Image }, { x: width / 2, y: height - 2800, image: obstacle2Image }, { x: width / 2 - 180, y: height - 3300, image: obstacle1Image }, { x: width / 2 + 180, y: height - 3300, image: obstacle2Image }, { x: width / 2 + 250, y: height - 3800, image: obstacle2Image }, { x: width / 2 - 150, y: height - 4300, image: obstacle1Image }, { x: width / 2 + 250, y: height - 4800, image: obstacle2Image }, { x: width / 2, y: height - 5300, image: obstacle1Image }, { x: width / 2 - 180, y: height - 5500, image: obstacle2Image } ]; // Adding fuel sprite in the game this.addSprites(fuels, 4, fuelImage, 0.02); // Adding coin sprite in the game this.addSprites(powerCoins, 18, powerCoinImage, 0.09); //Adding obstacles sprite in the game this.addSprites( obstacles, obstaclesPositions.length, obstacle1Image, 0.04, obstaclesPositions ); } addSprites(spriteGroup, numberOfSprites, spriteImage, scale, positions = []) { for (var i = 0; i < numberOfSprites; i++) { var x, y; //C41 //SA if (positions.length > 0) { x = positions[i].x; y = positions[i].y; spriteImage = positions[i].image; } else { x = random(width / 2 + 150, width / 2 - 150); y = random(-height * 4.5, height - 400); } var sprite = createSprite(x, y); sprite.addImage("sprite", spriteImage); sprite.scale = scale; spriteGroup.add(sprite); } } handleElements() { form.hide(); form.titleImg.position(40, 50); form.titleImg.class("gameTitleAfterEffect"); //C39 this.resetTitle.html("Reset Game"); this.resetTitle.class("resetText"); this.resetTitle.position(width / 2 + 200, 40); this.resetButton.class("resetButton"); this.resetButton.position(width / 2 + 230, 100); this.leadeboardTitle.html("Leaderboard"); this.leadeboardTitle.class("resetText"); this.leadeboardTitle.position(width / 3 - 60, 40); this.leader1.class("leadersText"); this.leader1.position(width / 3 - 50, 80); this.leader2.class("leadersText"); this.leader2.position(width / 3 - 50, 130); } play() { this.handleElements(); this.handleResetButton(); Player.getPlayersInfo(); player.getCarsAtEnd(); if (allPlayers !== undefined) { image(track, 0, -height * 5, width, height * 6); this.showFuelBar(); this.showLife(); this.showLeaderboard(); //index of the array var index = 0; for (var plr in allPlayers) { //add 1 to the index for every loop index = index + 1; //use data form the database to display the cars in x and y direction var x = allPlayers[plr].positionX; var y = height - allPlayers[plr].positionY; var currentLife = allPlayers[plr].life; if(currentLife <=0){ cars[index - 1].changeImage("blast"); cars[index - 1].sclae=0.3; } cars[index - 1].position.x = x; cars[index - 1].position.y = y; if (index === player.index) { stroke(10); fill("red"); ellipse(x, y, 60, 60); this.handleFuel(index); this.handlePowerCoins(index); this.handleCarACollisionWithCarB(index); this.handleObstacleCollision(index); if(player.life<0){ this.blast = true; this.playerMoving = false; } // Changing camera position in y direction camera.position.y = cars[index - 1].position.y; } } if (this.playerMoving) { player.positionY += 5; player.update(); } // handling keyboard events this.handlePlayerControls(); // Finshing Line const finshLine = height * 6 - 100; if (player.positionY > finshLine) { gameState = 2; player.rank += 1; Player.updateCarsAtEnd(player.rank); player.update(); this.showRank(); } drawSprites(); } } handleResetButton() { this.resetButton.mousePressed(() => { database.ref("/").set({ playerCount: 0, gameState: 0, players: {}, carsAtEnd: 0 }); window.location.reload(); }); } handleCarACollisionWithCarB(index) { if (index === 1) { if (cars[index - 1].collide(cars[1])) { if (this.leftKeyActive) { player.positionX += 100; } else { player.positionX -= 100; } //Reducing Player Life if (player.life > 0) { player.life -= 185 / 4; } player.update(); } } if (index === 2) { if (cars[index - 1].collide(cars[0])) { if (this.leftKeyActive) { player.positionX += 100; } else { player.positionX -= 100; } //Reducing Player Life if (player.life > 0) { player.life -= 185 / 4; } player.update(); } } } showLife() { push(); image(lifeImage, width / 2 - 130, height - player.positionY - 400, 20, 20); fill("white"); rect(width / 2 - 100, height - player.positionY - 400, 185, 20); fill("#f50057"); rect(width / 2 - 100, height - player.positionY - 400, player.life, 20); noStroke(); pop(); } showFuelBar() { push(); image(fuelImage, width / 2 - 130, height - player.positionY - 350, 20, 20); fill("white"); rect(width / 2 - 100, height - player.positionY - 350, 185, 20); fill("#ffc400"); rect(width / 2 - 100, height - player.positionY - 350, player.fuel, 20); noStroke(); pop(); } showLeaderboard() { var leader1, leader2; var players = Object.values(allPlayers); if ( (players[0].rank === 0 && players[1].rank === 0) || players[0].rank === 1 ) { // &emsp; This tag is used for displaying four spaces. leader1 = players[0].rank + "&emsp;" + players[0].name + "&emsp;" + players[0].score; leader2 = players[1].rank + "&emsp;" + players[1].name + "&emsp;" + players[1].score; } if (players[1].rank === 1) { leader1 = players[1].rank + "&emsp;" + players[1].name + "&emsp;" + players[1].score; leader2 = players[0].rank + "&emsp;" + players[0].name + "&emsp;" + players[0].score; } this.leader1.html(leader1); this.leader2.html(leader2); } handlePlayerControls() { if(!this.blast){ if (keyIsDown(UP_ARROW)) { this.playerMoving = true; player.positionY += 10; player.update(); } if (keyIsDown(LEFT_ARROW) && player.positionX > width / 3 - 50) { this.leftKeyActive = true; player.positionX -= 5; player.update(); } if (keyIsDown(RIGHT_ARROW) && player.positionX < width / 2 + 300) { this.leftKeyActive = false; player.positionX += 5; player.update(); } } } handleFuel(index) { // Adding fuel cars[index - 1].overlap(fuels, function(collector, collected) { player.fuel = 185; //collected is the sprite in the group collectibles that triggered //the event collected.remove(); }); // Reducing Player car fuel if (player.fuel > 0 && this.playerMoving) { player.fuel -= 0.3; } if (player.fuel <= 0) { gameState = 2; this.gameOver(); } } handlePowerCoins(index) { cars[index - 1].overlap(powerCoins, function(collector, collected) { player.score += 21; player.update(); //collected is the sprite in the group collectibles that triggered //the event collected.remove(); }); } handleObstacleCollision(index){ if(cars[index-1].collide(obstacles)){ if(this.leftKeyActive){ player.positionX +=100 } else{ player.positionX -=100 } if(player.life>0){ player.life -= 185/4 } } player.update(); } showRank() { swal({ title: `Awesome!${"\n"}Rank${"\n"}${player.rank}`, text: "You reached the finish line successfully", imageUrl: "https://raw.githubusercontent.com/vishalgaddam873/p5-multiplayer-car-race-game/master/assets/cup.png", imageSize: "100x100", confirmButtonText: "Ok" }); } gameOver() { swal({ title: `Game Over`, text: "Oops you lost the race....!!!", imageUrl: "https://cdn.shopify.com/s/files/1/1061/1924/products/Thumbs_Down_Sign_Emoji_Icon_ios10_grande.png", imageSize: "100x100", confirmButtonText: "Thanks For Playing" }); } end(){ console.log("Game Over") } }
// @flow import React from "react" import { assert } from "chai" import { shallow } from "enzyme" import TopAppBar from "./TopAppBar" import AnonymousMenu from "./AnonymousMenu" import UserMenu from "./UserMenu" import { routes } from "../lib/urls" import { makeUser, makeAnonymousUser } from "../factories/user" describe("TopAppBar component", () => { describe("for anonymous users", () => { const user = makeAnonymousUser() it("has a button to collapse the menu", () => { assert.isOk( shallow(<TopAppBar currentUser={user} location={null} />) .find("button") .exists() ) }) it("has an AnonymousMenu component", () => { assert.isOk( shallow(<TopAppBar currentUser={user} location={null} />) .find("AnonymousMenu") .exists() ) }) }) describe("for logged in users", () => { const user = makeUser() it("has a UserMenu component", () => { assert.isOk( shallow(<TopAppBar currentUser={user} location={null} />) .find("UserMenu") .exists() ) }) }) })
import path from 'path'; import webpack from 'webpack'; import { createFsFromVolume, Volume } from 'memfs'; export default (fixture, loaderOptions = {}, config = {}) => { const fullConfig = { mode: 'development', devtool: config.devtool || false, context: path.resolve(__dirname, '../fixtures'), entry: path.resolve(__dirname, '../fixtures', fixture), output: { path: path.resolve(__dirname, '../outputs'), filename: '[name].bundle.js', chunkFilename: '[name].chunk.js', publicPath: '/webpack/public/path/', }, module: { rules: [ { test: /\.js$/i, use: [ { loader: path.resolve(__dirname, '../../src'), options: loaderOptions || {}, }, ], }, { test: /\.css$/, use: [ 'css-loader', { loader: path.resolve(__dirname, '../../src'), options: loaderOptions || {}, }, ], }, ], }, optimization: { minimize: false, }, plugins: [], ...config, }; const compiler = webpack(fullConfig); if (!config.outputFileSystem) { const outputFileSystem = createFsFromVolume(new Volume()); // Todo remove when we drop webpack@4 support outputFileSystem.join = path.join.bind(path); compiler.outputFileSystem = outputFileSystem; } return compiler; };
# Knjiznica import threading, re, time, os from time import strftime from BeautifulSoup import BeautifulSoup import RPi.GPIO as GPIO # GPIO Pini GPIO.setmode(GPIO.BCM) GPIO.setup(17, GPIO.IN) GPIO.setup(23, GPIO.IN) # Pini luck GPIO.setup(24, GPIO.OUT) GPIO.setup(25, GPIO.OUT) # Razlaga count1 = 0 pollTime = 1 statusPath = "/var/www/html/status.html" def checkStatus(): # klic f() again in pollTime sekunde threading.Timer(pollTime, checkStatus).start() global count1 if (GPIO.Input(17)): # Kopalnica je zaprta updateHTML("Kopalnica1", 1) count1 += pollTime GPIO.output(25, GPIO.LOW) else: # Kopalnica je odprta updateHTML("Kopalnica1", 0) count1 = 0 GPIO.output(25, GPIO.HIGH) if (count1 >= 600): updateHTML("Kopalnica1", 3) def upload(): # Nalaganje vsakih 5 Sekund threading.Timer(15, upload).start() os.system('/var/www/html/status.html') def updateHTML(bathNumber, status): global count1 with open(statusPath, "r+") as f: data = f.read() if (status == 1): replaceString = bathNumber + " je zaprto! :(\n Ze od " + strftime("%H:%M:%S %d-%m-%Y") soup = BeatifulSoup(data) div = soup.find('div', {'class': bathNumber}) div['style'] = 'background-color: #FF0000; fontsize:xx-large;' div.string=replaceString f.close html = soup.prettify("utf-8") with open(statusPath, "wb") as file: file.write(html) if (status == 0): replaceString = bathNumber + " je odprto!\n Ze od " + strftime("%H:%M:%S %d-%m-%Y") soup = BeatifulSoup(data) div = soup.find('div', {'class': bathNumber}) div['style'] = 'background-color: #0080000; fontsize:xx-large;' div.string=replaceString f.close html = soup.prettify("utf-8") with open(statusPath, "wb") as file: file.write(html) if (status == 3): # Ce so vrata zaprta predolgo replaceString = "" if (bathNumber == "Kopalnica1"): replaceString = bathNumber + " je bilo zaprto že " + str(count1) + " seconds." else: replaceString = bathNumber + " je bilo zaprto že " + str(count1) + " seconds." soup = BeatifulSoup(data) div = soup.find('div', {'class': bathNumber}) div['style'] = 'background-color: #FFF00; fontsize:xx-large;' div.string=replaceString f.close html = soup.prettify("utf-8") with open(statusPath, "wb") as file: file.write(html) checkStatus() upload()
import os import math import json import time import requests import lxml.html from datetime import datetime class CraigsAPI: def __init__(self, path_to_categories): self.num_results_pp = 120 self.domain = 'https://toronto.craigslist.org/' self.login_url = 'https://accounts.craigslist.org/login' self.our_ads_url = 'https://accounts.craigslist.org/login/home' self.base_headers = { 'Connection': 'keep-alive', 'Cache-Control': 'max-age=0', 'Upgrade-Insecure-Requests': '1', 'Content-Type': 'application/x-www-form-urlencoded', 'User-Agent': 'Mozilla/5.0 (Macintosh; Intel Mac OS X 10_13_3) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.86 Safari/537.36', 'Accept': 'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8,application/signed-exchange;v=b3', 'Referer': 'https://www.google.com', 'Accept-Encoding': 'gzip, deflate, br', 'Accept-Language': 'en-US,en;q=0.9', } self.ok_codes = [200, 301] self.category_dict = _get_categories_from_file(path_to_categories) def _get_categories_from_web(self, file_path=False): response = requests.get(self.domain, headers=headers) soup = BeautifulSoup(response.content) categories = soup.find('div', {'id': 'center'}).findChildren('div') links = [] for category in categories: category_links = category.find_all('a') links += category_links link_dict = {link.text: link['href'] for link in links} if file_path: with open(file_path, 'w+') as outfile: json.dump(link_dict, outfile, indent=4) print('Generated Category File.') return link_dict def _get_categories_from_file(file_path): try: with open(file_path, 'r') as readfile: return json.load(readfile) except Exception as e: return _get_categories_from_web(file_path) def login(self, username, password): self._username = username self._password = password _ = _refresh_session(username, password) pass def _refresh_session(self, username, password): login_data = = { 'step': 'confirmation', 'rt': 'L', 'rp': '/login/home', 't': str(get_epoch_time()), 'p': '0', 'inputEmailHandle': username, 'inputPassword': password } login_headers = self.base_headers.copy() login_headers['Origin'] = 'https://accounts.craigslist.org' login_headers['Referer'] = 'https://accounts.craigslist.org/login?rt=L&rp=%2Flogin%2Fhome' session = requests.session() response = session.post(self.login_url, headers=login_headers, data=login_data) if response.status_code in self.ok_codes: self.session = session print('Sucessful Login.') else: print('Failed to login.') def get_epoch_time(self): return round((datetime.now() - datetime(1970, 1, 1)).total_seconds()) def get_our_postings(self): headers = headers.copy() response = self.session.get(self.our_ads_url, headers=headers) if response: content = lxml.html.fromstring(response.text) postings = content.xpath('//section[@class="body"][0]//table[0]/li/text()') return postings else: return None def post_our_ad(self): pass def get_ads(self, category, query=False, num_results, timer=1): num_pages = math.ceil(num_results / self.num_results_pp) if query: urls = [self.domain + self.category_dict[category] + '?s=%s&query=%s&sort=rel' % (int(counter)*120, \ query.replace(' ', '+')) \ for counter in range(num_pages)] else: urls = [self.domain + self.category_dict[category] + '?s=%s' % (int(counter)*120) for counter in range(num_pages)] ad_dict = {} for url in urls: response = requests.get(url, headers=headers) time.sleep(timer) page_dict = _parse_page_content(response) if len(page_dict) == 0: return ad_dict else: ad_dict.update(page_dict) return ad_dict def _parse_page_content(response): try: content = lxml.html.fromstring(response.text) page_links = content.xpath('//div[@class="content"]/ul[@class="rows"]//li/p/a/@href') page_infos = content.xpath('//div[@class="content"]/ul[@class="rows"]//li/p/a/text()') post_dates = content.xpath('//div[@class="content"]/ul[@class="rows"]//li/p/time/@datetime') # Optional Attributes prices = content.xpath('//div[@class="content"]/ul[@class="rows"]//li/span[@class="result-price"]') locations = [location.strip() if 'pic' not in location else '' \ for location in content.xpath('//div[@class="content"]/ul[@class="rows"]//li/p/span[@class="result-meta"]/span[1]/text()[1]')] # Ensure Equal Lengths for Dictionary Generation assert len(page_links) == len(page_infos) == len(post_dates) dict_length = len(page_links) # Validation for Adding Attributes if len(prices) != dict_length: prices = [None] * dict_length if len(locations) != dict_length: locations = [None] * dict_length page_dict = {page_links[counter]: {'info': page_infos[counter], 'date': post_dates[counter], \ 'price': prices[counter], 'location': locations[counter]} \ for counter in range(dict_length)} except Exception as e: print('Error') return {}
import React from "react"; import styled from "styled-components/macro"; import { Button, LoaderButton, Select, Text } from "theme"; import WizardStepLayout from "./WizardStepLayout"; import { translations } from "i18n"; import { connectDeviceWizardActions } from "apps/admin/store/actions"; import { connect } from "react-redux"; import { useWizard } from "apps/admin/wizard/Wizard"; import { isGoogleAccountSelector } from "../store/selectors"; const LocaleWrapper = styled.div` display: flex; justify-content: stretch; width: 100%; > :first-child { flex: 1 1 0; } > :last-child { width: 130px; margin-left: 20px; } `; const Content = ({ isDashboard, isGoogleAccount, calendars, calendarId, onSetCalendar, language, onSetLanguage, clockType, onSetClockType, showAvailableRooms, onSetShowAvailableRooms }) => { const { isCurrentStep, isTransitioning } = useWizard(); const calendarSelector = ( <> <Text large block> Calendar </Text> <Select instanceId="edit-device-choose-calendar" value={calendarId} options={Object.values(calendars)} getOptionLabel={calendar => calendar.summary + (calendar.canModifyEvents ? "" : " (read only)")} getOptionValue={calendar => calendar.id} isOptionDisabled={calendar => !calendar.canModifyEvents} onChange={calendar => onSetCalendar(calendar && calendar.id)} styles={{ container: base => ({ ...base, marginTop: 15, marginBottom: 10 }) }} menuPortalTarget={document.body} autofocus={isCurrentStep && !isTransitioning} tabIndex={isCurrentStep ? 0 : -1} /> {isGoogleAccount && ( <Button link href="https://go.roombelt.com/scMpEB" target="_blank" tabIndex={isCurrentStep ? 0 : -1} style={{ padding: "5px 3px" }}> Why is my calendar read-only or absent? </Button> )} </> ); const showAllAvailableRoomsSelector = ( <> <Text large block> Highlight available rooms </Text> <Select instanceId="wizard-device-show-available-rooms" value={showAvailableRooms} options={[{ label: "Yes", value: true }, { label: "No", value: false }]} onChange={option => onSetShowAvailableRooms(option.value)} styles={{ container: base => ({ ...base, marginTop: 15, marginBottom: 10 }) }} menuPortalTarget={document.body} autofocus={isCurrentStep && !isTransitioning} tabIndex={isCurrentStep ? 0 : -1} /> </> ); const languageSelector = ( <> <Text large block style={{ marginTop: 15, marginBottom: 10 }}>Locale</Text> <LocaleWrapper> <Select instanceId="edit-device-choose-language" value={language} options={Object.values(translations)} getOptionLabel={lang => lang.language} getOptionValue={lang => lang.key} onChange={translation => onSetLanguage && onSetLanguage(translation && translation.key)} menuPortalTarget={document.body} tabIndex={isCurrentStep ? 0 : -1} /> <Select instanceId="edit-device-choose-clock" value={clockType} options={[{ label: "12h clock", value: 12 }, { label: "24h clock", value: 24 }]} menuPortalTarget={document.body} tabIndex={isCurrentStep ? 0 : -1} onChange={option => onSetClockType && onSetClockType(option && option.value)} /> </LocaleWrapper> </> ); return ( <WizardStepLayout img={require("./calendar.png")}> {!isDashboard && calendarSelector} {isDashboard && showAllAvailableRoomsSelector} {languageSelector} </WizardStepLayout> ); }; const Buttons = ({ onSubmit, onBack, isSubmitting }) => ( <div> <Button disabled={isSubmitting} onClick={onBack}>Back</Button> <LoaderButton primary onClick={onSubmit} isLoading={isSubmitting}>Voila</LoaderButton> </div> ); const mapStateToProps = state => ({ calendars: state.calendars, isDashboard: state.connectDeviceWizard.deviceType === "dashboard", isSubmitting: state.connectDeviceWizard.isSubmitting, calendarId: state.connectDeviceWizard.calendarId, language: state.connectDeviceWizard.language, clockType: state.connectDeviceWizard.clockType, showAvailableRooms: state.connectDeviceWizard.showAvailableRooms, isGoogleAccount: isGoogleAccountSelector(state) }); const mapDispatchToProps = dispatch => ({ onBack: () => dispatch(connectDeviceWizardActions.thirdStep.previousStep()), onSubmit: () => dispatch(connectDeviceWizardActions.thirdStep.submit()), onSetCalendar: calendarId => dispatch(connectDeviceWizardActions.thirdStep.setCalendarId(calendarId)), onSetLanguage: language => dispatch(connectDeviceWizardActions.thirdStep.setLanguage(language)), onSetClockType: clockType => dispatch(connectDeviceWizardActions.thirdStep.setClockType(clockType)), onSetShowAvailableRooms: value => dispatch(connectDeviceWizardActions.thirdStep.setShowAvailableRooms(value)) }); export default { key: "configuration", name: "Configure", content: connect(mapStateToProps, mapDispatchToProps)(Content), buttons: connect(mapStateToProps, mapDispatchToProps)(Buttons) };
import {assign, constant} from "d3plus-common"; import {default as Plot} from "./Plot"; /** @class BoxWhisker @extends Plot @desc Creates a simple box and whisker based on an array of data. @example <caption>the equivalent of calling:</caption> new d3plus.Plot() .discrete("x") .shape("Box") */ export default class BoxWhisker extends Plot { /** @memberof BoxWhisker @desc Invoked when creating a new class instance, and overrides any default parameters inherited from Plot. @private */ constructor() { super(); this._discrete = "x"; this._shape = constant("Box"); this.x("x"); this._tooltipConfig = assign(this._tooltipConfig, { title: (d, i) => { if (!d) return ""; while (d.__d3plus__ && d.data) { d = d.data; i = d.i; } if (this._label) return this._label(d, i); const l = this._ids(d, i).slice(0, this._drawDepth); return l[l.length - 1]; } }); } }
import React from 'react'; import PropTypes from 'prop-types'; import SvgIcon from '../SvgIcon'; const GearIcon = ({ setRef, ...rest }) => ( <SvgIcon {...rest} ref={setRef}> {/* <path d="M19.43,12.97L21.54,14.63C21.73,14.78 21.78,15.05 21.66,15.27L19.66,18.73C19.54,18.95 19.27,19.03 19.05,18.95L16.56,17.94C16.04,18.34 15.5,18.67 14.87,18.93L14.5,21.58C14.46,21.82 14.25,22 14,22H10C9.75,22 9.54,21.82 9.5,21.58L9.13,18.93C8.5,18.68 7.96,18.34 7.44,17.94L4.95,18.95C4.73,19.03 4.46,18.95 4.34,18.73L2.34,15.27C2.21,15.05 2.27,14.78 2.46,14.63L4.57,12.97L4.5,12L4.57,11L2.46,9.37C2.27,9.22 2.21,8.95 2.34,8.73L4.34,5.27C4.46,5.05 4.73,4.96 4.95,5.05L7.44,6.05C7.96,5.66 8.5,5.32 9.13,5.07L9.5,2.42C9.54,2.18 9.75,2 10,2H14C14.25,2 14.46,2.18 14.5,2.42L14.87,5.07C15.5,5.32 16.04,5.66 16.56,6.05L19.05,5.05C19.27,4.96 19.54,5.05 19.66,5.27L21.66,8.73C21.78,8.95 21.73,9.22 21.54,9.37L19.43,11L19.5,12L19.43,12.97M6.5,12C6.5,12.58 6.59,13.13 6.75,13.66L4.68,15.36L5.43,16.66L7.95,15.72C8.69,16.53 9.68,17.12 10.8,17.37L11.24,20H12.74L13.18,17.37C14.3,17.13 15.3,16.54 16.05,15.73L18.56,16.67L19.31,15.37L17.24,13.67C17.41,13.14 17.5,12.58 17.5,12C17.5,11.43 17.41,10.87 17.25,10.35L19.31,8.66L18.56,7.36L16.06,8.29C15.31,7.47 14.31,6.88 13.19,6.63L12.75,4H11.25L10.81,6.63C9.69,6.88 8.69,7.47 7.94,8.29L5.44,7.35L4.69,8.65L6.75,10.35C6.59,10.87 6.5,11.43 6.5,12M12,8.5A3.5,3.5 0 0,1 15.5,12A3.5,3.5 0 0,1 12,15.5A3.5,3.5 0 0,1 8.5,12A3.5,3.5 0 0,1 12,8.5M12,10.5A1.5,1.5 0 0,0 10.5,12A1.5,1.5 0 0,0 12,13.5A1.5,1.5 0 0,0 13.5,12A1.5,1.5 0 0,0 12,10.5Z" /> */} <path d="M556.133 591.467c-44 11.733-90 5.733-129.467-17.067s-67.733-59.6-79.467-103.6c-11.733-44-5.733-90 17.067-129.467s59.6-67.733 103.6-79.467c14.667-4 29.6-5.867 44.4-5.867 29.6 0 58.8 7.733 85.067 22.933 81.467 47.067 109.467 151.6 62.533 233.2-22.8 39.333-59.6 67.6-103.733 79.333zM576 315.867c-29.6-17.067-64.133-21.6-97.067-12.8-33.067 8.8-60.667 30-77.733 59.6s-21.6 64.133-12.8 97.067c8.8 33.067 30 60.667 59.6 77.733 19.733 11.333 41.6 17.2 63.733 17.2 11.067 0 22.267-1.467 33.333-4.4 33.067-8.8 60.667-30 77.733-59.6 35.333-61.067 14.267-139.6-46.8-174.8zM534.133 509.067c-22 5.867-45.067 2.933-64.8-8.533-19.733-11.333-33.867-29.733-39.733-51.867-5.867-22-2.933-45.067 8.533-64.8s29.733-33.867 51.867-39.733c7.333-2 14.8-2.933 22.267-2.933 14.8 0 29.333 3.867 42.533 11.467 19.733 11.333 33.867 29.733 39.733 51.867s2.933 45.067-8.533 64.8-29.867 33.867-51.867 39.733zM553.2 415.6c-2.933-11.067-10-20.267-19.867-25.867-9.867-5.733-21.333-7.2-32.4-4.267s-20.267 10-25.867 19.867-7.2 21.333-4.267 32.4 10 20.267 19.867 25.867c6.533 3.733 13.867 5.733 21.2 5.733 3.733 0 7.467-0.533 11.067-1.467 11.067-2.933 20.267-10 25.867-19.867s7.333-21.333 4.4-32.4zM945.467 324.134l-95.467 55.2c4.4 31.467 4.4 63.467 0.133 94.8l95.467 55.067c19.733 11.467 33.867 29.867 39.733 51.867s2.8 45.067-8.533 64.8l-42.667 73.867c-23.467 40.8-75.867 54.8-116.533 31.2l-95.467-55.067c-24.933 19.467-52.667 35.333-82.133 47.333v110.267c-0.133 47.067-38.4 85.2-85.333 85.2h-85.467c-22.667 0-44-8.8-60.133-24.933-16.267-16.133-25.067-37.6-25.067-60.4v-110.267c-14.667-6-28.933-12.933-42.667-20.8-13.733-8-26.933-16.8-39.333-26.4l-95.467 55.2c-19.733 11.467-42.8 14.533-64.8 8.533-22-5.867-40.4-20-51.733-39.733l-42.533-73.867c-23.733-40.667-9.733-92.933 31.067-116.667l95.6-55.2c-4.4-31.467-4.4-63.467-0.133-94.8l-95.467-55.2c-19.733-11.467-33.867-29.867-39.733-51.867s-2.8-45.067 8.533-64.8l42.667-73.867c23.467-40.8 75.867-54.8 116.533-31.2l95.6 55.2c24.933-19.467 52.667-35.333 82-47.333l-0.133-110.533c0.133-47.067 38.267-85.2 85.2-85.2h85.6c22.667 0 44 8.8 60.133 24.933s25.067 37.6 25.067 60.4l0.133 110.4c14.667 6 28.933 12.933 42.533 20.667 13.867 8 27.067 16.933 39.467 26.533l95.333-55.067c19.733-11.467 42.8-14.533 64.8-8.533 22 5.867 40.4 20 51.733 39.733l42.533 73.867c23.733 40.8 9.733 93.067-31.067 116.667zM469.333-0v0c0 0 0 0 0 0s0 0 0 0zM860.133 176.4l-121.333 70.267c-16.4 9.467-36.933 7.067-50.667-6-14.267-13.467-30.4-25.467-48-35.733-17.067-9.867-35.467-17.867-54.8-23.6-18-5.467-30.267-22-30.4-40.8l-0.267-140.533h-85.333l0.133 140.533c0 18.933-12.4 35.467-30.4 40.933-38.267 11.467-73.867 32-102.933 59.333-13.733 12.933-34.267 15.333-50.667 5.867l-121.6-70.267-42.667 73.867 121.6 70.267c16.4 9.467 24.533 28.533 20.133 46.933-9.333 38.533-9.2 79.6 0.133 118.533 4.4 18.4-3.733 37.467-20.133 46.933l-121.733 70.4 42.667 73.733 121.6-70.267c16.4-9.467 36.933-7.067 50.667 6 14.267 13.467 30.4 25.467 47.867 35.6 17.2 10 35.733 18 54.933 23.733 18 5.467 30.4 22 30.4 40.8v140.4h85.333v-140.4c0-18.8 12.4-35.467 30.4-40.933 38.267-11.467 73.867-32 102.933-59.333 13.733-12.933 34.267-15.333 50.533-5.867l121.6 70.133 42.667-73.867-121.6-70.133c-16.4-9.467-24.533-28.533-20.133-46.933 9.333-38.533 9.2-79.6-0.133-118.533-4.4-18.4 3.733-37.467 20.133-46.933l121.733-70.4-42.667-73.733z" /> </SvgIcon> ); GearIcon.propTypes = { setRef: PropTypes.object, viewBox: PropTypes.string, }; GearIcon.defaultProps = { setRef: null, // viewBox: '0 0 24 24' viewBox: '0 0 1050 850', }; export default GearIcon;
# Protocol Buffers - Google's data interchange format # Copyright 2008 Google Inc. All rights reserved. # https://developers.google.com/protocol-buffers/ # # Redistribution and use in source and binary forms, with or without # modification, are permitted provided that the following conditions are # met: # # * Redistributions of source code must retain the above copyright # notice, this list of conditions and the following disclaimer. # * Redistributions in binary form must reproduce the above # copyright notice, this list of conditions and the following disclaimer # in the documentation and/or other materials provided with the # distribution. # * Neither the name of Google Inc. nor the names of its # contributors may be used to endorse or promote products derived from # this software without specific prior written permission. # # THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS # "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT # LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR # A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT # OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, # SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT # LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, # DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY # THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT # (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE # OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. """Provides DescriptorPool to use as a container for proto2 descriptors. The DescriptorPool is used in conjection with a DescriptorDatabase to maintain a collection of protocol buffer descriptors for use when dynamically creating message types at runtime. For most applications protocol buffers should be used via modules generated by the protocol buffer compiler tool. This should only be used when the type of protocol buffers used in an application or library cannot be predetermined. Below is a straightforward example on how to use this class: pool = DescriptorPool() file_descriptor_protos = [ ... ] for file_descriptor_proto in file_descriptor_protos: pool.Add(file_descriptor_proto) my_message_descriptor = pool.FindMessageTypeByName('some.package.MessageType') The message descriptor can be used in conjunction with the message_factory module in order to create a protocol buffer class that can be encoded and decoded. If you want to get a Python class for the specified proto, use the helper functions inside google.protobuf.message_factory directly instead of this class. """ __author__ = '[email protected] (Matt Toia)' import collections from google.protobuf import descriptor from google.protobuf import descriptor_database from google.protobuf import text_encoding _USE_C_DESCRIPTORS = descriptor._USE_C_DESCRIPTORS # pylint: disable=protected-access def _NormalizeFullyQualifiedName(name): """Remove leading period from fully-qualified type name. Due to b/13860351 in descriptor_database.py, types in the root namespace are generated with a leading period. This function removes that prefix. Args: name: A str, the fully-qualified symbol name. Returns: A str, the normalized fully-qualified symbol name. """ return name.lstrip('.') def _OptionsOrNone(descriptor_proto): """Returns the value of the field `options`, or None if it is not set.""" if descriptor_proto.HasField('options'): return descriptor_proto.options else: return None def _IsMessageSetExtension(field): return (field.is_extension and field.containing_type.has_options and field.containing_type.GetOptions().message_set_wire_format and field.type == descriptor.FieldDescriptor.TYPE_MESSAGE and field.label == descriptor.FieldDescriptor.LABEL_OPTIONAL) class DescriptorPool(object): """A collection of protobufs dynamically constructed by descriptor protos.""" if _USE_C_DESCRIPTORS: def __new__(cls, descriptor_db=None): # pylint: disable=protected-access return descriptor._message.DescriptorPool(descriptor_db) def __init__(self, descriptor_db=None): """Initializes a Pool of proto buffs. The descriptor_db argument to the constructor is provided to allow specialized file descriptor proto lookup code to be triggered on demand. An example would be an implementation which will read and compile a file specified in a call to FindFileByName() and not require the call to Add() at all. Results from this database will be cached internally here as well. Args: descriptor_db: A secondary source of file descriptors. """ self._internal_db = descriptor_database.DescriptorDatabase() self._descriptor_db = descriptor_db self._descriptors = {} self._enum_descriptors = {} self._file_descriptors = {} self._toplevel_extensions = {} # We store extensions in two two-level mappings: The first key is the # descriptor of the message being extended, the second key is the extension # full name or its tag number. self._extensions_by_name = collections.defaultdict(dict) self._extensions_by_number = collections.defaultdict(dict) def Add(self, file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: file_desc_proto: The FileDescriptorProto to add. """ self._internal_db.Add(file_desc_proto) def AddSerializedFile(self, serialized_file_desc_proto): """Adds the FileDescriptorProto and its types to this pool. Args: serialized_file_desc_proto: A bytes string, serialization of the FileDescriptorProto to add. """ # pylint: disable=g-import-not-at-top from google.protobuf import descriptor_pb2 file_desc_proto = descriptor_pb2.FileDescriptorProto.FromString( serialized_file_desc_proto) self.Add(file_desc_proto) def AddDescriptor(self, desc): """Adds a Descriptor to the pool, non-recursively. If the Descriptor contains nested messages or enums, the caller must explicitly register them. This method also registers the FileDescriptor associated with the message. Args: desc: A Descriptor. """ if not isinstance(desc, descriptor.Descriptor): raise TypeError('Expected instance of descriptor.Descriptor.') self._descriptors[desc.full_name] = desc self.AddFileDescriptor(desc.file) def AddEnumDescriptor(self, enum_desc): """Adds an EnumDescriptor to the pool. This method also registers the FileDescriptor associated with the message. Args: enum_desc: An EnumDescriptor. """ if not isinstance(enum_desc, descriptor.EnumDescriptor): raise TypeError('Expected instance of descriptor.EnumDescriptor.') self._enum_descriptors[enum_desc.full_name] = enum_desc self.AddFileDescriptor(enum_desc.file) def AddExtensionDescriptor(self, extension): """Adds a FieldDescriptor describing an extension to the pool. Args: extension: A FieldDescriptor. Raises: AssertionError: when another extension with the same number extends the same message. TypeError: when the specified extension is not a descriptor.FieldDescriptor. """ if not (isinstance(extension, descriptor.FieldDescriptor) and extension.is_extension): raise TypeError('Expected an extension descriptor.') if extension.extension_scope is None: self._toplevel_extensions[extension.full_name] = extension try: existing_desc = self._extensions_by_number[ extension.containing_type][extension.number] except KeyError: pass else: if extension is not existing_desc: raise AssertionError( 'Extensions "%s" and "%s" both try to extend message type "%s" ' 'with field number %d.' % (extension.full_name, existing_desc.full_name, extension.containing_type.full_name, extension.number)) self._extensions_by_number[extension.containing_type][ extension.number] = extension self._extensions_by_name[extension.containing_type][ extension.full_name] = extension # Also register MessageSet extensions with the type name. if _IsMessageSetExtension(extension): self._extensions_by_name[extension.containing_type][ extension.message_type.full_name] = extension def AddFileDescriptor(self, file_desc): """Adds a FileDescriptor to the pool, non-recursively. If the FileDescriptor contains messages or enums, the caller must explicitly register them. Args: file_desc: A FileDescriptor. """ if not isinstance(file_desc, descriptor.FileDescriptor): raise TypeError('Expected instance of descriptor.FileDescriptor.') self._file_descriptors[file_desc.name] = file_desc def FindFileByName(self, file_name): """Gets a FileDescriptor by file name. Args: file_name: The path to the file to get a descriptor for. Returns: A FileDescriptor for the named file. Raises: KeyError: if the file can not be found in the pool. """ try: return self._file_descriptors[file_name] except KeyError: pass try: file_proto = self._internal_db.FindFileByName(file_name) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileByName(file_name) else: raise error if not file_proto: raise KeyError('Cannot find a file named %s' % file_name) return self._ConvertFileProtoToFileDescriptor(file_proto) def FindFileContainingSymbol(self, symbol): """Gets the FileDescriptor for the file containing the specified symbol. Args: symbol: The name of the symbol to search for. Returns: A FileDescriptor that contains the specified symbol. Raises: KeyError: if the file can not be found in the pool. """ symbol = _NormalizeFullyQualifiedName(symbol) try: return self._descriptors[symbol].file except KeyError: pass try: return self._enum_descriptors[symbol].file except KeyError: pass try: file_proto = self._internal_db.FindFileContainingSymbol(symbol) except KeyError as error: if self._descriptor_db: file_proto = self._descriptor_db.FindFileContainingSymbol(symbol) else: raise error if not file_proto: raise KeyError('Cannot find a file containing %s' % symbol) return self._ConvertFileProtoToFileDescriptor(file_proto) def FindMessageTypeByName(self, full_name): """Loads the named descriptor from the pool. Args: full_name: The full name of the descriptor to load. Returns: The descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._descriptors: self.FindFileContainingSymbol(full_name) return self._descriptors[full_name] def FindEnumTypeByName(self, full_name): """Loads the named enum descriptor from the pool. Args: full_name: The full name of the enum descriptor to load. Returns: The enum descriptor for the named type. """ full_name = _NormalizeFullyQualifiedName(full_name) if full_name not in self._enum_descriptors: self.FindFileContainingSymbol(full_name) return self._enum_descriptors[full_name] def FindFieldByName(self, full_name): """Loads the named field descriptor from the pool. Args: full_name: The full name of the field descriptor to load. Returns: The field descriptor for the named field. """ full_name = _NormalizeFullyQualifiedName(full_name) message_name, _, field_name = full_name.rpartition('.') message_descriptor = self.FindMessageTypeByName(message_name) return message_descriptor.fields_by_name[field_name] def FindExtensionByName(self, full_name): """Loads the named extension descriptor from the pool. Args: full_name: The full name of the extension descriptor to load. Returns: A FieldDescriptor, describing the named extension. """ full_name = _NormalizeFullyQualifiedName(full_name) try: # The proto compiler does not give any link between the FileDescriptor # and top-level extensions unless the FileDescriptorProto is added to # the DescriptorDatabase, but this can impact memory usage. # So we registered these extensions by name explicitly. return self._toplevel_extensions[full_name] except KeyError: pass message_name, _, extension_name = full_name.rpartition('.') try: # Most extensions are nested inside a message. scope = self.FindMessageTypeByName(message_name) except KeyError: # Some extensions are defined at file scope. scope = self.FindFileContainingSymbol(full_name) return scope.extensions_by_name[extension_name] def FindExtensionByNumber(self, message_descriptor, number): """Gets the extension of the specified message with the specified number. Extensions have to be registered to this pool by calling AddExtensionDescriptor. Args: message_descriptor: descriptor of the extended message. number: integer, number of the extension field. Returns: A FieldDescriptor describing the extension. Raise: KeyError: when no extension with the given number is known for the specified message. """ return self._extensions_by_number[message_descriptor][number] def FindAllExtensions(self, message_descriptor): """Gets all the known extension of a given message. Extensions have to be registered to this pool by calling AddExtensionDescriptor. Args: message_descriptor: descriptor of the extended message. Returns: A list of FieldDescriptor describing the extensions. """ return list(self._extensions_by_number[message_descriptor].values()) def _ConvertFileProtoToFileDescriptor(self, file_proto): """Creates a FileDescriptor from a proto or returns a cached copy. This method also has the side effect of loading all the symbols found in the file into the appropriate dictionaries in the pool. Args: file_proto: The proto to convert. Returns: A FileDescriptor matching the passed in proto. """ if file_proto.name not in self._file_descriptors: built_deps = list(self._GetDeps(file_proto.dependency)) direct_deps = [self.FindFileByName(n) for n in file_proto.dependency] public_deps = [direct_deps[i] for i in file_proto.public_dependency] file_descriptor = descriptor.FileDescriptor( pool=self, name=file_proto.name, package=file_proto.package, syntax=file_proto.syntax, options=_OptionsOrNone(file_proto), serialized_pb=file_proto.SerializeToString(), dependencies=direct_deps, public_dependencies=public_deps) scope = {} # This loop extracts all the message and enum types from all the # dependencies of the file_proto. This is necessary to create the # scope of available message types when defining the passed in # file proto. for dependency in built_deps: scope.update(self._ExtractSymbols( dependency.message_types_by_name.values())) scope.update((_PrefixWithDot(enum.full_name), enum) for enum in dependency.enum_types_by_name.values()) for message_type in file_proto.message_type: message_desc = self._ConvertMessageDescriptor( message_type, file_proto.package, file_descriptor, scope, file_proto.syntax) file_descriptor.message_types_by_name[message_desc.name] = ( message_desc) for enum_type in file_proto.enum_type: file_descriptor.enum_types_by_name[enum_type.name] = ( self._ConvertEnumDescriptor(enum_type, file_proto.package, file_descriptor, None, scope)) for index, extension_proto in enumerate(file_proto.extension): extension_desc = self._MakeFieldDescriptor( extension_proto, file_proto.package, index, is_extension=True) extension_desc.containing_type = self._GetTypeFromScope( file_descriptor.package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, file_descriptor.package, scope) file_descriptor.extensions_by_name[extension_desc.name] = ( extension_desc) for desc_proto in file_proto.message_type: self._SetAllFieldTypes(file_proto.package, desc_proto, scope) if file_proto.package: desc_proto_prefix = _PrefixWithDot(file_proto.package) else: desc_proto_prefix = '' for desc_proto in file_proto.message_type: desc = self._GetTypeFromScope( desc_proto_prefix, desc_proto.name, scope) file_descriptor.message_types_by_name[desc_proto.name] = desc for index, service_proto in enumerate(file_proto.service): file_descriptor.services_by_name[service_proto.name] = ( self._MakeServiceDescriptor(service_proto, index, scope, file_proto.package, file_descriptor)) self.Add(file_proto) self._file_descriptors[file_proto.name] = file_descriptor return self._file_descriptors[file_proto.name] def _ConvertMessageDescriptor(self, desc_proto, package=None, file_desc=None, scope=None, syntax=None): """Adds the proto to the pool in the specified package. Args: desc_proto: The descriptor_pb2.DescriptorProto protobuf message. package: The package the proto should be located in. file_desc: The file containing this message. scope: Dict mapping short and full symbols to message and enum types. syntax: string indicating syntax of the file ("proto2" or "proto3") Returns: The added descriptor. """ if package: desc_name = '.'.join((package, desc_proto.name)) else: desc_name = desc_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name if scope is None: scope = {} nested = [ self._ConvertMessageDescriptor( nested, desc_name, file_desc, scope, syntax) for nested in desc_proto.nested_type] enums = [ self._ConvertEnumDescriptor(enum, desc_name, file_desc, None, scope) for enum in desc_proto.enum_type] fields = [self._MakeFieldDescriptor(field, desc_name, index) for index, field in enumerate(desc_proto.field)] extensions = [ self._MakeFieldDescriptor(extension, desc_name, index, is_extension=True) for index, extension in enumerate(desc_proto.extension)] oneofs = [ descriptor.OneofDescriptor(desc.name, '.'.join((desc_name, desc.name)), index, None, [], desc.options) for index, desc in enumerate(desc_proto.oneof_decl)] extension_ranges = [(r.start, r.end) for r in desc_proto.extension_range] if extension_ranges: is_extendable = True else: is_extendable = False desc = descriptor.Descriptor( name=desc_proto.name, full_name=desc_name, filename=file_name, containing_type=None, fields=fields, oneofs=oneofs, nested_types=nested, enum_types=enums, extensions=extensions, options=_OptionsOrNone(desc_proto), is_extendable=is_extendable, extension_ranges=extension_ranges, file=file_desc, serialized_start=None, serialized_end=None, syntax=syntax) for nested in desc.nested_types: nested.containing_type = desc for enum in desc.enum_types: enum.containing_type = desc for field_index, field_desc in enumerate(desc_proto.field): if field_desc.HasField('oneof_index'): oneof_index = field_desc.oneof_index oneofs[oneof_index].fields.append(fields[field_index]) fields[field_index].containing_oneof = oneofs[oneof_index] scope[_PrefixWithDot(desc_name)] = desc self._descriptors[desc_name] = desc return desc def _ConvertEnumDescriptor(self, enum_proto, package=None, file_desc=None, containing_type=None, scope=None): """Make a protobuf EnumDescriptor given an EnumDescriptorProto protobuf. Args: enum_proto: The descriptor_pb2.EnumDescriptorProto protobuf message. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the enum descriptor. containing_type: The type containing this enum. scope: Scope containing available types. Returns: The added descriptor """ if package: enum_name = '.'.join((package, enum_proto.name)) else: enum_name = enum_proto.name if file_desc is None: file_name = None else: file_name = file_desc.name values = [self._MakeEnumValueDescriptor(value, index) for index, value in enumerate(enum_proto.value)] desc = descriptor.EnumDescriptor(name=enum_proto.name, full_name=enum_name, filename=file_name, file=file_desc, values=values, containing_type=containing_type, options=_OptionsOrNone(enum_proto)) scope['.%s' % enum_name] = desc self._enum_descriptors[enum_name] = desc return desc def _MakeFieldDescriptor(self, field_proto, message_name, index, is_extension=False): """Creates a field descriptor from a FieldDescriptorProto. For message and enum type fields, this method will do a look up in the pool for the appropriate descriptor for that type. If it is unavailable, it will fall back to the _source function to create it. If this type is still unavailable, construction will fail. Args: field_proto: The proto describing the field. message_name: The name of the containing message. index: Index of the field is_extension: Indication that this field is for an extension. Returns: An initialized FieldDescriptor object """ if message_name: full_name = '.'.join((message_name, field_proto.name)) else: full_name = field_proto.name return descriptor.FieldDescriptor( name=field_proto.name, full_name=full_name, index=index, number=field_proto.number, type=field_proto.type, cpp_type=None, message_type=None, enum_type=None, containing_type=None, label=field_proto.label, has_default_value=False, default_value=None, is_extension=is_extension, extension_scope=None, options=_OptionsOrNone(field_proto)) def _SetAllFieldTypes(self, package, desc_proto, scope): """Sets all the descriptor's fields's types. This method also sets the containing types on any extensions. Args: package: The current package of desc_proto. desc_proto: The message descriptor to update. scope: Enclosing scope of available types. """ package = _PrefixWithDot(package) main_desc = self._GetTypeFromScope(package, desc_proto.name, scope) if package == '.': nested_package = _PrefixWithDot(desc_proto.name) else: nested_package = '.'.join([package, desc_proto.name]) for field_proto, field_desc in zip(desc_proto.field, main_desc.fields): self._SetFieldType(field_proto, field_desc, nested_package, scope) for extension_proto, extension_desc in ( zip(desc_proto.extension, main_desc.extensions)): extension_desc.containing_type = self._GetTypeFromScope( nested_package, extension_proto.extendee, scope) self._SetFieldType(extension_proto, extension_desc, nested_package, scope) for nested_type in desc_proto.nested_type: self._SetAllFieldTypes(nested_package, nested_type, scope) def _SetFieldType(self, field_proto, field_desc, package, scope): """Sets the field's type, cpp_type, message_type and enum_type. Args: field_proto: Data about the field in proto format. field_desc: The descriptor to modiy. package: The package the field's container is in. scope: Enclosing scope of available types. """ if field_proto.type_name: desc = self._GetTypeFromScope(package, field_proto.type_name, scope) else: desc = None if not field_proto.HasField('type'): if isinstance(desc, descriptor.Descriptor): field_proto.type = descriptor.FieldDescriptor.TYPE_MESSAGE else: field_proto.type = descriptor.FieldDescriptor.TYPE_ENUM field_desc.cpp_type = descriptor.FieldDescriptor.ProtoTypeToCppProtoType( field_proto.type) if (field_proto.type == descriptor.FieldDescriptor.TYPE_MESSAGE or field_proto.type == descriptor.FieldDescriptor.TYPE_GROUP): field_desc.message_type = desc if field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.enum_type = desc if field_proto.label == descriptor.FieldDescriptor.LABEL_REPEATED: field_desc.has_default_value = False field_desc.default_value = [] elif field_proto.HasField('default_value'): field_desc.has_default_value = True if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = float(field_proto.default_value) elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = field_proto.default_value elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = field_proto.default_value.lower() == 'true' elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values_by_name[ field_proto.default_value].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = text_encoding.CUnescape( field_proto.default_value) else: # All other types are of the "int" type. field_desc.default_value = int(field_proto.default_value) else: field_desc.has_default_value = False if (field_proto.type == descriptor.FieldDescriptor.TYPE_DOUBLE or field_proto.type == descriptor.FieldDescriptor.TYPE_FLOAT): field_desc.default_value = 0.0 elif field_proto.type == descriptor.FieldDescriptor.TYPE_STRING: field_desc.default_value = u'' elif field_proto.type == descriptor.FieldDescriptor.TYPE_BOOL: field_desc.default_value = False elif field_proto.type == descriptor.FieldDescriptor.TYPE_ENUM: field_desc.default_value = field_desc.enum_type.values[0].number elif field_proto.type == descriptor.FieldDescriptor.TYPE_BYTES: field_desc.default_value = b'' else: # All other types are of the "int" type. field_desc.default_value = 0 field_desc.type = field_proto.type def _MakeEnumValueDescriptor(self, value_proto, index): """Creates a enum value descriptor object from a enum value proto. Args: value_proto: The proto describing the enum value. index: The index of the enum value. Returns: An initialized EnumValueDescriptor object. """ return descriptor.EnumValueDescriptor( name=value_proto.name, index=index, number=value_proto.number, options=_OptionsOrNone(value_proto), type=None) def _MakeServiceDescriptor(self, service_proto, service_index, scope, package, file_desc): """Make a protobuf ServiceDescriptor given a ServiceDescriptorProto. Args: service_proto: The descriptor_pb2.ServiceDescriptorProto protobuf message. service_index: The index of the service in the File. scope: Dict mapping short and full symbols to message and enum types. package: Optional package name for the new message EnumDescriptor. file_desc: The file containing the service descriptor. Returns: The added descriptor. """ if package: service_name = '.'.join((package, service_proto.name)) else: service_name = service_proto.name methods = [self._MakeMethodDescriptor(method_proto, service_name, package, scope, index) for index, method_proto in enumerate(service_proto.method)] desc = descriptor.ServiceDescriptor(name=service_proto.name, full_name=service_name, index=service_index, methods=methods, options=_OptionsOrNone(service_proto), file=file_desc) return desc def _MakeMethodDescriptor(self, method_proto, service_name, package, scope, index): """Creates a method descriptor from a MethodDescriptorProto. Args: method_proto: The proto describing the method. service_name: The name of the containing service. package: Optional package name to look up for types. scope: Scope containing available types. index: Index of the method in the service. Returns: An initialized MethodDescriptor object. """ full_name = '.'.join((service_name, method_proto.name)) input_type = self._GetTypeFromScope( package, method_proto.input_type, scope) output_type = self._GetTypeFromScope( package, method_proto.output_type, scope) return descriptor.MethodDescriptor(name=method_proto.name, full_name=full_name, index=index, containing_service=None, input_type=input_type, output_type=output_type, options=_OptionsOrNone(method_proto)) def _ExtractSymbols(self, descriptors): """Pulls out all the symbols from descriptor protos. Args: descriptors: The messages to extract descriptors from. Yields: A two element tuple of the type name and descriptor object. """ for desc in descriptors: yield (_PrefixWithDot(desc.full_name), desc) for symbol in self._ExtractSymbols(desc.nested_types): yield symbol for enum in desc.enum_types: yield (_PrefixWithDot(enum.full_name), enum) def _GetDeps(self, dependencies): """Recursively finds dependencies for file protos. Args: dependencies: The names of the files being depended on. Yields: Each direct and indirect dependency. """ for dependency in dependencies: dep_desc = self.FindFileByName(dependency) yield dep_desc for parent_dep in dep_desc.dependencies: yield parent_dep def _GetTypeFromScope(self, package, type_name, scope): """Finds a given type name in the current scope. Args: package: The package the proto should be located in. type_name: The name of the type to be found in the scope. scope: Dict mapping short and full symbols to message and enum types. Returns: The descriptor for the requested type. """ if type_name not in scope: components = _PrefixWithDot(package).split('.') while components: possible_match = '.'.join(components + [type_name]) if possible_match in scope: type_name = possible_match break else: components.pop(-1) return scope[type_name] def _PrefixWithDot(name): return name if name.startswith('.') else '.%s' % name if _USE_C_DESCRIPTORS: # TODO(user): This pool could be constructed from Python code, when we # support a flag like 'use_cpp_generated_pool=True'. # pylint: disable=protected-access _DEFAULT = descriptor._message.default_pool else: _DEFAULT = DescriptorPool() def Default(): return _DEFAULT
/*! * Materialize v1.0.0 (http://materializecss.com) * Copyright 2014-2017 Materialize * MIT License (https://raw.githubusercontent.com/Dogfalo/materialize/master/LICENSE) */ var _get=function t(e,i,n){null===e&&(e=Function.prototype);var s=Object.getOwnPropertyDescriptor(e,i);if(void 0===s){var o=Object.getPrototypeOf(e);return null===o?void 0:t(o,i,n)}if("value"in s)return s.value;var a=s.get;return void 0!==a?a.call(n):void 0},_createClass=function(){function n(t,e){for(var i=0;i<e.length;i++){var n=e[i];n.enumerable=n.enumerable||!1,n.configurable=!0,"value"in n&&(n.writable=!0),Object.defineProperty(t,n.key,n)}}return function(t,e,i){return e&&n(t.prototype,e),i&&n(t,i),t}}();function _possibleConstructorReturn(t,e){if(!t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!e||"object"!=typeof e&&"function"!=typeof e?t:e}function _inherits(t,e){if("function"!=typeof e&&null!==e)throw new TypeError("Super expression must either be null or a function, not "+typeof e);t.prototype=Object.create(e&&e.prototype,{constructor:{value:t,enumerable:!1,writable:!0,configurable:!0}}),e&&(Object.setPrototypeOf?Object.setPrototypeOf(t,e):t.__proto__=e)}function _classCallCheck(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}window.cash=function(){var i,o=document,a=window,t=Array.prototype,r=t.slice,n=t.filter,s=t.push,e=function(){},h=function(t){return typeof t==typeof e&&t.call},d=function(t){return"string"==typeof t},l=/^#[\w-]*$/,u=/^\.[\w-]*$/,c=/<.+>/,p=/^\w+$/;function v(t,e){e=e||o;var i=u.test(t)?e.getElementsByClassName(t.slice(1)):p.test(t)?e.getElementsByTagName(t):e.querySelectorAll(t);return i}function f(t){if(!i){var e=(i=o.implementation.createHTMLDocument(null)).createElement("base");e.href=o.location.href,i.head.appendChild(e)}return i.body.innerHTML=t,i.body.childNodes}function m(t){"loading"!==o.readyState?t():o.addEventListener("DOMContentLoaded",t)}function g(t,e){if(!t)return this;if(t.cash&&t!==a)return t;var i,n=t,s=0;if(d(t))n=l.test(t)?o.getElementById(t.slice(1)):c.test(t)?f(t):v(t,e);else if(h(t))return m(t),this;if(!n)return this;if(n.nodeType||n===a)this[0]=n,this.length=1;else for(i=this.length=n.length;s<i;s++)this[s]=n[s];return this}function _(t,e){return new g(t,e)}var y=_.fn=_.prototype=g.prototype={cash:!0,length:0,push:s,splice:t.splice,map:t.map,init:g};function k(t,e){for(var i=t.length,n=0;n<i&&!1!==e.call(t[n],t[n],n,t);n++);}function b(t,e){var i=t&&(t.matches||t.webkitMatchesSelector||t.mozMatchesSelector||t.msMatchesSelector||t.oMatchesSelector);return!!i&&i.call(t,e)}function w(e){return d(e)?b:e.cash?function(t){return e.is(t)}:function(t,e){return t===e}}function C(t){return _(r.call(t).filter(function(t,e,i){return i.indexOf(t)===e}))}Object.defineProperty(y,"constructor",{value:_}),_.parseHTML=f,_.noop=e,_.isFunction=h,_.isString=d,_.extend=y.extend=function(t){t=t||{};var e=r.call(arguments),i=e.length,n=1;for(1===e.length&&(t=this,n=0);n<i;n++)if(e[n])for(var s in e[n])e[n].hasOwnProperty(s)&&(t[s]=e[n][s]);return t},_.extend({merge:function(t,e){for(var i=+e.length,n=t.length,s=0;s<i;n++,s++)t[n]=e[s];return t.length=n,t},each:k,matches:b,unique:C,isArray:Array.isArray,isNumeric:function(t){return!isNaN(parseFloat(t))&&isFinite(t)}});var E=_.uid="_cash"+Date.now();function M(t){return t[E]=t[E]||{}}function O(t,e,i){return M(t)[e]=i}function x(t,e){var i=M(t);return void 0===i[e]&&(i[e]=t.dataset?t.dataset[e]:_(t).attr("data-"+e)),i[e]}y.extend({data:function(e,i){if(d(e))return void 0===i?x(this[0],e):this.each(function(t){return O(t,e,i)});for(var t in e)this.data(t,e[t]);return this},removeData:function(s){return this.each(function(t){return i=s,void((n=M(e=t))?delete n[i]:e.dataset?delete e.dataset[i]:_(e).removeAttr("data-"+name));var e,i,n})}});var L=/\S+/g;function T(t){return d(t)&&t.match(L)}function $(t,e){return t.classList?t.classList.contains(e):new RegExp("(^| )"+e+"( |$)","gi").test(t.className)}function B(t,e,i){t.classList?t.classList.add(e):i.indexOf(" "+e+" ")&&(t.className+=" "+e)}function D(t,e){t.classList?t.classList.remove(e):t.className=t.className.replace(e,"")}y.extend({addClass:function(t){var n=T(t);return n?this.each(function(e){var i=" "+e.className+" ";k(n,function(t){B(e,t,i)})}):this},attr:function(e,i){if(e){if(d(e))return void 0===i?this[0]?this[0].getAttribute?this[0].getAttribute(e):this[0][e]:void 0:this.each(function(t){t.setAttribute?t.setAttribute(e,i):t[e]=i});for(var t in e)this.attr(t,e[t]);return this}},hasClass:function(t){var e=!1,i=T(t);return i&&i.length&&this.each(function(t){return!(e=$(t,i[0]))}),e},prop:function(e,i){if(d(e))return void 0===i?this[0][e]:this.each(function(t){t[e]=i});for(var t in e)this.prop(t,e[t]);return this},removeAttr:function(e){return this.each(function(t){t.removeAttribute?t.removeAttribute(e):delete t[e]})},removeClass:function(t){if(!arguments.length)return this.attr("class","");var i=T(t);return i?this.each(function(e){k(i,function(t){D(e,t)})}):this},removeProp:function(e){return this.each(function(t){delete t[e]})},toggleClass:function(t,e){if(void 0!==e)return this[e?"addClass":"removeClass"](t);var n=T(t);return n?this.each(function(e){var i=" "+e.className+" ";k(n,function(t){$(e,t)?D(e,t):B(e,t,i)})}):this}}),y.extend({add:function(t,e){return C(_.merge(this,_(t,e)))},each:function(t){return k(this,t),this},eq:function(t){return _(this.get(t))},filter:function(e){if(!e)return this;var i=h(e)?e:w(e);return _(n.call(this,function(t){return i(t,e)}))},first:function(){return this.eq(0)},get:function(t){return void 0===t?r.call(this):t<0?this[t+this.length]:this[t]},index:function(t){var e=t?_(t)[0]:this[0],i=t?this:_(e).parent().children();return r.call(i).indexOf(e)},last:function(){return this.eq(-1)}});var S,I,A,R,H,P,W=(H=/(?:^\w|[A-Z]|\b\w)/g,P=/[\s-_]+/g,function(t){return t.replace(H,function(t,e){return t[0===e?"toLowerCase":"toUpperCase"]()}).replace(P,"")}),j=(S={},I=document,A=I.createElement("div"),R=A.style,function(e){if(e=W(e),S[e])return S[e];var t=e.charAt(0).toUpperCase()+e.slice(1),i=(e+" "+["webkit","moz","ms","o"].join(t+" ")+t).split(" ");return k(i,function(t){if(t in R)return S[t]=e=S[e]=t,!1}),S[e]});function F(t,e){return parseInt(a.getComputedStyle(t[0],null)[e],10)||0}function q(e,i,t){var n,s=x(e,"_cashEvents"),o=s&&s[i];o&&(t?(e.removeEventListener(i,t),0<=(n=o.indexOf(t))&&o.splice(n,1)):(k(o,function(t){e.removeEventListener(i,t)}),o=[]))}function N(t,e){return"&"+encodeURIComponent(t)+"="+encodeURIComponent(e).replace(/%20/g,"+")}function z(t){var e,i,n,s=t.type;if(!s)return null;switch(s.toLowerCase()){case"select-one":return 0<=(n=(i=t).selectedIndex)?i.options[n].value:null;case"select-multiple":return e=[],k(t.options,function(t){t.selected&&e.push(t.value)}),e.length?e:null;case"radio":case"checkbox":return t.checked?t.value:null;default:return t.value?t.value:null}}function V(e,i,n){var t=d(i);t||!i.length?k(e,t?function(t){return t.insertAdjacentHTML(n?"afterbegin":"beforeend",i)}:function(t,e){return function(t,e,i){if(i){var n=t.childNodes[0];t.insertBefore(e,n)}else t.appendChild(e)}(t,0===e?i:i.cloneNode(!0),n)}):k(i,function(t){return V(e,t,n)})}_.prefixedProp=j,_.camelCase=W,y.extend({css:function(e,i){if(d(e))return e=j(e),1<arguments.length?this.each(function(t){return t.style[e]=i}):a.getComputedStyle(this[0])[e];for(var t in e)this.css(t,e[t]);return this}}),k(["Width","Height"],function(e){var t=e.toLowerCase();y[t]=function(){return this[0].getBoundingClientRect()[t]},y["inner"+e]=function(){return this[0]["client"+e]},y["outer"+e]=function(t){return this[0]["offset"+e]+(t?F(this,"margin"+("Width"===e?"Left":"Top"))+F(this,"margin"+("Width"===e?"Right":"Bottom")):0)}}),y.extend({off:function(e,i){return this.each(function(t){return q(t,e,i)})},on:function(a,i,r,l){var n;if(!d(a)){for(var t in a)this.on(t,i,a[t]);return this}return h(i)&&(r=i,i=null),"ready"===a?(m(r),this):(i&&(n=r,r=function(t){for(var e=t.target;!b(e,i);){if(e===this||null===e)return e=!1;e=e.parentNode}e&&n.call(e,t)}),this.each(function(t){var e,i,n,s,o=r;l&&(o=function(){r.apply(this,arguments),q(t,a,o)}),i=a,n=o,(s=x(e=t,"_cashEvents")||O(e,"_cashEvents",{}))[i]=s[i]||[],s[i].push(n),e.addEventListener(i,n)}))},one:function(t,e,i){return this.on(t,e,i,!0)},ready:m,trigger:function(t,e){if(document.createEvent){var i=document.createEvent("HTMLEvents");return i.initEvent(t,!0,!1),i=this.extend(i,e),this.each(function(t){return t.dispatchEvent(i)})}}}),y.extend({serialize:function(){var s="";return k(this[0].elements||this,function(t){if(!t.disabled&&"FIELDSET"!==t.tagName){var e=t.name;switch(t.type.toLowerCase()){case"file":case"reset":case"submit":case"button":break;case"select-multiple":var i=z(t);null!==i&&k(i,function(t){s+=N(e,t)});break;default:var n=z(t);null!==n&&(s+=N(e,n))}}}),s.substr(1)},val:function(e){return void 0===e?z(this[0]):this.each(function(t){return t.value=e})}}),y.extend({after:function(t){return _(t).insertAfter(this),this},append:function(t){return V(this,t),this},appendTo:function(t){return V(_(t),this),this},before:function(t){return _(t).insertBefore(this),this},clone:function(){return _(this.map(function(t){return t.cloneNode(!0)}))},empty:function(){return this.html(""),this},html:function(t){if(void 0===t)return this[0].innerHTML;var e=t.nodeType?t[0].outerHTML:t;return this.each(function(t){return t.innerHTML=e})},insertAfter:function(t){var s=this;return _(t).each(function(t,e){var i=t.parentNode,n=t.nextSibling;s.each(function(t){i.insertBefore(0===e?t:t.cloneNode(!0),n)})}),this},insertBefore:function(t){var s=this;return _(t).each(function(e,i){var n=e.parentNode;s.each(function(t){n.insertBefore(0===i?t:t.cloneNode(!0),e)})}),this},prepend:function(t){return V(this,t,!0),this},prependTo:function(t){return V(_(t),this,!0),this},remove:function(){return this.each(function(t){if(t.parentNode)return t.parentNode.removeChild(t)})},text:function(e){return void 0===e?this[0].textContent:this.each(function(t){return t.textContent=e})}});var X=o.documentElement;return y.extend({position:function(){var t=this[0];return{left:t.offsetLeft,top:t.offsetTop}},offset:function(){var t=this[0].getBoundingClientRect();return{top:t.top+a.pageYOffset-X.clientTop,left:t.left+a.pageXOffset-X.clientLeft}},offsetParent:function(){return _(this[0].offsetParent)}}),y.extend({children:function(e){var i=[];return this.each(function(t){s.apply(i,t.children)}),i=C(i),e?i.filter(function(t){return b(t,e)}):i},closest:function(t){return!t||this.length<1?_():this.is(t)?this.filter(t):this.parent().closest(t)},is:function(e){if(!e)return!1;var i=!1,n=w(e);return this.each(function(t){return!(i=n(t,e))}),i},find:function(e){if(!e||e.nodeType)return _(e&&this.has(e).length?e:null);var i=[];return this.each(function(t){s.apply(i,v(e,t))}),C(i)},has:function(e){var t=d(e)?function(t){return 0!==v(e,t).length}:function(t){return t.contains(e)};return this.filter(t)},next:function(){return _(this[0].nextElementSibling)},not:function(e){if(!e)return this;var i=w(e);return this.filter(function(t){return!i(t,e)})},parent:function(){var e=[];return this.each(function(t){t&&t.parentNode&&e.push(t.parentNode)}),C(e)},parents:function(e){var i,n=[];return this.each(function(t){for(i=t;i&&i.parentNode&&i!==o.body.parentNode;)i=i.parentNode,(!e||e&&b(i,e))&&n.push(i)}),C(n)},prev:function(){return _(this[0].previousElementSibling)},siblings:function(t){var e=this.parent().children(t),i=this[0];return e.filter(function(t){return t!==i})}}),_}();var Component=function(){function s(t,e,i){_classCallCheck(this,s),e instanceof Element||console.error(Error(e+" is not an HTML Element"));var n=t.getInstance(e);n&&n.destroy(),this.el=e,this.$el=cash(e)}return _createClass(s,null,[{key:"init",value:function(t,e,i){var n=null;if(e instanceof Element)n=new t(e,i);else if(e&&(e.jquery||e.cash||e instanceof NodeList)){for(var s=[],o=0;o<e.length;o++)s.push(new t(e[o],i));n=s}return n}}]),s}();!function(t){t.Package?M={}:t.M={},M.jQueryLoaded=!!t.jQuery}(window),"function"==typeof define&&define.amd?define("M",[],function(){return M}):"undefined"==typeof exports||exports.nodeType||("undefined"!=typeof module&&!module.nodeType&&module.exports&&(exports=module.exports=M),exports.default=M),M.version="1.0.0",M.keys={TAB:9,ENTER:13,ESC:27,ARROW_UP:38,ARROW_DOWN:40},M.tabPressed=!1,M.keyDown=!1;var docHandleKeydown=function(t){M.keyDown=!0,t.which!==M.keys.TAB&&t.which!==M.keys.ARROW_DOWN&&t.which!==M.keys.ARROW_UP||(M.tabPressed=!0)},docHandleKeyup=function(t){M.keyDown=!1,t.which!==M.keys.TAB&&t.which!==M.keys.ARROW_DOWN&&t.which!==M.keys.ARROW_UP||(M.tabPressed=!1)},docHandleFocus=function(t){M.keyDown&&document.body.classList.add("keyboard-focused")},docHandleBlur=function(t){document.body.classList.remove("keyboard-focused")};document.addEventListener("keydown",docHandleKeydown,!0),document.addEventListener("keyup",docHandleKeyup,!0),document.addEventListener("focus",docHandleFocus,!0),document.addEventListener("blur",docHandleBlur,!0),M.initializeJqueryWrapper=function(n,s,o){jQuery.fn[s]=function(e){if(n.prototype[e]){var i=Array.prototype.slice.call(arguments,1);if("get"===e.slice(0,3)){var t=this.first()[0][o];return t[e].apply(t,i)}return this.each(function(){var t=this[o];t[e].apply(t,i)})}if("object"==typeof e||!e)return n.init(this,e),this;jQuery.error("Method "+e+" does not exist on jQuery."+s)}},M.AutoInit=function(t){var e=t||document.body,i={Autocomplete:e.querySelectorAll(".autocomplete:not(.no-autoinit)"),Carousel:e.querySelectorAll(".carousel:not(.no-autoinit)"),Chips:e.querySelectorAll(".chips:not(.no-autoinit)"),Collapsible:e.querySelectorAll(".collapsible:not(.no-autoinit)"),Datepicker:e.querySelectorAll(".datepicker:not(.no-autoinit)"),Dropdown:e.querySelectorAll(".dropdown-trigger:not(.no-autoinit)"),Materialbox:e.querySelectorAll(".materialboxed:not(.no-autoinit)"),Modal:e.querySelectorAll(".modal:not(.no-autoinit)"),Parallax:e.querySelectorAll(".parallax:not(.no-autoinit)"),Pushpin:e.querySelectorAll(".pushpin:not(.no-autoinit)"),ScrollSpy:e.querySelectorAll(".scrollspy:not(.no-autoinit)"),FormSelect:e.querySelectorAll("select:not(.no-autoinit)"),Sidenav:e.querySelectorAll(".sidenav:not(.no-autoinit)"),Tabs:e.querySelectorAll(".tabs:not(.no-autoinit)"),TapTarget:e.querySelectorAll(".tap-target:not(.no-autoinit)"),Timepicker:e.querySelectorAll(".timepicker:not(.no-autoinit)"),Tooltip:e.querySelectorAll(".tooltipped:not(.no-autoinit)"),FloatingActionButton:e.querySelectorAll(".fixed-action-btn:not(.no-autoinit)")};for(var n in i){M[n].init(i[n])}},M.objectSelectorString=function(t){return((t.prop("tagName")||"")+(t.attr("id")||"")+(t.attr("class")||"")).replace(/\s/g,"")},M.guid=function(){function t(){return Math.floor(65536*(1+Math.random())).toString(16).substring(1)}return function(){return t()+t()+"-"+t()+"-"+t()+"-"+t()+"-"+t()+t()+t()}}(),M.escapeHash=function(t){return t.replace(/(:|\.|\[|\]|,|=|\/)/g,"\\$1")},M.elementOrParentIsFixed=function(t){var e=$(t),i=e.add(e.parents()),n=!1;return i.each(function(){if("fixed"===$(this).css("position"))return!(n=!0)}),n},M.checkWithinContainer=function(t,e,i){var n={top:!1,right:!1,bottom:!1,left:!1},s=t.getBoundingClientRect(),o=t===document.body?Math.max(s.bottom,window.innerHeight):s.bottom,a=t.scrollLeft,r=t.scrollTop,l=e.left-a,h=e.top-r;return(l<s.left+i||l<i)&&(n.left=!0),(l+e.width>s.right-i||l+e.width>window.innerWidth-i)&&(n.right=!0),(h<s.top+i||h<i)&&(n.top=!0),(h+e.height>o-i||h+e.height>window.innerHeight-i)&&(n.bottom=!0),n},M.checkPossibleAlignments=function(t,e,i,n){var s={top:!0,right:!0,bottom:!0,left:!0,spaceOnTop:null,spaceOnRight:null,spaceOnBottom:null,spaceOnLeft:null},o="visible"===getComputedStyle(e).overflow,a=e.getBoundingClientRect(),r=Math.min(a.height,window.innerHeight),l=Math.min(a.width,window.innerWidth),h=t.getBoundingClientRect(),d=e.scrollLeft,u=e.scrollTop,c=i.left-d,p=i.top-u,v=i.top+h.height-u;return s.spaceOnRight=o?window.innerWidth-(h.left+i.width):l-(c+i.width),s.spaceOnRight<0&&(s.left=!1),s.spaceOnLeft=o?h.right-i.width:c-i.width+h.width,s.spaceOnLeft<0&&(s.right=!1),s.spaceOnBottom=o?window.innerHeight-(h.top+i.height+n):r-(p+i.height+n),s.spaceOnBottom<0&&(s.top=!1),s.spaceOnTop=o?h.bottom-(i.height+n):v-(i.height-n),s.spaceOnTop<0&&(s.bottom=!1),s},M.getOverflowParent=function(t){return null==t?null:t===document.body||"visible"!==getComputedStyle(t).overflow?t:M.getOverflowParent(t.parentElement)},M.getIdFromTrigger=function(t){var e=t.getAttribute("data-target");return e||(e=(e=t.getAttribute("href"))?e.slice(1):""),e},M.getDocumentScrollTop=function(){return window.pageYOffset||document.documentElement.scrollTop||document.body.scrollTop||0},M.getDocumentScrollLeft=function(){return window.pageXOffset||document.documentElement.scrollLeft||document.body.scrollLeft||0};var getTime=Date.now||function(){return(new Date).getTime()};M.throttle=function(i,n,s){var o=void 0,a=void 0,r=void 0,l=null,h=0;s||(s={});var d=function(){h=!1===s.leading?0:getTime(),l=null,r=i.apply(o,a),o=a=null};return function(){var t=getTime();h||!1!==s.leading||(h=t);var e=n-(t-h);return o=this,a=arguments,e<=0?(clearTimeout(l),l=null,h=t,r=i.apply(o,a),o=a=null):l||!1===s.trailing||(l=setTimeout(d,e)),r}};var $jscomp={scope:{}};$jscomp.defineProperty="function"==typeof Object.defineProperties?Object.defineProperty:function(t,e,i){if(i.get||i.set)throw new TypeError("ES3 does not support getters and setters.");t!=Array.prototype&&t!=Object.prototype&&(t[e]=i.value)},$jscomp.getGlobal=function(t){return"undefined"!=typeof window&&window===t?t:"undefined"!=typeof global&&null!=global?global:t},$jscomp.global=$jscomp.getGlobal(this),$jscomp.SYMBOL_PREFIX="jscomp_symbol_",$jscomp.initSymbol=function(){$jscomp.initSymbol=function(){},$jscomp.global.Symbol||($jscomp.global.Symbol=$jscomp.Symbol)},$jscomp.symbolCounter_=0,$jscomp.Symbol=function(t){return $jscomp.SYMBOL_PREFIX+(t||"")+$jscomp.symbolCounter_++},$jscomp.initSymbolIterator=function(){$jscomp.initSymbol();var t=$jscomp.global.Symbol.iterator;t||(t=$jscomp.global.Symbol.iterator=$jscomp.global.Symbol("iterator")),"function"!=typeof Array.prototype[t]&&$jscomp.defineProperty(Array.prototype,t,{configurable:!0,writable:!0,value:function(){return $jscomp.arrayIterator(this)}}),$jscomp.initSymbolIterator=function(){}},$jscomp.arrayIterator=function(t){var e=0;return $jscomp.iteratorPrototype(function(){return e<t.length?{done:!1,value:t[e++]}:{done:!0}})},$jscomp.iteratorPrototype=function(t){return $jscomp.initSymbolIterator(),(t={next:t})[$jscomp.global.Symbol.iterator]=function(){return this},t},$jscomp.array=$jscomp.array||{},$jscomp.iteratorFromArray=function(e,i){$jscomp.initSymbolIterator(),e instanceof String&&(e+="");var n=0,s={next:function(){if(n<e.length){var t=n++;return{value:i(t,e[t]),done:!1}}return s.next=function(){return{done:!0,value:void 0}},s.next()}};return s[Symbol.iterator]=function(){return s},s},$jscomp.polyfill=function(t,e,i,n){if(e){for(i=$jscomp.global,t=t.split("."),n=0;n<t.length-1;n++){var s=t[n];s in i||(i[s]={}),i=i[s]}(e=e(n=i[t=t[t.length-1]]))!=n&&null!=e&&$jscomp.defineProperty(i,t,{configurable:!0,writable:!0,value:e})}},$jscomp.polyfill("Array.prototype.keys",function(t){return t||function(){return $jscomp.iteratorFromArray(this,function(t){return t})}},"es6-impl","es3");var $jscomp$this=this;M.anime=function(){function s(t){if(!B.col(t))try{return document.querySelectorAll(t)}catch(t){}}function b(t,e){for(var i=t.length,n=2<=arguments.length?e:void 0,s=[],o=0;o<i;o++)if(o in t){var a=t[o];e.call(n,a,o,t)&&s.push(a)}return s}function d(t){return t.reduce(function(t,e){return t.concat(B.arr(e)?d(e):e)},[])}function o(t){return B.arr(t)?t:(B.str(t)&&(t=s(t)||t),t instanceof NodeList||t instanceof HTMLCollection?[].slice.call(t):[t])}function a(t,e){return t.some(function(t){return t===e})}function r(t){var e,i={};for(e in t)i[e]=t[e];return i}function u(t,e){var i,n=r(t);for(i in t)n[i]=e.hasOwnProperty(i)?e[i]:t[i];return n}function c(t,e){var i,n=r(t);for(i in e)n[i]=B.und(t[i])?e[i]:t[i];return n}function l(t){if(t=/([\+\-]?[0-9#\.]+)(%|px|pt|em|rem|in|cm|mm|ex|ch|pc|vw|vh|vmin|vmax|deg|rad|turn)?$/.exec(t))return t[2]}function h(t,e){return B.fnc(t)?t(e.target,e.id,e.total):t}function w(t,e){if(e in t.style)return getComputedStyle(t).getPropertyValue(e.replace(/([a-z])([A-Z])/g,"$1-$2").toLowerCase())||"0"}function p(t,e){return B.dom(t)&&a($,e)?"transform":B.dom(t)&&(t.getAttribute(e)||B.svg(t)&&t[e])?"attribute":B.dom(t)&&"transform"!==e&&w(t,e)?"css":null!=t[e]?"object":void 0}function v(t,e){switch(p(t,e)){case"transform":return function(t,i){var e,n=-1<(e=i).indexOf("translate")||"perspective"===e?"px":-1<e.indexOf("rotate")||-1<e.indexOf("skew")?"deg":void 0,n=-1<i.indexOf("scale")?1:0+n;if(!(t=t.style.transform))return n;for(var s=[],o=[],a=[],r=/(\w+)\((.+?)\)/g;s=r.exec(t);)o.push(s[1]),a.push(s[2]);return(t=b(a,function(t,e){return o[e]===i})).length?t[0]:n}(t,e);case"css":return w(t,e);case"attribute":return t.getAttribute(e)}return t[e]||0}function f(t,e){var i=/^(\*=|\+=|-=)/.exec(t);if(!i)return t;var n=l(t)||0;switch(e=parseFloat(e),t=parseFloat(t.replace(i[0],"")),i[0][0]){case"+":return e+t+n;case"-":return e-t+n;case"*":return e*t+n}}function m(t,e){return Math.sqrt(Math.pow(e.x-t.x,2)+Math.pow(e.y-t.y,2))}function i(t){t=t.points;for(var e,i=0,n=0;n<t.numberOfItems;n++){var s=t.getItem(n);0<n&&(i+=m(e,s)),e=s}return i}function g(t){if(t.getTotalLength)return t.getTotalLength();switch(t.tagName.toLowerCase()){case"circle":return 2*Math.PI*t.getAttribute("r");case"rect":return 2*t.getAttribute("width")+2*t.getAttribute("height");case"line":return m({x:t.getAttribute("x1"),y:t.getAttribute("y1")},{x:t.getAttribute("x2"),y:t.getAttribute("y2")});case"polyline":return i(t);case"polygon":var e=t.points;return i(t)+m(e.getItem(e.numberOfItems-1),e.getItem(0))}}function C(e,i){function t(t){return t=void 0===t?0:t,e.el.getPointAtLength(1<=i+t?i+t:0)}var n=t(),s=t(-1),o=t(1);switch(e.property){case"x":return n.x;case"y":return n.y;case"angle":return 180*Math.atan2(o.y-s.y,o.x-s.x)/Math.PI}}function _(t,e){var i,n=/-?\d*\.?\d+/g;if(i=B.pth(t)?t.totalLength:t,B.col(i))if(B.rgb(i)){var s=/rgb\((\d+,\s*[\d]+,\s*[\d]+)\)/g.exec(i);i=s?"rgba("+s[1]+",1)":i}else i=B.hex(i)?function(t){t=t.replace(/^#?([a-f\d])([a-f\d])([a-f\d])$/i,function(t,e,i,n){return e+e+i+i+n+n});var e=/^#?([a-f\d]{2})([a-f\d]{2})([a-f\d]{2})$/i.exec(t);t=parseInt(e[1],16);var i=parseInt(e[2],16),e=parseInt(e[3],16);return"rgba("+t+","+i+","+e+",1)"}(i):B.hsl(i)?function(t){function e(t,e,i){return i<0&&(i+=1),1<i&&--i,i<1/6?t+6*(e-t)*i:i<.5?e:i<2/3?t+(e-t)*(2/3-i)*6:t}var i=/hsl\((\d+),\s*([\d.]+)%,\s*([\d.]+)%\)/g.exec(t)||/hsla\((\d+),\s*([\d.]+)%,\s*([\d.]+)%,\s*([\d.]+)\)/g.exec(t);t=parseInt(i[1])/360;var n=parseInt(i[2])/100,s=parseInt(i[3])/100,i=i[4]||1;if(0==n)s=n=t=s;else{var o=s<.5?s*(1+n):s+n-s*n,a=2*s-o,s=e(a,o,t+1/3),n=e(a,o,t);t=e(a,o,t-1/3)}return"rgba("+255*s+","+255*n+","+255*t+","+i+")"}(i):void 0;else s=(s=l(i))?i.substr(0,i.length-s.length):i,i=e&&!/\s/g.test(i)?s+e:s;return{original:i+="",numbers:i.match(n)?i.match(n).map(Number):[0],strings:B.str(t)||e?i.split(n):[]}}function y(t){return b(t=t?d(B.arr(t)?t.map(o):o(t)):[],function(t,e,i){return i.indexOf(t)===e})}function k(t,i){var e=r(i);if(B.arr(t)){var n=t.length;2!==n||B.obj(t[0])?B.fnc(i.duration)||(e.duration=i.duration/n):t={value:t}}return o(t).map(function(t,e){return e=e?0:i.delay,t=B.obj(t)&&!B.pth(t)?t:{value:t},B.und(t.delay)&&(t.delay=e),t}).map(function(t){return c(t,e)})}function E(o,a){var r;return o.tweens.map(function(t){var e=(t=function(t,e){var i,n={};for(i in t){var s=h(t[i],e);B.arr(s)&&1===(s=s.map(function(t){return h(t,e)})).length&&(s=s[0]),n[i]=s}return n.duration=parseFloat(n.duration),n.delay=parseFloat(n.delay),n}(t,a)).value,i=v(a.target,o.name),n=r?r.to.original:i,n=B.arr(e)?e[0]:n,s=f(B.arr(e)?e[1]:e,n),i=l(s)||l(n)||l(i);return t.from=_(n,i),t.to=_(s,i),t.start=r?r.end:o.offset,t.end=t.start+t.delay+t.duration,t.easing=function(t){return B.arr(t)?D.apply(this,t):S[t]}(t.easing),t.elasticity=(1e3-Math.min(Math.max(t.elasticity,1),999))/1e3,t.isPath=B.pth(e),t.isColor=B.col(t.from.original),t.isColor&&(t.round=1),r=t})}function M(e,t,i,n){var s="delay"===e;return t.length?(s?Math.min:Math.max).apply(Math,t.map(function(t){return t[e]})):s?n.delay:i.offset+n.delay+n.duration}function n(t){var e,i,n,s,o=u(L,t),a=u(T,t),r=(i=t.targets,(n=y(i)).map(function(t,e){return{target:t,id:e,total:n.length}})),l=[],h=c(o,a);for(e in t)h.hasOwnProperty(e)||"targets"===e||l.push({name:e,offset:h.offset,tweens:k(t[e],a)});return s=l,t=b(d(r.map(function(n){return s.map(function(t){var e=p(n.target,t.name);if(e){var i=E(t,n);t={type:e,property:t.name,animatable:n,tweens:i,duration:i[i.length-1].end,delay:i[0].delay}}else t=void 0;return t})})),function(t){return!B.und(t)}),c(o,{children:[],animatables:r,animations:t,duration:M("duration",t,o,a),delay:M("delay",t,o,a)})}function O(t){function d(){return window.Promise&&new Promise(function(t){return _=t})}function u(t){return k.reversed?k.duration-t:t}function c(e){for(var t=0,i={},n=k.animations,s=n.length;t<s;){var o=n[t],a=o.animatable,r=o.tweens,l=r.length-1,h=r[l];l&&(h=b(r,function(t){return e<t.end})[0]||h);for(var r=Math.min(Math.max(e-h.start-h.delay,0),h.duration)/h.duration,d=isNaN(r)?1:h.easing(r,h.elasticity),r=h.to.strings,u=h.round,l=[],c=void 0,c=h.to.numbers.length,p=0;p<c;p++){var v=void 0,v=h.to.numbers[p],f=h.from.numbers[p],v=h.isPath?C(h.value,d*v):f+d*(v-f);u&&(h.isColor&&2<p||(v=Math.round(v*u)/u)),l.push(v)}if(h=r.length)for(c=r[0],d=0;d<h;d++)u=r[d+1],p=l[d],isNaN(p)||(c=u?c+(p+u):c+(p+" "));else c=l[0];I[o.type](a.target,o.property,c,i,a.id),o.currentValue=c,t++}if(t=Object.keys(i).length)for(n=0;n<t;n++)x||(x=w(document.body,"transform")?"transform":"-webkit-transform"),k.animatables[n].target.style[x]=i[n].join(" ");k.currentTime=e,k.progress=e/k.duration*100}function p(t){k[t]&&k[t](k)}function v(){k.remaining&&!0!==k.remaining&&k.remaining--}function e(t){var e=k.duration,i=k.offset,n=i+k.delay,s=k.currentTime,o=k.reversed,a=u(t);if(k.children.length){var r=k.children,l=r.length;if(a>=k.currentTime)for(var h=0;h<l;h++)r[h].seek(a);else for(;l--;)r[l].seek(a)}(n<=a||!e)&&(k.began||(k.began=!0,p("begin")),p("run")),i<a&&a<e?c(a):(a<=i&&0!==s&&(c(0),o&&v()),(e<=a&&s!==e||!e)&&(c(e),o||v())),p("update"),e<=t&&(k.remaining?(m=f,"alternate"===k.direction&&(k.reversed=!k.reversed)):(k.pause(),k.completed||(k.completed=!0,p("complete"),"Promise"in window&&(_(),y=d()))),g=0)}t=void 0===t?{}:t;var f,m,g=0,_=null,y=d(),k=n(t);return k.reset=function(){var t=k.direction,e=k.loop;for(k.currentTime=0,k.progress=0,k.paused=!0,k.began=!1,k.completed=!1,k.reversed="reverse"===t,k.remaining="alternate"===t&&1===e?2:e,c(0),t=k.children.length;t--;)k.children[t].reset()},k.tick=function(t){f=t,m||(m=f),e((g+f-m)*O.speed)},k.seek=function(t){e(u(t))},k.pause=function(){var t=A.indexOf(k);-1<t&&A.splice(t,1),k.paused=!0},k.play=function(){k.paused&&(k.paused=!1,m=0,g=u(k.currentTime),A.push(k),R||H())},k.reverse=function(){k.reversed=!k.reversed,m=0,g=u(k.currentTime)},k.restart=function(){k.pause(),k.reset(),k.play()},k.finished=y,k.reset(),k.autoplay&&k.play(),k}var x,L={update:void 0,begin:void 0,run:void 0,complete:void 0,loop:1,direction:"normal",autoplay:!0,offset:0},T={duration:1e3,delay:0,easing:"easeOutElastic",elasticity:500,round:0},$="translateX translateY translateZ rotate rotateX rotateY rotateZ scale scaleX scaleY scaleZ skewX skewY perspective".split(" "),B={arr:function(t){return Array.isArray(t)},obj:function(t){return-1<Object.prototype.toString.call(t).indexOf("Object")},pth:function(t){return B.obj(t)&&t.hasOwnProperty("totalLength")},svg:function(t){return t instanceof SVGElement},dom:function(t){return t.nodeType||B.svg(t)},str:function(t){return"string"==typeof t},fnc:function(t){return"function"==typeof t},und:function(t){return void 0===t},hex:function(t){return/(^#[0-9A-F]{6}$)|(^#[0-9A-F]{3}$)/i.test(t)},rgb:function(t){return/^rgb/.test(t)},hsl:function(t){return/^hsl/.test(t)},col:function(t){return B.hex(t)||B.rgb(t)||B.hsl(t)}},D=function(){function u(t,e,i){return(((1-3*i+3*e)*t+(3*i-6*e))*t+3*e)*t}return function(a,r,l,h){if(0<=a&&a<=1&&0<=l&&l<=1){var d=new Float32Array(11);if(a!==r||l!==h)for(var t=0;t<11;++t)d[t]=u(.1*t,a,l);return function(t){if(a===r&&l===h)return t;if(0===t)return 0;if(1===t)return 1;for(var e=0,i=1;10!==i&&d[i]<=t;++i)e+=.1;var i=e+(t-d[--i])/(d[i+1]-d[i])*.1,n=3*(1-3*l+3*a)*i*i+2*(3*l-6*a)*i+3*a;if(.001<=n){for(e=0;e<4&&0!=(n=3*(1-3*l+3*a)*i*i+2*(3*l-6*a)*i+3*a);++e)var s=u(i,a,l)-t,i=i-s/n;t=i}else if(0===n)t=i;else{for(var i=e,e=e+.1,o=0;0<(n=u(s=i+(e-i)/2,a,l)-t)?e=s:i=s,1e-7<Math.abs(n)&&++o<10;);t=s}return u(t,r,h)}}}}(),S=function(){function i(t,e){return 0===t||1===t?t:-Math.pow(2,10*(t-1))*Math.sin(2*(t-1-e/(2*Math.PI)*Math.asin(1))*Math.PI/e)}var t,n="Quad Cubic Quart Quint Sine Expo Circ Back Elastic".split(" "),e={In:[[.55,.085,.68,.53],[.55,.055,.675,.19],[.895,.03,.685,.22],[.755,.05,.855,.06],[.47,0,.745,.715],[.95,.05,.795,.035],[.6,.04,.98,.335],[.6,-.28,.735,.045],i],Out:[[.25,.46,.45,.94],[.215,.61,.355,1],[.165,.84,.44,1],[.23,1,.32,1],[.39,.575,.565,1],[.19,1,.22,1],[.075,.82,.165,1],[.175,.885,.32,1.275],function(t,e){return 1-i(1-t,e)}],InOut:[[.455,.03,.515,.955],[.645,.045,.355,1],[.77,0,.175,1],[.86,0,.07,1],[.445,.05,.55,.95],[1,0,0,1],[.785,.135,.15,.86],[.68,-.55,.265,1.55],function(t,e){return t<.5?i(2*t,e)/2:1-i(-2*t+2,e)/2}]},s={linear:D(.25,.25,.75,.75)},o={};for(t in e)o.type=t,e[o.type].forEach(function(i){return function(t,e){s["ease"+i.type+n[e]]=B.fnc(t)?t:D.apply($jscomp$this,t)}}(o)),o={type:o.type};return s}(),I={css:function(t,e,i){return t.style[e]=i},attribute:function(t,e,i){return t.setAttribute(e,i)},object:function(t,e,i){return t[e]=i},transform:function(t,e,i,n,s){n[s]||(n[s]=[]),n[s].push(e+"("+i+")")}},A=[],R=0,H=function(){function n(){R=requestAnimationFrame(t)}function t(t){var e=A.length;if(e){for(var i=0;i<e;)A[i]&&A[i].tick(t),i++;n()}else cancelAnimationFrame(R),R=0}return n}();return O.version="2.2.0",O.speed=1,O.running=A,O.remove=function(t){t=y(t);for(var e=A.length;e--;)for(var i=A[e],n=i.animations,s=n.length;s--;)a(t,n[s].animatable.target)&&(n.splice(s,1),n.length||i.pause())},O.getValue=v,O.path=function(t,e){var i=B.str(t)?s(t)[0]:t,n=e||100;return function(t){return{el:i,property:t,totalLength:g(i)*(n/100)}}},O.setDashoffset=function(t){var e=g(t);return t.setAttribute("stroke-dasharray",e),e},O.bezier=D,O.easings=S,O.timeline=function(n){var s=O(n);return s.pause(),s.duration=0,s.add=function(t){return s.children.forEach(function(t){t.began=!0,t.completed=!0}),o(t).forEach(function(t){var e=c(t,u(T,n||{}));e.targets=e.targets||n.targets,t=s.duration;var i=e.offset;e.autoplay=!1,e.direction=s.direction,e.offset=B.und(i)?t:f(i,t),s.began=!0,s.completed=!0,s.seek(e.offset),(e=O(e)).began=!0,e.completed=!0,e.duration>t&&(s.duration=e.duration),s.children.push(e)}),s.seek(0),s.reset(),s.autoplay&&s.restart(),s},s},O.random=function(t,e){return Math.floor(Math.random()*(e-t+1))+t},O}(),function(r,l){"use strict";var e={accordion:!0,onOpenStart:void 0,onOpenEnd:void 0,onCloseStart:void 0,onCloseEnd:void 0,inDuration:300,outDuration:300},t=function(t){function s(t,e){_classCallCheck(this,s);var i=_possibleConstructorReturn(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,s,t,e));(i.el.M_Collapsible=i).options=r.extend({},s.defaults,e),i.$headers=i.$el.children("li").children(".collapsible-header"),i.$headers.attr("tabindex",0),i._setupEventHandlers();var n=i.$el.children("li.active").children(".collapsible-body");return i.options.accordion?n.first().css("display","block"):n.css("display","block"),i}return _inherits(s,Component),_createClass(s,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.M_Collapsible=void 0}},{key:"_setupEventHandlers",value:function(){var e=this;this._handleCollapsibleClickBound=this._handleCollapsibleClick.bind(this),this._handleCollapsibleKeydownBound=this._handleCollapsibleKeydown.bind(this),this.el.addEventListener("click",this._handleCollapsibleClickBound),this.$headers.each(function(t){t.addEventListener("keydown",e._handleCollapsibleKeydownBound)})}},{key:"_removeEventHandlers",value:function(){var e=this;this.el.removeEventListener("click",this._handleCollapsibleClickBound),this.$headers.each(function(t){t.removeEventListener("keydown",e._handleCollapsibleKeydownBound)})}},{key:"_handleCollapsibleClick",value:function(t){var e=r(t.target).closest(".collapsible-header");if(t.target&&e.length){var i=e.closest(".collapsible");if(i[0]===this.el){var n=e.closest("li"),s=i.children("li"),o=n[0].classList.contains("active"),a=s.index(n);o?this.close(a):this.open(a)}}}},{key:"_handleCollapsibleKeydown",value:function(t){13===t.keyCode&&this._handleCollapsibleClickBound(t)}},{key:"_animateIn",value:function(t){var e=this,i=this.$el.children("li").eq(t);if(i.length){var n=i.children(".collapsible-body");l.remove(n[0]),n.css({display:"block",overflow:"hidden",height:0,paddingTop:"",paddingBottom:""});var s=n.css("padding-top"),o=n.css("padding-bottom"),a=n[0].scrollHeight;n.css({paddingTop:0,paddingBottom:0}),l({targets:n[0],height:a,paddingTop:s,paddingBottom:o,duration:this.options.inDuration,easing:"easeInOutCubic",complete:function(t){n.css({overflow:"",paddingTop:"",paddingBottom:"",height:""}),"function"==typeof e.options.onOpenEnd&&e.options.onOpenEnd.call(e,i[0])}})}}},{key:"_animateOut",value:function(t){var e=this,i=this.$el.children("li").eq(t);if(i.length){var n=i.children(".collapsible-body");l.remove(n[0]),n.css("overflow","hidden"),l({targets:n[0],height:0,paddingTop:0,paddingBottom:0,duration:this.options.outDuration,easing:"easeInOutCubic",complete:function(){n.css({height:"",overflow:"",padding:"",display:""}),"function"==typeof e.options.onCloseEnd&&e.options.onCloseEnd.call(e,i[0])}})}}},{key:"open",value:function(t){var i=this,e=this.$el.children("li").eq(t);if(e.length&&!e[0].classList.contains("active")){if("function"==typeof this.options.onOpenStart&&this.options.onOpenStart.call(this,e[0]),this.options.accordion){var n=this.$el.children("li");this.$el.children("li.active").each(function(t){var e=n.index(r(t));i.close(e)})}e[0].classList.add("active"),this._animateIn(t)}}},{key:"close",value:function(t){var e=this.$el.children("li").eq(t);e.length&&e[0].classList.contains("active")&&("function"==typeof this.options.onCloseStart&&this.options.onCloseStart.call(this,e[0]),e[0].classList.remove("active"),this._animateOut(t))}}],[{key:"init",value:function(t,e){return _get(s.__proto__||Object.getPrototypeOf(s),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Collapsible}},{key:"defaults",get:function(){return e}}]),s}();M.Collapsible=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"collapsible","M_Collapsible")}(cash,M.anime),function(h,i){"use strict";var e={alignment:"left",autoFocus:!0,constrainWidth:!0,container:null,coverTrigger:!0,closeOnClick:!0,hover:!1,inDuration:150,outDuration:250,onOpenStart:null,onOpenEnd:null,onCloseStart:null,onCloseEnd:null,onItemClick:null},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return i.el.M_Dropdown=i,n._dropdowns.push(i),i.id=M.getIdFromTrigger(t),i.dropdownEl=document.getElementById(i.id),i.$dropdownEl=h(i.dropdownEl),i.options=h.extend({},n.defaults,e),i.isOpen=!1,i.isScrollable=!1,i.isTouchMoving=!1,i.focusedIndex=-1,i.filterQuery=[],i.options.container?h(i.options.container).append(i.dropdownEl):i.$el.after(i.dropdownEl),i._makeDropdownFocusable(),i._resetFilterQueryBound=i._resetFilterQuery.bind(i),i._handleDocumentClickBound=i._handleDocumentClick.bind(i),i._handleDocumentTouchmoveBound=i._handleDocumentTouchmove.bind(i),i._handleDropdownClickBound=i._handleDropdownClick.bind(i),i._handleDropdownKeydownBound=i._handleDropdownKeydown.bind(i),i._handleTriggerKeydownBound=i._handleTriggerKeydown.bind(i),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._resetDropdownStyles(),this._removeEventHandlers(),n._dropdowns.splice(n._dropdowns.indexOf(this),1),this.el.M_Dropdown=void 0}},{key:"_setupEventHandlers",value:function(){this.el.addEventListener("keydown",this._handleTriggerKeydownBound),this.dropdownEl.addEventListener("click",this._handleDropdownClickBound),this.options.hover?(this._handleMouseEnterBound=this._handleMouseEnter.bind(this),this.el.addEventListener("mouseenter",this._handleMouseEnterBound),this._handleMouseLeaveBound=this._handleMouseLeave.bind(this),this.el.addEventListener("mouseleave",this._handleMouseLeaveBound),this.dropdownEl.addEventListener("mouseleave",this._handleMouseLeaveBound)):(this._handleClickBound=this._handleClick.bind(this),this.el.addEventListener("click",this._handleClickBound))}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("keydown",this._handleTriggerKeydownBound),this.dropdownEl.removeEventListener("click",this._handleDropdownClickBound),this.options.hover?(this.el.removeEventListener("mouseenter",this._handleMouseEnterBound),this.el.removeEventListener("mouseleave",this._handleMouseLeaveBound),this.dropdownEl.removeEventListener("mouseleave",this._handleMouseLeaveBound)):this.el.removeEventListener("click",this._handleClickBound)}},{key:"_setupTemporaryEventHandlers",value:function(){document.body.addEventListener("click",this._handleDocumentClickBound,!0),document.body.addEventListener("touchend",this._handleDocumentClickBound),document.body.addEventListener("touchmove",this._handleDocumentTouchmoveBound),this.dropdownEl.addEventListener("keydown",this._handleDropdownKeydownBound)}},{key:"_removeTemporaryEventHandlers",value:function(){document.body.removeEventListener("click",this._handleDocumentClickBound,!0),document.body.removeEventListener("touchend",this._handleDocumentClickBound),document.body.removeEventListener("touchmove",this._handleDocumentTouchmoveBound),this.dropdownEl.removeEventListener("keydown",this._handleDropdownKeydownBound)}},{key:"_handleClick",value:function(t){t.preventDefault(),this.open()}},{key:"_handleMouseEnter",value:function(){this.open()}},{key:"_handleMouseLeave",value:function(t){var e=t.toElement||t.relatedTarget,i=!!h(e).closest(".dropdown-content").length,n=!1,s=h(e).closest(".dropdown-trigger");s.length&&s[0].M_Dropdown&&s[0].M_Dropdown.isOpen&&(n=!0),n||i||this.close()}},{key:"_handleDocumentClick",value:function(t){var e=this,i=h(t.target);this.options.closeOnClick&&i.closest(".dropdown-content").length&&!this.isTouchMoving?setTimeout(function(){e.close()},0):!i.closest(".dropdown-trigger").length&&i.closest(".dropdown-content").length||setTimeout(function(){e.close()},0),this.isTouchMoving=!1}},{key:"_handleTriggerKeydown",value:function(t){t.which!==M.keys.ARROW_DOWN&&t.which!==M.keys.ENTER||this.isOpen||(t.preventDefault(),this.open())}},{key:"_handleDocumentTouchmove",value:function(t){h(t.target).closest(".dropdown-content").length&&(this.isTouchMoving=!0)}},{key:"_handleDropdownClick",value:function(t){if("function"==typeof this.options.onItemClick){var e=h(t.target).closest("li")[0];this.options.onItemClick.call(this,e)}}},{key:"_handleDropdownKeydown",value:function(t){if(t.which===M.keys.TAB)t.preventDefault(),this.close();else if(t.which!==M.keys.ARROW_DOWN&&t.which!==M.keys.ARROW_UP||!this.isOpen)if(t.which===M.keys.ENTER&&this.isOpen){var e=this.dropdownEl.children[this.focusedIndex],i=h(e).find("a, button").first();i.length?i[0].click():e&&e.click()}else t.which===M.keys.ESC&&this.isOpen&&(t.preventDefault(),this.close());else{t.preventDefault();var n=t.which===M.keys.ARROW_DOWN?1:-1,s=this.focusedIndex,o=!1;do{if(s+=n,this.dropdownEl.children[s]&&-1!==this.dropdownEl.children[s].tabIndex){o=!0;break}}while(s<this.dropdownEl.children.length&&0<=s);o&&(this.focusedIndex=s,this._focusFocusedItem())}var a=String.fromCharCode(t.which).toLowerCase();if(a&&-1===[9,13,27,38,40].indexOf(t.which)){this.filterQuery.push(a);var r=this.filterQuery.join(""),l=h(this.dropdownEl).find("li").filter(function(t){return 0===h(t).text().toLowerCase().indexOf(r)})[0];l&&(this.focusedIndex=h(l).index(),this._focusFocusedItem())}this.filterTimeout=setTimeout(this._resetFilterQueryBound,1e3)}},{key:"_resetFilterQuery",value:function(){this.filterQuery=[]}},{key:"_resetDropdownStyles",value:function(){this.$dropdownEl.css({display:"",width:"",height:"",left:"",top:"","transform-origin":"",transform:"",opacity:""})}},{key:"_makeDropdownFocusable",value:function(){this.dropdownEl.tabIndex=0,h(this.dropdownEl).children().each(function(t){t.getAttribute("tabindex")||t.setAttribute("tabindex",0)})}},{key:"_focusFocusedItem",value:function(){0<=this.focusedIndex&&this.focusedIndex<this.dropdownEl.children.length&&this.options.autoFocus&&this.dropdownEl.children[this.focusedIndex].focus()}},{key:"_getDropdownPosition",value:function(){this.el.offsetParent.getBoundingClientRect();var t=this.el.getBoundingClientRect(),e=this.dropdownEl.getBoundingClientRect(),i=e.height,n=e.width,s=t.left-e.left,o=t.top-e.top,a={left:s,top:o,height:i,width:n},r=this.dropdownEl.offsetParent?this.dropdownEl.offsetParent:this.dropdownEl.parentNode,l=M.checkPossibleAlignments(this.el,r,a,this.options.coverTrigger?0:t.height),h="top",d=this.options.alignment;if(o+=this.options.coverTrigger?0:t.height,this.isScrollable=!1,l.top||(l.bottom?h="bottom":(this.isScrollable=!0,l.spaceOnTop>l.spaceOnBottom?(h="bottom",i+=l.spaceOnTop,o-=l.spaceOnTop):i+=l.spaceOnBottom)),!l[d]){var u="left"===d?"right":"left";l[u]?d=u:l.spaceOnLeft>l.spaceOnRight?(d="right",n+=l.spaceOnLeft,s-=l.spaceOnLeft):(d="left",n+=l.spaceOnRight)}return"bottom"===h&&(o=o-e.height+(this.options.coverTrigger?t.height:0)),"right"===d&&(s=s-e.width+t.width),{x:s,y:o,verticalAlignment:h,horizontalAlignment:d,height:i,width:n}}},{key:"_animateIn",value:function(){var e=this;i.remove(this.dropdownEl),i({targets:this.dropdownEl,opacity:{value:[0,1],easing:"easeOutQuad"},scaleX:[.3,1],scaleY:[.3,1],duration:this.options.inDuration,easing:"easeOutQuint",complete:function(t){e.options.autoFocus&&e.dropdownEl.focus(),"function"==typeof e.options.onOpenEnd&&e.options.onOpenEnd.call(e,e.el)}})}},{key:"_animateOut",value:function(){var e=this;i.remove(this.dropdownEl),i({targets:this.dropdownEl,opacity:{value:0,easing:"easeOutQuint"},scaleX:.3,scaleY:.3,duration:this.options.outDuration,easing:"easeOutQuint",complete:function(t){e._resetDropdownStyles(),"function"==typeof e.options.onCloseEnd&&e.options.onCloseEnd.call(e,e.el)}})}},{key:"_placeDropdown",value:function(){var t=this.options.constrainWidth?this.el.getBoundingClientRect().width:this.dropdownEl.getBoundingClientRect().width;this.dropdownEl.style.width=t+"px";var e=this._getDropdownPosition();this.dropdownEl.style.left=e.x+"px",this.dropdownEl.style.top=e.y+"px",this.dropdownEl.style.height=e.height+"px",this.dropdownEl.style.width=e.width+"px",this.dropdownEl.style.transformOrigin=("left"===e.horizontalAlignment?"0":"100%")+" "+("top"===e.verticalAlignment?"0":"100%")}},{key:"open",value:function(){this.isOpen||(this.isOpen=!0,"function"==typeof this.options.onOpenStart&&this.options.onOpenStart.call(this,this.el),this._resetDropdownStyles(),this.dropdownEl.style.display="block",this._placeDropdown(),this._animateIn(),this._setupTemporaryEventHandlers())}},{key:"close",value:function(){this.isOpen&&(this.isOpen=!1,this.focusedIndex=-1,"function"==typeof this.options.onCloseStart&&this.options.onCloseStart.call(this,this.el),this._animateOut(),this._removeTemporaryEventHandlers(),this.options.autoFocus&&this.el.focus())}},{key:"recalculateDimensions",value:function(){this.isOpen&&(this.$dropdownEl.css({width:"",height:"",left:"",top:"","transform-origin":""}),this._placeDropdown())}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Dropdown}},{key:"defaults",get:function(){return e}}]),n}();t._dropdowns=[],M.Dropdown=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"dropdown","M_Dropdown")}(cash,M.anime),function(s,i){"use strict";var e={opacity:.5,inDuration:250,outDuration:250,onOpenStart:null,onOpenEnd:null,onCloseStart:null,onCloseEnd:null,preventScrolling:!0,dismissible:!0,startingTop:"4%",endingTop:"10%"},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Modal=i).options=s.extend({},n.defaults,e),i.isOpen=!1,i.id=i.$el.attr("id"),i._openingTrigger=void 0,i.$overlay=s('<div class="modal-overlay"></div>'),i.el.tabIndex=0,i._nthModalOpened=0,n._count++,i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){n._count--,this._removeEventHandlers(),this.el.removeAttribute("style"),this.$overlay.remove(),this.el.M_Modal=void 0}},{key:"_setupEventHandlers",value:function(){this._handleOverlayClickBound=this._handleOverlayClick.bind(this),this._handleModalCloseClickBound=this._handleModalCloseClick.bind(this),1===n._count&&document.body.addEventListener("click",this._handleTriggerClick),this.$overlay[0].addEventListener("click",this._handleOverlayClickBound),this.el.addEventListener("click",this._handleModalCloseClickBound)}},{key:"_removeEventHandlers",value:function(){0===n._count&&document.body.removeEventListener("click",this._handleTriggerClick),this.$overlay[0].removeEventListener("click",this._handleOverlayClickBound),this.el.removeEventListener("click",this._handleModalCloseClickBound)}},{key:"_handleTriggerClick",value:function(t){var e=s(t.target).closest(".modal-trigger");if(e.length){var i=M.getIdFromTrigger(e[0]),n=document.getElementById(i).M_Modal;n&&n.open(e),t.preventDefault()}}},{key:"_handleOverlayClick",value:function(){this.options.dismissible&&this.close()}},{key:"_handleModalCloseClick",value:function(t){s(t.target).closest(".modal-close").length&&this.close()}},{key:"_handleKeydown",value:function(t){27===t.keyCode&&this.options.dismissible&&this.close()}},{key:"_handleFocus",value:function(t){this.el.contains(t.target)||this._nthModalOpened!==n._modalsOpen||this.el.focus()}},{key:"_animateIn",value:function(){var t=this;s.extend(this.el.style,{display:"block",opacity:0}),s.extend(this.$overlay[0].style,{display:"block",opacity:0}),i({targets:this.$overlay[0],opacity:this.options.opacity,duration:this.options.inDuration,easing:"easeOutQuad"});var e={targets:this.el,duration:this.options.inDuration,easing:"easeOutCubic",complete:function(){"function"==typeof t.options.onOpenEnd&&t.options.onOpenEnd.call(t,t.el,t._openingTrigger)}};this.el.classList.contains("bottom-sheet")?s.extend(e,{bottom:0,opacity:1}):s.extend(e,{top:[this.options.startingTop,this.options.endingTop],opacity:1,scaleX:[.8,1],scaleY:[.8,1]}),i(e)}},{key:"_animateOut",value:function(){var t=this;i({targets:this.$overlay[0],opacity:0,duration:this.options.outDuration,easing:"easeOutQuart"});var e={targets:this.el,duration:this.options.outDuration,easing:"easeOutCubic",complete:function(){t.el.style.display="none",t.$overlay.remove(),"function"==typeof t.options.onCloseEnd&&t.options.onCloseEnd.call(t,t.el)}};this.el.classList.contains("bottom-sheet")?s.extend(e,{bottom:"-100%",opacity:0}):s.extend(e,{top:[this.options.endingTop,this.options.startingTop],opacity:0,scaleX:.8,scaleY:.8}),i(e)}},{key:"open",value:function(t){if(!this.isOpen)return this.isOpen=!0,n._modalsOpen++,this._nthModalOpened=n._modalsOpen,this.$overlay[0].style.zIndex=1e3+2*n._modalsOpen,this.el.style.zIndex=1e3+2*n._modalsOpen+1,this._openingTrigger=t?t[0]:void 0,"function"==typeof this.options.onOpenStart&&this.options.onOpenStart.call(this,this.el,this._openingTrigger),this.options.preventScrolling&&(document.body.style.overflow="hidden"),this.el.classList.add("open"),this.el.insertAdjacentElement("afterend",this.$overlay[0]),this.options.dismissible&&(this._handleKeydownBound=this._handleKeydown.bind(this),this._handleFocusBound=this._handleFocus.bind(this),document.addEventListener("keydown",this._handleKeydownBound),document.addEventListener("focus",this._handleFocusBound,!0)),i.remove(this.el),i.remove(this.$overlay[0]),this._animateIn(),this.el.focus(),this}},{key:"close",value:function(){if(this.isOpen)return this.isOpen=!1,n._modalsOpen--,this._nthModalOpened=0,"function"==typeof this.options.onCloseStart&&this.options.onCloseStart.call(this,this.el),this.el.classList.remove("open"),0===n._modalsOpen&&(document.body.style.overflow=""),this.options.dismissible&&(document.removeEventListener("keydown",this._handleKeydownBound),document.removeEventListener("focus",this._handleFocusBound,!0)),i.remove(this.el),i.remove(this.$overlay[0]),this._animateOut(),this}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Modal}},{key:"defaults",get:function(){return e}}]),n}();t._modalsOpen=0,t._count=0,M.Modal=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"modal","M_Modal")}(cash,M.anime),function(o,a){"use strict";var e={inDuration:275,outDuration:200,onOpenStart:null,onOpenEnd:null,onCloseStart:null,onCloseEnd:null},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Materialbox=i).options=o.extend({},n.defaults,e),i.overlayActive=!1,i.doneAnimating=!0,i.placeholder=o("<div></div>").addClass("material-placeholder"),i.originalWidth=0,i.originalHeight=0,i.originInlineStyles=i.$el.attr("style"),i.caption=i.el.getAttribute("data-caption")||"",i.$el.before(i.placeholder),i.placeholder.append(i.$el),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.M_Materialbox=void 0,o(this.placeholder).after(this.el).remove(),this.$el.removeAttr("style")}},{key:"_setupEventHandlers",value:function(){this._handleMaterialboxClickBound=this._handleMaterialboxClick.bind(this),this.el.addEventListener("click",this._handleMaterialboxClickBound)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("click",this._handleMaterialboxClickBound)}},{key:"_handleMaterialboxClick",value:function(t){!1===this.doneAnimating||this.overlayActive&&this.doneAnimating?this.close():this.open()}},{key:"_handleWindowScroll",value:function(){this.overlayActive&&this.close()}},{key:"_handleWindowResize",value:function(){this.overlayActive&&this.close()}},{key:"_handleWindowEscape",value:function(t){27===t.keyCode&&this.doneAnimating&&this.overlayActive&&this.close()}},{key:"_makeAncestorsOverflowVisible",value:function(){this.ancestorsChanged=o();for(var t=this.placeholder[0].parentNode;null!==t&&!o(t).is(document);){var e=o(t);"visible"!==e.css("overflow")&&(e.css("overflow","visible"),void 0===this.ancestorsChanged?this.ancestorsChanged=e:this.ancestorsChanged=this.ancestorsChanged.add(e)),t=t.parentNode}}},{key:"_animateImageIn",value:function(){var t=this,e={targets:this.el,height:[this.originalHeight,this.newHeight],width:[this.originalWidth,this.newWidth],left:M.getDocumentScrollLeft()+this.windowWidth/2-this.placeholder.offset().left-this.newWidth/2,top:M.getDocumentScrollTop()+this.windowHeight/2-this.placeholder.offset().top-this.newHeight/2,duration:this.options.inDuration,easing:"easeOutQuad",complete:function(){t.doneAnimating=!0,"function"==typeof t.options.onOpenEnd&&t.options.onOpenEnd.call(t,t.el)}};this.maxWidth=this.$el.css("max-width"),this.maxHeight=this.$el.css("max-height"),"none"!==this.maxWidth&&(e.maxWidth=this.newWidth),"none"!==this.maxHeight&&(e.maxHeight=this.newHeight),a(e)}},{key:"_animateImageOut",value:function(){var t=this,e={targets:this.el,width:this.originalWidth,height:this.originalHeight,left:0,top:0,duration:this.options.outDuration,easing:"easeOutQuad",complete:function(){t.placeholder.css({height:"",width:"",position:"",top:"",left:""}),t.attrWidth&&t.$el.attr("width",t.attrWidth),t.attrHeight&&t.$el.attr("height",t.attrHeight),t.$el.removeAttr("style"),t.originInlineStyles&&t.$el.attr("style",t.originInlineStyles),t.$el.removeClass("active"),t.doneAnimating=!0,t.ancestorsChanged.length&&t.ancestorsChanged.css("overflow",""),"function"==typeof t.options.onCloseEnd&&t.options.onCloseEnd.call(t,t.el)}};a(e)}},{key:"_updateVars",value:function(){this.windowWidth=window.innerWidth,this.windowHeight=window.innerHeight,this.caption=this.el.getAttribute("data-caption")||""}},{key:"open",value:function(){var t=this;this._updateVars(),this.originalWidth=this.el.getBoundingClientRect().width,this.originalHeight=this.el.getBoundingClientRect().height,this.doneAnimating=!1,this.$el.addClass("active"),this.overlayActive=!0,"function"==typeof this.options.onOpenStart&&this.options.onOpenStart.call(this,this.el),this.placeholder.css({width:this.placeholder[0].getBoundingClientRect().width+"px",height:this.placeholder[0].getBoundingClientRect().height+"px",position:"relative",top:0,left:0}),this._makeAncestorsOverflowVisible(),this.$el.css({position:"absolute","z-index":1e3,"will-change":"left, top, width, height"}),this.attrWidth=this.$el.attr("width"),this.attrHeight=this.$el.attr("height"),this.attrWidth&&(this.$el.css("width",this.attrWidth+"px"),this.$el.removeAttr("width")),this.attrHeight&&(this.$el.css("width",this.attrHeight+"px"),this.$el.removeAttr("height")),this.$overlay=o('<div id="materialbox-overlay"></div>').css({opacity:0}).one("click",function(){t.doneAnimating&&t.close()}),this.$el.before(this.$overlay);var e=this.$overlay[0].getBoundingClientRect();this.$overlay.css({width:this.windowWidth+"px",height:this.windowHeight+"px",left:-1*e.left+"px",top:-1*e.top+"px"}),a.remove(this.el),a.remove(this.$overlay[0]),a({targets:this.$overlay[0],opacity:1,duration:this.options.inDuration,easing:"easeOutQuad"}),""!==this.caption&&(this.$photocaption&&a.remove(this.$photoCaption[0]),this.$photoCaption=o('<div class="materialbox-caption"></div>'),this.$photoCaption.text(this.caption),o("body").append(this.$photoCaption),this.$photoCaption.css({display:"inline"}),a({targets:this.$photoCaption[0],opacity:1,duration:this.options.inDuration,easing:"easeOutQuad"}));var i=0,n=this.originalWidth/this.windowWidth,s=this.originalHeight/this.windowHeight;this.newWidth=0,this.newHeight=0,s<n?(i=this.originalHeight/this.originalWidth,this.newWidth=.9*this.windowWidth,this.newHeight=.9*this.windowWidth*i):(i=this.originalWidth/this.originalHeight,this.newWidth=.9*this.windowHeight*i,this.newHeight=.9*this.windowHeight),this._animateImageIn(),this._handleWindowScrollBound=this._handleWindowScroll.bind(this),this._handleWindowResizeBound=this._handleWindowResize.bind(this),this._handleWindowEscapeBound=this._handleWindowEscape.bind(this),window.addEventListener("scroll",this._handleWindowScrollBound),window.addEventListener("resize",this._handleWindowResizeBound),window.addEventListener("keyup",this._handleWindowEscapeBound)}},{key:"close",value:function(){var t=this;this._updateVars(),this.doneAnimating=!1,"function"==typeof this.options.onCloseStart&&this.options.onCloseStart.call(this,this.el),a.remove(this.el),a.remove(this.$overlay[0]),""!==this.caption&&a.remove(this.$photoCaption[0]),window.removeEventListener("scroll",this._handleWindowScrollBound),window.removeEventListener("resize",this._handleWindowResizeBound),window.removeEventListener("keyup",this._handleWindowEscapeBound),a({targets:this.$overlay[0],opacity:0,duration:this.options.outDuration,easing:"easeOutQuad",complete:function(){t.overlayActive=!1,t.$overlay.remove()}}),this._animateImageOut(),""!==this.caption&&a({targets:this.$photoCaption[0],opacity:0,duration:this.options.outDuration,easing:"easeOutQuad",complete:function(){t.$photoCaption.remove()}})}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Materialbox}},{key:"defaults",get:function(){return e}}]),n}();M.Materialbox=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"materialbox","M_Materialbox")}(cash,M.anime),function(s){"use strict";var e={responsiveThreshold:0},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Parallax=i).options=s.extend({},n.defaults,e),i._enabled=window.innerWidth>i.options.responsiveThreshold,i.$img=i.$el.find("img").first(),i.$img.each(function(){this.complete&&s(this).trigger("load")}),i._updateParallax(),i._setupEventHandlers(),i._setupStyles(),n._parallaxes.push(i),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){n._parallaxes.splice(n._parallaxes.indexOf(this),1),this.$img[0].style.transform="",this._removeEventHandlers(),this.$el[0].M_Parallax=void 0}},{key:"_setupEventHandlers",value:function(){this._handleImageLoadBound=this._handleImageLoad.bind(this),this.$img[0].addEventListener("load",this._handleImageLoadBound),0===n._parallaxes.length&&(n._handleScrollThrottled=M.throttle(n._handleScroll,5),window.addEventListener("scroll",n._handleScrollThrottled),n._handleWindowResizeThrottled=M.throttle(n._handleWindowResize,5),window.addEventListener("resize",n._handleWindowResizeThrottled))}},{key:"_removeEventHandlers",value:function(){this.$img[0].removeEventListener("load",this._handleImageLoadBound),0===n._parallaxes.length&&(window.removeEventListener("scroll",n._handleScrollThrottled),window.removeEventListener("resize",n._handleWindowResizeThrottled))}},{key:"_setupStyles",value:function(){this.$img[0].style.opacity=1}},{key:"_handleImageLoad",value:function(){this._updateParallax()}},{key:"_updateParallax",value:function(){var t=0<this.$el.height()?this.el.parentNode.offsetHeight:500,e=this.$img[0].offsetHeight-t,i=this.$el.offset().top+t,n=this.$el.offset().top,s=M.getDocumentScrollTop(),o=window.innerHeight,a=e*((s+o-n)/(t+o));this._enabled?s<i&&n<s+o&&(this.$img[0].style.transform="translate3D(-50%, "+a+"px, 0)"):this.$img[0].style.transform=""}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Parallax}},{key:"_handleScroll",value:function(){for(var t=0;t<n._parallaxes.length;t++){var e=n._parallaxes[t];e._updateParallax.call(e)}}},{key:"_handleWindowResize",value:function(){for(var t=0;t<n._parallaxes.length;t++){var e=n._parallaxes[t];e._enabled=window.innerWidth>e.options.responsiveThreshold}}},{key:"defaults",get:function(){return e}}]),n}();t._parallaxes=[],M.Parallax=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"parallax","M_Parallax")}(cash),function(a,s){"use strict";var e={duration:300,onShow:null,swipeable:!1,responsiveThreshold:1/0},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Tabs=i).options=a.extend({},n.defaults,e),i.$tabLinks=i.$el.children("li.tab").children("a"),i.index=0,i._setupActiveTabLink(),i.options.swipeable?i._setupSwipeableTabs():i._setupNormalTabs(),i._setTabsAndTabWidth(),i._createIndicator(),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this._indicator.parentNode.removeChild(this._indicator),this.options.swipeable?this._teardownSwipeableTabs():this._teardownNormalTabs(),this.$el[0].M_Tabs=void 0}},{key:"_setupEventHandlers",value:function(){this._handleWindowResizeBound=this._handleWindowResize.bind(this),window.addEventListener("resize",this._handleWindowResizeBound),this._handleTabClickBound=this._handleTabClick.bind(this),this.el.addEventListener("click",this._handleTabClickBound)}},{key:"_removeEventHandlers",value:function(){window.removeEventListener("resize",this._handleWindowResizeBound),this.el.removeEventListener("click",this._handleTabClickBound)}},{key:"_handleWindowResize",value:function(){this._setTabsAndTabWidth(),0!==this.tabWidth&&0!==this.tabsWidth&&(this._indicator.style.left=this._calcLeftPos(this.$activeTabLink)+"px",this._indicator.style.right=this._calcRightPos(this.$activeTabLink)+"px")}},{key:"_handleTabClick",value:function(t){var e=this,i=a(t.target).closest("li.tab"),n=a(t.target).closest("a");if(n.length&&n.parent().hasClass("tab"))if(i.hasClass("disabled"))t.preventDefault();else if(!n.attr("target")){this.$activeTabLink.removeClass("active");var s=this.$content;this.$activeTabLink=n,this.$content=a(M.escapeHash(n[0].hash)),this.$tabLinks=this.$el.children("li.tab").children("a"),this.$activeTabLink.addClass("active");var o=this.index;this.index=Math.max(this.$tabLinks.index(n),0),this.options.swipeable?this._tabsCarousel&&this._tabsCarousel.set(this.index,function(){"function"==typeof e.options.onShow&&e.options.onShow.call(e,e.$content[0])}):this.$content.length&&(this.$content[0].style.display="block",this.$content.addClass("active"),"function"==typeof this.options.onShow&&this.options.onShow.call(this,this.$content[0]),s.length&&!s.is(this.$content)&&(s[0].style.display="none",s.removeClass("active"))),this._setTabsAndTabWidth(),this._animateIndicator(o),t.preventDefault()}}},{key:"_createIndicator",value:function(){var t=this,e=document.createElement("li");e.classList.add("indicator"),this.el.appendChild(e),this._indicator=e,setTimeout(function(){t._indicator.style.left=t._calcLeftPos(t.$activeTabLink)+"px",t._indicator.style.right=t._calcRightPos(t.$activeTabLink)+"px"},0)}},{key:"_setupActiveTabLink",value:function(){this.$activeTabLink=a(this.$tabLinks.filter('[href="'+location.hash+'"]')),0===this.$activeTabLink.length&&(this.$activeTabLink=this.$el.children("li.tab").children("a.active").first()),0===this.$activeTabLink.length&&(this.$activeTabLink=this.$el.children("li.tab").children("a").first()),this.$tabLinks.removeClass("active"),this.$activeTabLink[0].classList.add("active"),this.index=Math.max(this.$tabLinks.index(this.$activeTabLink),0),this.$activeTabLink.length&&(this.$content=a(M.escapeHash(this.$activeTabLink[0].hash)),this.$content.addClass("active"))}},{key:"_setupSwipeableTabs",value:function(){var i=this;window.innerWidth>this.options.responsiveThreshold&&(this.options.swipeable=!1);var n=a();this.$tabLinks.each(function(t){var e=a(M.escapeHash(t.hash));e.addClass("carousel-item"),n=n.add(e)});var t=a('<div class="tabs-content carousel carousel-slider"></div>');n.first().before(t),t.append(n),n[0].style.display="";var e=this.$activeTabLink.closest(".tab").index();this._tabsCarousel=M.Carousel.init(t[0],{fullWidth:!0,noWrap:!0,onCycleTo:function(t){var e=i.index;i.index=a(t).index(),i.$activeTabLink.removeClass("active"),i.$activeTabLink=i.$tabLinks.eq(i.index),i.$activeTabLink.addClass("active"),i._animateIndicator(e),"function"==typeof i.options.onShow&&i.options.onShow.call(i,i.$content[0])}}),this._tabsCarousel.set(e)}},{key:"_teardownSwipeableTabs",value:function(){var t=this._tabsCarousel.$el;this._tabsCarousel.destroy(),t.after(t.children()),t.remove()}},{key:"_setupNormalTabs",value:function(){this.$tabLinks.not(this.$activeTabLink).each(function(t){if(t.hash){var e=a(M.escapeHash(t.hash));e.length&&(e[0].style.display="none")}})}},{key:"_teardownNormalTabs",value:function(){this.$tabLinks.each(function(t){if(t.hash){var e=a(M.escapeHash(t.hash));e.length&&(e[0].style.display="")}})}},{key:"_setTabsAndTabWidth",value:function(){this.tabsWidth=this.$el.width(),this.tabWidth=Math.max(this.tabsWidth,this.el.scrollWidth)/this.$tabLinks.length}},{key:"_calcRightPos",value:function(t){return Math.ceil(this.tabsWidth-t.position().left-t[0].getBoundingClientRect().width)}},{key:"_calcLeftPos",value:function(t){return Math.floor(t.position().left)}},{key:"updateTabIndicator",value:function(){this._setTabsAndTabWidth(),this._animateIndicator(this.index)}},{key:"_animateIndicator",value:function(t){var e=0,i=0;0<=this.index-t?e=90:i=90;var n={targets:this._indicator,left:{value:this._calcLeftPos(this.$activeTabLink),delay:e},right:{value:this._calcRightPos(this.$activeTabLink),delay:i},duration:this.options.duration,easing:"easeOutQuad"};s.remove(this._indicator),s(n)}},{key:"select",value:function(t){var e=this.$tabLinks.filter('[href="#'+t+'"]');e.length&&e.trigger("click")}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Tabs}},{key:"defaults",get:function(){return e}}]),n}();M.Tabs=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"tabs","M_Tabs")}(cash,M.anime),function(d,e){"use strict";var i={exitDelay:200,enterDelay:0,html:null,margin:5,inDuration:250,outDuration:200,position:"bottom",transitionMovement:10},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Tooltip=i).options=d.extend({},n.defaults,e),i.isOpen=!1,i.isHovered=!1,i.isFocused=!1,i._appendTooltipEl(),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){d(this.tooltipEl).remove(),this._removeEventHandlers(),this.el.M_Tooltip=void 0}},{key:"_appendTooltipEl",value:function(){var t=document.createElement("div");t.classList.add("material-tooltip"),this.tooltipEl=t;var e=document.createElement("div");e.classList.add("tooltip-content"),e.innerHTML=this.options.html,t.appendChild(e),document.body.appendChild(t)}},{key:"_updateTooltipContent",value:function(){this.tooltipEl.querySelector(".tooltip-content").innerHTML=this.options.html}},{key:"_setupEventHandlers",value:function(){this._handleMouseEnterBound=this._handleMouseEnter.bind(this),this._handleMouseLeaveBound=this._handleMouseLeave.bind(this),this._handleFocusBound=this._handleFocus.bind(this),this._handleBlurBound=this._handleBlur.bind(this),this.el.addEventListener("mouseenter",this._handleMouseEnterBound),this.el.addEventListener("mouseleave",this._handleMouseLeaveBound),this.el.addEventListener("focus",this._handleFocusBound,!0),this.el.addEventListener("blur",this._handleBlurBound,!0)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("mouseenter",this._handleMouseEnterBound),this.el.removeEventListener("mouseleave",this._handleMouseLeaveBound),this.el.removeEventListener("focus",this._handleFocusBound,!0),this.el.removeEventListener("blur",this._handleBlurBound,!0)}},{key:"open",value:function(t){this.isOpen||(t=void 0===t||void 0,this.isOpen=!0,this.options=d.extend({},this.options,this._getAttributeOptions()),this._updateTooltipContent(),this._setEnterDelayTimeout(t))}},{key:"close",value:function(){this.isOpen&&(this.isHovered=!1,this.isFocused=!1,this.isOpen=!1,this._setExitDelayTimeout())}},{key:"_setExitDelayTimeout",value:function(){var t=this;clearTimeout(this._exitDelayTimeout),this._exitDelayTimeout=setTimeout(function(){t.isHovered||t.isFocused||t._animateOut()},this.options.exitDelay)}},{key:"_setEnterDelayTimeout",value:function(t){var e=this;clearTimeout(this._enterDelayTimeout),this._enterDelayTimeout=setTimeout(function(){(e.isHovered||e.isFocused||t)&&e._animateIn()},this.options.enterDelay)}},{key:"_positionTooltip",value:function(){var t,e=this.el,i=this.tooltipEl,n=e.offsetHeight,s=e.offsetWidth,o=i.offsetHeight,a=i.offsetWidth,r=this.options.margin,l=void 0,h=void 0;this.xMovement=0,this.yMovement=0,l=e.getBoundingClientRect().top+M.getDocumentScrollTop(),h=e.getBoundingClientRect().left+M.getDocumentScrollLeft(),"top"===this.options.position?(l+=-o-r,h+=s/2-a/2,this.yMovement=-this.options.transitionMovement):"right"===this.options.position?(l+=n/2-o/2,h+=s+r,this.xMovement=this.options.transitionMovement):"left"===this.options.position?(l+=n/2-o/2,h+=-a-r,this.xMovement=-this.options.transitionMovement):(l+=n+r,h+=s/2-a/2,this.yMovement=this.options.transitionMovement),t=this._repositionWithinScreen(h,l,a,o),d(i).css({top:t.y+"px",left:t.x+"px"})}},{key:"_repositionWithinScreen",value:function(t,e,i,n){var s=M.getDocumentScrollLeft(),o=M.getDocumentScrollTop(),a=t-s,r=e-o,l={left:a,top:r,width:i,height:n},h=this.options.margin+this.options.transitionMovement,d=M.checkWithinContainer(document.body,l,h);return d.left?a=h:d.right&&(a-=a+i-window.innerWidth),d.top?r=h:d.bottom&&(r-=r+n-window.innerHeight),{x:a+s,y:r+o}}},{key:"_animateIn",value:function(){this._positionTooltip(),this.tooltipEl.style.visibility="visible",e.remove(this.tooltipEl),e({targets:this.tooltipEl,opacity:1,translateX:this.xMovement,translateY:this.yMovement,duration:this.options.inDuration,easing:"easeOutCubic"})}},{key:"_animateOut",value:function(){e.remove(this.tooltipEl),e({targets:this.tooltipEl,opacity:0,translateX:0,translateY:0,duration:this.options.outDuration,easing:"easeOutCubic"})}},{key:"_handleMouseEnter",value:function(){this.isHovered=!0,this.isFocused=!1,this.open(!1)}},{key:"_handleMouseLeave",value:function(){this.isHovered=!1,this.isFocused=!1,this.close()}},{key:"_handleFocus",value:function(){M.tabPressed&&(this.isFocused=!0,this.open(!1))}},{key:"_handleBlur",value:function(){this.isFocused=!1,this.close()}},{key:"_getAttributeOptions",value:function(){var t={},e=this.el.getAttribute("data-tooltip"),i=this.el.getAttribute("data-position");return e&&(t.html=e),i&&(t.position=i),t}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Tooltip}},{key:"defaults",get:function(){return i}}]),n}();M.Tooltip=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"tooltip","M_Tooltip")}(cash,M.anime),function(i){"use strict";var t=t||{},e=document.querySelectorAll.bind(document);function m(t){var e="";for(var i in t)t.hasOwnProperty(i)&&(e+=i+":"+t[i]+";");return e}var g={duration:750,show:function(t,e){if(2===t.button)return!1;var i=e||this,n=document.createElement("div");n.className="waves-ripple",i.appendChild(n);var s,o,a,r,l,h,d,u=(h={top:0,left:0},d=(s=i)&&s.ownerDocument,o=d.documentElement,void 0!==s.getBoundingClientRect&&(h=s.getBoundingClientRect()),a=null!==(l=r=d)&&l===l.window?r:9===r.nodeType&&r.defaultView,{top:h.top+a.pageYOffset-o.clientTop,left:h.left+a.pageXOffset-o.clientLeft}),c=t.pageY-u.top,p=t.pageX-u.left,v="scale("+i.clientWidth/100*10+")";"touches"in t&&(c=t.touches[0].pageY-u.top,p=t.touches[0].pageX-u.left),n.setAttribute("data-hold",Date.now()),n.setAttribute("data-scale",v),n.setAttribute("data-x",p),n.setAttribute("data-y",c);var f={top:c+"px",left:p+"px"};n.className=n.className+" waves-notransition",n.setAttribute("style",m(f)),n.className=n.className.replace("waves-notransition",""),f["-webkit-transform"]=v,f["-moz-transform"]=v,f["-ms-transform"]=v,f["-o-transform"]=v,f.transform=v,f.opacity="1",f["-webkit-transition-duration"]=g.duration+"ms",f["-moz-transition-duration"]=g.duration+"ms",f["-o-transition-duration"]=g.duration+"ms",f["transition-duration"]=g.duration+"ms",f["-webkit-transition-timing-function"]="cubic-bezier(0.250, 0.460, 0.450, 0.940)",f["-moz-transition-timing-function"]="cubic-bezier(0.250, 0.460, 0.450, 0.940)",f["-o-transition-timing-function"]="cubic-bezier(0.250, 0.460, 0.450, 0.940)",f["transition-timing-function"]="cubic-bezier(0.250, 0.460, 0.450, 0.940)",n.setAttribute("style",m(f))},hide:function(t){l.touchup(t);var e=this,i=(e.clientWidth,null),n=e.getElementsByClassName("waves-ripple");if(!(0<n.length))return!1;var s=(i=n[n.length-1]).getAttribute("data-x"),o=i.getAttribute("data-y"),a=i.getAttribute("data-scale"),r=350-(Date.now()-Number(i.getAttribute("data-hold")));r<0&&(r=0),setTimeout(function(){var t={top:o+"px",left:s+"px",opacity:"0","-webkit-transition-duration":g.duration+"ms","-moz-transition-duration":g.duration+"ms","-o-transition-duration":g.duration+"ms","transition-duration":g.duration+"ms","-webkit-transform":a,"-moz-transform":a,"-ms-transform":a,"-o-transform":a,transform:a};i.setAttribute("style",m(t)),setTimeout(function(){try{e.removeChild(i)}catch(t){return!1}},g.duration)},r)},wrapInput:function(t){for(var e=0;e<t.length;e++){var i=t[e];if("input"===i.tagName.toLowerCase()){var n=i.parentNode;if("i"===n.tagName.toLowerCase()&&-1!==n.className.indexOf("waves-effect"))continue;var s=document.createElement("i");s.className=i.className+" waves-input-wrapper";var o=i.getAttribute("style");o||(o=""),s.setAttribute("style",o),i.className="waves-button-input",i.removeAttribute("style"),n.replaceChild(s,i),s.appendChild(i)}}}},l={touches:0,allowEvent:function(t){var e=!0;return"touchstart"===t.type?l.touches+=1:"touchend"===t.type||"touchcancel"===t.type?setTimeout(function(){0<l.touches&&(l.touches-=1)},500):"mousedown"===t.type&&0<l.touches&&(e=!1),e},touchup:function(t){l.allowEvent(t)}};function n(t){var e=function(t){if(!1===l.allowEvent(t))return null;for(var e=null,i=t.target||t.srcElement;null!==i.parentNode;){if(!(i instanceof SVGElement)&&-1!==i.className.indexOf("waves-effect")){e=i;break}i=i.parentNode}return e}(t);null!==e&&(g.show(t,e),"ontouchstart"in i&&(e.addEventListener("touchend",g.hide,!1),e.addEventListener("touchcancel",g.hide,!1)),e.addEventListener("mouseup",g.hide,!1),e.addEventListener("mouseleave",g.hide,!1),e.addEventListener("dragend",g.hide,!1))}t.displayEffect=function(t){"duration"in(t=t||{})&&(g.duration=t.duration),g.wrapInput(e(".waves-effect")),"ontouchstart"in i&&document.body.addEventListener("touchstart",n,!1),document.body.addEventListener("mousedown",n,!1)},t.attach=function(t){"input"===t.tagName.toLowerCase()&&(g.wrapInput([t]),t=t.parentNode),"ontouchstart"in i&&t.addEventListener("touchstart",n,!1),t.addEventListener("mousedown",n,!1)},i.Waves=t,document.addEventListener("DOMContentLoaded",function(){t.displayEffect()},!1)}(window),function(i,n){"use strict";var t={html:"",displayLength:4e3,inDuration:300,outDuration:375,classes:"",completeCallback:null,activationPercent:.8},e=function(){function s(t){_classCallCheck(this,s),this.options=i.extend({},s.defaults,t),this.message=this.options.html,this.panning=!1,this.timeRemaining=this.options.displayLength,0===s._toasts.length&&s._createContainer(),s._toasts.push(this);var e=this._createToast();(e.M_Toast=this).el=e,this.$el=i(e),this._animateIn(),this._setTimer()}return _createClass(s,[{key:"_createToast",value:function(){var t=document.createElement("div");return t.classList.add("toast"),this.options.classes.length&&i(t).addClass(this.options.classes),("object"==typeof HTMLElement?this.message instanceof HTMLElement:this.message&&"object"==typeof this.message&&null!==this.message&&1===this.message.nodeType&&"string"==typeof this.message.nodeName)?t.appendChild(this.message):this.message.jquery?i(t).append(this.message[0]):t.innerHTML=this.message,s._container.appendChild(t),t}},{key:"_animateIn",value:function(){n({targets:this.el,top:0,opacity:1,duration:this.options.inDuration,easing:"easeOutCubic"})}},{key:"_setTimer",value:function(){var t=this;this.timeRemaining!==1/0&&(this.counterInterval=setInterval(function(){t.panning||(t.timeRemaining-=20),t.timeRemaining<=0&&t.dismiss()},20))}},{key:"dismiss",value:function(){var t=this;window.clearInterval(this.counterInterval);var e=this.el.offsetWidth*this.options.activationPercent;this.wasSwiped&&(this.el.style.transition="transform .05s, opacity .05s",this.el.style.transform="translateX("+e+"px)",this.el.style.opacity=0),n({targets:this.el,opacity:0,marginTop:-40,duration:this.options.outDuration,easing:"easeOutExpo",complete:function(){"function"==typeof t.options.completeCallback&&t.options.completeCallback(),t.$el.remove(),s._toasts.splice(s._toasts.indexOf(t),1),0===s._toasts.length&&s._removeContainer()}})}}],[{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Toast}},{key:"_createContainer",value:function(){var t=document.createElement("div");t.setAttribute("id","toast-container"),t.addEventListener("touchstart",s._onDragStart),t.addEventListener("touchmove",s._onDragMove),t.addEventListener("touchend",s._onDragEnd),t.addEventListener("mousedown",s._onDragStart),document.addEventListener("mousemove",s._onDragMove),document.addEventListener("mouseup",s._onDragEnd),document.body.appendChild(t),s._container=t}},{key:"_removeContainer",value:function(){document.removeEventListener("mousemove",s._onDragMove),document.removeEventListener("mouseup",s._onDragEnd),i(s._container).remove(),s._container=null}},{key:"_onDragStart",value:function(t){if(t.target&&i(t.target).closest(".toast").length){var e=i(t.target).closest(".toast")[0].M_Toast;e.panning=!0,(s._draggedToast=e).el.classList.add("panning"),e.el.style.transition="",e.startingXPos=s._xPos(t),e.time=Date.now(),e.xPos=s._xPos(t)}}},{key:"_onDragMove",value:function(t){if(s._draggedToast){t.preventDefault();var e=s._draggedToast;e.deltaX=Math.abs(e.xPos-s._xPos(t)),e.xPos=s._xPos(t),e.velocityX=e.deltaX/(Date.now()-e.time),e.time=Date.now();var i=e.xPos-e.startingXPos,n=e.el.offsetWidth*e.options.activationPercent;e.el.style.transform="translateX("+i+"px)",e.el.style.opacity=1-Math.abs(i/n)}}},{key:"_onDragEnd",value:function(){if(s._draggedToast){var t=s._draggedToast;t.panning=!1,t.el.classList.remove("panning");var e=t.xPos-t.startingXPos,i=t.el.offsetWidth*t.options.activationPercent;Math.abs(e)>i||1<t.velocityX?(t.wasSwiped=!0,t.dismiss()):(t.el.style.transition="transform .2s, opacity .2s",t.el.style.transform="",t.el.style.opacity=""),s._draggedToast=null}}},{key:"_xPos",value:function(t){return t.targetTouches&&1<=t.targetTouches.length?t.targetTouches[0].clientX:t.clientX}},{key:"dismissAll",value:function(){for(var t in s._toasts)s._toasts[t].dismiss()}},{key:"defaults",get:function(){return t}}]),s}();e._toasts=[],e._container=null,e._draggedToast=null,M.Toast=e,M.toast=function(t){return new e(t)}}(cash,M.anime),function(s,o){"use strict";var e={edge:"left",draggable:!0,inDuration:250,outDuration:200,onOpenStart:null,onOpenEnd:null,onCloseStart:null,onCloseEnd:null,preventScrolling:!0},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Sidenav=i).id=i.$el.attr("id"),i.options=s.extend({},n.defaults,e),i.isOpen=!1,i.isFixed=i.el.classList.contains("sidenav-fixed"),i.isDragged=!1,i.lastWindowWidth=window.innerWidth,i.lastWindowHeight=window.innerHeight,i._createOverlay(),i._createDragTarget(),i._setupEventHandlers(),i._setupClasses(),i._setupFixed(),n._sidenavs.push(i),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this._enableBodyScrolling(),this._overlay.parentNode.removeChild(this._overlay),this.dragTarget.parentNode.removeChild(this.dragTarget),this.el.M_Sidenav=void 0,this.el.style.transform="";var t=n._sidenavs.indexOf(this);0<=t&&n._sidenavs.splice(t,1)}},{key:"_createOverlay",value:function(){var t=document.createElement("div");this._closeBound=this.close.bind(this),t.classList.add("sidenav-overlay"),t.addEventListener("click",this._closeBound),document.body.appendChild(t),this._overlay=t}},{key:"_setupEventHandlers",value:function(){0===n._sidenavs.length&&document.body.addEventListener("click",this._handleTriggerClick),this._handleDragTargetDragBound=this._handleDragTargetDrag.bind(this),this._handleDragTargetReleaseBound=this._handleDragTargetRelease.bind(this),this._handleCloseDragBound=this._handleCloseDrag.bind(this),this._handleCloseReleaseBound=this._handleCloseRelease.bind(this),this._handleCloseTriggerClickBound=this._handleCloseTriggerClick.bind(this),this.dragTarget.addEventListener("touchmove",this._handleDragTargetDragBound),this.dragTarget.addEventListener("touchend",this._handleDragTargetReleaseBound),this._overlay.addEventListener("touchmove",this._handleCloseDragBound),this._overlay.addEventListener("touchend",this._handleCloseReleaseBound),this.el.addEventListener("touchmove",this._handleCloseDragBound),this.el.addEventListener("touchend",this._handleCloseReleaseBound),this.el.addEventListener("click",this._handleCloseTriggerClickBound),this.isFixed&&(this._handleWindowResizeBound=this._handleWindowResize.bind(this),window.addEventListener("resize",this._handleWindowResizeBound))}},{key:"_removeEventHandlers",value:function(){1===n._sidenavs.length&&document.body.removeEventListener("click",this._handleTriggerClick),this.dragTarget.removeEventListener("touchmove",this._handleDragTargetDragBound),this.dragTarget.removeEventListener("touchend",this._handleDragTargetReleaseBound),this._overlay.removeEventListener("touchmove",this._handleCloseDragBound),this._overlay.removeEventListener("touchend",this._handleCloseReleaseBound),this.el.removeEventListener("touchmove",this._handleCloseDragBound),this.el.removeEventListener("touchend",this._handleCloseReleaseBound),this.el.removeEventListener("click",this._handleCloseTriggerClickBound),this.isFixed&&window.removeEventListener("resize",this._handleWindowResizeBound)}},{key:"_handleTriggerClick",value:function(t){var e=s(t.target).closest(".sidenav-trigger");if(t.target&&e.length){var i=M.getIdFromTrigger(e[0]),n=document.getElementById(i).M_Sidenav;n&&n.open(e),t.preventDefault()}}},{key:"_startDrag",value:function(t){var e=t.targetTouches[0].clientX;this.isDragged=!0,this._startingXpos=e,this._xPos=this._startingXpos,this._time=Date.now(),this._width=this.el.getBoundingClientRect().width,this._overlay.style.display="block",this._initialScrollTop=this.isOpen?this.el.scrollTop:M.getDocumentScrollTop(),this._verticallyScrolling=!1,o.remove(this.el),o.remove(this._overlay)}},{key:"_dragMoveUpdate",value:function(t){var e=t.targetTouches[0].clientX,i=this.isOpen?this.el.scrollTop:M.getDocumentScrollTop();this.deltaX=Math.abs(this._xPos-e),this._xPos=e,this.velocityX=this.deltaX/(Date.now()-this._time),this._time=Date.now(),this._initialScrollTop!==i&&(this._verticallyScrolling=!0)}},{key:"_handleDragTargetDrag",value:function(t){if(this.options.draggable&&!this._isCurrentlyFixed()&&!this._verticallyScrolling){this.isDragged||this._startDrag(t),this._dragMoveUpdate(t);var e=this._xPos-this._startingXpos,i=0<e?"right":"left";e=Math.min(this._width,Math.abs(e)),this.options.edge===i&&(e=0);var n=e,s="translateX(-100%)";"right"===this.options.edge&&(s="translateX(100%)",n=-n),this.percentOpen=Math.min(1,e/this._width),this.el.style.transform=s+" translateX("+n+"px)",this._overlay.style.opacity=this.percentOpen}}},{key:"_handleDragTargetRelease",value:function(){this.isDragged&&(.2<this.percentOpen?this.open():this._animateOut(),this.isDragged=!1,this._verticallyScrolling=!1)}},{key:"_handleCloseDrag",value:function(t){if(this.isOpen){if(!this.options.draggable||this._isCurrentlyFixed()||this._verticallyScrolling)return;this.isDragged||this._startDrag(t),this._dragMoveUpdate(t);var e=this._xPos-this._startingXpos,i=0<e?"right":"left";e=Math.min(this._width,Math.abs(e)),this.options.edge!==i&&(e=0);var n=-e;"right"===this.options.edge&&(n=-n),this.percentOpen=Math.min(1,1-e/this._width),this.el.style.transform="translateX("+n+"px)",this._overlay.style.opacity=this.percentOpen}}},{key:"_handleCloseRelease",value:function(){this.isOpen&&this.isDragged&&(.8<this.percentOpen?this._animateIn():this.close(),this.isDragged=!1,this._verticallyScrolling=!1)}},{key:"_handleCloseTriggerClick",value:function(t){s(t.target).closest(".sidenav-close").length&&!this._isCurrentlyFixed()&&this.close()}},{key:"_handleWindowResize",value:function(){this.lastWindowWidth!==window.innerWidth&&(992<window.innerWidth?this.open():this.close()),this.lastWindowWidth=window.innerWidth,this.lastWindowHeight=window.innerHeight}},{key:"_setupClasses",value:function(){"right"===this.options.edge&&(this.el.classList.add("right-aligned"),this.dragTarget.classList.add("right-aligned"))}},{key:"_removeClasses",value:function(){this.el.classList.remove("right-aligned"),this.dragTarget.classList.remove("right-aligned")}},{key:"_setupFixed",value:function(){this._isCurrentlyFixed()&&this.open()}},{key:"_isCurrentlyFixed",value:function(){return this.isFixed&&992<window.innerWidth}},{key:"_createDragTarget",value:function(){var t=document.createElement("div");t.classList.add("drag-target"),document.body.appendChild(t),this.dragTarget=t}},{key:"_preventBodyScrolling",value:function(){document.body.style.overflow="hidden"}},{key:"_enableBodyScrolling",value:function(){document.body.style.overflow=""}},{key:"open",value:function(){!0!==this.isOpen&&(this.isOpen=!0,"function"==typeof this.options.onOpenStart&&this.options.onOpenStart.call(this,this.el),this._isCurrentlyFixed()?(o.remove(this.el),o({targets:this.el,translateX:0,duration:0,easing:"easeOutQuad"}),this._enableBodyScrolling(),this._overlay.style.display="none"):(this.options.preventScrolling&&this._preventBodyScrolling(),this.isDragged&&1==this.percentOpen||this._animateIn()))}},{key:"close",value:function(){if(!1!==this.isOpen)if(this.isOpen=!1,"function"==typeof this.options.onCloseStart&&this.options.onCloseStart.call(this,this.el),this._isCurrentlyFixed()){var t="left"===this.options.edge?"-105%":"105%";this.el.style.transform="translateX("+t+")"}else this._enableBodyScrolling(),this.isDragged&&0==this.percentOpen?this._overlay.style.display="none":this._animateOut()}},{key:"_animateIn",value:function(){this._animateSidenavIn(),this._animateOverlayIn()}},{key:"_animateSidenavIn",value:function(){var t=this,e="left"===this.options.edge?-1:1;this.isDragged&&(e="left"===this.options.edge?e+this.percentOpen:e-this.percentOpen),o.remove(this.el),o({targets:this.el,translateX:[100*e+"%",0],duration:this.options.inDuration,easing:"easeOutQuad",complete:function(){"function"==typeof t.options.onOpenEnd&&t.options.onOpenEnd.call(t,t.el)}})}},{key:"_animateOverlayIn",value:function(){var t=0;this.isDragged?t=this.percentOpen:s(this._overlay).css({display:"block"}),o.remove(this._overlay),o({targets:this._overlay,opacity:[t,1],duration:this.options.inDuration,easing:"easeOutQuad"})}},{key:"_animateOut",value:function(){this._animateSidenavOut(),this._animateOverlayOut()}},{key:"_animateSidenavOut",value:function(){var t=this,e="left"===this.options.edge?-1:1,i=0;this.isDragged&&(i="left"===this.options.edge?e+this.percentOpen:e-this.percentOpen),o.remove(this.el),o({targets:this.el,translateX:[100*i+"%",105*e+"%"],duration:this.options.outDuration,easing:"easeOutQuad",complete:function(){"function"==typeof t.options.onCloseEnd&&t.options.onCloseEnd.call(t,t.el)}})}},{key:"_animateOverlayOut",value:function(){var t=this;o.remove(this._overlay),o({targets:this._overlay,opacity:0,duration:this.options.outDuration,easing:"easeOutQuad",complete:function(){s(t._overlay).css("display","none")}})}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Sidenav}},{key:"defaults",get:function(){return e}}]),n}();t._sidenavs=[],M.Sidenav=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"sidenav","M_Sidenav")}(cash,M.anime),function(o,a){"use strict";var e={throttle:100,scrollOffset:200,activeClass:"active",getActiveElement:function(t){return'a[href="#'+t+'"]'}},t=function(t){function c(t,e){_classCallCheck(this,c);var i=_possibleConstructorReturn(this,(c.__proto__||Object.getPrototypeOf(c)).call(this,c,t,e));return(i.el.M_ScrollSpy=i).options=o.extend({},c.defaults,e),c._elements.push(i),c._count++,c._increment++,i.tickId=-1,i.id=c._increment,i._setupEventHandlers(),i._handleWindowScroll(),i}return _inherits(c,Component),_createClass(c,[{key:"destroy",value:function(){c._elements.splice(c._elements.indexOf(this),1),c._elementsInView.splice(c._elementsInView.indexOf(this),1),c._visibleElements.splice(c._visibleElements.indexOf(this.$el),1),c._count--,this._removeEventHandlers(),o(this.options.getActiveElement(this.$el.attr("id"))).removeClass(this.options.activeClass),this.el.M_ScrollSpy=void 0}},{key:"_setupEventHandlers",value:function(){var t=M.throttle(this._handleWindowScroll,200);this._handleThrottledResizeBound=t.bind(this),this._handleWindowScrollBound=this._handleWindowScroll.bind(this),1===c._count&&(window.addEventListener("scroll",this._handleWindowScrollBound),window.addEventListener("resize",this._handleThrottledResizeBound),document.body.addEventListener("click",this._handleTriggerClick))}},{key:"_removeEventHandlers",value:function(){0===c._count&&(window.removeEventListener("scroll",this._handleWindowScrollBound),window.removeEventListener("resize",this._handleThrottledResizeBound),document.body.removeEventListener("click",this._handleTriggerClick))}},{key:"_handleTriggerClick",value:function(t){for(var e=o(t.target),i=c._elements.length-1;0<=i;i--){var n=c._elements[i];if(e.is('a[href="#'+n.$el.attr("id")+'"]')){t.preventDefault();var s=n.$el.offset().top+1;a({targets:[document.documentElement,document.body],scrollTop:s-n.options.scrollOffset,duration:400,easing:"easeOutCubic"});break}}}},{key:"_handleWindowScroll",value:function(){c._ticks++;for(var t=M.getDocumentScrollTop(),e=M.getDocumentScrollLeft(),i=e+window.innerWidth,n=t+window.innerHeight,s=c._findElements(t,i,n,e),o=0;o<s.length;o++){var a=s[o];a.tickId<0&&a._enter(),a.tickId=c._ticks}for(var r=0;r<c._elementsInView.length;r++){var l=c._elementsInView[r],h=l.tickId;0<=h&&h!==c._ticks&&(l._exit(),l.tickId=-1)}c._elementsInView=s}},{key:"_enter",value:function(){(c._visibleElements=c._visibleElements.filter(function(t){return 0!=t.height()}))[0]?(o(this.options.getActiveElement(c._visibleElements[0].attr("id"))).removeClass(this.options.activeClass),c._visibleElements[0][0].M_ScrollSpy&&this.id<c._visibleElements[0][0].M_ScrollSpy.id?c._visibleElements.unshift(this.$el):c._visibleElements.push(this.$el)):c._visibleElements.push(this.$el),o(this.options.getActiveElement(c._visibleElements[0].attr("id"))).addClass(this.options.activeClass)}},{key:"_exit",value:function(){var e=this;(c._visibleElements=c._visibleElements.filter(function(t){return 0!=t.height()}))[0]&&(o(this.options.getActiveElement(c._visibleElements[0].attr("id"))).removeClass(this.options.activeClass),(c._visibleElements=c._visibleElements.filter(function(t){return t.attr("id")!=e.$el.attr("id")}))[0]&&o(this.options.getActiveElement(c._visibleElements[0].attr("id"))).addClass(this.options.activeClass))}}],[{key:"init",value:function(t,e){return _get(c.__proto__||Object.getPrototypeOf(c),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_ScrollSpy}},{key:"_findElements",value:function(t,e,i,n){for(var s=[],o=0;o<c._elements.length;o++){var a=c._elements[o],r=t+a.options.scrollOffset||200;if(0<a.$el.height()){var l=a.$el.offset().top,h=a.$el.offset().left,d=h+a.$el.width(),u=l+a.$el.height();!(e<h||d<n||i<l||u<r)&&s.push(a)}}return s}},{key:"defaults",get:function(){return e}}]),c}();t._elements=[],t._elementsInView=[],t._visibleElements=[],t._count=0,t._increment=0,t._ticks=0,M.ScrollSpy=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"scrollSpy","M_ScrollSpy")}(cash,M.anime),function(h){"use strict";var e={data:{},limit:1/0,onAutocomplete:null,minLength:1,sortFunction:function(t,e,i){return t.indexOf(i)-e.indexOf(i)}},t=function(t){function s(t,e){_classCallCheck(this,s);var i=_possibleConstructorReturn(this,(s.__proto__||Object.getPrototypeOf(s)).call(this,s,t,e));return(i.el.M_Autocomplete=i).options=h.extend({},s.defaults,e),i.isOpen=!1,i.count=0,i.activeIndex=-1,i.oldVal,i.$inputField=i.$el.closest(".input-field"),i.$active=h(),i._mousedown=!1,i._setupDropdown(),i._setupEventHandlers(),i}return _inherits(s,Component),_createClass(s,[{key:"destroy",value:function(){this._removeEventHandlers(),this._removeDropdown(),this.el.M_Autocomplete=void 0}},{key:"_setupEventHandlers",value:function(){this._handleInputBlurBound=this._handleInputBlur.bind(this),this._handleInputKeyupAndFocusBound=this._handleInputKeyupAndFocus.bind(this),this._handleInputKeydownBound=this._handleInputKeydown.bind(this),this._handleInputClickBound=this._handleInputClick.bind(this),this._handleContainerMousedownAndTouchstartBound=this._handleContainerMousedownAndTouchstart.bind(this),this._handleContainerMouseupAndTouchendBound=this._handleContainerMouseupAndTouchend.bind(this),this.el.addEventListener("blur",this._handleInputBlurBound),this.el.addEventListener("keyup",this._handleInputKeyupAndFocusBound),this.el.addEventListener("focus",this._handleInputKeyupAndFocusBound),this.el.addEventListener("keydown",this._handleInputKeydownBound),this.el.addEventListener("click",this._handleInputClickBound),this.container.addEventListener("mousedown",this._handleContainerMousedownAndTouchstartBound),this.container.addEventListener("mouseup",this._handleContainerMouseupAndTouchendBound),void 0!==window.ontouchstart&&(this.container.addEventListener("touchstart",this._handleContainerMousedownAndTouchstartBound),this.container.addEventListener("touchend",this._handleContainerMouseupAndTouchendBound))}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("blur",this._handleInputBlurBound),this.el.removeEventListener("keyup",this._handleInputKeyupAndFocusBound),this.el.removeEventListener("focus",this._handleInputKeyupAndFocusBound),this.el.removeEventListener("keydown",this._handleInputKeydownBound),this.el.removeEventListener("click",this._handleInputClickBound),this.container.removeEventListener("mousedown",this._handleContainerMousedownAndTouchstartBound),this.container.removeEventListener("mouseup",this._handleContainerMouseupAndTouchendBound),void 0!==window.ontouchstart&&(this.container.removeEventListener("touchstart",this._handleContainerMousedownAndTouchstartBound),this.container.removeEventListener("touchend",this._handleContainerMouseupAndTouchendBound))}},{key:"_setupDropdown",value:function(){var e=this;this.container=document.createElement("ul"),this.container.id="autocomplete-options-"+M.guid(),h(this.container).addClass("autocomplete-content dropdown-content"),this.$inputField.append(this.container),this.el.setAttribute("data-target",this.container.id),this.dropdown=M.Dropdown.init(this.el,{autoFocus:!1,closeOnClick:!1,coverTrigger:!1,onItemClick:function(t){e.selectOption(h(t))}}),this.el.removeEventListener("click",this.dropdown._handleClickBound)}},{key:"_removeDropdown",value:function(){this.container.parentNode.removeChild(this.container)}},{key:"_handleInputBlur",value:function(){this._mousedown||(this.close(),this._resetAutocomplete())}},{key:"_handleInputKeyupAndFocus",value:function(t){"keyup"===t.type&&(s._keydown=!1),this.count=0;var e=this.el.value.toLowerCase();13!==t.keyCode&&38!==t.keyCode&&40!==t.keyCode&&(this.oldVal===e||!M.tabPressed&&"focus"===t.type||this.open(),this.oldVal=e)}},{key:"_handleInputKeydown",value:function(t){s._keydown=!0;var e=t.keyCode,i=void 0,n=h(this.container).children("li").length;e===M.keys.ENTER&&0<=this.activeIndex?(i=h(this.container).children("li").eq(this.activeIndex)).length&&(this.selectOption(i),t.preventDefault()):e!==M.keys.ARROW_UP&&e!==M.keys.ARROW_DOWN||(t.preventDefault(),e===M.keys.ARROW_UP&&0<this.activeIndex&&this.activeIndex--,e===M.keys.ARROW_DOWN&&this.activeIndex<n-1&&this.activeIndex++,this.$active.removeClass("active"),0<=this.activeIndex&&(this.$active=h(this.container).children("li").eq(this.activeIndex),this.$active.addClass("active")))}},{key:"_handleInputClick",value:function(t){this.open()}},{key:"_handleContainerMousedownAndTouchstart",value:function(t){this._mousedown=!0}},{key:"_handleContainerMouseupAndTouchend",value:function(t){this._mousedown=!1}},{key:"_highlight",value:function(t,e){var i=e.find("img"),n=e.text().toLowerCase().indexOf(""+t.toLowerCase()),s=n+t.length-1,o=e.text().slice(0,n),a=e.text().slice(n,s+1),r=e.text().slice(s+1);e.html("<span>"+o+"<span class='highlight'>"+a+"</span>"+r+"</span>"),i.length&&e.prepend(i)}},{key:"_resetCurrentElement",value:function(){this.activeIndex=-1,this.$active.removeClass("active")}},{key:"_resetAutocomplete",value:function(){h(this.container).empty(),this._resetCurrentElement(),this.oldVal=null,this.isOpen=!1,this._mousedown=!1}},{key:"selectOption",value:function(t){var e=t.text().trim();this.el.value=e,this.$el.trigger("change"),this._resetAutocomplete(),this.close(),"function"==typeof this.options.onAutocomplete&&this.options.onAutocomplete.call(this,e)}},{key:"_renderDropdown",value:function(t,i){var n=this;this._resetAutocomplete();var e=[];for(var s in t)if(t.hasOwnProperty(s)&&-1!==s.toLowerCase().indexOf(i)){if(this.count>=this.options.limit)break;var o={data:t[s],key:s};e.push(o),this.count++}if(this.options.sortFunction){e.sort(function(t,e){return n.options.sortFunction(t.key.toLowerCase(),e.key.toLowerCase(),i.toLowerCase())})}for(var a=0;a<e.length;a++){var r=e[a],l=h("<li></li>");r.data?l.append('<img src="'+r.data+'" class="right circle"><span>'+r.key+"</span>"):l.append("<span>"+r.key+"</span>"),h(this.container).append(l),this._highlight(i,l)}}},{key:"open",value:function(){var t=this.el.value.toLowerCase();this._resetAutocomplete(),t.length>=this.options.minLength&&(this.isOpen=!0,this._renderDropdown(this.options.data,t)),this.dropdown.isOpen?this.dropdown.recalculateDimensions():this.dropdown.open()}},{key:"close",value:function(){this.dropdown.close()}},{key:"updateData",value:function(t){var e=this.el.value.toLowerCase();this.options.data=t,this.isOpen&&this._renderDropdown(t,e)}}],[{key:"init",value:function(t,e){return _get(s.__proto__||Object.getPrototypeOf(s),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Autocomplete}},{key:"defaults",get:function(){return e}}]),s}();t._keydown=!1,M.Autocomplete=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"autocomplete","M_Autocomplete")}(cash),function(d){M.updateTextFields=function(){d("input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea").each(function(t,e){var i=d(this);0<t.value.length||d(t).is(":focus")||t.autofocus||null!==i.attr("placeholder")?i.siblings("label").addClass("active"):t.validity?i.siblings("label").toggleClass("active",!0===t.validity.badInput):i.siblings("label").removeClass("active")})},M.validate_field=function(t){var e=null!==t.attr("data-length"),i=parseInt(t.attr("data-length")),n=t[0].value.length;0!==n||!1!==t[0].validity.badInput||t.is(":required")?t.hasClass("validate")&&(t.is(":valid")&&e&&n<=i||t.is(":valid")&&!e?(t.removeClass("invalid"),t.addClass("valid")):(t.removeClass("valid"),t.addClass("invalid"))):t.hasClass("validate")&&(t.removeClass("valid"),t.removeClass("invalid"))},M.textareaAutoResize=function(t){if(t instanceof Element&&(t=d(t)),t.length){var e=d(".hiddendiv").first();e.length||(e=d('<div class="hiddendiv common"></div>'),d("body").append(e));var i=t.css("font-family"),n=t.css("font-size"),s=t.css("line-height"),o=t.css("padding-top"),a=t.css("padding-right"),r=t.css("padding-bottom"),l=t.css("padding-left");n&&e.css("font-size",n),i&&e.css("font-family",i),s&&e.css("line-height",s),o&&e.css("padding-top",o),a&&e.css("padding-right",a),r&&e.css("padding-bottom",r),l&&e.css("padding-left",l),t.data("original-height")||t.data("original-height",t.height()),"off"===t.attr("wrap")&&e.css("overflow-wrap","normal").css("white-space","pre"),e.text(t[0].value+"\n");var h=e.html().replace(/\n/g,"<br>");e.html(h),0<t[0].offsetWidth&&0<t[0].offsetHeight?e.css("width",t.width()+"px"):e.css("width",window.innerWidth/2+"px"),t.data("original-height")<=e.innerHeight()?t.css("height",e.innerHeight()+"px"):t[0].value.length<t.data("previous-length")&&t.css("height",t.data("original-height")+"px"),t.data("previous-length",t[0].value.length)}else console.error("No textarea element found")},d(document).ready(function(){var n="input[type=text], input[type=password], input[type=email], input[type=url], input[type=tel], input[type=number], input[type=search], input[type=date], input[type=time], textarea";d(document).on("change",n,function(){0===this.value.length&&null===d(this).attr("placeholder")||d(this).siblings("label").addClass("active"),M.validate_field(d(this))}),d(document).ready(function(){M.updateTextFields()}),d(document).on("reset",function(t){var e=d(t.target);e.is("form")&&(e.find(n).removeClass("valid").removeClass("invalid"),e.find(n).each(function(t){this.value.length&&d(this).siblings("label").removeClass("active")}),setTimeout(function(){e.find("select").each(function(){this.M_FormSelect&&d(this).trigger("change")})},0))}),document.addEventListener("focus",function(t){d(t.target).is(n)&&d(t.target).siblings("label, .prefix").addClass("active")},!0),document.addEventListener("blur",function(t){var e=d(t.target);if(e.is(n)){var i=".prefix";0===e[0].value.length&&!0!==e[0].validity.badInput&&null===e.attr("placeholder")&&(i+=", label"),e.siblings(i).removeClass("active"),M.validate_field(e)}},!0);d(document).on("keyup","input[type=radio], input[type=checkbox]",function(t){if(t.which===M.keys.TAB)return d(this).addClass("tabbed"),void d(this).one("blur",function(t){d(this).removeClass("tabbed")})});var t=".materialize-textarea";d(t).each(function(){var t=d(this);t.data("original-height",t.height()),t.data("previous-length",this.value.length),M.textareaAutoResize(t)}),d(document).on("keyup",t,function(){M.textareaAutoResize(d(this))}),d(document).on("keydown",t,function(){M.textareaAutoResize(d(this))}),d(document).on("change",'.file-field input[type="file"]',function(){for(var t=d(this).closest(".file-field").find("input.file-path"),e=d(this)[0].files,i=[],n=0;n<e.length;n++)i.push(e[n].name);t[0].value=i.join(", "),t.trigger("change")})})}(cash),function(s,o){"use strict";var e={indicators:!0,height:400,duration:500,interval:6e3},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Slider=i).options=s.extend({},n.defaults,e),i.$slider=i.$el.find(".slides"),i.$slides=i.$slider.children("li"),i.activeIndex=i.$slides.filter(function(t){return s(t).hasClass("active")}).first().index(),-1!=i.activeIndex&&(i.$active=i.$slides.eq(i.activeIndex)),i._setSliderHeight(),i.$slides.find(".caption").each(function(t){i._animateCaptionIn(t,0)}),i.$slides.find("img").each(function(t){var e="data:image/gif;base64,R0lGODlhAQABAIABAP///wAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw==";s(t).attr("src")!==e&&(s(t).css("background-image",'url("'+s(t).attr("src")+'")'),s(t).attr("src",e))}),i._setupIndicators(),i.$active?i.$active.css("display","block"):(i.$slides.first().addClass("active"),o({targets:i.$slides.first()[0],opacity:1,duration:i.options.duration,easing:"easeOutQuad"}),i.activeIndex=0,i.$active=i.$slides.eq(i.activeIndex),i.options.indicators&&i.$indicators.eq(i.activeIndex).addClass("active")),i.$active.find("img").each(function(t){o({targets:i.$active.find(".caption")[0],opacity:1,translateX:0,translateY:0,duration:i.options.duration,easing:"easeOutQuad"})}),i._setupEventHandlers(),i.start(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this.pause(),this._removeIndicators(),this._removeEventHandlers(),this.el.M_Slider=void 0}},{key:"_setupEventHandlers",value:function(){var e=this;this._handleIntervalBound=this._handleInterval.bind(this),this._handleIndicatorClickBound=this._handleIndicatorClick.bind(this),this.options.indicators&&this.$indicators.each(function(t){t.addEventListener("click",e._handleIndicatorClickBound)})}},{key:"_removeEventHandlers",value:function(){var e=this;this.options.indicators&&this.$indicators.each(function(t){t.removeEventListener("click",e._handleIndicatorClickBound)})}},{key:"_handleIndicatorClick",value:function(t){var e=s(t.target).index();this.set(e)}},{key:"_handleInterval",value:function(){var t=this.$slider.find(".active").index();this.$slides.length===t+1?t=0:t+=1,this.set(t)}},{key:"_animateCaptionIn",value:function(t,e){var i={targets:t,opacity:0,duration:e,easing:"easeOutQuad"};s(t).hasClass("center-align")?i.translateY=-100:s(t).hasClass("right-align")?i.translateX=100:s(t).hasClass("left-align")&&(i.translateX=-100),o(i)}},{key:"_setSliderHeight",value:function(){this.$el.hasClass("fullscreen")||(this.options.indicators?this.$el.css("height",this.options.height+40+"px"):this.$el.css("height",this.options.height+"px"),this.$slider.css("height",this.options.height+"px"))}},{key:"_setupIndicators",value:function(){var n=this;this.options.indicators&&(this.$indicators=s('<ul class="indicators"></ul>'),this.$slides.each(function(t,e){var i=s('<li class="indicator-item"></li>');n.$indicators.append(i[0])}),this.$el.append(this.$indicators[0]),this.$indicators=this.$indicators.children("li.indicator-item"))}},{key:"_removeIndicators",value:function(){this.$el.find("ul.indicators").remove()}},{key:"set",value:function(t){var e=this;if(t>=this.$slides.length?t=0:t<0&&(t=this.$slides.length-1),this.activeIndex!=t){this.$active=this.$slides.eq(this.activeIndex);var i=this.$active.find(".caption");this.$active.removeClass("active"),o({targets:this.$active[0],opacity:0,duration:this.options.duration,easing:"easeOutQuad",complete:function(){e.$slides.not(".active").each(function(t){o({targets:t,opacity:0,translateX:0,translateY:0,duration:0,easing:"easeOutQuad"})})}}),this._animateCaptionIn(i[0],this.options.duration),this.options.indicators&&(this.$indicators.eq(this.activeIndex).removeClass("active"),this.$indicators.eq(t).addClass("active")),o({targets:this.$slides.eq(t)[0],opacity:1,duration:this.options.duration,easing:"easeOutQuad"}),o({targets:this.$slides.eq(t).find(".caption")[0],opacity:1,translateX:0,translateY:0,duration:this.options.duration,delay:this.options.duration,easing:"easeOutQuad"}),this.$slides.eq(t).addClass("active"),this.activeIndex=t,this.start()}}},{key:"pause",value:function(){clearInterval(this.interval)}},{key:"start",value:function(){clearInterval(this.interval),this.interval=setInterval(this._handleIntervalBound,this.options.duration+this.options.interval)}},{key:"next",value:function(){var t=this.activeIndex+1;t>=this.$slides.length?t=0:t<0&&(t=this.$slides.length-1),this.set(t)}},{key:"prev",value:function(){var t=this.activeIndex-1;t>=this.$slides.length?t=0:t<0&&(t=this.$slides.length-1),this.set(t)}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Slider}},{key:"defaults",get:function(){return e}}]),n}();M.Slider=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"slider","M_Slider")}(cash,M.anime),function(n,s){n(document).on("click",".card",function(t){if(n(this).children(".card-reveal").length){var i=n(t.target).closest(".card");void 0===i.data("initialOverflow")&&i.data("initialOverflow",void 0===i.css("overflow")?"":i.css("overflow"));var e=n(this).find(".card-reveal");n(t.target).is(n(".card-reveal .card-title"))||n(t.target).is(n(".card-reveal .card-title i"))?s({targets:e[0],translateY:0,duration:225,easing:"easeInOutQuad",complete:function(t){var e=t.animatables[0].target;n(e).css({display:"none"}),i.css("overflow",i.data("initialOverflow"))}}):(n(t.target).is(n(".card .activator"))||n(t.target).is(n(".card .activator i")))&&(i.css("overflow","hidden"),e.css({display:"block"}),s({targets:e[0],translateY:"-100%",duration:300,easing:"easeInOutQuad"}))}})}(cash,M.anime),function(h){"use strict";var e={data:[],placeholder:"",secondaryPlaceholder:"",autocompleteOptions:{},limit:1/0,onChipAdd:null,onChipSelect:null,onChipDelete:null},t=function(t){function l(t,e){_classCallCheck(this,l);var i=_possibleConstructorReturn(this,(l.__proto__||Object.getPrototypeOf(l)).call(this,l,t,e));return(i.el.M_Chips=i).options=h.extend({},l.defaults,e),i.$el.addClass("chips input-field"),i.chipsData=[],i.$chips=h(),i._setupInput(),i.hasAutocomplete=0<Object.keys(i.options.autocompleteOptions).length,i.$input.attr("id")||i.$input.attr("id",M.guid()),i.options.data.length&&(i.chipsData=i.options.data,i._renderChips(i.chipsData)),i.hasAutocomplete&&i._setupAutocomplete(),i._setPlaceholder(),i._setupLabel(),i._setupEventHandlers(),i}return _inherits(l,Component),_createClass(l,[{key:"getData",value:function(){return this.chipsData}},{key:"destroy",value:function(){this._removeEventHandlers(),this.$chips.remove(),this.el.M_Chips=void 0}},{key:"_setupEventHandlers",value:function(){this._handleChipClickBound=this._handleChipClick.bind(this),this._handleInputKeydownBound=this._handleInputKeydown.bind(this),this._handleInputFocusBound=this._handleInputFocus.bind(this),this._handleInputBlurBound=this._handleInputBlur.bind(this),this.el.addEventListener("click",this._handleChipClickBound),document.addEventListener("keydown",l._handleChipsKeydown),document.addEventListener("keyup",l._handleChipsKeyup),this.el.addEventListener("blur",l._handleChipsBlur,!0),this.$input[0].addEventListener("focus",this._handleInputFocusBound),this.$input[0].addEventListener("blur",this._handleInputBlurBound),this.$input[0].addEventListener("keydown",this._handleInputKeydownBound)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("click",this._handleChipClickBound),document.removeEventListener("keydown",l._handleChipsKeydown),document.removeEventListener("keyup",l._handleChipsKeyup),this.el.removeEventListener("blur",l._handleChipsBlur,!0),this.$input[0].removeEventListener("focus",this._handleInputFocusBound),this.$input[0].removeEventListener("blur",this._handleInputBlurBound),this.$input[0].removeEventListener("keydown",this._handleInputKeydownBound)}},{key:"_handleChipClick",value:function(t){var e=h(t.target).closest(".chip"),i=h(t.target).is(".close");if(e.length){var n=e.index();i?(this.deleteChip(n),this.$input[0].focus()):this.selectChip(n)}else this.$input[0].focus()}},{key:"_handleInputFocus",value:function(){this.$el.addClass("focus")}},{key:"_handleInputBlur",value:function(){this.$el.removeClass("focus")}},{key:"_handleInputKeydown",value:function(t){if(l._keydown=!0,13===t.keyCode){if(this.hasAutocomplete&&this.autocomplete&&this.autocomplete.isOpen)return;t.preventDefault(),this.addChip({tag:this.$input[0].value}),this.$input[0].value=""}else 8!==t.keyCode&&37!==t.keyCode||""!==this.$input[0].value||!this.chipsData.length||(t.preventDefault(),this.selectChip(this.chipsData.length-1))}},{key:"_renderChip",value:function(t){if(t.tag){var e=document.createElement("div"),i=document.createElement("i");if(e.classList.add("chip"),e.textContent=t.tag,e.setAttribute("tabindex",0),h(i).addClass("material-icons close"),i.textContent="close",t.image){var n=document.createElement("img");n.setAttribute("src",t.image),e.insertBefore(n,e.firstChild)}return e.appendChild(i),e}}},{key:"_renderChips",value:function(){this.$chips.remove();for(var t=0;t<this.chipsData.length;t++){var e=this._renderChip(this.chipsData[t]);this.$el.append(e),this.$chips.add(e)}this.$el.append(this.$input[0])}},{key:"_setupAutocomplete",value:function(){var e=this;this.options.autocompleteOptions.onAutocomplete=function(t){e.addChip({tag:t}),e.$input[0].value="",e.$input[0].focus()},this.autocomplete=M.Autocomplete.init(this.$input[0],this.options.autocompleteOptions)}},{key:"_setupInput",value:function(){this.$input=this.$el.find("input"),this.$input.length||(this.$input=h("<input></input>"),this.$el.append(this.$input)),this.$input.addClass("input")}},{key:"_setupLabel",value:function(){this.$label=this.$el.find("label"),this.$label.length&&this.$label.setAttribute("for",this.$input.attr("id"))}},{key:"_setPlaceholder",value:function(){void 0!==this.chipsData&&!this.chipsData.length&&this.options.placeholder?h(this.$input).prop("placeholder",this.options.placeholder):(void 0===this.chipsData||this.chipsData.length)&&this.options.secondaryPlaceholder&&h(this.$input).prop("placeholder",this.options.secondaryPlaceholder)}},{key:"_isValid",value:function(t){if(t.hasOwnProperty("tag")&&""!==t.tag){for(var e=!1,i=0;i<this.chipsData.length;i++)if(this.chipsData[i].tag===t.tag){e=!0;break}return!e}return!1}},{key:"addChip",value:function(t){if(this._isValid(t)&&!(this.chipsData.length>=this.options.limit)){var e=this._renderChip(t);this.$chips.add(e),this.chipsData.push(t),h(this.$input).before(e),this._setPlaceholder(),"function"==typeof this.options.onChipAdd&&this.options.onChipAdd.call(this,this.$el,e)}}},{key:"deleteChip",value:function(t){var e=this.$chips.eq(t);this.$chips.eq(t).remove(),this.$chips=this.$chips.filter(function(t){return 0<=h(t).index()}),this.chipsData.splice(t,1),this._setPlaceholder(),"function"==typeof this.options.onChipDelete&&this.options.onChipDelete.call(this,this.$el,e[0])}},{key:"selectChip",value:function(t){var e=this.$chips.eq(t);(this._selectedChip=e)[0].focus(),"function"==typeof this.options.onChipSelect&&this.options.onChipSelect.call(this,this.$el,e[0])}}],[{key:"init",value:function(t,e){return _get(l.__proto__||Object.getPrototypeOf(l),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Chips}},{key:"_handleChipsKeydown",value:function(t){l._keydown=!0;var e=h(t.target).closest(".chips"),i=t.target&&e.length;if(!h(t.target).is("input, textarea")&&i){var n=e[0].M_Chips;if(8===t.keyCode||46===t.keyCode){t.preventDefault();var s=n.chipsData.length;if(n._selectedChip){var o=n._selectedChip.index();n.deleteChip(o),n._selectedChip=null,s=Math.max(o-1,0)}n.chipsData.length&&n.selectChip(s)}else if(37===t.keyCode){if(n._selectedChip){var a=n._selectedChip.index()-1;if(a<0)return;n.selectChip(a)}}else if(39===t.keyCode&&n._selectedChip){var r=n._selectedChip.index()+1;r>=n.chipsData.length?n.$input[0].focus():n.selectChip(r)}}}},{key:"_handleChipsKeyup",value:function(t){l._keydown=!1}},{key:"_handleChipsBlur",value:function(t){l._keydown||(h(t.target).closest(".chips")[0].M_Chips._selectedChip=null)}},{key:"defaults",get:function(){return e}}]),l}();t._keydown=!1,M.Chips=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"chips","M_Chips"),h(document).ready(function(){h(document.body).on("click",".chip .close",function(){var t=h(this).closest(".chips");t.length&&t[0].M_Chips||h(this).closest(".chip").remove()})})}(cash),function(s){"use strict";var e={top:0,bottom:1/0,offset:0,onPositionChange:null},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Pushpin=i).options=s.extend({},n.defaults,e),i.originalOffset=i.el.offsetTop,n._pushpins.push(i),i._setupEventHandlers(),i._updatePosition(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this.el.style.top=null,this._removePinClasses(),this._removeEventHandlers();var t=n._pushpins.indexOf(this);n._pushpins.splice(t,1)}},{key:"_setupEventHandlers",value:function(){document.addEventListener("scroll",n._updateElements)}},{key:"_removeEventHandlers",value:function(){document.removeEventListener("scroll",n._updateElements)}},{key:"_updatePosition",value:function(){var t=M.getDocumentScrollTop()+this.options.offset;this.options.top<=t&&this.options.bottom>=t&&!this.el.classList.contains("pinned")&&(this._removePinClasses(),this.el.style.top=this.options.offset+"px",this.el.classList.add("pinned"),"function"==typeof this.options.onPositionChange&&this.options.onPositionChange.call(this,"pinned")),t<this.options.top&&!this.el.classList.contains("pin-top")&&(this._removePinClasses(),this.el.style.top=0,this.el.classList.add("pin-top"),"function"==typeof this.options.onPositionChange&&this.options.onPositionChange.call(this,"pin-top")),t>this.options.bottom&&!this.el.classList.contains("pin-bottom")&&(this._removePinClasses(),this.el.classList.add("pin-bottom"),this.el.style.top=this.options.bottom-this.originalOffset+"px","function"==typeof this.options.onPositionChange&&this.options.onPositionChange.call(this,"pin-bottom"))}},{key:"_removePinClasses",value:function(){this.el.classList.remove("pin-top"),this.el.classList.remove("pinned"),this.el.classList.remove("pin-bottom")}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Pushpin}},{key:"_updateElements",value:function(){for(var t in n._pushpins){n._pushpins[t]._updatePosition()}}},{key:"defaults",get:function(){return e}}]),n}();t._pushpins=[],M.Pushpin=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"pushpin","M_Pushpin")}(cash),function(r,s){"use strict";var e={direction:"top",hoverEnabled:!0,toolbarEnabled:!1};r.fn.reverse=[].reverse;var t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_FloatingActionButton=i).options=r.extend({},n.defaults,e),i.isOpen=!1,i.$anchor=i.$el.children("a").first(),i.$menu=i.$el.children("ul").first(),i.$floatingBtns=i.$el.find("ul .btn-floating"),i.$floatingBtnsReverse=i.$el.find("ul .btn-floating").reverse(),i.offsetY=0,i.offsetX=0,i.$el.addClass("direction-"+i.options.direction),"top"===i.options.direction?i.offsetY=40:"right"===i.options.direction?i.offsetX=-40:"bottom"===i.options.direction?i.offsetY=-40:i.offsetX=40,i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.M_FloatingActionButton=void 0}},{key:"_setupEventHandlers",value:function(){this._handleFABClickBound=this._handleFABClick.bind(this),this._handleOpenBound=this.open.bind(this),this._handleCloseBound=this.close.bind(this),this.options.hoverEnabled&&!this.options.toolbarEnabled?(this.el.addEventListener("mouseenter",this._handleOpenBound),this.el.addEventListener("mouseleave",this._handleCloseBound)):this.el.addEventListener("click",this._handleFABClickBound)}},{key:"_removeEventHandlers",value:function(){this.options.hoverEnabled&&!this.options.toolbarEnabled?(this.el.removeEventListener("mouseenter",this._handleOpenBound),this.el.removeEventListener("mouseleave",this._handleCloseBound)):this.el.removeEventListener("click",this._handleFABClickBound)}},{key:"_handleFABClick",value:function(){this.isOpen?this.close():this.open()}},{key:"_handleDocumentClick",value:function(t){r(t.target).closest(this.$menu).length||this.close()}},{key:"open",value:function(){this.isOpen||(this.options.toolbarEnabled?this._animateInToolbar():this._animateInFAB(),this.isOpen=!0)}},{key:"close",value:function(){this.isOpen&&(this.options.toolbarEnabled?(window.removeEventListener("scroll",this._handleCloseBound,!0),document.body.removeEventListener("click",this._handleDocumentClickBound,!0),this._animateOutToolbar()):this._animateOutFAB(),this.isOpen=!1)}},{key:"_animateInFAB",value:function(){var e=this;this.$el.addClass("active");var i=0;this.$floatingBtnsReverse.each(function(t){s({targets:t,opacity:1,scale:[.4,1],translateY:[e.offsetY,0],translateX:[e.offsetX,0],duration:275,delay:i,easing:"easeInOutQuad"}),i+=40})}},{key:"_animateOutFAB",value:function(){var e=this;this.$floatingBtnsReverse.each(function(t){s.remove(t),s({targets:t,opacity:0,scale:.4,translateY:e.offsetY,translateX:e.offsetX,duration:175,easing:"easeOutQuad",complete:function(){e.$el.removeClass("active")}})})}},{key:"_animateInToolbar",value:function(){var t,e=this,i=window.innerWidth,n=window.innerHeight,s=this.el.getBoundingClientRect(),o=r('<div class="fab-backdrop"></div>'),a=this.$anchor.css("background-color");this.$anchor.append(o),this.offsetX=s.left-i/2+s.width/2,this.offsetY=n-s.bottom,t=i/o[0].clientWidth,this.btnBottom=s.bottom,this.btnLeft=s.left,this.btnWidth=s.width,this.$el.addClass("active"),this.$el.css({"text-align":"center",width:"100%",bottom:0,left:0,transform:"translateX("+this.offsetX+"px)",transition:"none"}),this.$anchor.css({transform:"translateY("+-this.offsetY+"px)",transition:"none"}),o.css({"background-color":a}),setTimeout(function(){e.$el.css({transform:"",transition:"transform .2s cubic-bezier(0.550, 0.085, 0.680, 0.530), background-color 0s linear .2s"}),e.$anchor.css({overflow:"visible",transform:"",transition:"transform .2s"}),setTimeout(function(){e.$el.css({overflow:"hidden","background-color":a}),o.css({transform:"scale("+t+")",transition:"transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)"}),e.$menu.children("li").children("a").css({opacity:1}),e._handleDocumentClickBound=e._handleDocumentClick.bind(e),window.addEventListener("scroll",e._handleCloseBound,!0),document.body.addEventListener("click",e._handleDocumentClickBound,!0)},100)},0)}},{key:"_animateOutToolbar",value:function(){var t=this,e=window.innerWidth,i=window.innerHeight,n=this.$el.find(".fab-backdrop"),s=this.$anchor.css("background-color");this.offsetX=this.btnLeft-e/2+this.btnWidth/2,this.offsetY=i-this.btnBottom,this.$el.removeClass("active"),this.$el.css({"background-color":"transparent",transition:"none"}),this.$anchor.css({transition:"none"}),n.css({transform:"scale(0)","background-color":s}),this.$menu.children("li").children("a").css({opacity:""}),setTimeout(function(){n.remove(),t.$el.css({"text-align":"",width:"",bottom:"",left:"",overflow:"","background-color":"",transform:"translate3d("+-t.offsetX+"px,0,0)"}),t.$anchor.css({overflow:"",transform:"translate3d(0,"+t.offsetY+"px,0)"}),setTimeout(function(){t.$el.css({transform:"translate3d(0,0,0)",transition:"transform .2s"}),t.$anchor.css({transform:"translate3d(0,0,0)",transition:"transform .2s cubic-bezier(0.550, 0.055, 0.675, 0.190)"})},20)},200)}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_FloatingActionButton}},{key:"defaults",get:function(){return e}}]),n}();M.FloatingActionButton=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"floatingActionButton","M_FloatingActionButton")}(cash,M.anime),function(g){"use strict";var e={autoClose:!1,format:"mmm dd, yyyy",parse:null,defaultDate:null,setDefaultDate:!1,disableWeekends:!1,disableDayFn:null,firstDay:0,minDate:null,maxDate:null,yearRange:10,minYear:0,maxYear:9999,minMonth:void 0,maxMonth:void 0,startRange:null,endRange:null,isRTL:!1,showMonthAfterYear:!1,showDaysInNextAndPreviousMonths:!1,container:null,showClearBtn:!1,i18n:{cancel:"Cancel",clear:"Clear",done:"Ok",previousMonth:"‹",nextMonth:"›",months:["January","February","March","April","May","June","July","August","September","October","November","December"],monthsShort:["Jan","Feb","Mar","Apr","May","Jun","Jul","Aug","Sep","Oct","Nov","Dec"],weekdays:["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"],weekdaysShort:["Sun","Mon","Tue","Wed","Thu","Fri","Sat"],weekdaysAbbrev:["S","M","T","W","T","F","S"]},events:[],onSelect:null,onOpen:null,onClose:null,onDraw:null},t=function(t){function B(t,e){_classCallCheck(this,B);var i=_possibleConstructorReturn(this,(B.__proto__||Object.getPrototypeOf(B)).call(this,B,t,e));(i.el.M_Datepicker=i).options=g.extend({},B.defaults,e),e&&e.hasOwnProperty("i18n")&&"object"==typeof e.i18n&&(i.options.i18n=g.extend({},B.defaults.i18n,e.i18n)),i.options.minDate&&i.options.minDate.setHours(0,0,0,0),i.options.maxDate&&i.options.maxDate.setHours(0,0,0,0),i.id=M.guid(),i._setupVariables(),i._insertHTMLIntoDOM(),i._setupModal(),i._setupEventHandlers(),i.options.defaultDate||(i.options.defaultDate=new Date(Date.parse(i.el.value)));var n=i.options.defaultDate;return B._isDate(n)?i.options.setDefaultDate?(i.setDate(n,!0),i.setInputValue()):i.gotoDate(n):i.gotoDate(new Date),i.isOpen=!1,i}return _inherits(B,Component),_createClass(B,[{key:"destroy",value:function(){this._removeEventHandlers(),this.modal.destroy(),g(this.modalEl).remove(),this.destroySelects(),this.el.M_Datepicker=void 0}},{key:"destroySelects",value:function(){var t=this.calendarEl.querySelector(".orig-select-year");t&&M.FormSelect.getInstance(t).destroy();var e=this.calendarEl.querySelector(".orig-select-month");e&&M.FormSelect.getInstance(e).destroy()}},{key:"_insertHTMLIntoDOM",value:function(){this.options.showClearBtn&&(g(this.clearBtn).css({visibility:""}),this.clearBtn.innerHTML=this.options.i18n.clear),this.doneBtn.innerHTML=this.options.i18n.done,this.cancelBtn.innerHTML=this.options.i18n.cancel,this.options.container?this.$modalEl.appendTo(this.options.container):this.$modalEl.insertBefore(this.el)}},{key:"_setupModal",value:function(){var t=this;this.modalEl.id="modal-"+this.id,this.modal=M.Modal.init(this.modalEl,{onCloseEnd:function(){t.isOpen=!1}})}},{key:"toString",value:function(t){var e=this;return t=t||this.options.format,B._isDate(this.date)?t.split(/(d{1,4}|m{1,4}|y{4}|yy|!.)/g).map(function(t){return e.formats[t]?e.formats[t]():t}).join(""):""}},{key:"setDate",value:function(t,e){if(!t)return this.date=null,this._renderDateDisplay(),this.draw();if("string"==typeof t&&(t=new Date(Date.parse(t))),B._isDate(t)){var i=this.options.minDate,n=this.options.maxDate;B._isDate(i)&&t<i?t=i:B._isDate(n)&&n<t&&(t=n),this.date=new Date(t.getTime()),this._renderDateDisplay(),B._setToStartOfDay(this.date),this.gotoDate(this.date),e||"function"!=typeof this.options.onSelect||this.options.onSelect.call(this,this.date)}}},{key:"setInputValue",value:function(){this.el.value=this.toString(),this.$el.trigger("change",{firedBy:this})}},{key:"_renderDateDisplay",value:function(){var t=B._isDate(this.date)?this.date:new Date,e=this.options.i18n,i=e.weekdaysShort[t.getDay()],n=e.monthsShort[t.getMonth()],s=t.getDate();this.yearTextEl.innerHTML=t.getFullYear(),this.dateTextEl.innerHTML=i+", "+n+" "+s}},{key:"gotoDate",value:function(t){var e=!0;if(B._isDate(t)){if(this.calendars){var i=new Date(this.calendars[0].year,this.calendars[0].month,1),n=new Date(this.calendars[this.calendars.length-1].year,this.calendars[this.calendars.length-1].month,1),s=t.getTime();n.setMonth(n.getMonth()+1),n.setDate(n.getDate()-1),e=s<i.getTime()||n.getTime()<s}e&&(this.calendars=[{month:t.getMonth(),year:t.getFullYear()}]),this.adjustCalendars()}}},{key:"adjustCalendars",value:function(){this.calendars[0]=this.adjustCalendar(this.calendars[0]),this.draw()}},{key:"adjustCalendar",value:function(t){return t.month<0&&(t.year-=Math.ceil(Math.abs(t.month)/12),t.month+=12),11<t.month&&(t.year+=Math.floor(Math.abs(t.month)/12),t.month-=12),t}},{key:"nextMonth",value:function(){this.calendars[0].month++,this.adjustCalendars()}},{key:"prevMonth",value:function(){this.calendars[0].month--,this.adjustCalendars()}},{key:"render",value:function(t,e,i){var n=this.options,s=new Date,o=B._getDaysInMonth(t,e),a=new Date(t,e,1).getDay(),r=[],l=[];B._setToStartOfDay(s),0<n.firstDay&&(a-=n.firstDay)<0&&(a+=7);for(var h=0===e?11:e-1,d=11===e?0:e+1,u=0===e?t-1:t,c=11===e?t+1:t,p=B._getDaysInMonth(u,h),v=o+a,f=v;7<f;)f-=7;v+=7-f;for(var m=!1,g=0,_=0;g<v;g++){var y=new Date(t,e,g-a+1),k=!!B._isDate(this.date)&&B._compareDates(y,this.date),b=B._compareDates(y,s),w=-1!==n.events.indexOf(y.toDateString()),C=g<a||o+a<=g,E=g-a+1,M=e,O=t,x=n.startRange&&B._compareDates(n.startRange,y),L=n.endRange&&B._compareDates(n.endRange,y),T=n.startRange&&n.endRange&&n.startRange<y&&y<n.endRange;C&&(g<a?(E=p+E,M=h,O=u):(E-=o,M=d,O=c));var $={day:E,month:M,year:O,hasEvent:w,isSelected:k,isToday:b,isDisabled:n.minDate&&y<n.minDate||n.maxDate&&y>n.maxDate||n.disableWeekends&&B._isWeekend(y)||n.disableDayFn&&n.disableDayFn(y),isEmpty:C,isStartRange:x,isEndRange:L,isInRange:T,showDaysInNextAndPreviousMonths:n.showDaysInNextAndPreviousMonths};l.push(this.renderDay($)),7==++_&&(r.push(this.renderRow(l,n.isRTL,m)),_=0,m=!(l=[]))}return this.renderTable(n,r,i)}},{key:"renderDay",value:function(t){var e=[],i="false";if(t.isEmpty){if(!t.showDaysInNextAndPreviousMonths)return'<td class="is-empty"></td>';e.push("is-outside-current-month"),e.push("is-selection-disabled")}return t.isDisabled&&e.push("is-disabled"),t.isToday&&e.push("is-today"),t.isSelected&&(e.push("is-selected"),i="true"),t.hasEvent&&e.push("has-event"),t.isInRange&&e.push("is-inrange"),t.isStartRange&&e.push("is-startrange"),t.isEndRange&&e.push("is-endrange"),'<td data-day="'+t.day+'" class="'+e.join(" ")+'" aria-selected="'+i+'"><button class="datepicker-day-button" type="button" data-year="'+t.year+'" data-month="'+t.month+'" data-day="'+t.day+'">'+t.day+"</button></td>"}},{key:"renderRow",value:function(t,e,i){return'<tr class="datepicker-row'+(i?" is-selected":"")+'">'+(e?t.reverse():t).join("")+"</tr>"}},{key:"renderTable",value:function(t,e,i){return'<div class="datepicker-table-wrapper"><table cellpadding="0" cellspacing="0" class="datepicker-table" role="grid" aria-labelledby="'+i+'">'+this.renderHead(t)+this.renderBody(e)+"</table></div>"}},{key:"renderHead",value:function(t){var e=void 0,i=[];for(e=0;e<7;e++)i.push('<th scope="col"><abbr title="'+this.renderDayName(t,e)+'">'+this.renderDayName(t,e,!0)+"</abbr></th>");return"<thead><tr>"+(t.isRTL?i.reverse():i).join("")+"</tr></thead>"}},{key:"renderBody",value:function(t){return"<tbody>"+t.join("")+"</tbody>"}},{key:"renderTitle",value:function(t,e,i,n,s,o){var a,r,l=void 0,h=void 0,d=void 0,u=this.options,c=i===u.minYear,p=i===u.maxYear,v='<div id="'+o+'" class="datepicker-controls" role="heading" aria-live="assertive">',f=!0,m=!0;for(d=[],l=0;l<12;l++)d.push('<option value="'+(i===s?l-e:12+l-e)+'"'+(l===n?' selected="selected"':"")+(c&&l<u.minMonth||p&&l>u.maxMonth?'disabled="disabled"':"")+">"+u.i18n.months[l]+"</option>");for(a='<select class="datepicker-select orig-select-month" tabindex="-1">'+d.join("")+"</select>",g.isArray(u.yearRange)?(l=u.yearRange[0],h=u.yearRange[1]+1):(l=i-u.yearRange,h=1+i+u.yearRange),d=[];l<h&&l<=u.maxYear;l++)l>=u.minYear&&d.push('<option value="'+l+'" '+(l===i?'selected="selected"':"")+">"+l+"</option>");r='<select class="datepicker-select orig-select-year" tabindex="-1">'+d.join("")+"</select>";v+='<button class="month-prev'+(f?"":" is-disabled")+'" type="button"><svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M15.41 16.09l-4.58-4.59 4.58-4.59L14 5.5l-6 6 6 6z"/><path d="M0-.5h24v24H0z" fill="none"/></svg></button>',v+='<div class="selects-container">',u.showMonthAfterYear?v+=r+a:v+=a+r,v+="</div>",c&&(0===n||u.minMonth>=n)&&(f=!1),p&&(11===n||u.maxMonth<=n)&&(m=!1);return(v+='<button class="month-next'+(m?"":" is-disabled")+'" type="button"><svg fill="#000000" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M8.59 16.34l4.58-4.59-4.58-4.59L10 5.75l6 6-6 6z"/><path d="M0-.25h24v24H0z" fill="none"/></svg></button>')+"</div>"}},{key:"draw",value:function(t){if(this.isOpen||t){var e,i=this.options,n=i.minYear,s=i.maxYear,o=i.minMonth,a=i.maxMonth,r="";this._y<=n&&(this._y=n,!isNaN(o)&&this._m<o&&(this._m=o)),this._y>=s&&(this._y=s,!isNaN(a)&&this._m>a&&(this._m=a)),e="datepicker-title-"+Math.random().toString(36).replace(/[^a-z]+/g,"").substr(0,2);for(var l=0;l<1;l++)this._renderDateDisplay(),r+=this.renderTitle(this,l,this.calendars[l].year,this.calendars[l].month,this.calendars[0].year,e)+this.render(this.calendars[l].year,this.calendars[l].month,e);this.destroySelects(),this.calendarEl.innerHTML=r;var h=this.calendarEl.querySelector(".orig-select-year"),d=this.calendarEl.querySelector(".orig-select-month");M.FormSelect.init(h,{classes:"select-year",dropdownOptions:{container:document.body,constrainWidth:!1}}),M.FormSelect.init(d,{classes:"select-month",dropdownOptions:{container:document.body,constrainWidth:!1}}),h.addEventListener("change",this._handleYearChange.bind(this)),d.addEventListener("change",this._handleMonthChange.bind(this)),"function"==typeof this.options.onDraw&&this.options.onDraw(this)}}},{key:"_setupEventHandlers",value:function(){this._handleInputKeydownBound=this._handleInputKeydown.bind(this),this._handleInputClickBound=this._handleInputClick.bind(this),this._handleInputChangeBound=this._handleInputChange.bind(this),this._handleCalendarClickBound=this._handleCalendarClick.bind(this),this._finishSelectionBound=this._finishSelection.bind(this),this._handleMonthChange=this._handleMonthChange.bind(this),this._closeBound=this.close.bind(this),this.el.addEventListener("click",this._handleInputClickBound),this.el.addEventListener("keydown",this._handleInputKeydownBound),this.el.addEventListener("change",this._handleInputChangeBound),this.calendarEl.addEventListener("click",this._handleCalendarClickBound),this.doneBtn.addEventListener("click",this._finishSelectionBound),this.cancelBtn.addEventListener("click",this._closeBound),this.options.showClearBtn&&(this._handleClearClickBound=this._handleClearClick.bind(this),this.clearBtn.addEventListener("click",this._handleClearClickBound))}},{key:"_setupVariables",value:function(){var e=this;this.$modalEl=g(B._template),this.modalEl=this.$modalEl[0],this.calendarEl=this.modalEl.querySelector(".datepicker-calendar"),this.yearTextEl=this.modalEl.querySelector(".year-text"),this.dateTextEl=this.modalEl.querySelector(".date-text"),this.options.showClearBtn&&(this.clearBtn=this.modalEl.querySelector(".datepicker-clear")),this.doneBtn=this.modalEl.querySelector(".datepicker-done"),this.cancelBtn=this.modalEl.querySelector(".datepicker-cancel"),this.formats={d:function(){return e.date.getDate()},dd:function(){var t=e.date.getDate();return(t<10?"0":"")+t},ddd:function(){return e.options.i18n.weekdaysShort[e.date.getDay()]},dddd:function(){return e.options.i18n.weekdays[e.date.getDay()]},m:function(){return e.date.getMonth()+1},mm:function(){var t=e.date.getMonth()+1;return(t<10?"0":"")+t},mmm:function(){return e.options.i18n.monthsShort[e.date.getMonth()]},mmmm:function(){return e.options.i18n.months[e.date.getMonth()]},yy:function(){return(""+e.date.getFullYear()).slice(2)},yyyy:function(){return e.date.getFullYear()}}}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("click",this._handleInputClickBound),this.el.removeEventListener("keydown",this._handleInputKeydownBound),this.el.removeEventListener("change",this._handleInputChangeBound),this.calendarEl.removeEventListener("click",this._handleCalendarClickBound)}},{key:"_handleInputClick",value:function(){this.open()}},{key:"_handleInputKeydown",value:function(t){t.which===M.keys.ENTER&&(t.preventDefault(),this.open())}},{key:"_handleCalendarClick",value:function(t){if(this.isOpen){var e=g(t.target);e.hasClass("is-disabled")||(!e.hasClass("datepicker-day-button")||e.hasClass("is-empty")||e.parent().hasClass("is-disabled")?e.closest(".month-prev").length?this.prevMonth():e.closest(".month-next").length&&this.nextMonth():(this.setDate(new Date(t.target.getAttribute("data-year"),t.target.getAttribute("data-month"),t.target.getAttribute("data-day"))),this.options.autoClose&&this._finishSelection()))}}},{key:"_handleClearClick",value:function(){this.date=null,this.setInputValue(),this.close()}},{key:"_handleMonthChange",value:function(t){this.gotoMonth(t.target.value)}},{key:"_handleYearChange",value:function(t){this.gotoYear(t.target.value)}},{key:"gotoMonth",value:function(t){isNaN(t)||(this.calendars[0].month=parseInt(t,10),this.adjustCalendars())}},{key:"gotoYear",value:function(t){isNaN(t)||(this.calendars[0].year=parseInt(t,10),this.adjustCalendars())}},{key:"_handleInputChange",value:function(t){var e=void 0;t.firedBy!==this&&(e=this.options.parse?this.options.parse(this.el.value,this.options.format):new Date(Date.parse(this.el.value)),B._isDate(e)&&this.setDate(e))}},{key:"renderDayName",value:function(t,e,i){for(e+=t.firstDay;7<=e;)e-=7;return i?t.i18n.weekdaysAbbrev[e]:t.i18n.weekdays[e]}},{key:"_finishSelection",value:function(){this.setInputValue(),this.close()}},{key:"open",value:function(){if(!this.isOpen)return this.isOpen=!0,"function"==typeof this.options.onOpen&&this.options.onOpen.call(this),this.draw(),this.modal.open(),this}},{key:"close",value:function(){if(this.isOpen)return this.isOpen=!1,"function"==typeof this.options.onClose&&this.options.onClose.call(this),this.modal.close(),this}}],[{key:"init",value:function(t,e){return _get(B.__proto__||Object.getPrototypeOf(B),"init",this).call(this,this,t,e)}},{key:"_isDate",value:function(t){return/Date/.test(Object.prototype.toString.call(t))&&!isNaN(t.getTime())}},{key:"_isWeekend",value:function(t){var e=t.getDay();return 0===e||6===e}},{key:"_setToStartOfDay",value:function(t){B._isDate(t)&&t.setHours(0,0,0,0)}},{key:"_getDaysInMonth",value:function(t,e){return[31,B._isLeapYear(t)?29:28,31,30,31,30,31,31,30,31,30,31][e]}},{key:"_isLeapYear",value:function(t){return t%4==0&&t%100!=0||t%400==0}},{key:"_compareDates",value:function(t,e){return t.getTime()===e.getTime()}},{key:"_setToStartOfDay",value:function(t){B._isDate(t)&&t.setHours(0,0,0,0)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Datepicker}},{key:"defaults",get:function(){return e}}]),B}();t._template=['<div class= "modal datepicker-modal">','<div class="modal-content datepicker-container">','<div class="datepicker-date-display">','<span class="year-text"></span>','<span class="date-text"></span>',"</div>",'<div class="datepicker-calendar-container">','<div class="datepicker-calendar"></div>','<div class="datepicker-footer">','<button class="btn-flat datepicker-clear waves-effect" style="visibility: hidden;" type="button"></button>','<div class="confirmation-btns">','<button class="btn-flat datepicker-cancel waves-effect" type="button"></button>','<button class="btn-flat datepicker-done waves-effect" type="button"></button>',"</div>","</div>","</div>","</div>","</div>"].join(""),M.Datepicker=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"datepicker","M_Datepicker")}(cash),function(h){"use strict";var e={dialRadius:135,outerRadius:105,innerRadius:70,tickRadius:20,duration:350,container:null,defaultTime:"now",fromNow:0,showClearBtn:!1,i18n:{cancel:"Cancel",clear:"Clear",done:"Ok"},autoClose:!1,twelveHour:!0,vibrate:!0,onOpenStart:null,onOpenEnd:null,onCloseStart:null,onCloseEnd:null,onSelect:null},t=function(t){function f(t,e){_classCallCheck(this,f);var i=_possibleConstructorReturn(this,(f.__proto__||Object.getPrototypeOf(f)).call(this,f,t,e));return(i.el.M_Timepicker=i).options=h.extend({},f.defaults,e),i.id=M.guid(),i._insertHTMLIntoDOM(),i._setupModal(),i._setupVariables(),i._setupEventHandlers(),i._clockSetup(),i._pickerSetup(),i}return _inherits(f,Component),_createClass(f,[{key:"destroy",value:function(){this._removeEventHandlers(),this.modal.destroy(),h(this.modalEl).remove(),this.el.M_Timepicker=void 0}},{key:"_setupEventHandlers",value:function(){this._handleInputKeydownBound=this._handleInputKeydown.bind(this),this._handleInputClickBound=this._handleInputClick.bind(this),this._handleClockClickStartBound=this._handleClockClickStart.bind(this),this._handleDocumentClickMoveBound=this._handleDocumentClickMove.bind(this),this._handleDocumentClickEndBound=this._handleDocumentClickEnd.bind(this),this.el.addEventListener("click",this._handleInputClickBound),this.el.addEventListener("keydown",this._handleInputKeydownBound),this.plate.addEventListener("mousedown",this._handleClockClickStartBound),this.plate.addEventListener("touchstart",this._handleClockClickStartBound),h(this.spanHours).on("click",this.showView.bind(this,"hours")),h(this.spanMinutes).on("click",this.showView.bind(this,"minutes"))}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("click",this._handleInputClickBound),this.el.removeEventListener("keydown",this._handleInputKeydownBound)}},{key:"_handleInputClick",value:function(){this.open()}},{key:"_handleInputKeydown",value:function(t){t.which===M.keys.ENTER&&(t.preventDefault(),this.open())}},{key:"_handleClockClickStart",value:function(t){t.preventDefault();var e=this.plate.getBoundingClientRect(),i=e.left,n=e.top;this.x0=i+this.options.dialRadius,this.y0=n+this.options.dialRadius,this.moved=!1;var s=f._Pos(t);this.dx=s.x-this.x0,this.dy=s.y-this.y0,this.setHand(this.dx,this.dy,!1),document.addEventListener("mousemove",this._handleDocumentClickMoveBound),document.addEventListener("touchmove",this._handleDocumentClickMoveBound),document.addEventListener("mouseup",this._handleDocumentClickEndBound),document.addEventListener("touchend",this._handleDocumentClickEndBound)}},{key:"_handleDocumentClickMove",value:function(t){t.preventDefault();var e=f._Pos(t),i=e.x-this.x0,n=e.y-this.y0;this.moved=!0,this.setHand(i,n,!1,!0)}},{key:"_handleDocumentClickEnd",value:function(t){var e=this;t.preventDefault(),document.removeEventListener("mouseup",this._handleDocumentClickEndBound),document.removeEventListener("touchend",this._handleDocumentClickEndBound);var i=f._Pos(t),n=i.x-this.x0,s=i.y-this.y0;this.moved&&n===this.dx&&s===this.dy&&this.setHand(n,s),"hours"===this.currentView?this.showView("minutes",this.options.duration/2):this.options.autoClose&&(h(this.minutesView).addClass("timepicker-dial-out"),setTimeout(function(){e.done()},this.options.duration/2)),"function"==typeof this.options.onSelect&&this.options.onSelect.call(this,this.hours,this.minutes),document.removeEventListener("mousemove",this._handleDocumentClickMoveBound),document.removeEventListener("touchmove",this._handleDocumentClickMoveBound)}},{key:"_insertHTMLIntoDOM",value:function(){this.$modalEl=h(f._template),this.modalEl=this.$modalEl[0],this.modalEl.id="modal-"+this.id;var t=document.querySelector(this.options.container);this.options.container&&t?this.$modalEl.appendTo(t):this.$modalEl.insertBefore(this.el)}},{key:"_setupModal",value:function(){var t=this;this.modal=M.Modal.init(this.modalEl,{onOpenStart:this.options.onOpenStart,onOpenEnd:this.options.onOpenEnd,onCloseStart:this.options.onCloseStart,onCloseEnd:function(){"function"==typeof t.options.onCloseEnd&&t.options.onCloseEnd.call(t),t.isOpen=!1}})}},{key:"_setupVariables",value:function(){this.currentView="hours",this.vibrate=navigator.vibrate?"vibrate":navigator.webkitVibrate?"webkitVibrate":null,this._canvas=this.modalEl.querySelector(".timepicker-canvas"),this.plate=this.modalEl.querySelector(".timepicker-plate"),this.hoursView=this.modalEl.querySelector(".timepicker-hours"),this.minutesView=this.modalEl.querySelector(".timepicker-minutes"),this.spanHours=this.modalEl.querySelector(".timepicker-span-hours"),this.spanMinutes=this.modalEl.querySelector(".timepicker-span-minutes"),this.spanAmPm=this.modalEl.querySelector(".timepicker-span-am-pm"),this.footer=this.modalEl.querySelector(".timepicker-footer"),this.amOrPm="PM"}},{key:"_pickerSetup",value:function(){var t=h('<button class="btn-flat timepicker-clear waves-effect" style="visibility: hidden;" type="button" tabindex="'+(this.options.twelveHour?"3":"1")+'">'+this.options.i18n.clear+"</button>").appendTo(this.footer).on("click",this.clear.bind(this));this.options.showClearBtn&&t.css({visibility:""});var e=h('<div class="confirmation-btns"></div>');h('<button class="btn-flat timepicker-close waves-effect" type="button" tabindex="'+(this.options.twelveHour?"3":"1")+'">'+this.options.i18n.cancel+"</button>").appendTo(e).on("click",this.close.bind(this)),h('<button class="btn-flat timepicker-close waves-effect" type="button" tabindex="'+(this.options.twelveHour?"3":"1")+'">'+this.options.i18n.done+"</button>").appendTo(e).on("click",this.done.bind(this)),e.appendTo(this.footer)}},{key:"_clockSetup",value:function(){this.options.twelveHour&&(this.$amBtn=h('<div class="am-btn">AM</div>'),this.$pmBtn=h('<div class="pm-btn">PM</div>'),this.$amBtn.on("click",this._handleAmPmClick.bind(this)).appendTo(this.spanAmPm),this.$pmBtn.on("click",this._handleAmPmClick.bind(this)).appendTo(this.spanAmPm)),this._buildHoursView(),this._buildMinutesView(),this._buildSVGClock()}},{key:"_buildSVGClock",value:function(){var t=this.options.dialRadius,e=this.options.tickRadius,i=2*t,n=f._createSVGEl("svg");n.setAttribute("class","timepicker-svg"),n.setAttribute("width",i),n.setAttribute("height",i);var s=f._createSVGEl("g");s.setAttribute("transform","translate("+t+","+t+")");var o=f._createSVGEl("circle");o.setAttribute("class","timepicker-canvas-bearing"),o.setAttribute("cx",0),o.setAttribute("cy",0),o.setAttribute("r",4);var a=f._createSVGEl("line");a.setAttribute("x1",0),a.setAttribute("y1",0);var r=f._createSVGEl("circle");r.setAttribute("class","timepicker-canvas-bg"),r.setAttribute("r",e),s.appendChild(a),s.appendChild(r),s.appendChild(o),n.appendChild(s),this._canvas.appendChild(n),this.hand=a,this.bg=r,this.bearing=o,this.g=s}},{key:"_buildHoursView",value:function(){var t=h('<div class="timepicker-tick"></div>');if(this.options.twelveHour)for(var e=1;e<13;e+=1){var i=t.clone(),n=e/6*Math.PI,s=this.options.outerRadius;i.css({left:this.options.dialRadius+Math.sin(n)*s-this.options.tickRadius+"px",top:this.options.dialRadius-Math.cos(n)*s-this.options.tickRadius+"px"}),i.html(0===e?"00":e),this.hoursView.appendChild(i[0])}else for(var o=0;o<24;o+=1){var a=t.clone(),r=o/6*Math.PI,l=0<o&&o<13?this.options.innerRadius:this.options.outerRadius;a.css({left:this.options.dialRadius+Math.sin(r)*l-this.options.tickRadius+"px",top:this.options.dialRadius-Math.cos(r)*l-this.options.tickRadius+"px"}),a.html(0===o?"00":o),this.hoursView.appendChild(a[0])}}},{key:"_buildMinutesView",value:function(){for(var t=h('<div class="timepicker-tick"></div>'),e=0;e<60;e+=5){var i=t.clone(),n=e/30*Math.PI;i.css({left:this.options.dialRadius+Math.sin(n)*this.options.outerRadius-this.options.tickRadius+"px",top:this.options.dialRadius-Math.cos(n)*this.options.outerRadius-this.options.tickRadius+"px"}),i.html(f._addLeadingZero(e)),this.minutesView.appendChild(i[0])}}},{key:"_handleAmPmClick",value:function(t){var e=h(t.target);this.amOrPm=e.hasClass("am-btn")?"AM":"PM",this._updateAmPmView()}},{key:"_updateAmPmView",value:function(){this.options.twelveHour&&(this.$amBtn.toggleClass("text-primary","AM"===this.amOrPm),this.$pmBtn.toggleClass("text-primary","PM"===this.amOrPm))}},{key:"_updateTimeFromInput",value:function(){var t=((this.el.value||this.options.defaultTime||"")+"").split(":");if(this.options.twelveHour&&void 0!==t[1]&&(0<t[1].toUpperCase().indexOf("AM")?this.amOrPm="AM":this.amOrPm="PM",t[1]=t[1].replace("AM","").replace("PM","")),"now"===t[0]){var e=new Date(+new Date+this.options.fromNow);t=[e.getHours(),e.getMinutes()],this.options.twelveHour&&(this.amOrPm=12<=t[0]&&t[0]<24?"PM":"AM")}this.hours=+t[0]||0,this.minutes=+t[1]||0,this.spanHours.innerHTML=this.hours,this.spanMinutes.innerHTML=f._addLeadingZero(this.minutes),this._updateAmPmView()}},{key:"showView",value:function(t,e){"minutes"===t&&h(this.hoursView).css("visibility");var i="hours"===t,n=i?this.hoursView:this.minutesView,s=i?this.minutesView:this.hoursView;this.currentView=t,h(this.spanHours).toggleClass("text-primary",i),h(this.spanMinutes).toggleClass("text-primary",!i),s.classList.add("timepicker-dial-out"),h(n).css("visibility","visible").removeClass("timepicker-dial-out"),this.resetClock(e),clearTimeout(this.toggleViewTimer),this.toggleViewTimer=setTimeout(function(){h(s).css("visibility","hidden")},this.options.duration)}},{key:"resetClock",value:function(t){var e=this.currentView,i=this[e],n="hours"===e,s=i*(Math.PI/(n?6:30)),o=n&&0<i&&i<13?this.options.innerRadius:this.options.outerRadius,a=Math.sin(s)*o,r=-Math.cos(s)*o,l=this;t?(h(this.canvas).addClass("timepicker-canvas-out"),setTimeout(function(){h(l.canvas).removeClass("timepicker-canvas-out"),l.setHand(a,r)},t)):this.setHand(a,r)}},{key:"setHand",value:function(t,e,i){var n=this,s=Math.atan2(t,-e),o="hours"===this.currentView,a=Math.PI/(o||i?6:30),r=Math.sqrt(t*t+e*e),l=o&&r<(this.options.outerRadius+this.options.innerRadius)/2,h=l?this.options.innerRadius:this.options.outerRadius;this.options.twelveHour&&(h=this.options.outerRadius),s<0&&(s=2*Math.PI+s);var d=Math.round(s/a);s=d*a,this.options.twelveHour?o?0===d&&(d=12):(i&&(d*=5),60===d&&(d=0)):o?(12===d&&(d=0),d=l?0===d?12:d:0===d?0:d+12):(i&&(d*=5),60===d&&(d=0)),this[this.currentView]!==d&&this.vibrate&&this.options.vibrate&&(this.vibrateTimer||(navigator[this.vibrate](10),this.vibrateTimer=setTimeout(function(){n.vibrateTimer=null},100))),this[this.currentView]=d,o?this.spanHours.innerHTML=d:this.spanMinutes.innerHTML=f._addLeadingZero(d);var u=Math.sin(s)*(h-this.options.tickRadius),c=-Math.cos(s)*(h-this.options.tickRadius),p=Math.sin(s)*h,v=-Math.cos(s)*h;this.hand.setAttribute("x2",u),this.hand.setAttribute("y2",c),this.bg.setAttribute("cx",p),this.bg.setAttribute("cy",v)}},{key:"open",value:function(){this.isOpen||(this.isOpen=!0,this._updateTimeFromInput(),this.showView("hours"),this.modal.open())}},{key:"close",value:function(){this.isOpen&&(this.isOpen=!1,this.modal.close())}},{key:"done",value:function(t,e){var i=this.el.value,n=e?"":f._addLeadingZero(this.hours)+":"+f._addLeadingZero(this.minutes);this.time=n,!e&&this.options.twelveHour&&(n=n+" "+this.amOrPm),(this.el.value=n)!==i&&this.$el.trigger("change"),this.close(),this.el.focus()}},{key:"clear",value:function(){this.done(null,!0)}}],[{key:"init",value:function(t,e){return _get(f.__proto__||Object.getPrototypeOf(f),"init",this).call(this,this,t,e)}},{key:"_addLeadingZero",value:function(t){return(t<10?"0":"")+t}},{key:"_createSVGEl",value:function(t){return document.createElementNS("http://www.w3.org/2000/svg",t)}},{key:"_Pos",value:function(t){return t.targetTouches&&1<=t.targetTouches.length?{x:t.targetTouches[0].clientX,y:t.targetTouches[0].clientY}:{x:t.clientX,y:t.clientY}}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Timepicker}},{key:"defaults",get:function(){return e}}]),f}();t._template=['<div class= "modal timepicker-modal">','<div class="modal-content timepicker-container">','<div class="timepicker-digital-display">','<div class="timepicker-text-container">','<div class="timepicker-display-column">','<span class="timepicker-span-hours text-primary"></span>',":",'<span class="timepicker-span-minutes"></span>',"</div>",'<div class="timepicker-display-column timepicker-display-am-pm">','<div class="timepicker-span-am-pm"></div>',"</div>","</div>","</div>",'<div class="timepicker-analog-display">','<div class="timepicker-plate">','<div class="timepicker-canvas"></div>','<div class="timepicker-dial timepicker-hours"></div>','<div class="timepicker-dial timepicker-minutes timepicker-dial-out"></div>',"</div>",'<div class="timepicker-footer"></div>',"</div>","</div>","</div>"].join(""),M.Timepicker=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"timepicker","M_Timepicker")}(cash),function(s){"use strict";var e={},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_CharacterCounter=i).options=s.extend({},n.defaults,e),i.isInvalid=!1,i.isValidLength=!1,i._setupCounter(),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.CharacterCounter=void 0,this._removeCounter()}},{key:"_setupEventHandlers",value:function(){this._handleUpdateCounterBound=this.updateCounter.bind(this),this.el.addEventListener("focus",this._handleUpdateCounterBound,!0),this.el.addEventListener("input",this._handleUpdateCounterBound,!0)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("focus",this._handleUpdateCounterBound,!0),this.el.removeEventListener("input",this._handleUpdateCounterBound,!0)}},{key:"_setupCounter",value:function(){this.counterEl=document.createElement("span"),s(this.counterEl).addClass("character-counter").css({float:"right","font-size":"12px",height:1}),this.$el.parent().append(this.counterEl)}},{key:"_removeCounter",value:function(){s(this.counterEl).remove()}},{key:"updateCounter",value:function(){var t=+this.$el.attr("data-length"),e=this.el.value.length;this.isValidLength=e<=t;var i=e;t&&(i+="/"+t,this._validateInput()),s(this.counterEl).html(i)}},{key:"_validateInput",value:function(){this.isValidLength&&this.isInvalid?(this.isInvalid=!1,this.$el.removeClass("invalid")):this.isValidLength||this.isInvalid||(this.isInvalid=!0,this.$el.removeClass("valid"),this.$el.addClass("invalid"))}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_CharacterCounter}},{key:"defaults",get:function(){return e}}]),n}();M.CharacterCounter=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"characterCounter","M_CharacterCounter")}(cash),function(b){"use strict";var e={duration:200,dist:-100,shift:0,padding:0,numVisible:5,fullWidth:!1,indicators:!1,noWrap:!1,onCycleTo:null},t=function(t){function i(t,e){_classCallCheck(this,i);var n=_possibleConstructorReturn(this,(i.__proto__||Object.getPrototypeOf(i)).call(this,i,t,e));return(n.el.M_Carousel=n).options=b.extend({},i.defaults,e),n.hasMultipleSlides=1<n.$el.find(".carousel-item").length,n.showIndicators=n.options.indicators&&n.hasMultipleSlides,n.noWrap=n.options.noWrap||!n.hasMultipleSlides,n.pressed=!1,n.dragged=!1,n.offset=n.target=0,n.images=[],n.itemWidth=n.$el.find(".carousel-item").first().innerWidth(),n.itemHeight=n.$el.find(".carousel-item").first().innerHeight(),n.dim=2*n.itemWidth+n.options.padding||1,n._autoScrollBound=n._autoScroll.bind(n),n._trackBound=n._track.bind(n),n.options.fullWidth&&(n.options.dist=0,n._setCarouselHeight(),n.showIndicators&&n.$el.find(".carousel-fixed-item").addClass("with-indicators")),n.$indicators=b('<ul class="indicators"></ul>'),n.$el.find(".carousel-item").each(function(t,e){if(n.images.push(t),n.showIndicators){var i=b('<li class="indicator-item"></li>');0===e&&i[0].classList.add("active"),n.$indicators.append(i)}}),n.showIndicators&&n.$el.append(n.$indicators),n.count=n.images.length,n.options.numVisible=Math.min(n.count,n.options.numVisible),n.xform="transform",["webkit","Moz","O","ms"].every(function(t){var e=t+"Transform";return void 0===document.body.style[e]||(n.xform=e,!1)}),n._setupEventHandlers(),n._scroll(n.offset),n}return _inherits(i,Component),_createClass(i,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.M_Carousel=void 0}},{key:"_setupEventHandlers",value:function(){var i=this;this._handleCarouselTapBound=this._handleCarouselTap.bind(this),this._handleCarouselDragBound=this._handleCarouselDrag.bind(this),this._handleCarouselReleaseBound=this._handleCarouselRelease.bind(this),this._handleCarouselClickBound=this._handleCarouselClick.bind(this),void 0!==window.ontouchstart&&(this.el.addEventListener("touchstart",this._handleCarouselTapBound),this.el.addEventListener("touchmove",this._handleCarouselDragBound),this.el.addEventListener("touchend",this._handleCarouselReleaseBound)),this.el.addEventListener("mousedown",this._handleCarouselTapBound),this.el.addEventListener("mousemove",this._handleCarouselDragBound),this.el.addEventListener("mouseup",this._handleCarouselReleaseBound),this.el.addEventListener("mouseleave",this._handleCarouselReleaseBound),this.el.addEventListener("click",this._handleCarouselClickBound),this.showIndicators&&this.$indicators&&(this._handleIndicatorClickBound=this._handleIndicatorClick.bind(this),this.$indicators.find(".indicator-item").each(function(t,e){t.addEventListener("click",i._handleIndicatorClickBound)}));var t=M.throttle(this._handleResize,200);this._handleThrottledResizeBound=t.bind(this),window.addEventListener("resize",this._handleThrottledResizeBound)}},{key:"_removeEventHandlers",value:function(){var i=this;void 0!==window.ontouchstart&&(this.el.removeEventListener("touchstart",this._handleCarouselTapBound),this.el.removeEventListener("touchmove",this._handleCarouselDragBound),this.el.removeEventListener("touchend",this._handleCarouselReleaseBound)),this.el.removeEventListener("mousedown",this._handleCarouselTapBound),this.el.removeEventListener("mousemove",this._handleCarouselDragBound),this.el.removeEventListener("mouseup",this._handleCarouselReleaseBound),this.el.removeEventListener("mouseleave",this._handleCarouselReleaseBound),this.el.removeEventListener("click",this._handleCarouselClickBound),this.showIndicators&&this.$indicators&&this.$indicators.find(".indicator-item").each(function(t,e){t.removeEventListener("click",i._handleIndicatorClickBound)}),window.removeEventListener("resize",this._handleThrottledResizeBound)}},{key:"_handleCarouselTap",value:function(t){"mousedown"===t.type&&b(t.target).is("img")&&t.preventDefault(),this.pressed=!0,this.dragged=!1,this.verticalDragged=!1,this.reference=this._xpos(t),this.referenceY=this._ypos(t),this.velocity=this.amplitude=0,this.frame=this.offset,this.timestamp=Date.now(),clearInterval(this.ticker),this.ticker=setInterval(this._trackBound,100)}},{key:"_handleCarouselDrag",value:function(t){var e=void 0,i=void 0,n=void 0;if(this.pressed)if(e=this._xpos(t),i=this._ypos(t),n=this.reference-e,Math.abs(this.referenceY-i)<30&&!this.verticalDragged)(2<n||n<-2)&&(this.dragged=!0,this.reference=e,this._scroll(this.offset+n));else{if(this.dragged)return t.preventDefault(),t.stopPropagation(),!1;this.verticalDragged=!0}if(this.dragged)return t.preventDefault(),t.stopPropagation(),!1}},{key:"_handleCarouselRelease",value:function(t){if(this.pressed)return this.pressed=!1,clearInterval(this.ticker),this.target=this.offset,(10<this.velocity||this.velocity<-10)&&(this.amplitude=.9*this.velocity,this.target=this.offset+this.amplitude),this.target=Math.round(this.target/this.dim)*this.dim,this.noWrap&&(this.target>=this.dim*(this.count-1)?this.target=this.dim*(this.count-1):this.target<0&&(this.target=0)),this.amplitude=this.target-this.offset,this.timestamp=Date.now(),requestAnimationFrame(this._autoScrollBound),this.dragged&&(t.preventDefault(),t.stopPropagation()),!1}},{key:"_handleCarouselClick",value:function(t){if(this.dragged)return t.preventDefault(),t.stopPropagation(),!1;if(!this.options.fullWidth){var e=b(t.target).closest(".carousel-item").index();0!==this._wrap(this.center)-e&&(t.preventDefault(),t.stopPropagation()),this._cycleTo(e)}}},{key:"_handleIndicatorClick",value:function(t){t.stopPropagation();var e=b(t.target).closest(".indicator-item");e.length&&this._cycleTo(e.index())}},{key:"_handleResize",value:function(t){this.options.fullWidth?(this.itemWidth=this.$el.find(".carousel-item").first().innerWidth(),this.imageHeight=this.$el.find(".carousel-item.active").height(),this.dim=2*this.itemWidth+this.options.padding,this.offset=2*this.center*this.itemWidth,this.target=this.offset,this._setCarouselHeight(!0)):this._scroll()}},{key:"_setCarouselHeight",value:function(t){var i=this,e=this.$el.find(".carousel-item.active").length?this.$el.find(".carousel-item.active").first():this.$el.find(".carousel-item").first(),n=e.find("img").first();if(n.length)if(n[0].complete){var s=n.height();if(0<s)this.$el.css("height",s+"px");else{var o=n[0].naturalWidth,a=n[0].naturalHeight,r=this.$el.width()/o*a;this.$el.css("height",r+"px")}}else n.one("load",function(t,e){i.$el.css("height",t.offsetHeight+"px")});else if(!t){var l=e.height();this.$el.css("height",l+"px")}}},{key:"_xpos",value:function(t){return t.targetTouches&&1<=t.targetTouches.length?t.targetTouches[0].clientX:t.clientX}},{key:"_ypos",value:function(t){return t.targetTouches&&1<=t.targetTouches.length?t.targetTouches[0].clientY:t.clientY}},{key:"_wrap",value:function(t){return t>=this.count?t%this.count:t<0?this._wrap(this.count+t%this.count):t}},{key:"_track",value:function(){var t,e,i,n;e=(t=Date.now())-this.timestamp,this.timestamp=t,i=this.offset-this.frame,this.frame=this.offset,n=1e3*i/(1+e),this.velocity=.8*n+.2*this.velocity}},{key:"_autoScroll",value:function(){var t=void 0,e=void 0;this.amplitude&&(t=Date.now()-this.timestamp,2<(e=this.amplitude*Math.exp(-t/this.options.duration))||e<-2?(this._scroll(this.target-e),requestAnimationFrame(this._autoScrollBound)):this._scroll(this.target))}},{key:"_scroll",value:function(t){var e=this;this.$el.hasClass("scrolling")||this.el.classList.add("scrolling"),null!=this.scrollingTimeout&&window.clearTimeout(this.scrollingTimeout),this.scrollingTimeout=window.setTimeout(function(){e.$el.removeClass("scrolling")},this.options.duration);var i,n,s,o,a=void 0,r=void 0,l=void 0,h=void 0,d=void 0,u=void 0,c=this.center,p=1/this.options.numVisible;if(this.offset="number"==typeof t?t:this.offset,this.center=Math.floor((this.offset+this.dim/2)/this.dim),o=-(s=(n=this.offset-this.center*this.dim)<0?1:-1)*n*2/this.dim,i=this.count>>1,this.options.fullWidth?(l="translateX(0)",u=1):(l="translateX("+(this.el.clientWidth-this.itemWidth)/2+"px) ",l+="translateY("+(this.el.clientHeight-this.itemHeight)/2+"px)",u=1-p*o),this.showIndicators){var v=this.center%this.count,f=this.$indicators.find(".indicator-item.active");f.index()!==v&&(f.removeClass("active"),this.$indicators.find(".indicator-item").eq(v)[0].classList.add("active"))}if(!this.noWrap||0<=this.center&&this.center<this.count){r=this.images[this._wrap(this.center)],b(r).hasClass("active")||(this.$el.find(".carousel-item").removeClass("active"),r.classList.add("active"));var m=l+" translateX("+-n/2+"px) translateX("+s*this.options.shift*o*a+"px) translateZ("+this.options.dist*o+"px)";this._updateItemStyle(r,u,0,m)}for(a=1;a<=i;++a){if(this.options.fullWidth?(h=this.options.dist,d=a===i&&n<0?1-o:1):(h=this.options.dist*(2*a+o*s),d=1-p*(2*a+o*s)),!this.noWrap||this.center+a<this.count){r=this.images[this._wrap(this.center+a)];var g=l+" translateX("+(this.options.shift+(this.dim*a-n)/2)+"px) translateZ("+h+"px)";this._updateItemStyle(r,d,-a,g)}if(this.options.fullWidth?(h=this.options.dist,d=a===i&&0<n?1-o:1):(h=this.options.dist*(2*a-o*s),d=1-p*(2*a-o*s)),!this.noWrap||0<=this.center-a){r=this.images[this._wrap(this.center-a)];var _=l+" translateX("+(-this.options.shift+(-this.dim*a-n)/2)+"px) translateZ("+h+"px)";this._updateItemStyle(r,d,-a,_)}}if(!this.noWrap||0<=this.center&&this.center<this.count){r=this.images[this._wrap(this.center)];var y=l+" translateX("+-n/2+"px) translateX("+s*this.options.shift*o+"px) translateZ("+this.options.dist*o+"px)";this._updateItemStyle(r,u,0,y)}var k=this.$el.find(".carousel-item").eq(this._wrap(this.center));c!==this.center&&"function"==typeof this.options.onCycleTo&&this.options.onCycleTo.call(this,k[0],this.dragged),"function"==typeof this.oneTimeCallback&&(this.oneTimeCallback.call(this,k[0],this.dragged),this.oneTimeCallback=null)}},{key:"_updateItemStyle",value:function(t,e,i,n){t.style[this.xform]=n,t.style.zIndex=i,t.style.opacity=e,t.style.visibility="visible"}},{key:"_cycleTo",value:function(t,e){var i=this.center%this.count-t;this.noWrap||(i<0?Math.abs(i+this.count)<Math.abs(i)&&(i+=this.count):0<i&&Math.abs(i-this.count)<i&&(i-=this.count)),this.target=this.dim*Math.round(this.offset/this.dim),i<0?this.target+=this.dim*Math.abs(i):0<i&&(this.target-=this.dim*i),"function"==typeof e&&(this.oneTimeCallback=e),this.offset!==this.target&&(this.amplitude=this.target-this.offset,this.timestamp=Date.now(),requestAnimationFrame(this._autoScrollBound))}},{key:"next",value:function(t){(void 0===t||isNaN(t))&&(t=1);var e=this.center+t;if(e>=this.count||e<0){if(this.noWrap)return;e=this._wrap(e)}this._cycleTo(e)}},{key:"prev",value:function(t){(void 0===t||isNaN(t))&&(t=1);var e=this.center-t;if(e>=this.count||e<0){if(this.noWrap)return;e=this._wrap(e)}this._cycleTo(e)}},{key:"set",value:function(t,e){if((void 0===t||isNaN(t))&&(t=0),t>this.count||t<0){if(this.noWrap)return;t=this._wrap(t)}this._cycleTo(t,e)}}],[{key:"init",value:function(t,e){return _get(i.__proto__||Object.getPrototypeOf(i),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Carousel}},{key:"defaults",get:function(){return e}}]),i}();M.Carousel=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"carousel","M_Carousel")}(cash),function(S){"use strict";var e={onOpen:void 0,onClose:void 0},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_TapTarget=i).options=S.extend({},n.defaults,e),i.isOpen=!1,i.$origin=S("#"+i.$el.attr("data-target")),i._setup(),i._calculatePositioning(),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this.el.TapTarget=void 0}},{key:"_setupEventHandlers",value:function(){this._handleDocumentClickBound=this._handleDocumentClick.bind(this),this._handleTargetClickBound=this._handleTargetClick.bind(this),this._handleOriginClickBound=this._handleOriginClick.bind(this),this.el.addEventListener("click",this._handleTargetClickBound),this.originEl.addEventListener("click",this._handleOriginClickBound);var t=M.throttle(this._handleResize,200);this._handleThrottledResizeBound=t.bind(this),window.addEventListener("resize",this._handleThrottledResizeBound)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("click",this._handleTargetClickBound),this.originEl.removeEventListener("click",this._handleOriginClickBound),window.removeEventListener("resize",this._handleThrottledResizeBound)}},{key:"_handleTargetClick",value:function(t){this.open()}},{key:"_handleOriginClick",value:function(t){this.close()}},{key:"_handleResize",value:function(t){this._calculatePositioning()}},{key:"_handleDocumentClick",value:function(t){S(t.target).closest(".tap-target-wrapper").length||(this.close(),t.preventDefault(),t.stopPropagation())}},{key:"_setup",value:function(){this.wrapper=this.$el.parent()[0],this.waveEl=S(this.wrapper).find(".tap-target-wave")[0],this.originEl=S(this.wrapper).find(".tap-target-origin")[0],this.contentEl=this.$el.find(".tap-target-content")[0],S(this.wrapper).hasClass(".tap-target-wrapper")||(this.wrapper=document.createElement("div"),this.wrapper.classList.add("tap-target-wrapper"),this.$el.before(S(this.wrapper)),this.wrapper.append(this.el)),this.contentEl||(this.contentEl=document.createElement("div"),this.contentEl.classList.add("tap-target-content"),this.$el.append(this.contentEl)),this.waveEl||(this.waveEl=document.createElement("div"),this.waveEl.classList.add("tap-target-wave"),this.originEl||(this.originEl=this.$origin.clone(!0,!0),this.originEl.addClass("tap-target-origin"),this.originEl.removeAttr("id"),this.originEl.removeAttr("style"),this.originEl=this.originEl[0],this.waveEl.append(this.originEl)),this.wrapper.append(this.waveEl))}},{key:"_calculatePositioning",value:function(){var t="fixed"===this.$origin.css("position");if(!t)for(var e=this.$origin.parents(),i=0;i<e.length&&!(t="fixed"==S(e[i]).css("position"));i++);var n=this.$origin.outerWidth(),s=this.$origin.outerHeight(),o=t?this.$origin.offset().top-M.getDocumentScrollTop():this.$origin.offset().top,a=t?this.$origin.offset().left-M.getDocumentScrollLeft():this.$origin.offset().left,r=window.innerWidth,l=window.innerHeight,h=r/2,d=l/2,u=a<=h,c=h<a,p=o<=d,v=d<o,f=.25*r<=a&&a<=.75*r,m=this.$el.outerWidth(),g=this.$el.outerHeight(),_=o+s/2-g/2,y=a+n/2-m/2,k=t?"fixed":"absolute",b=f?m:m/2+n,w=g/2,C=p?g/2:0,E=u&&!f?m/2-n:0,O=n,x=v?"bottom":"top",L=2*n,T=L,$=g/2-T/2,B=m/2-L/2,D={};D.top=p?_+"px":"",D.right=c?r-y-m+"px":"",D.bottom=v?l-_-g+"px":"",D.left=u?y+"px":"",D.position=k,S(this.wrapper).css(D),S(this.contentEl).css({width:b+"px",height:w+"px",top:C+"px",right:"0px",bottom:"0px",left:E+"px",padding:O+"px",verticalAlign:x}),S(this.waveEl).css({top:$+"px",left:B+"px",width:L+"px",height:T+"px"})}},{key:"open",value:function(){this.isOpen||("function"==typeof this.options.onOpen&&this.options.onOpen.call(this,this.$origin[0]),this.isOpen=!0,this.wrapper.classList.add("open"),document.body.addEventListener("click",this._handleDocumentClickBound,!0),document.body.addEventListener("touchend",this._handleDocumentClickBound))}},{key:"close",value:function(){this.isOpen&&("function"==typeof this.options.onClose&&this.options.onClose.call(this,this.$origin[0]),this.isOpen=!1,this.wrapper.classList.remove("open"),document.body.removeEventListener("click",this._handleDocumentClickBound,!0),document.body.removeEventListener("touchend",this._handleDocumentClickBound))}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_TapTarget}},{key:"defaults",get:function(){return e}}]),n}();M.TapTarget=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"tapTarget","M_TapTarget")}(cash),function(d){"use strict";var e={classes:"",dropdownOptions:{}},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return i.$el.hasClass("browser-default")?_possibleConstructorReturn(i):((i.el.M_FormSelect=i).options=d.extend({},n.defaults,e),i.isMultiple=i.$el.prop("multiple"),i.el.tabIndex=-1,i._keysSelected={},i._valueDict={},i._setupDropdown(),i._setupEventHandlers(),i)}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this._removeDropdown(),this.el.M_FormSelect=void 0}},{key:"_setupEventHandlers",value:function(){var e=this;this._handleSelectChangeBound=this._handleSelectChange.bind(this),this._handleOptionClickBound=this._handleOptionClick.bind(this),this._handleInputClickBound=this._handleInputClick.bind(this),d(this.dropdownOptions).find("li:not(.optgroup)").each(function(t){t.addEventListener("click",e._handleOptionClickBound)}),this.el.addEventListener("change",this._handleSelectChangeBound),this.input.addEventListener("click",this._handleInputClickBound)}},{key:"_removeEventHandlers",value:function(){var e=this;d(this.dropdownOptions).find("li:not(.optgroup)").each(function(t){t.removeEventListener("click",e._handleOptionClickBound)}),this.el.removeEventListener("change",this._handleSelectChangeBound),this.input.removeEventListener("click",this._handleInputClickBound)}},{key:"_handleSelectChange",value:function(t){this._setValueToInput()}},{key:"_handleOptionClick",value:function(t){t.preventDefault();var e=d(t.target).closest("li")[0],i=e.id;if(!d(e).hasClass("disabled")&&!d(e).hasClass("optgroup")&&i.length){var n=!0;if(this.isMultiple){var s=d(this.dropdownOptions).find("li.disabled.selected");s.length&&(s.removeClass("selected"),s.find('input[type="checkbox"]').prop("checked",!1),this._toggleEntryFromArray(s[0].id)),n=this._toggleEntryFromArray(i)}else d(this.dropdownOptions).find("li").removeClass("selected"),d(e).toggleClass("selected",n);d(this._valueDict[i].el).prop("selected")!==n&&(d(this._valueDict[i].el).prop("selected",n),this.$el.trigger("change"))}t.stopPropagation()}},{key:"_handleInputClick",value:function(){this.dropdown&&this.dropdown.isOpen&&(this._setValueToInput(),this._setSelectedStates())}},{key:"_setupDropdown",value:function(){var n=this;this.wrapper=document.createElement("div"),d(this.wrapper).addClass("select-wrapper "+this.options.classes),this.$el.before(d(this.wrapper)),this.wrapper.appendChild(this.el),this.el.disabled&&this.wrapper.classList.add("disabled"),this.$selectOptions=this.$el.children("option, optgroup"),this.dropdownOptions=document.createElement("ul"),this.dropdownOptions.id="select-options-"+M.guid(),d(this.dropdownOptions).addClass("dropdown-content select-dropdown "+(this.isMultiple?"multiple-select-dropdown":"")),this.$selectOptions.length&&this.$selectOptions.each(function(t){if(d(t).is("option")){var e=void 0;e=n.isMultiple?n._appendOptionWithIcon(n.$el,t,"multiple"):n._appendOptionWithIcon(n.$el,t),n._addOptionToValueDict(t,e)}else if(d(t).is("optgroup")){var i=d(t).children("option");d(n.dropdownOptions).append(d('<li class="optgroup"><span>'+t.getAttribute("label")+"</span></li>")[0]),i.each(function(t){var e=n._appendOptionWithIcon(n.$el,t,"optgroup-option");n._addOptionToValueDict(t,e)})}}),this.$el.after(this.dropdownOptions),this.input=document.createElement("input"),d(this.input).addClass("select-dropdown dropdown-trigger"),this.input.setAttribute("type","text"),this.input.setAttribute("readonly","true"),this.input.setAttribute("data-target",this.dropdownOptions.id),this.el.disabled&&d(this.input).prop("disabled","true"),this.$el.before(this.input),this._setValueToInput();var t=d('<svg class="caret" height="24" viewBox="0 0 24 24" width="24" xmlns="http://www.w3.org/2000/svg"><path d="M7 10l5 5 5-5z"/><path d="M0 0h24v24H0z" fill="none"/></svg>');if(this.$el.before(t[0]),!this.el.disabled){var e=d.extend({},this.options.dropdownOptions);e.onOpenEnd=function(t){var e=d(n.dropdownOptions).find(".selected").first();if(e.length&&(M.keyDown=!0,n.dropdown.focusedIndex=e.index(),n.dropdown._focusFocusedItem(),M.keyDown=!1,n.dropdown.isScrollable)){var i=e[0].getBoundingClientRect().top-n.dropdownOptions.getBoundingClientRect().top;i-=n.dropdownOptions.clientHeight/2,n.dropdownOptions.scrollTop=i}},this.isMultiple&&(e.closeOnClick=!1),this.dropdown=M.Dropdown.init(this.input,e)}this._setSelectedStates()}},{key:"_addOptionToValueDict",value:function(t,e){var i=Object.keys(this._valueDict).length,n=this.dropdownOptions.id+i,s={};e.id=n,s.el=t,s.optionEl=e,this._valueDict[n]=s}},{key:"_removeDropdown",value:function(){d(this.wrapper).find(".caret").remove(),d(this.input).remove(),d(this.dropdownOptions).remove(),d(this.wrapper).before(this.$el),d(this.wrapper).remove()}},{key:"_appendOptionWithIcon",value:function(t,e,i){var n=e.disabled?"disabled ":"",s="optgroup-option"===i?"optgroup-option ":"",o=this.isMultiple?'<label><input type="checkbox"'+n+'"/><span>'+e.innerHTML+"</span></label>":e.innerHTML,a=d("<li></li>"),r=d("<span></span>");r.html(o),a.addClass(n+" "+s),a.append(r);var l=e.getAttribute("data-icon");if(l){var h=d('<img alt="" src="'+l+'">');a.prepend(h)}return d(this.dropdownOptions).append(a[0]),a[0]}},{key:"_toggleEntryFromArray",value:function(t){var e=!this._keysSelected.hasOwnProperty(t),i=d(this._valueDict[t].optionEl);return e?this._keysSelected[t]=!0:delete this._keysSelected[t],i.toggleClass("selected",e),i.find('input[type="checkbox"]').prop("checked",e),i.prop("selected",e),e}},{key:"_setValueToInput",value:function(){var i=[];if(this.$el.find("option").each(function(t){if(d(t).prop("selected")){var e=d(t).text();i.push(e)}}),!i.length){var t=this.$el.find("option:disabled").eq(0);t.length&&""===t[0].value&&i.push(t.text())}this.input.value=i.join(", ")}},{key:"_setSelectedStates",value:function(){for(var t in this._keysSelected={},this._valueDict){var e=this._valueDict[t],i=d(e.el).prop("selected");d(e.optionEl).find('input[type="checkbox"]').prop("checked",i),i?(this._activateOption(d(this.dropdownOptions),d(e.optionEl)),this._keysSelected[t]=!0):d(e.optionEl).removeClass("selected")}}},{key:"_activateOption",value:function(t,e){e&&(this.isMultiple||t.find("li.selected").removeClass("selected"),d(e).addClass("selected"))}},{key:"getSelectedValues",value:function(){var t=[];for(var e in this._keysSelected)t.push(this._valueDict[e].el.value);return t}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_FormSelect}},{key:"defaults",get:function(){return e}}]),n}();M.FormSelect=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"formSelect","M_FormSelect")}(cash),function(s,e){"use strict";var i={},t=function(t){function n(t,e){_classCallCheck(this,n);var i=_possibleConstructorReturn(this,(n.__proto__||Object.getPrototypeOf(n)).call(this,n,t,e));return(i.el.M_Range=i).options=s.extend({},n.defaults,e),i._mousedown=!1,i._setupThumb(),i._setupEventHandlers(),i}return _inherits(n,Component),_createClass(n,[{key:"destroy",value:function(){this._removeEventHandlers(),this._removeThumb(),this.el.M_Range=void 0}},{key:"_setupEventHandlers",value:function(){this._handleRangeChangeBound=this._handleRangeChange.bind(this),this._handleRangeMousedownTouchstartBound=this._handleRangeMousedownTouchstart.bind(this),this._handleRangeInputMousemoveTouchmoveBound=this._handleRangeInputMousemoveTouchmove.bind(this),this._handleRangeMouseupTouchendBound=this._handleRangeMouseupTouchend.bind(this),this._handleRangeBlurMouseoutTouchleaveBound=this._handleRangeBlurMouseoutTouchleave.bind(this),this.el.addEventListener("change",this._handleRangeChangeBound),this.el.addEventListener("mousedown",this._handleRangeMousedownTouchstartBound),this.el.addEventListener("touchstart",this._handleRangeMousedownTouchstartBound),this.el.addEventListener("input",this._handleRangeInputMousemoveTouchmoveBound),this.el.addEventListener("mousemove",this._handleRangeInputMousemoveTouchmoveBound),this.el.addEventListener("touchmove",this._handleRangeInputMousemoveTouchmoveBound),this.el.addEventListener("mouseup",this._handleRangeMouseupTouchendBound),this.el.addEventListener("touchend",this._handleRangeMouseupTouchendBound),this.el.addEventListener("blur",this._handleRangeBlurMouseoutTouchleaveBound),this.el.addEventListener("mouseout",this._handleRangeBlurMouseoutTouchleaveBound),this.el.addEventListener("touchleave",this._handleRangeBlurMouseoutTouchleaveBound)}},{key:"_removeEventHandlers",value:function(){this.el.removeEventListener("change",this._handleRangeChangeBound),this.el.removeEventListener("mousedown",this._handleRangeMousedownTouchstartBound),this.el.removeEventListener("touchstart",this._handleRangeMousedownTouchstartBound),this.el.removeEventListener("input",this._handleRangeInputMousemoveTouchmoveBound),this.el.removeEventListener("mousemove",this._handleRangeInputMousemoveTouchmoveBound),this.el.removeEventListener("touchmove",this._handleRangeInputMousemoveTouchmoveBound),this.el.removeEventListener("mouseup",this._handleRangeMouseupTouchendBound),this.el.removeEventListener("touchend",this._handleRangeMouseupTouchendBound),this.el.removeEventListener("blur",this._handleRangeBlurMouseoutTouchleaveBound),this.el.removeEventListener("mouseout",this._handleRangeBlurMouseoutTouchleaveBound),this.el.removeEventListener("touchleave",this._handleRangeBlurMouseoutTouchleaveBound)}},{key:"_handleRangeChange",value:function(){s(this.value).html(this.$el.val()),s(this.thumb).hasClass("active")||this._showRangeBubble();var t=this._calcRangeOffset();s(this.thumb).addClass("active").css("left",t+"px")}},{key:"_handleRangeMousedownTouchstart",value:function(t){if(s(this.value).html(this.$el.val()),this._mousedown=!0,this.$el.addClass("active"),s(this.thumb).hasClass("active")||this._showRangeBubble(),"input"!==t.type){var e=this._calcRangeOffset();s(this.thumb).addClass("active").css("left",e+"px")}}},{key:"_handleRangeInputMousemoveTouchmove",value:function(){if(this._mousedown){s(this.thumb).hasClass("active")||this._showRangeBubble();var t=this._calcRangeOffset();s(this.thumb).addClass("active").css("left",t+"px"),s(this.value).html(this.$el.val())}}},{key:"_handleRangeMouseupTouchend",value:function(){this._mousedown=!1,this.$el.removeClass("active")}},{key:"_handleRangeBlurMouseoutTouchleave",value:function(){if(!this._mousedown){var t=7+parseInt(this.$el.css("padding-left"))+"px";s(this.thumb).hasClass("active")&&(e.remove(this.thumb),e({targets:this.thumb,height:0,width:0,top:10,easing:"easeOutQuad",marginLeft:t,duration:100})),s(this.thumb).removeClass("active")}}},{key:"_setupThumb",value:function(){this.thumb=document.createElement("span"),this.value=document.createElement("span"),s(this.thumb).addClass("thumb"),s(this.value).addClass("value"),s(this.thumb).append(this.value),this.$el.after(this.thumb)}},{key:"_removeThumb",value:function(){s(this.thumb).remove()}},{key:"_showRangeBubble",value:function(){var t=-7+parseInt(s(this.thumb).parent().css("padding-left"))+"px";e.remove(this.thumb),e({targets:this.thumb,height:30,width:30,top:-30,marginLeft:t,duration:300,easing:"easeOutQuint"})}},{key:"_calcRangeOffset",value:function(){var t=this.$el.width()-15,e=parseFloat(this.$el.attr("max"))||100,i=parseFloat(this.$el.attr("min"))||0;return(parseFloat(this.$el.val())-i)/(e-i)*t}}],[{key:"init",value:function(t,e){return _get(n.__proto__||Object.getPrototypeOf(n),"init",this).call(this,this,t,e)}},{key:"getInstance",value:function(t){return(t.jquery?t[0]:t).M_Range}},{key:"defaults",get:function(){return i}}]),n}();M.Range=t,M.jQueryLoaded&&M.initializeJqueryWrapper(t,"range","M_Range"),t.init(s("input[type=range]"))}(cash,M.anime);
import styled from 'styled-components/native'; import logo from 'assets/logo.png'; export const Container = styled.View` padding: 20px; flex: 1; justify-content: center; `; export const Logo = styled.Image.attrs({ source: logo, resizeMode: 'contain', })` width: 200px; height: 200px; align-self: center; margin-bottom: 40px; `;
const terser = require('rollup-plugin-terser').terser; const pkg = require('./package.json'); const banner = `/*! * ${pkg.name} v${pkg.version} * ${pkg.homepage} * (c) ${new Date().getFullYear()} Chart.js Contributors * Released under the ${pkg.license} license */`; const input = 'src/index.js'; module.exports = [ { input, output: { file: `dist/${pkg.name}.js`, banner: banner, format: 'umd', indent: false, globals: { 'chart.js': 'Chart', luxon: 'luxon' } }, external: [ 'chart.js', 'luxon' ] }, { input, plugins: [ terser({ output: { preamble: banner } }) ], output: { file: `dist/${pkg.name}.min.js`, format: 'umd', indent: false, globals: { 'chart.js': 'Chart', luxon: 'luxon' } }, external: [ 'chart.js', 'luxon' ] }, { input, output: { file: `dist/${pkg.name}.esm.js`, banner, format: 'esm', indent: false, }, external: [ 'chart.js', 'luxon' ] }, { input, plugins: [ terser({ output: { preamble: banner } }) ], output: { file: `dist/${pkg.name}.esm.min.js`, format: 'esm', indent: false }, external: [ 'chart.js', 'luxon' ] } ];
#! /usr/bin/env python # -*- coding: utf-8 -*- # # Copyright © Her Majesty the Queen in Right of Canada, as represented # by the Minister of Statistics Canada, 2020. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. import unittest, json from jsonschema import Draft7Validator, validate from pyproddi.io.protobuf import ddicdi_pb2 from pyproddi.ddicdi import PhysicalStructure class PhysicalStructureTestCase(unittest.TestCase): def setUp(self): print("+++++++++++++++++++++++++++++++++++++++") print("Begining new TestCase %s" % self._testMethodName) print("+++++++++++++++++++++++++++++++++++++++") with open("pyproddi/io/json/ddicdi.json") as f: self.schema = json.load(f) print("Schema validator result:") print(Draft7Validator.check_schema(self.schema)) def test_PhysicalStructure(self): my_ps = PhysicalStructure("ddt", "ddp", "dds", "dd", "ddgs", "desc", "df", ["grs"], ["label"], ["psn"]) print("Python object") print(my_ps) my_ps_pb = my_ps.to_pb() print("Protocol buffer message") print(my_ps_pb) def test_PhysicalStructure_json(self): my_ps_json = { "PhysicalStructure" : { "DefaultDataType" : "ddt", "DefaultDecimalPositions" : "ddp", "DefaultDecimalSeparator" : "dds", "DefaultDelimiter" : "dd", "DefaultDigitGroupSeparator" : "ddgs", "Description" : "Some desc.", "FileFormat" : "ff", "GrossRecordStructure" : ["grs1", "grs2", "grs3", "grs4"], "Label" : ["lab1"], "PhysicalStructureName" : ["psn1", "psn2", "psn3", "psn4"] } } print("JSON PhysicalStructure message") print(validate(instance=my_ps_json, schema=self.schema)) if __name__ == "__main__": unittest.main()
import unittest class TestHello(unittest.TestCase): def test_hello(self): self.assertEqual("hello","hello")
/* -*- Mode: C++; tab-width: 2; indent-tabs-mode: nil; c-basic-offset: 2 -*- */ /* ***** BEGIN LICENSE BLOCK ***** * Version: MPL 1.1/GPL 2.0/LGPL 2.1 * * The contents of this file are subject to the Mozilla Public License Version * 1.1 (the "License"); you may not use this file except in compliance with * the License. You may obtain a copy of the License at * http://www.mozilla.org/MPL/ * * Software distributed under the License is distributed on an "AS IS" basis, * WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License * for the specific language governing rights and limitations under the * License. * * The Original Code is Mozilla Communicator client code, released * March 31, 1998. * * The Initial Developer of the Original Code is * Netscape Communications Corporation. * Portions created by the Initial Developer are Copyright (C) 1998 * the Initial Developer. All Rights Reserved. * * Contributor(s): * * Alternatively, the contents of this file may be used under the terms of * either the GNU General Public License Version 2 or later (the "GPL"), or * the GNU Lesser General Public License Version 2.1 or later (the "LGPL"), * in which case the provisions of the GPL or the LGPL are applicable instead * of those above. If you wish to allow use of your version of this file only * under the terms of either the GPL or the LGPL, and not to allow others to * use your version of this file under the terms of the MPL, indicate your * decision by deleting the provisions above and replace them with the notice * and other provisions required by the GPL or the LGPL. If you do not delete * the provisions above, a recipient may use your version of this file under * the terms of any one of the MPL, the GPL or the LGPL. * * ***** END LICENSE BLOCK ***** */ gTestfile = '15.9.5.16.js'; /** File Name: 15.9.5.16.js ECMA Section: 15.9.5.16 Description: Date.prototype.getMinutes 1.Let t be this time value. 2.If t is NaN, return NaN. 3.Return MinFromTime(LocalTime(t)). Author: [email protected] Date: 12 november 1997 */ var SECTION = "15.9.5.16"; var VERSION = "ECMA_1"; startTest(); var TITLE = "Date.prototype.getMinutes()"; writeHeaderToLog( SECTION + " "+ TITLE); addTestCase( TIME_NOW ); addTestCase( TIME_0000 ); addTestCase( TIME_1970 ); addTestCase( TIME_1900 ); addTestCase( TIME_2000 ); addTestCase( UTC_FEB_29_2000 ); addTestCase( UTC_JAN_1_2005 ); new TestCase( SECTION, "(new Date(NaN)).getMinutes()", NaN, (new Date(NaN)).getMinutes() ); new TestCase( SECTION, "Date.prototype.getMinutes.length", 0, Date.prototype.getMinutes.length ); test(); function addTestCase( t ) { for ( m = 0; m <= 60; m+=10 ) { t += msPerMinute; new TestCase( SECTION, "(new Date("+t+")).getMinutes()", MinFromTime((LocalTime(t))), (new Date(t)).getMinutes() ); } }
export { BsCard } from './bs-card'; export { BsCardText } from './bs-card-text'; export { BsCardBody } from './bs-card-body'; export { BsCardTitle } from './bs-card-title'; export { BsCardOverlay } from './bs-card-overlay'; export { BsCardSubtitle } from './bs-card-subtitle'; export { BsCardLinks } from './bs-card-links'; export { BsCardLink } from './bs-card-link'; export { BsCardImg } from './bs-card-img'; export { BsCardHeader } from './bs-card-header'; export { BsCardGroup } from './bs-card-group'; export { BsCardFooter } from './bs-card-footer'; export { BsCardDeck } from './bs-card-deck'; export { BsCardColumns } from './bs-card-columns';
/** * @license * Copyright 2018 Brigham Young University * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. **/ 'use strict'; const base = require('../validator-parameter-base'); const Exception = require('../exception'); const Result = require('../result'); const util = require('../util'); module.exports = { init: function (data) { const { context, exception, major, warn } = data; if (major === 2) { const def = base.extractSchemaDefinition({}, this); const [schema, error, warning] = context.Schema(def); if (schema) this.schema = schema; if (error) exception.merge(error); if (warning) warn.merge(warning); } util.validateExamples(this, exception); }, prototype: { stringify: function (value) { const { major } = this.enforcerData; const schema = this.schema; const exception = Exception('Unable to stringify value'); if (major === 2) { return new Result(v2Stringify(this, this, exception, value), exception); } else if (major === 3) { const type = schema && schema.type; let result; if (type === 'array') { result = value .map((value, index) => stringifyPrimitive(this, schema.items, exception.at(index), value)) .join(',') } else if (type === 'object') { const array = []; Object.keys(value).forEach(key => { const subSchema = schema.properties.hasOwnProperty(key) ? schema.properties[key] : schema.additionalProperties; let val = value[key]; if (subSchema !== true) { val = stringifyPrimitive(this, subSchema, exception.at(key), val); } else if (typeof val !== 'string') { exception.message('Unable to stringify value: ' + util.smart(val)); } if (typeof val === 'string') { if (this.explode) { array.push(key + '=' + val) } else { array.push(key, val) } } }); result = array.join(','); } else { result = stringifyPrimitive(this, schema, exception, value); } return new Result(result, exception); } } }, validator: function (data) { const { major } = data; const validator = base.validator(data); Object.assign(validator.properties, { explode: { type: 'boolean', default: false }, required: { type: 'boolean', default: false }, style: { weight: -5, allowed: major === 3, type: 'string', default: 'simple', enum: ['simple'] } }); return validator; } }; function stringifyPrimitive(header, schema, exception, value) { if (value === undefined) { if (header.allowEmptyValue) return ''; exception.message('Empty value not allowed'); } else if (value === null) { if (schema.nullable) return 'null'; exception.message('Null value not allowed'); } else if (schema.type === 'boolean') { if (value === true) return 'true'; if (value === false) return 'false'; exception.message('Expected true or false. Received: ' + util.smart(value)) } else if (schema.type === 'integer' || schema.type === 'number') { if (typeof value === 'number' && !isNaN(value)) return String(value); const mode = schema.type === 'integer' ? 'an integer' : 'a number'; exception.message('Expected ' + mode + '. Received: ' + util.smart(value)); } else if (schema.type === 'string') { return value; } else { exception.message('Unable to stringify value: ' + util.smart(value)) } } function v2Stringify(parameter, schema, exception, value) { if (schema.type === 'array') { const values = value.map((value, index) => schema.items ? v2Stringify(parameter, schema.items, exception.at(index), value) : value); switch (schema.collectionFormat) { case 'csv': return values.join(','); case 'pipes': return values.join('|'); case 'ssv': return values.join(' '); case 'tsv': return values.join('\t'); } } else { return stringifyPrimitive(parameter, schema, exception, value); } }
import take1C from "./take1C.js"; import curry from "../curry.js"; import rejectLazy from "../Lazy/rejectLazy.js"; import go1 from "../go1.js"; export default curry(function everyC(f, iter) { return go1(take1C(rejectLazy(f, iter)), ({length}) => length == 0); });;
/** * Copyright 2015 The AMP HTML Authors. All Rights Reserved. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS-IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import {BaseElement} from '../src/base-element'; import {assertHttpsUrl} from '../src/url'; import {getLengthNumeral, isLayoutSizeDefined} from '../src/layout'; import {loadPromise} from '../src/event-helper'; import {registerElement} from '../src/custom-element'; import {getMode} from '../src/mode'; /** * @param {!Window} win Destination window for the new element. * @this {undefined} // Make linter happy * @return {undefined} */ export function installVideo(win) { class AmpVideo extends BaseElement { /** @override */ isLayoutSupported(layout) { return isLayoutSizeDefined(layout); } /** @override */ buildCallback() { /** @private @const {!HTMLVideoElement} */ this.video_ = this.element.ownerDocument.createElement('video'); const width = this.element.getAttribute('width'); const height = this.element.getAttribute('height'); this.video_.width = getLengthNumeral(width); this.video_.height = getLengthNumeral(height); const posterAttr = this.element.getAttribute('poster'); if (!posterAttr && getMode().development) { console/*OK*/.error( 'No "poster" attribute has been provided for amp-video.'); } // Disable video preload in prerender mode. this.video_.setAttribute('preload', 'none'); this.propagateAttributes(['poster'], this.video_); this.applyFillContent(this.video_, true); this.element.appendChild(this.video_); } /** @override */ layoutCallback() { if (!this.isVideoSupported_()) { this.toggleFallback(true); return Promise.resolve(); } if (this.element.getAttribute('src')) { assertHttpsUrl(this.element.getAttribute('src'), this.element); } this.propagateAttributes( ['src', 'controls', 'autoplay', 'muted', 'loop'], this.video_); if (this.element.hasAttribute('preload')) { this.video_.setAttribute( 'preload', this.element.getAttribute('preload')); } else { this.video_.removeAttribute('preload'); } this.getRealChildNodes().forEach(child => { // Skip the video we already added to the element. if (this.video_ === child) { return; } if (child.getAttribute && child.getAttribute('src')) { assertHttpsUrl(child.getAttribute('src'), child); } this.video_.appendChild(child); }); return loadPromise(this.video_); } /** @override */ pauseCallback() { if (this.video_) { this.video_.pause(); } } /** @private */ isVideoSupported_() { return !!this.video_.play; } } registerElement(win, 'amp-video', AmpVideo); }
var elections = require('./elections'); var early_vote_sites = require('./early-vote-sites'); var schedules = require('./schedules'); var assignments = require('./assignments'); var auth = require('../authentication/services.js'); var file_generation = require('./file-generation'); function registerEarlyVoteServices(app) { app.all('/earlyvote/*', auth.checkJwt); elections.registerElectionServices(app); early_vote_sites.registerEarlyVoteSiteServices(app); schedules.registerScheduleServices(app); assignments.registerAssignmentServices(app); file_generation.registerFileGenerationServices(app); } exports.registerEarlyVoteServices = registerEarlyVoteServices;
const { expect } = require("chai"); const extractTypescript = require("./extract-typescript.utl"); describe("ast-extractors/extract-typescript - dynamic imports", () => { it("correctly detects a dynamic import statement", () => { expect( extractTypescript( "import('judeljo').then(judeljo => { judeljo.hochik() })" ) ).to.deep.equal([ { module: "judeljo", moduleSystem: "es6", dynamic: true, exoticallyRequired: false, }, ]); }); it("correctly detects a dynamic import statement with a template that has no placeholders", () => { expect( extractTypescript( "import(`judeljo`).then(judeljo => { judeljo.hochik() })" ) ).to.deep.equal([ { module: "judeljo", moduleSystem: "es6", dynamic: true, exoticallyRequired: false, }, ]); }); it("ignores dynamic import statements with a template that has placeholders", () => { expect( extractTypescript( // eslint-disable-next-line no-template-curly-in-string "import(`judeljo/${vlap}`).then(judeljo => { judeljo.hochik() })" ) ).to.deep.equal([]); }); it("ignores dynamic import statements with a non-string parameter", () => { expect( extractTypescript( "import(elaborateFunctionCall()).then(judeljo => { judeljo.hochik() })" ) ).to.deep.equal([]); }); it("ignores dynamic import statements without a parameter", () => { expect( extractTypescript( "import(/* nothing */).then(judeljo => { judeljo.hochik() })" ) ).to.deep.equal([]); }); });
/* eslint-env jest */ const { mockClient, fetchMock } = require('../mocks/client.mock') const Module = require('../../src/endpoints/masteries') describe('endpoints > masteries', () => { let endpoint beforeEach(() => { endpoint = new Module(mockClient) fetchMock.reset() }) it('test /v2/masteries', async () => { expect(endpoint.isPaginated).toEqual(true) expect(endpoint.isBulk).toEqual(true) expect(endpoint.supportsBulkAll).toEqual(true) expect(endpoint.isLocalized).toEqual(true) expect(endpoint.isAuthenticated).toEqual(false) expect(endpoint.cacheTime).not.toEqual(undefined) expect(endpoint.url).toEqual('/v2/masteries') fetchMock.addResponse({ id: 1, name: 'Exalted Lore' }) let content = await endpoint.get(1) expect(content.name).toEqual('Exalted Lore') }) })
import unittest from gbakeboy import Cpu from gbakeboy import Memory from gbakeboy import hex2int as h2i from gbakeboy import print_bin_8 class test_cpu(unittest.TestCase): def setUp(self): mem = Memory() self.cpu = Cpu(mem) def clear_registers(self): cpu = self.cpu cpu.set_register_16('AF', 0) cpu.set_register_16('BC', 0) cpu.set_register_16('DE', 0) cpu.set_register_16('HL', 0) cpu.set_register_16('SP', 0) cpu.set_register_16('PC', 0) def test_init(self): cpu = self.cpu mem = self.cpu.mem self.assertNotEqual(mem, None) self.assertEqual(cpu.A, h2i("01")) self.assertEqual(cpu.F, h2i("B0")) self.assertEqual(cpu.B, h2i("00")) self.assertEqual(cpu.C, h2i("13")) self.assertEqual(cpu.D, h2i("00")) self.assertEqual(cpu.E, h2i("D8")) self.assertEqual(cpu.H, h2i("01")) self.assertEqual(cpu.L, h2i("4D")) self.assertEqual(cpu.SP, h2i("FFFE")) self.assertEqual(cpu.PC, h2i("0"))
Ext.define('Ext.data.proxy.Functions', { extend: 'Ext.data.proxy.Direct', alias: 'proxy.functions', extractResponseData: function(event) { var me = this, rootProperty = me.getReader().getRootProperty(); if (!rootProperty) { return event.result } else { return event.result[rootProperty]; } }, createRequestCallback: function(request, operation) { var me = this; return function(data, event) { if (!me.canceledOperations[operation.id]) { me.processResponse(event.success, operation, request, event); } delete me.canceledOperations[operation.id]; }; }, doRequest: function(operation) { var me = this, writer, request, action, params, api, fn; if (!me.methodsResolved) { me.resolveMethods(); } request = me.buildRequest(operation); action = request.getAction(); api = me.getApi(); if (api) { fn = api[action]; } fn = fn || me.getDirectFn(); writer = me.getWriter(); if (writer && operation.allowWrite()) { request = writer.write(request); } if (action === 'read') { params = request.getParams(); } else { params = request.getJsonData(); } fn.apply(window, [params, me.createRequestCallback(request, operation)]); return request; } });
/* Modernizr 2.6.2 (Custom Build) | MIT & BSD * Build: http://modernizr.com/download/#-canvas-canvastext-audio-shiv-cssclasses-load */ ;window.Modernizr=function(a,b,c){function u(a){j.cssText=a}function v(a,b){return u(prefixes.join(a+";")+(b||""))}function w(a,b){return typeof a===b}function x(a,b){return!!~(""+a).indexOf(b)}function y(a,b,d){for(var e in a){var f=b[a[e]];if(f!==c)return d===!1?a[e]:w(f,"function")?f.bind(d||b):f}return!1}var d="2.6.2",e={},f=!0,g=b.documentElement,h="modernizr",i=b.createElement(h),j=i.style,k,l={}.toString,m={},n={},o={},p=[],q=p.slice,r,s={}.hasOwnProperty,t;!w(s,"undefined")&&!w(s.call,"undefined")?t=function(a,b){return s.call(a,b)}:t=function(a,b){return b in a&&w(a.constructor.prototype[b],"undefined")},Function.prototype.bind||(Function.prototype.bind=function(b){var c=this;if(typeof c!="function")throw new TypeError;var d=q.call(arguments,1),e=function(){if(this instanceof e){var a=function(){};a.prototype=c.prototype;var f=new a,g=c.apply(f,d.concat(q.call(arguments)));return Object(g)===g?g:f}return c.apply(b,d.concat(q.call(arguments)))};return e}),m.canvas=function(){var a=b.createElement("canvas");return!!a.getContext&&!!a.getContext("2d")},m.canvastext=function(){return!!e.canvas&&!!w(b.createElement("canvas").getContext("2d").fillText,"function")},m.audio=function(){var a=b.createElement("audio"),c=!1;try{if(c=!!a.canPlayType)c=new Boolean(c),c.ogg=a.canPlayType('audio/ogg; codecs="vorbis"').replace(/^no$/,""),c.mp3=a.canPlayType("audio/mpeg;").replace(/^no$/,""),c.wav=a.canPlayType('audio/wav; codecs="1"').replace(/^no$/,""),c.m4a=(a.canPlayType("audio/x-m4a;")||a.canPlayType("audio/aac;")).replace(/^no$/,"")}catch(d){}return c};for(var z in m)t(m,z)&&(r=z.toLowerCase(),e[r]=m[z](),p.push((e[r]?"":"no-")+r));return e.addTest=function(a,b){if(typeof a=="object")for(var d in a)t(a,d)&&e.addTest(d,a[d]);else{a=a.toLowerCase();if(e[a]!==c)return e;b=typeof b=="function"?b():b,typeof f!="undefined"&&f&&(g.className+=" "+(b?"":"no-")+a),e[a]=b}return e},u(""),i=k=null,function(a,b){function k(a,b){var c=a.createElement("p"),d=a.getElementsByTagName("head")[0]||a.documentElement;return c.innerHTML="x<style>"+b+"</style>",d.insertBefore(c.lastChild,d.firstChild)}function l(){var a=r.elements;return typeof a=="string"?a.split(" "):a}function m(a){var b=i[a[g]];return b||(b={},h++,a[g]=h,i[h]=b),b}function n(a,c,f){c||(c=b);if(j)return c.createElement(a);f||(f=m(c));var g;return f.cache[a]?g=f.cache[a].cloneNode():e.test(a)?g=(f.cache[a]=f.createElem(a)).cloneNode():g=f.createElem(a),g.canHaveChildren&&!d.test(a)?f.frag.appendChild(g):g}function o(a,c){a||(a=b);if(j)return a.createDocumentFragment();c=c||m(a);var d=c.frag.cloneNode(),e=0,f=l(),g=f.length;for(;e<g;e++)d.createElement(f[e]);return d}function p(a,b){b.cache||(b.cache={},b.createElem=a.createElement,b.createFrag=a.createDocumentFragment,b.frag=b.createFrag()),a.createElement=function(c){return r.shivMethods?n(c,a,b):b.createElem(c)},a.createDocumentFragment=Function("h,f","return function(){var n=f.cloneNode(),c=n.createElement;h.shivMethods&&("+l().join().replace(/\w+/g,function(a){return b.createElem(a),b.frag.createElement(a),'c("'+a+'")'})+");return n}")(r,b.frag)}function q(a){a||(a=b);var c=m(a);return r.shivCSS&&!f&&!c.hasCSS&&(c.hasCSS=!!k(a,"article,aside,figcaption,figure,footer,header,hgroup,nav,section{display:block}mark{background:#FF0;color:#000}")),j||p(a,c),a}var c=a.html5||{},d=/^<|^(?:button|map|select|textarea|object|iframe|option|optgroup)$/i,e=/^(?:a|b|code|div|fieldset|h1|h2|h3|h4|h5|h6|i|label|li|ol|p|q|span|strong|style|table|tbody|td|th|tr|ul)$/i,f,g="_html5shiv",h=0,i={},j;(function(){try{var a=b.createElement("a");a.innerHTML="<xyz></xyz>",f="hidden"in a,j=a.childNodes.length==1||function(){b.createElement("a");var a=b.createDocumentFragment();return typeof a.cloneNode=="undefined"||typeof a.createDocumentFragment=="undefined"||typeof a.createElement=="undefined"}()}catch(c){f=!0,j=!0}})();var r={elements:c.elements||"abbr article aside audio bdi canvas data datalist details figcaption figure footer header hgroup mark meter nav output progress section summary time video",shivCSS:c.shivCSS!==!1,supportsUnknownElements:j,shivMethods:c.shivMethods!==!1,type:"default",shivDocument:q,createElement:n,createDocumentFragment:o};a.html5=r,q(b)}(this,b),e._version=d,g.className=g.className.replace(/(^|\s)no-js(\s|$)/,"$1$2")+(f?" js "+p.join(" "):""),e}(this,this.document),function(a,b,c){function d(a){return"[object Function]"==o.call(a)}function e(a){return"string"==typeof a}function f(){}function g(a){return!a||"loaded"==a||"complete"==a||"uninitialized"==a}function h(){var a=p.shift();q=1,a?a.t?m(function(){("c"==a.t?B.injectCss:B.injectJs)(a.s,0,a.a,a.x,a.e,1)},0):(a(),h()):q=0}function i(a,c,d,e,f,i,j){function k(b){if(!o&&g(l.readyState)&&(u.r=o=1,!q&&h(),l.onload=l.onreadystatechange=null,b)){"img"!=a&&m(function(){t.removeChild(l)},50);for(var d in y[c])y[c].hasOwnProperty(d)&&y[c][d].onload()}}var j=j||B.errorTimeout,l=b.createElement(a),o=0,r=0,u={t:d,s:c,e:f,a:i,x:j};1===y[c]&&(r=1,y[c]=[]),"object"==a?l.data=c:(l.src=c,l.type=a),l.width=l.height="0",l.onerror=l.onload=l.onreadystatechange=function(){k.call(this,r)},p.splice(e,0,u),"img"!=a&&(r||2===y[c]?(t.insertBefore(l,s?null:n),m(k,j)):y[c].push(l))}function j(a,b,c,d,f){return q=0,b=b||"j",e(a)?i("c"==b?v:u,a,b,this.i++,c,d,f):(p.splice(this.i++,0,a),1==p.length&&h()),this}function k(){var a=B;return a.loader={load:j,i:0},a}var l=b.documentElement,m=a.setTimeout,n=b.getElementsByTagName("script")[0],o={}.toString,p=[],q=0,r="MozAppearance"in l.style,s=r&&!!b.createRange().compareNode,t=s?l:n.parentNode,l=a.opera&&"[object Opera]"==o.call(a.opera),l=!!b.attachEvent&&!l,u=r?"object":l?"script":"img",v=l?"script":u,w=Array.isArray||function(a){return"[object Array]"==o.call(a)},x=[],y={},z={timeout:function(a,b){return b.length&&(a.timeout=b[0]),a}},A,B;B=function(a){function b(a){var a=a.split("!"),b=x.length,c=a.pop(),d=a.length,c={url:c,origUrl:c,prefixes:a},e,f,g;for(f=0;f<d;f++)g=a[f].split("="),(e=z[g.shift()])&&(c=e(c,g));for(f=0;f<b;f++)c=x[f](c);return c}function g(a,e,f,g,h){var i=b(a),j=i.autoCallback;i.url.split(".").pop().split("?").shift(),i.bypass||(e&&(e=d(e)?e:e[a]||e[g]||e[a.split("/").pop().split("?")[0]]),i.instead?i.instead(a,e,f,g,h):(y[i.url]?i.noexec=!0:y[i.url]=1,f.load(i.url,i.forceCSS||!i.forceJS&&"css"==i.url.split(".").pop().split("?").shift()?"c":c,i.noexec,i.attrs,i.timeout),(d(e)||d(j))&&f.load(function(){k(),e&&e(i.origUrl,h,g),j&&j(i.origUrl,h,g),y[i.url]=2})))}function h(a,b){function c(a,c){if(a){if(e(a))c||(j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}),g(a,j,b,0,h);else if(Object(a)===a)for(n in m=function(){var b=0,c;for(c in a)a.hasOwnProperty(c)&&b++;return b}(),a)a.hasOwnProperty(n)&&(!c&&!--m&&(d(j)?j=function(){var a=[].slice.call(arguments);k.apply(this,a),l()}:j[n]=function(a){return function(){var b=[].slice.call(arguments);a&&a.apply(this,b),l()}}(k[n])),g(a[n],j,b,n,h))}else!c&&l()}var h=!!a.test,i=a.load||a.both,j=a.callback||f,k=j,l=a.complete||f,m,n;c(h?a.yep:a.nope,!!i),i&&c(i)}var i,j,l=this.yepnope.loader;if(e(a))g(a,0,l,0);else if(w(a))for(i=0;i<a.length;i++)j=a[i],e(j)?g(j,0,l,0):w(j)?B(j):Object(j)===j&&h(j,l);else Object(a)===a&&h(a,l)},B.addPrefix=function(a,b){z[a]=b},B.addFilter=function(a){x.push(a)},B.errorTimeout=1e4,null==b.readyState&&b.addEventListener&&(b.readyState="loading",b.addEventListener("DOMContentLoaded",A=function(){b.removeEventListener("DOMContentLoaded",A,0),b.readyState="complete"},0)),a.yepnope=k(),a.yepnope.executeStack=h,a.yepnope.injectJs=function(a,c,d,e,i,j){var k=b.createElement("script"),l,o,e=e||B.errorTimeout;k.src=a;for(o in d)k.setAttribute(o,d[o]);c=j?h:c||f,k.onreadystatechange=k.onload=function(){!l&&g(k.readyState)&&(l=1,c(),k.onload=k.onreadystatechange=null)},m(function(){l||(l=1,c(1))},e),i?k.onload():n.parentNode.insertBefore(k,n)},a.yepnope.injectCss=function(a,c,d,e,g,i){var e=b.createElement("link"),j,c=i?h:c||f;e.href=a,e.rel="stylesheet",e.type="text/css";for(j in d)e.setAttribute(j,d[j]);g||(n.parentNode.insertBefore(e,n),m(c,0))}}(this,document),Modernizr.load=function(){yepnope.apply(window,[].slice.call(arguments,0))};
/****************************************** * My Login * * Bootstrap 4 Login Page * * @author Muhamad Nauval Azhar * @uri https://nauval.in * @copyright Copyright (c) 2018 Muhamad Nauval Azhar * @license My Login is licensed under the MIT license. * @github https://github.com/nauvalazhar/my-login * @version 1.2.0 * * Help me to keep this project alive * https://www.buymeacoffee.com/mhdnauvalazhar * ******************************************/ 'use strict'; $(function() { // author badge :) var author = '<div style="position: fixed;bottom: 0;right: 20px;background-color: #fff;box-shadow: 0 4px 8px rgba(0,0,0,.05);border-radius: 3px 3px 0 0;font-size: 12px;padding: 5px 10px;">By <a href="https://twitter.com/mhdnauvalazhar">@mhdnauvalazhar</a> &nbsp;&bull;&nbsp; <a href="https://www.buymeacoffee.com/mhdnauvalazhar">Buy me a Coffee</a></div>'; $("body").append(author); $("input[type='password'][data-eye]").each(function(i) { var $this = $(this), id = 'eye-password-' + i, el = $('#' + id); $this.wrap($("<div/>", { style: 'position:relative', id: id })); $this.css({ paddingRight: 60 }); $this.after($("<div/>", { html: 'Show', class: 'btn btn-primary btn-sm', id: 'passeye-toggle-'+i, }).css({ position: 'absolute', right: 10, top: ($this.outerHeight() / 2) - 12, padding: '2px 7px', fontSize: 12, cursor: 'pointer', })); $this.after($("<input/>", { type: 'hidden', id: 'passeye-' + i })); var invalid_feedback = $this.parent().parent().find('.invalid-feedback'); if(invalid_feedback.length) { $this.after(invalid_feedback.clone()); } $this.on("keyup paste", function() { $("#passeye-"+i).val($(this).val()); }); $("#passeye-toggle-"+i).on("click", function() { if($this.hasClass("show")) { $this.attr('type', 'password'); $this.removeClass("show"); $(this).removeClass("btn-outline-primary"); }else{ $this.attr('type', 'text'); $this.val($("#passeye-"+i).val()); $this.addClass("show"); $(this).addClass("btn-outline-primary"); } }); }); $(".my-login-validation").submit(function() { var form = $(this); if (form[0].checkValidity() === false) { event.preventDefault(); event.stopPropagation(); } form.addClass('was-validated'); }); $("#loginbtn").click(function(e){ var email = $("#adminMail").val(); var regExp = /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/; var passwords =$("#adminPass").val().length; // var href = $(this).attr("http://127.0.0.1:8000/home"); // +++++++++ For Email +++++++++++ if(email == ""){ $('#adminEmail').text('Please Enter mail'); return false; } else if (!email.match(regExp)){ $('#adminEmail').text('Invalid Email'); return false; }else{ $('#adminEmail').text(''); } // +++++++++ For Password +++++++++++ if( passwords == "" ) { $('#adminPassword').text('Please Enter password'); return false; } else if(passwords < 5) { $('#adminPassword').text('Please Enter password Min 6 Charactor'); return false; } else if(passwords > 13) { $('#adminPassword').text('Please Enter Max 12 Charactor'); return false; } else{ // return true; $.ajaxSetup({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content') } }); $.ajax({ headers: { 'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')}, type:'get', uploadUrl: '{{route("product/create")}}', // data: {'viewmonth': date}, success: function (response) { // alert("hear"); // window.location.href = "http://127.0.0.1:8000/home // window.location = '{{ route('product.list.cats') }}'; $(".content-container").load('http://127.0.0.1:8000/home'); } }); } }); });
defineClass('Consoloid.Ui.List.Factory.Collapsing', 'Consoloid.Base.Object', { __constructor: function(options) { this.__base($.extend({ templateId: 'Consoloid-Ui-List-Factory-CollapsingElement' }, options)); this.__requireParameters(); }, __requireParameters: function() { this.requireProperty('collapsedTemplateId'); this.requireProperty('extendedTemplateId'); this.requireProperty('eventDispatcher'); }, render: function(data) { var element = this.create("Consoloid.Ui.List.Factory.CollapsingElement", { eventDispatcher: this.eventDispatcher, templateId: this.templateId, collapsedTemplateId: this.collapsedTemplateId, extendedTemplateId: this.extendedTemplateId, data: data, container: this.container }); element.render(); return element.node; } } );
const key = head; const value = tail; const insert_dict = (k,v) => dict => pair(pair(k,v),dict); function build_dict(list){ return is_null(list) ? null : insert_dict(head(list),build_dict(tail(list))); } const lookup = dict => k => !is_null(dict) && (key(head(dict))) === k ? value(head(dict)) : lookup(tail(dict),k); const update_dict = dict => (k,v) => value(head(dict)) === k ? insert_dict((k,v),build_dict(tail(dict))):(head(dict),update_dict(tail(dict))(k,v)); function hash(value){ return value%31; } function contains_hs(hashset,x){ if (is_null(hashset)){ return false; } const key = hash(x); const chain = lookup(hashset)(key); return !is_null(chain) && contains_l(chain,x); } function insert_hs(set,x){ return is_null(set) ? (x,null) : head(set) === x ? set : (head(set),insert_hs(tail(set),x)); } function union_hs(set1,set2){ return is_null(set1) ? set2 : (head(set1),union(tail(set1),set2)); }
var m = require('mithril'); module.exports = m.trust('<svg xmlns="http://www.w3.org/2000/svg" xmlns:xlink="http://www.w3.org/1999/xlink" version="1.1" baseProfile="full" width="24" height="24" viewBox="0 0 24.00 24.00" enable-background="new 0 0 24.00 24.00" xml:space="preserve"><path fill="#000000" fill-opacity="1" stroke-width="0.2" stroke-linejoin="round" d="M 8,5C 9.65685,5 11,6.34315 11,8C 11,9.65686 9.65685,11 8,11C 6.34315,11 5,9.65686 5,8C 5,6.34315 6.34315,5 8,5 Z M 16,5.00001C 17.6568,5.00001 19,6.34315 19,8.00001C 19,9.65686 17.6568,11 16,11C 14.3431,11 13,9.65686 13,8.00001C 13,6.34315 14.3431,5.00001 16,5.00001 Z M 8,13C 11.866,13 15,14.3431 15,16L 15,19L 1,19L 1,16C 1,14.3431 4.13401,13 8,13 Z M 16,13C 19.866,13 23,14.3431 23,16L 23,19L 17,19L 17,16C 17,14.8825 16.3402,13.8507 15.2251,13.0182L 16,13 Z "/></svg>');
import{getContext as C}from"svelte";import{writable as F}from"svelte/store";function p(e,a=!1){return e=e.slice(e.startsWith("/#")?2:0,e.endsWith("/*")?-2:void 0),e.startsWith("/")||(e="/"+e),e==="/"&&(e=""),a&&!e.endsWith("/")&&(e+="/"),e}function d(e,a){e=p(e,!0),a=p(a,!0);let r=[],n={},t=!0,s=e.split("/").map(o=>o.startsWith(":")?(r.push(o.slice(1)),"([^\\/]+)"):o).join("\\/"),c=a.match(new RegExp(`^${s}$`));return c||(t=!1,c=a.match(new RegExp(`^${s}`))),c?(r.forEach((o,h)=>n[o]=c[h+1]),{exact:t,params:n,part:c[0].slice(0,-1)}):null}function x(e,a,r){if(r==="")return e;if(r[0]==="/")return r;let n=c=>c.split("/").filter(o=>o!==""),t=n(e),s=a?n(a):[];return"/"+s.map((c,o)=>t[o]).join("/")+"/"+r}function m(e,a,r,n){let t=[a,"data-"+a].reduce((s,c)=>{let o=e.getAttribute(c);return r&&e.removeAttribute(c),o===null?s:o},!1);return!n&&t===""?!0:t||n||!1}function S(e){let a=e.split("&").map(r=>r.split("=")).reduce((r,n)=>{let t=n[0];if(!t)return r;let s=n.length>1?n[n.length-1]:!0;return typeof s=="string"&&s.includes(",")&&(s=s.split(",")),r[t]===void 0?r[t]=[s]:r[t].push(s),r},{});return Object.entries(a).reduce((r,n)=>(r[n[0]]=n[1].length>1?n[1]:n[1][0],r),{})}function M(e){return Object.entries(e).map(([a,r])=>r?r===!0?a:`${a}=${Array.isArray(r)?r.join(","):r}`:null).filter(a=>a).join("&")}function w(e,a){return e?a+e:""}function k(e){throw new Error("[Tinro] "+e)}var i={HISTORY:1,HASH:2,MEMORY:3,OFF:4,run(e,a,r,n){return e===this.HISTORY?a&&a():e===this.HASH?r&&r():n&&n()},getDefault(){return!window||window.location.pathname==="srcdoc"?this.MEMORY:this.HISTORY}};import"svelte/store";var y,$,H,b="",l=E();function E(){let e=i.getDefault(),a,r=c=>window.onhashchange=window.onpopstate=y=null,n=c=>a&&a(R(e)),t=c=>{c&&(e=c),r(),e!==i.OFF&&i.run(e,o=>window.onpopstate=n,o=>window.onhashchange=n)&&n()},s=c=>{let o=Object.assign(R(e),c);return o.path+w(M(o.query),"?")+w(o.hash,"#")};return{mode:t,get:c=>R(e),go(c,o){_(e,c,o),n()},start(c){a=c,t()},stop(){a=null,t(i.OFF)},set(c){this.go(s(c),!c.path)},methods(){return j(this)},base:c=>b=c}}function _(e,a,r){!r&&($=H);let n=t=>history[`${r?"replace":"push"}State`]({},"",t);i.run(e,t=>n(b+a),t=>n(`#${a}`),t=>y=a)}function R(e){let a=window.location,r=i.run(e,t=>(b?a.pathname.replace(b,""):a.pathname)+a.search+a.hash,t=>String(a.hash.slice(1)||"/"),t=>y||"/"),n=r.match(/^([^?#]+)(?:\?([^#]+))?(?:\#(.+))?$/);return H=r,{url:r,from:$,path:n[1]||"",query:S(n[2]||""),hash:n[3]||""}}function j(e){let a=()=>e.get().query,r=c=>e.set({query:c}),n=c=>r(c(a())),t=()=>e.get().hash,s=c=>e.set({hash:c});return{hash:{get:t,set:s,clear:()=>s("")},query:{replace:r,clear:()=>r(""),get(c){return c?a()[c]:a()},set(c,o){n(h=>(h[c]=o,h))},delete(c){n(o=>(o[c]&&delete o[c],o))}}}}var f=T();function T(){let{subscribe:e}=F(l.get(),a=>{l.start(a);let r=P(l.go);return()=>{l.stop(),r()}});return{subscribe:e,goto:l.go,params:Q,meta:O,useHashNavigation:a=>l.mode(a?i.HASH:i.HISTORY),mode:{hash:()=>l.mode(i.HASH),history:()=>l.mode(i.HISTORY),memory:()=>l.mode(i.MEMORY)},base:l.base,location:l.methods()}}function Y(e){let a,r,n,t,s=()=>{a=m(e,"href").replace(/^\/#|[?#].*$|\/$/g,""),r=m(e,"exact",!0),n=m(e,"active-class",!0,"active")},c=()=>{let o=d(a,t);o&&(o.exact&&r||!r)?e.classList.add(n):e.classList.remove(n)};return s(),{destroy:f.subscribe(o=>{t=o.path,c()}),update:()=>{s(),c()}}}function P(e){let a=r=>{let n=r.target.closest("a[href]"),t=n&&m(n,"target",!1,"_self"),s=n&&m(n,"tinro-ignore"),c=r.ctrlKey||r.metaKey||r.altKey||r.shiftKey;if(t=="_self"&&!s&&!c&&n){let o=n.getAttribute("href").replace(/^\/#/,"");/^\/\/|^#|^[a-zA-Z]+:/.test(o)||(r.preventDefault(),e(o.startsWith("/")?o:n.href.replace(window.location.origin,"")))}};return addEventListener("click",a),()=>removeEventListener("click",a)}function Q(){return C("tinro").meta.params}import{hasContext as U,getContext as L,setContext as W,onMount as z,tick as D}from"svelte";import{writable as I}from"svelte/store";var g="tinro",K=v({pattern:"",matched:!0});function q(e){let a=L(g)||K;(a.exact||a.fallback)&&k(`${e.fallback?"<Route fallback>":`<Route path="${e.path}">`} can't be inside ${a.fallback?"<Route fallback>":`<Route path="${a.path||"/"}"> with exact path`}`);let r=e.fallback?"fallbacks":"childs",n=I({}),t=v({fallback:e.fallback,parent:a,update(s){t.exact=!s.path.endsWith("/*"),t.pattern=p(`${t.parent.pattern||""}${s.path}`),t.redirect=s.redirect,t.firstmatch=s.firstmatch,t.breadcrumb=s.breadcrumb,t.match()},register:()=>(t.parent[r].add(t),async()=>{t.parent[r].delete(t),t.parent.activeChilds.delete(t),t.router.un&&t.router.un(),t.parent.match()}),show:()=>{e.onShow(),!t.fallback&&t.parent.activeChilds.add(t)},hide:()=>{e.onHide(),t.parent.activeChilds.delete(t)},match:async()=>{t.matched=!1;let{path:s,url:c,from:o,query:h}=t.router.location,u=d(t.pattern,s);if(!t.fallback&&u&&t.redirect&&(!t.exact||t.exact&&u.exact)){let A=x(s,t.parent.pattern,t.redirect);return f.goto(A,!0)}t.meta=u&&{from:o,url:c,query:h,match:u.part,pattern:t.pattern,breadcrumbs:t.parent.meta&&t.parent.meta.breadcrumbs.slice()||[],params:u.params,subscribe:n.subscribe},t.breadcrumb&&t.meta&&t.meta.breadcrumbs.push({name:t.breadcrumb,path:u.part}),n.set(t.meta),u&&!t.fallback&&(!t.exact||t.exact&&u.exact)&&(!t.parent.firstmatch||!t.parent.matched)?(e.onMeta(t.meta),t.parent.matched=!0,t.show()):t.hide(),u&&t.showFallbacks()}});return W(g,t),z(()=>t.register()),t}function O(){return U(g)?L(g).meta:k("meta() function must be run inside any `<Route>` child component only")}function v(e){let a={router:{},exact:!1,pattern:null,meta:null,parent:null,fallback:!1,redirect:!1,firstmatch:!1,breadcrumb:null,matched:!1,childs:new Set,activeChilds:new Set,fallbacks:new Set,async showFallbacks(){if(!this.fallback&&(await D(),this.childs.size>0&&this.activeChilds.size==0||this.childs.size==0&&this.fallbacks.size>0)){let r=this;for(;r.fallbacks.size==0;)if(r=r.parent,!r)return;r&&r.fallbacks.forEach(n=>{if(n.redirect){let t=x("/",n.parent.pattern,n.redirect);f.goto(t,!0)}else n.show()})}},start(){this.router.un||(this.router.un=f.subscribe(r=>{this.router.location=r,this.pattern!==null&&this.match()}))},match(){this.showFallbacks()}};return Object.assign(a,e),a.start(),a}export{Y as active,q as createRouteObject,O as meta,f as router};
import React from 'react'; import onClickOutside from 'react-onclickoutside'; import {getDisplayName} from '../utils/'; import {BACKSPACE} from '../constants/keyCode'; /** * Higher-order component that encapsulates Token behaviors, allowing them to * be easily re-used. */ const tokenContainer = (Component) => { class WrappedComponent extends React.Component { displayName = `tokenContainer(${getDisplayName(Component)})`; state = { active: false, }; render() { const { disableOnClickOutside, enableOnClickOutside, eventTypes, outsideClickIgnoreClass, preventDefault, stopPropagation, ...tokenProps } = this.props; return ( <Component {...tokenProps} {...this.state} onBlur={this._handleBlur} onClick={this._handleActive} onFocus={this._handleActive} onKeyDown={this._handleKeyDown} /> ); } _handleBlur = (e) => { this.setState({active: false}); } _handleKeyDown = (e) => { switch (e.keyCode) { case BACKSPACE: if (this.state.active) { // Prevent backspace keypress from triggering the browser "back" // action. e.preventDefault(); this.props.onRemove(); } break; } } /** * From `onClickOutside` HOC. */ handleClickOutside = (e) => { this._handleBlur(); } _handleActive = (e) => { e.stopPropagation(); this.setState({active: true}); } } return onClickOutside(WrappedComponent); }; export default tokenContainer;
export {libraryReducer} from './library' export {playbackReducer} from './playback' export {settingsReducer} from './settings' export {tracklistReducer} from './tracklist'
/* * @Author: czy0729 * @Date: 2021-01-21 15:55:02 * @Last Modified by: czy0729 * @Last Modified time: 2021-11-14 16:19:10 */ import React from 'react' import { Text } from '@components' import { _ } from '@stores' import { obc } from '@utils/decorators' import { HTMLDecode } from '@utils/html' import { MODEL_SUBJECT_TYPE } from '@constants/model' const weekDayMap = { 0: '日', 1: '一', 2: '二', 3: '三', 4: '四', 5: '五', 6: '六', 7: '日' } function Title({ subject, subjectId }, { $ }) { const type = MODEL_SUBJECT_TYPE.getTitle(subject.type) const isBook = type === '书籍' const doing = isBook ? '读' : '看' const { weekDay, isExist } = $.onAirCustom(subjectId) const weekDayText = isExist ? ` / 周${weekDayMap[weekDay]}` : '' return ( <> <Text numberOfLines={2} bold> {HTMLDecode(subject.name_cn || subject.name)} </Text> {!!subject?.collection?.doing && ( <Text style={_.mt.xs} type='sub' size={12}> {subject.collection.doing} 人在{doing} {weekDayText} </Text> )} </> ) } export default obc(Title)
import pygame as pg import pygame_ai as pai import utilities.common_functions # world settings TILE_DIMENSIONS = 7 TILESIZE = 128 FOVSIZE = TILESIZE*1.5 TOTAL_SIZE = (TILESIZE*TILE_DIMENSIONS, TILESIZE*TILE_DIMENSIONS) FOG_OF_WAR = False # screen settings SCREEN_SIZE = TOTAL_SIZE FPS = 60 FONT_SIZE = 40 # splash screens WIN_MESSAGE = "You Win!" LOSS_MESSAGE = "You Lost!" # assets ASSETS_DIR = "assets" # verbose assets VERBOSE_ASSETS_DIR = utilities.common_functions.join_paths(ASSETS_DIR, ["verbose-assets"]) VERBOSE_TILE_A_IMG = utilities.common_functions.load_image(VERBOSE_ASSETS_DIR, "tile_a.png") VERBOSE_TILE_B_IMG = utilities.common_functions.load_image(VERBOSE_ASSETS_DIR, "tile_b.png") VERBOSE_TILE_C_IMG = utilities.common_functions.load_image(VERBOSE_ASSETS_DIR, "tile_c.png") VERBOSE_PLAYER_IMG = utilities.common_functions.load_image(VERBOSE_ASSETS_DIR, "player.png") VERBOSE_ENEMY_IMG = utilities.common_functions.load_image(VERBOSE_ASSETS_DIR, "enemy.png") # premade assets PREMADE_ASSETS_DIR = utilities.common_functions.join_paths(ASSETS_DIR, ["premade-assets"]) PREMADE_TILE_A_IMG = utilities.common_functions.load_image(PREMADE_ASSETS_DIR, "premade-tile_a.png") PREMADE_TILE_B_IMG = utilities.common_functions.load_image(PREMADE_ASSETS_DIR, "premade-tile_b.png") PREMADE_TILE_C_IMG = utilities.common_functions.load_image(PREMADE_ASSETS_DIR, "premade-tile_c.png") PREMADE_PLAYER_IMG = utilities.common_functions.load_image(PREMADE_ASSETS_DIR, "premade-player.png") PREMADE_ENEMY_IMG = utilities.common_functions.load_image(PREMADE_ASSETS_DIR, "premade-enemy.png") # class made assets CLASS_ASSETS_DIR = utilities.common_functions.join_paths(ASSETS_DIR, ["class-assets"]) CLASS_TILE_A_IMG = utilities.common_functions.load_image(CLASS_ASSETS_DIR, "tile_a.png") CLASS_TILE_B_IMG = utilities.common_functions.load_image(CLASS_ASSETS_DIR, "tile_b.png") CLASS_TILE_C_IMG = utilities.common_functions.load_image(CLASS_ASSETS_DIR, "tile_c.png") CLASS_PLAYER_IMG = utilities.common_functions.load_image(CLASS_ASSETS_DIR, "player.png") CLASS_ENEMY_IMG = utilities.common_functions.load_image(CLASS_ASSETS_DIR, "enemy.png") # active assets # active is class made TILE_A_IMG = CLASS_TILE_A_IMG TILE_B_IMG = CLASS_TILE_B_IMG TILE_C_IMG = CLASS_TILE_C_IMG PLAYER_IMG = CLASS_PLAYER_IMG ENEMY_IMG = CLASS_ENEMY_IMG # active is premade # TILE_A_IMG = PREMADE_TILE_A_IMG # TILE_B_IMG = PREMADE_TILE_B_IMG # TILE_C_IMG = PREMADE_TILE_C_IMG # PLAYER_IMG = PREMADE_PLAYER_IMG # ENEMY_IMG = PREMADE_ENEMY_IMG # active is verbose # TILE_A_IMG = VERBOSE_TILE_A_IMG # TILE_B_IMG = VERBOSE_TILE_B_IMG # TILE_C_IMG = VERBOSE_TILE_C_IMG # PLAYER_IMG = VERBOSE_PLAYER_IMG # ENEMY_IMG = VERBOSE_ENEMY_IMG # Drag DRAG = pai.steering.kinematic.Drag(15) # Player Settings PLAYER_MAX_SPEED = 15 PLAYER_MAX_ACCEL = 30 PLAYER_MAX_ROTATION = 40 PLAYER_MAX_ANGULAR_ACCEL = 30 PLAYER_STEERING = pai.steering.kinematic.SteeringOutput PLAYER_BOUNCE = 0.3 # ENEMY Settings NUMBER_OF_ENEMIES = 0 ENEMY_MAX_SPEED = 5 ENEMY_MAX_ACCEL = 20 ENEMY_MAX_ROTATION = 20 ENEMY_MAX_ANGULAR_ACCEL = 15 ENEMY_STEERING = pai.steering.kinematic.Seek
// Given a N by M matrix of numbers, // print out the matrix in a clockwise spiral. // For example, given the following matrix: // [[1, 2, 3, 4, 5], // [6, 7, 8, 9, 10], // [11, 12, 13, 14, 15], // [16, 17, 18, 19, 20]] // You should print out the following: // 1 // 2 // 3 // 4 // 5 // 10 // 15 // 20 // 19 // 18 // 17 // 16 // 11 // 6 // 7 // 8 // 9 // 14 // 13 // 12 function matrixSpiral(matrix){ //plan // use math to get each index after first // make the number that you turn at reduce after each revolution } let matrix1 = [ [1, 2, 3, 4, 5], [6, 7, 8, 9, 10], [11, 12, 13, 14, 15], [16, 17, 18, 19, 20] ] console.log(matrixSpiral(matrix1))
const Discord = require('discord.js') const Confax = require('../bot.js') Confax.registerCommand('invite', 'default', (message) => { return 'Invite Link: https://discordapp.com/oauth2/authorize?client_id=319545839951544320&permissions=519174&scope=bot' }, ['invitelink'], 'Get invite link to invite Confax to your server', '[]')
def isValid(s: str) -> bool: stack = [] mapping = { ")" : "(", "]" : "[", "}" : "{" } for i in s: if i in mapping: top_element = stack.pop() if stack else "" if mapping[i] != top_element: return False else: stack.append(i) return not stack s = input("Enter a Parentheses : ") result = isValid(s) print(result)
import numpy as np # モジュールnumpyをnpという名前で読み込み import csv # モジュールcsvの読み込み import matplotlib.pyplot as plt # モジュールmatplotlibのpyplot関数をplt # という名前で読み込み reader = csv.reader(open('out.csv', 'r')) # 先ほど出力したoutput.csvの読み込み f_history = [] # 目的関数の履歴 x1_history, x2_history = [], [] # 設計変数の履歴 for row in reader: # 1行目はラベル行なので読み飛ばし break for row in reader: f_history.append(float(row[1])) # 目的関数の読み込み x1_history.append(float(row[2])) # 設計変数の読み込み x2_history.append(float(row[3])) plt.figure(figsize=(15, 8)) # グラフ描画キャンバスを横縦比15:8で生成 x1 = np.arange(1.25, 4.75, 0.1) # 1.25〜4.75まで0.1刻みのベクトル x2 = np.arange(0.25, 3.75, 0.1) # 0.25〜3.75まで0.1刻みのベクトル X1, X2 = np.meshgrid(x1, x2) # x1,x2を組み合わせた行列 f = np.vectorize(lambda x1, x2: 0.50 * (x1 - 3.0) ** 2 + (x2 - 2.0)**2) # x1,x2を引数として # 目的関数を返す関数 plt.subplot(1, 2, 1) # 1行目の2列の並びの1列目にグラフを生成 plt.xlabel('x1') # 水平方向のラベル plt.ylabel('x2') # 鉛直方向のラベル C = plt.contour(X1, X2, f(X1, X2), 20, colors='black') # 等高線データ生成 plt.clabel(C, inline=1, fontsize=10) # 等高線図生成 plt.plot(x1_history, x2_history) # 目的関数の探索経路生成 plt.subplot(1, 2, 2) # 1行目の2列の並びの2列目にグラフを生成 plt.xlabel('step') # 水平方向のラベル plt.ylabel('f(x)') # 鉛直方向のラベル plt.plot(f_history) # 目的関数の履歴図の生成 # (x成分を省略すれば自動的に横軸はstep数となる) plt.show() # グラフを画面に表示する
define( ({ commonCore: { common: { add: "추가", edit: "편집", save: "저장", next: "다음", cancel: "취소", back: "뒤로", apply: "적용", close: "닫기", open: "열기", start: "시작", loading: "불러오는 중", disabledAdmin: "이 기능은 관리자가 사용하지 않도록 설정했습니다.", width: "너비", height: "높이" }, inlineFieldEdit: { editMe: "편집!" }, builderPanel: { panelHeader: "%TPL_NAME% 빌더", buttonSaving: "저장", buttonSaved: "저장됨", buttonShare: "공유", buttonSettings: "설정", buttonHelp: "도움말", buttonPreview: "실시간 보기", tooltipFirstSave: "저장하기 전까지 사용할 수 없습니다.", tooltipNotShared: "공유하기 전까지 사용할 수 없습니다.", noPendingChange: "보류 중인 변경 사항 없음", unSavedChangePlural: "보류 중인 변경 내용", closeWithPendingChange: "이 작업을 확인하시겠습니까? 변경 내용이 손실됩니다.", saveError: "저장하지 못했습니다. 다시 시도하세요.", shareStatus1: "응용프로그램을 아직 저장하지 않습니다.", shareStatus2: "응용프로그램이 공개적으로 공유됨", shareStatus3: "응용프로그램이 기관 내에서 공유됨", shareStatus4: "응용프로그램이 공유되지 않음" }, saveError: { title: "응용프로그램을 저장하는 동안 오류 발생", err1Div1: "같은 이름을 가진 다른 항목이 이미 있으므로 응용프로그램을 저장할 수 없습니다(<a class='linkagolroot' target='_blank'>콘텐츠 폴더</a> 참조).", err1Div2: "응용프로그램 제목을 수정한 후 응용프로그램을 저장하세요.", btnOk: "응용프로그램 제목 편집" }, share: { firstSaveTitle: "응용프로그램이 저장됨", firstSaveHeader: "응용프로그램을 %PORTAL%에 저장했지만 아직 공유하지 않았습니다.", firstSavePreview: "미리보기", firstSaveShare: "공유", firstSaveA1: "%PORTAL%에 익숙하지 않거나 바로가기를 통해 빌더 인터페이스에 접근하려면 다음 링크를 저장하면 됩니다. %LINK1%", firstSaveA1bis: "<a href='%LINK2%' target='_blank'>%PORTAL% 콘텐츠 폴더</a>에서도 응용프로그램을 찾을 수 있습니다.", shareTitle: "응용프로그램 공유", sharePrivateHeader: "응용프로그램이 공유되고 있지 않습니다. 공유하시겠습니까?", sharePrivateBtn1: "공개적으로 공유", sharePrivateBtn2: "내 기관과 공유", sharePrivateWarning: "<a href='%LINK%' target='_blank'>웹 맵</a>의 소유자가 아니므로 %WITH% 공유를 사용할 수 없습니다.", sharePrivateWarningWith1: "공개", sharePrivateWarningWith2: "기관에 공개", sharePrivateProgress: "공유 처리 중...", sharePrivateErr: "공유에 실패했습니다. 다시 시도하거나", sharePrivateOk: "공유가 업데이트되었습니다. 불러오는 중...", shareHeader1: "응용프로그램에 <strong>공개적으로 접근 가능</strong>합니다.", shareHeader2: "기관의 구성원이 응용프로그램에 접근할 수 있습니다(로그인 필요).", shareLinkCopy: "복사", shareLinkCopied: "복사됨", shareQ0: "웹 페이지에 응용프로그램을 포함하는 방법", shareQ1Opt1: "응용프로그램을 비공개 상태로 유지하려면 어떻게 해야 합니까?", shareQ1Opt2: "응용프로그램을 비공개 상태로 유지하거나 공개적으로 공유하려면 어떻게 해야 합니까?", shareA1: "<a href='%LINK1%' target='_blank'>응용프로그램 항목 페이지</a>의 %SHAREIMG%를 사용합니다.", shareQ2bis: "빌더 인터페이스로 돌아가려면 어떻게 해야 합니까?", shareA2div1: "%LINK1% 링크를 저장하여 다시 사용하거나 <a href='%LINK2%' target='_blank'>응용프로그램 항목 페이지</a>를 사용하세요.", shareA2div2: "응용프로그램의 소유자인 경우 %PORTAL%에 로그인하면 빌더를 열 수 있는 버튼이 응용프로그램에 표시됩니다.", shareQ3: "데이터는 어디에 저장되나요?", shareA3: "%TPL_NAME% 데이터 및 구성은 <a href='%LINK2%' target='_blank'>이 웹 응용프로그램 항목</a>에 저장됩니다. Flickr, Picasa, Facebook 또는 YouTube 가져오기를 사용한 경우 이미지와 동영상은 %PORTAL%에 복제되지 않습니다." }, settings: { header: "설정", tabError: "오류가 있는지 모든 탭을 확인하세요." }, settingsLayout: { title: "레이아웃", explain: "어떤 레이아웃을 사용하시겠습니까?", explainInit: "언제든지 설정 대화상자에서 레이아웃을 변경할 수 있습니다.", viewExample: "실시간 예 보기" }, settingsTheme: { title: "테마" }, settingsHeader: { title: "머리글", logoEsri: "Esri 로고", logoNone: "로고 없음", logoCustom: "사용자 지정 로고", logoCustomPlaceholder: "URL(최대 250x50픽셀)", logoCustomTargetPlaceholder: "클릭 이동 링크", logoSocialExplain: "머리글 링크를 사용자 정의합니다.", logoSocialText: "텍스트", logoSocialLink: "링크", lblSmallHeader: "압축 머리글 사용(부제목 없음)" }, header: { title: "%TPL_NAME% 제목 편집", subtitle: "%TPL_NAME% 부제목 편집" } } }) );
/* eslint-disable */ const path = require('path'); const fs = require('fs'); let ROOT = process.env.PWD; if (!ROOT) { ROOT = process.cwd(); } const config = { // Your website's name, used for favicon meta tags site_name: 'Winterweek 2020', // Your website's description, used for favicon meta tags site_description: 'Website for information and registration for winterweek 2020', // Your website's URL, used for sitemap site_url: 'https://winter.week.wtf', // Google Analytics tracking ID (leave blank to disable) googleAnalyticsUA: 'UA-118131939-2', // The viewport meta tag added to your HTML page's <head> tag viewport: 'width=device-width,initial-scale=1', // Source file for favicon generation. 512x512px recommended. favicon: path.join(ROOT, '/src/images/favicon.png'), // Local development URL dev_host: 'localhost', // Local development port port: process.env.PORT || 8000, // Advanced configuration, edit with caution! env: process.env.NODE_ENV, root: ROOT, paths: { config: 'config', src: 'src', dist: 'dist', }, package: JSON.parse( fs.readFileSync(path.join(ROOT, '/package.json'), { encoding: 'utf-8' }), ), }; module.exports = config;
# # Licensed to the Apache Software Foundation (ASF) under one or more # contributor license agreements. See the NOTICE file distributed with # this work for additional information regarding copyright ownership. # The ASF licenses this file to You under the Apache License, Version 2.0 # (the "License"); you may not use this file except in compliance with # the License. You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # """ Spark related features. Usually, the features here are missing in pandas but Spark has it. """ from abc import ABCMeta, abstractmethod from typing import TYPE_CHECKING, Optional, Union, List, cast from pyspark import StorageLevel from pyspark.sql import Column, DataFrame as SparkDataFrame from pyspark.sql.types import DataType, StructType if TYPE_CHECKING: import pyspark.pandas as ps # noqa: F401 (SPARK-34943) from pyspark.pandas.base import IndexOpsMixin # noqa: F401 (SPARK-34943) from pyspark.pandas.frame import CachedDataFrame # noqa: F401 (SPARK-34943) class SparkIndexOpsMethods(object, metaclass=ABCMeta): """Spark related features. Usually, the features here are missing in pandas but Spark has it.""" def __init__(self, data: Union["IndexOpsMixin"]): self._data = data @property def data_type(self) -> DataType: """ Returns the data type as defined by Spark, as a Spark DataType object.""" return self._data._internal.spark_type_for(self._data._column_label) @property def nullable(self) -> bool: """ Returns the nullability as defined by Spark. """ return self._data._internal.spark_column_nullable_for(self._data._column_label) @property def column(self) -> Column: """ Spark Column object representing the Series/Index. .. note:: This Spark Column object is strictly stick to its base DataFrame the Series/Index was derived from. """ return self._data._internal.spark_column_for(self._data._column_label) def transform(self, func) -> Union["ps.Series", "ps.Index"]: """ Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. The output length of the Spark column should be same as input's. .. note:: It requires to have the same input and output length; therefore, the aggregate Spark functions such as count does not work. Parameters ---------- func : function Function to use for transforming the data by using Spark columns. Returns ------- Series or Index Raises ------ ValueError : If the output from the function is not a Spark column. Examples -------- >>> from pyspark.sql.functions import log >>> df = ps.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, columns=["a", "b"]) >>> df a b 0 1 4 1 2 5 2 3 6 >>> df.a.spark.transform(lambda c: log(c)) 0 0.000000 1 0.693147 2 1.098612 Name: a, dtype: float64 >>> df.index.spark.transform(lambda c: c + 10) Int64Index([10, 11, 12], dtype='int64') >>> df.a.spark.transform(lambda c: c + df.b.spark.column) 0 5 1 7 2 9 Name: a, dtype: int64 """ from pyspark.pandas import MultiIndex if isinstance(self._data, MultiIndex): raise NotImplementedError("MultiIndex does not support spark.transform yet.") output = func(self._data.spark.column) if not isinstance(output, Column): raise ValueError( "The output of the function [%s] should be of a " "pyspark.sql.Column; however, got [%s]." % (func, type(output)) ) new_ser = self._data._with_new_scol(scol=output) # Trigger the resolution so it throws an exception if anything does wrong # within the function, for example, # `df1.a.spark.transform(lambda _: F.col("non-existent"))`. new_ser._internal.to_internal_spark_frame return new_ser @property @abstractmethod def analyzed(self) -> Union["ps.Series", "ps.Index"]: pass class SparkSeriesMethods(SparkIndexOpsMethods): def transform(self, func) -> "ps.Series": return cast("ps.Series", super().transform(func)) transform.__doc__ = SparkIndexOpsMethods.transform.__doc__ def apply(self, func) -> "ps.Series": """ Applies a function that takes and returns a Spark column. It allows to natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:: It forces to lose the index and end up with using default index. It is preferred to use :meth:`Series.spark.transform` or `:meth:`DataFrame.spark.apply` with specifying the `inedx_col`. .. note:: It does not require to have the same length of the input and output. However, it requires to create a new DataFrame internally which will require to set `compute.ops_on_diff_frames` to compute even with the same origin DataFrame that is expensive, whereas :meth:`Series.spark.transform` does not require it. Parameters ---------- func : function Function to apply the function against the data by using Spark columns. Returns ------- Series Raises ------ ValueError : If the output from the function is not a Spark column. Examples -------- >>> from pyspark import pandas as ps >>> from pyspark.sql.functions import count, lit >>> df = ps.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, columns=["a", "b"]) >>> df a b 0 1 4 1 2 5 2 3 6 >>> df.a.spark.apply(lambda c: count(c)) 0 3 Name: a, dtype: int64 >>> df.a.spark.apply(lambda c: c + df.b.spark.column) 0 5 1 7 2 9 Name: a, dtype: int64 """ from pyspark.pandas.frame import DataFrame from pyspark.pandas.series import Series, first_series from pyspark.pandas.internal import HIDDEN_COLUMNS output = func(self._data.spark.column) if not isinstance(output, Column): raise ValueError( "The output of the function [%s] should be of a " "pyspark.sql.Column; however, got [%s]." % (func, type(output)) ) assert isinstance(self._data, Series) sdf = self._data._internal.spark_frame.drop(*HIDDEN_COLUMNS).select(output) # Lose index. return first_series(DataFrame(sdf)).rename(self._data.name) @property def analyzed(self) -> "ps.Series": """ Returns a new Series with the analyzed Spark DataFrame. After multiple operations, the underlying Spark plan could grow huge and make the Spark planner take a long time to finish the planning. This function is for the workaround to avoid it. .. note:: After analyzed, operations between the analyzed Series and the original one will **NOT** work without setting a config `compute.ops_on_diff_frames` to `True`. Returns ------- Series Examples -------- >>> ser = ps.Series([1, 2, 3]) >>> ser 0 1 1 2 2 3 dtype: int64 The analyzed one should return the same value. >>> ser.spark.analyzed 0 1 1 2 2 3 dtype: int64 However, it won't work with the same anchor Series. >>> ser + ser.spark.analyzed Traceback (most recent call last): ... ValueError: ... enable 'compute.ops_on_diff_frames' option. >>> with ps.option_context('compute.ops_on_diff_frames', True): ... (ser + ser.spark.analyzed).sort_index() 0 2 1 4 2 6 dtype: int64 """ from pyspark.pandas.frame import DataFrame from pyspark.pandas.series import first_series return first_series(DataFrame(self._data._internal.resolved_copy)) class SparkIndexMethods(SparkIndexOpsMethods): def transform(self, func) -> "ps.Index": return cast("ps.Index", super().transform(func)) transform.__doc__ = SparkIndexOpsMethods.transform.__doc__ @property def analyzed(self) -> "ps.Index": """ Returns a new Index with the analyzed Spark DataFrame. After multiple operations, the underlying Spark plan could grow huge and make the Spark planner take a long time to finish the planning. This function is for the workaround to avoid it. .. note:: After analyzed, operations between the analyzed Series and the original one will **NOT** work without setting a config `compute.ops_on_diff_frames` to `True`. Returns ------- Index Examples -------- >>> idx = ps.Index([1, 2, 3]) >>> idx Int64Index([1, 2, 3], dtype='int64') The analyzed one should return the same value. >>> idx.spark.analyzed Int64Index([1, 2, 3], dtype='int64') However, it won't work with the same anchor Index. >>> idx + idx.spark.analyzed Traceback (most recent call last): ... ValueError: ... enable 'compute.ops_on_diff_frames' option. >>> with ps.option_context('compute.ops_on_diff_frames', True): ... (idx + idx.spark.analyzed).sort_values() Int64Index([2, 4, 6], dtype='int64') """ from pyspark.pandas.frame import DataFrame return DataFrame(self._data._internal.resolved_copy).index class SparkFrameMethods(object): """Spark related features. Usually, the features here are missing in pandas but Spark has it.""" def __init__(self, frame: "ps.DataFrame"): self._kdf = frame def schema(self, index_col: Optional[Union[str, List[str]]] = None) -> StructType: """ Returns the underlying Spark schema. Returns ------- pyspark.sql.types.StructType The underlying Spark schema. Parameters ---------- index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. Examples -------- >>> df = ps.DataFrame({'a': list('abc'), ... 'b': list(range(1, 4)), ... 'c': np.arange(3, 6).astype('i1'), ... 'd': np.arange(4.0, 7.0, dtype='float64'), ... 'e': [True, False, True], ... 'f': pd.date_range('20130101', periods=3)}, ... columns=['a', 'b', 'c', 'd', 'e', 'f']) >>> df.spark.schema().simpleString() 'struct<a:string,b:bigint,c:tinyint,d:double,e:boolean,f:timestamp>' >>> df.spark.schema(index_col='index').simpleString() 'struct<index:bigint,a:string,b:bigint,c:tinyint,d:double,e:boolean,f:timestamp>' """ return self.frame(index_col).schema def print_schema(self, index_col: Optional[Union[str, List[str]]] = None) -> None: """ Prints out the underlying Spark schema in the tree format. Parameters ---------- index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. Returns ------- None Examples -------- >>> df = ps.DataFrame({'a': list('abc'), ... 'b': list(range(1, 4)), ... 'c': np.arange(3, 6).astype('i1'), ... 'd': np.arange(4.0, 7.0, dtype='float64'), ... 'e': [True, False, True], ... 'f': pd.date_range('20130101', periods=3)}, ... columns=['a', 'b', 'c', 'd', 'e', 'f']) >>> df.spark.print_schema() # doctest: +NORMALIZE_WHITESPACE root |-- a: string (nullable = false) |-- b: long (nullable = false) |-- c: byte (nullable = false) |-- d: double (nullable = false) |-- e: boolean (nullable = false) |-- f: timestamp (nullable = false) >>> df.spark.print_schema(index_col='index') # doctest: +NORMALIZE_WHITESPACE root |-- index: long (nullable = false) |-- a: string (nullable = false) |-- b: long (nullable = false) |-- c: byte (nullable = false) |-- d: double (nullable = false) |-- e: boolean (nullable = false) |-- f: timestamp (nullable = false) """ self.frame(index_col).printSchema() def frame(self, index_col: Optional[Union[str, List[str]]] = None) -> SparkDataFrame: """ Return the current DataFrame as a Spark DataFrame. :meth:`DataFrame.spark.frame` is an alias of :meth:`DataFrame.to_spark`. Parameters ---------- index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. See Also -------- DataFrame.to_spark DataFrame.to_koalas DataFrame.spark.frame Examples -------- By default, this method loses the index as below. >>> df = ps.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) >>> df.to_spark().show() # doctest: +NORMALIZE_WHITESPACE +---+---+---+ | a| b| c| +---+---+---+ | 1| 4| 7| | 2| 5| 8| | 3| 6| 9| +---+---+---+ >>> df = ps.DataFrame({'a': [1, 2, 3], 'b': [4, 5, 6], 'c': [7, 8, 9]}) >>> df.spark.frame().show() # doctest: +NORMALIZE_WHITESPACE +---+---+---+ | a| b| c| +---+---+---+ | 1| 4| 7| | 2| 5| 8| | 3| 6| 9| +---+---+---+ If `index_col` is set, it keeps the index column as specified. >>> df.to_spark(index_col="index").show() # doctest: +NORMALIZE_WHITESPACE +-----+---+---+---+ |index| a| b| c| +-----+---+---+---+ | 0| 1| 4| 7| | 1| 2| 5| 8| | 2| 3| 6| 9| +-----+---+---+---+ Keeping index column is useful when you want to call some Spark APIs and convert it back to pandas-on-Spark DataFrame without creating a default index, which can affect performance. >>> spark_df = df.to_spark(index_col="index") >>> spark_df = spark_df.filter("a == 2") >>> spark_df.to_koalas(index_col="index") # doctest: +NORMALIZE_WHITESPACE a b c index 1 2 5 8 In case of multi-index, specify a list to `index_col`. >>> new_df = df.set_index("a", append=True) >>> new_spark_df = new_df.to_spark(index_col=["index_1", "index_2"]) >>> new_spark_df.show() # doctest: +NORMALIZE_WHITESPACE +-------+-------+---+---+ |index_1|index_2| b| c| +-------+-------+---+---+ | 0| 1| 4| 7| | 1| 2| 5| 8| | 2| 3| 6| 9| +-------+-------+---+---+ Likewise, can be converted to back to pandas-on-Spark DataFrame. >>> new_spark_df.to_koalas( ... index_col=["index_1", "index_2"]) # doctest: +NORMALIZE_WHITESPACE b c index_1 index_2 0 1 4 7 1 2 5 8 2 3 6 9 """ from pyspark.pandas.utils import name_like_string kdf = self._kdf data_column_names = [] data_columns = [] for i, (label, spark_column, column_name) in enumerate( zip( kdf._internal.column_labels, kdf._internal.data_spark_columns, kdf._internal.data_spark_column_names, ) ): name = str(i) if label is None else name_like_string(label) data_column_names.append(name) if column_name != name: spark_column = spark_column.alias(name) data_columns.append(spark_column) if index_col is None: return kdf._internal.spark_frame.select(data_columns) else: if isinstance(index_col, str): index_col = [index_col] old_index_scols = kdf._internal.index_spark_columns if len(index_col) != len(old_index_scols): raise ValueError( "length of index columns is %s; however, the length of the given " "'index_col' is %s." % (len(old_index_scols), len(index_col)) ) if any(col in data_column_names for col in index_col): raise ValueError("'index_col' cannot be overlapped with other columns.") new_index_scols = [ index_scol.alias(col) for index_scol, col in zip(old_index_scols, index_col) ] return kdf._internal.spark_frame.select(new_index_scols + data_columns) def cache(self) -> "CachedDataFrame": """ Yields and caches the current DataFrame. The pandas-on-Spark DataFrame is yielded as a protected resource and its corresponding data is cached which gets uncached after execution goes of the context. If you want to specify the StorageLevel manually, use :meth:`DataFrame.spark.persist` See Also -------- DataFrame.spark.persist Examples -------- >>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.6 0.0 3 0.2 0.1 >>> with df.spark.cache() as cached_df: ... print(cached_df.count()) ... dogs 4 cats 4 dtype: int64 >>> df = df.spark.cache() >>> df.to_pandas().mean(axis=1) 0 0.25 1 0.30 2 0.30 3 0.15 dtype: float64 To uncache the dataframe, use `unpersist` function >>> df.spark.unpersist() """ from pyspark.pandas.frame import CachedDataFrame self._kdf._update_internal_frame( self._kdf._internal.resolved_copy, requires_same_anchor=False ) return CachedDataFrame(self._kdf._internal) def persist( self, storage_level: StorageLevel = StorageLevel.MEMORY_AND_DISK ) -> "CachedDataFrame": """ Yields and caches the current DataFrame with a specific StorageLevel. If a StogeLevel is not given, the `MEMORY_AND_DISK` level is used by default like PySpark. The pandas-on-Spark DataFrame is yielded as a protected resource and its corresponding data is cached which gets uncached after execution goes of the context. See Also -------- DataFrame.spark.cache Examples -------- >>> import pyspark >>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.6 0.0 3 0.2 0.1 Set the StorageLevel to `MEMORY_ONLY`. >>> with df.spark.persist(pyspark.StorageLevel.MEMORY_ONLY) as cached_df: ... print(cached_df.spark.storage_level) ... print(cached_df.count()) ... Memory Serialized 1x Replicated dogs 4 cats 4 dtype: int64 Set the StorageLevel to `DISK_ONLY`. >>> with df.spark.persist(pyspark.StorageLevel.DISK_ONLY) as cached_df: ... print(cached_df.spark.storage_level) ... print(cached_df.count()) ... Disk Serialized 1x Replicated dogs 4 cats 4 dtype: int64 If a StorageLevel is not given, it uses `MEMORY_AND_DISK` by default. >>> with df.spark.persist() as cached_df: ... print(cached_df.spark.storage_level) ... print(cached_df.count()) ... Disk Memory Serialized 1x Replicated dogs 4 cats 4 dtype: int64 >>> df = df.spark.persist() >>> df.to_pandas().mean(axis=1) 0 0.25 1 0.30 2 0.30 3 0.15 dtype: float64 To uncache the dataframe, use `unpersist` function >>> df.spark.unpersist() """ from pyspark.pandas.frame import CachedDataFrame self._kdf._update_internal_frame( self._kdf._internal.resolved_copy, requires_same_anchor=False ) return CachedDataFrame(self._kdf._internal, storage_level=storage_level) def hint(self, name: str, *parameters) -> "ps.DataFrame": """ Specifies some hint on the current DataFrame. Parameters ---------- name : A name of the hint. parameters : Optional parameters. Returns ------- ret : DataFrame with the hint. See Also -------- broadcast : Marks a DataFrame as small enough for use in broadcast joins. Examples -------- >>> df1 = ps.DataFrame({'lkey': ['foo', 'bar', 'baz', 'foo'], ... 'value': [1, 2, 3, 5]}, ... columns=['lkey', 'value']).set_index('lkey') >>> df2 = ps.DataFrame({'rkey': ['foo', 'bar', 'baz', 'foo'], ... 'value': [5, 6, 7, 8]}, ... columns=['rkey', 'value']).set_index('rkey') >>> merged = df1.merge(df2.spark.hint("broadcast"), left_index=True, right_index=True) >>> merged.spark.explain() # doctest: +ELLIPSIS == Physical Plan == ... ...BroadcastHashJoin... ... """ from pyspark.pandas.frame import DataFrame internal = self._kdf._internal.resolved_copy return DataFrame(internal.with_new_sdf(internal.spark_frame.hint(name, *parameters))) def to_table( self, name: str, format: Optional[str] = None, mode: str = "overwrite", partition_cols: Optional[Union[str, List[str]]] = None, index_col: Optional[Union[str, List[str]]] = None, **options ) -> None: """ Write the DataFrame into a Spark table. :meth:`DataFrame.spark.to_table` is an alias of :meth:`DataFrame.to_table`. Parameters ---------- name : str, required Table name in Spark. format : string, optional Specifies the output data source format. Some common ones are: - 'delta' - 'parquet' - 'orc' - 'json' - 'csv' mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'}, default 'overwrite'. Specifies the behavior of the save operation when the table exists already. - 'append': Append the new data to existing data. - 'overwrite': Overwrite existing data. - 'ignore': Silently ignore this operation if data already exists. - 'error' or 'errorifexists': Throw an exception if data already exists. partition_cols : str or list of str, optional, default None Names of partitioning columns index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. options Additional options passed directly to Spark. Returns ------- None See Also -------- read_table DataFrame.to_spark_io DataFrame.spark.to_spark_io DataFrame.to_parquet Examples -------- >>> df = ps.DataFrame(dict( ... date=list(pd.date_range('2012-1-1 12:00:00', periods=3, freq='M')), ... country=['KR', 'US', 'JP'], ... code=[1, 2 ,3]), columns=['date', 'country', 'code']) >>> df date country code 0 2012-01-31 12:00:00 KR 1 1 2012-02-29 12:00:00 US 2 2 2012-03-31 12:00:00 JP 3 >>> df.to_table('%s.my_table' % db, partition_cols='date') """ if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1: options = options.get("options") # type: ignore self._kdf.spark.frame(index_col=index_col).write.saveAsTable( name=name, format=format, mode=mode, partitionBy=partition_cols, **options ) def to_spark_io( self, path: Optional[str] = None, format: Optional[str] = None, mode: str = "overwrite", partition_cols: Optional[Union[str, List[str]]] = None, index_col: Optional[Union[str, List[str]]] = None, **options ) -> None: """Write the DataFrame out to a Spark data source. :meth:`DataFrame.spark.to_spark_io` is an alias of :meth:`DataFrame.to_spark_io`. Parameters ---------- path : string, optional Path to the data source. format : string, optional Specifies the output data source format. Some common ones are: - 'delta' - 'parquet' - 'orc' - 'json' - 'csv' mode : str {'append', 'overwrite', 'ignore', 'error', 'errorifexists'}, default 'overwrite'. Specifies the behavior of the save operation when data already. - 'append': Append the new data to existing data. - 'overwrite': Overwrite existing data. - 'ignore': Silently ignore this operation if data already exists. - 'error' or 'errorifexists': Throw an exception if data already exists. partition_cols : str or list of str, optional Names of partitioning columns index_col: str or list of str, optional, default: None Column names to be used in Spark to represent pandas-on-Spark's index. The index name in pandas-on-Spark is ignored. By default, the index is always lost. options : dict All other options passed directly into Spark's data source. Returns ------- None See Also -------- read_spark_io DataFrame.to_delta DataFrame.to_parquet DataFrame.to_table DataFrame.to_spark_io DataFrame.spark.to_spark_io Examples -------- >>> df = ps.DataFrame(dict( ... date=list(pd.date_range('2012-1-1 12:00:00', periods=3, freq='M')), ... country=['KR', 'US', 'JP'], ... code=[1, 2 ,3]), columns=['date', 'country', 'code']) >>> df date country code 0 2012-01-31 12:00:00 KR 1 1 2012-02-29 12:00:00 US 2 2 2012-03-31 12:00:00 JP 3 >>> df.to_spark_io(path='%s/to_spark_io/foo.json' % path, format='json') """ if "options" in options and isinstance(options.get("options"), dict) and len(options) == 1: options = options.get("options") # type: ignore self._kdf.spark.frame(index_col=index_col).write.save( path=path, format=format, mode=mode, partitionBy=partition_cols, **options ) def explain(self, extended: Optional[bool] = None, mode: Optional[str] = None) -> None: """ Prints the underlying (logical and physical) Spark plans to the console for debugging purpose. Parameters ---------- extended : boolean, default ``False``. If ``False``, prints only the physical plan. mode : string, default ``None``. The expected output format of plans. Returns ------- None Examples -------- >>> df = ps.DataFrame({'id': range(10)}) >>> df.spark.explain() # doctest: +ELLIPSIS == Physical Plan == ... >>> df.spark.explain(True) # doctest: +ELLIPSIS == Parsed Logical Plan == ... == Analyzed Logical Plan == ... == Optimized Logical Plan == ... == Physical Plan == ... >>> df.spark.explain("extended") # doctest: +ELLIPSIS == Parsed Logical Plan == ... == Analyzed Logical Plan == ... == Optimized Logical Plan == ... == Physical Plan == ... >>> df.spark.explain(mode="extended") # doctest: +ELLIPSIS == Parsed Logical Plan == ... == Analyzed Logical Plan == ... == Optimized Logical Plan == ... == Physical Plan == ... """ self._kdf._internal.to_internal_spark_frame.explain(extended, mode) def apply(self, func, index_col: Optional[Union[str, List[str]]] = None) -> "ps.DataFrame": """ Applies a function that takes and returns a Spark DataFrame. It allows natively apply a Spark function and column APIs with the Spark column internally used in Series or Index. .. note:: set `index_col` and keep the column named as so in the output Spark DataFrame to avoid using the default index to prevent performance penalty. If you omit `index_col`, it will use default index which is potentially expensive in general. .. note:: it will lose column labels. This is a synonym of ``func(kdf.to_spark(index_col)).to_koalas(index_col)``. Parameters ---------- func : function Function to apply the function against the data by using Spark DataFrame. Returns ------- DataFrame Raises ------ ValueError : If the output from the function is not a Spark DataFrame. Examples -------- >>> kdf = ps.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, columns=["a", "b"]) >>> kdf a b 0 1 4 1 2 5 2 3 6 >>> kdf.spark.apply( ... lambda sdf: sdf.selectExpr("a + b as c", "index"), index_col="index") ... # doctest: +NORMALIZE_WHITESPACE c index 0 5 1 7 2 9 The case below ends up with using the default index, which should be avoided if possible. >>> kdf.spark.apply(lambda sdf: sdf.groupby("a").count().sort("a")) a count 0 1 1 1 2 1 2 3 1 """ output = func(self.frame(index_col)) if not isinstance(output, SparkDataFrame): raise ValueError( "The output of the function [%s] should be of a " "pyspark.sql.DataFrame; however, got [%s]." % (func, type(output)) ) return output.to_koalas(index_col) def repartition(self, num_partitions: int) -> "ps.DataFrame": """ Returns a new DataFrame partitioned by the given partitioning expressions. The resulting DataFrame is hash partitioned. Parameters ---------- num_partitions : int The target number of partitions. Returns ------- DataFrame Examples -------- >>> kdf = ps.DataFrame({"age": [5, 5, 2, 2], ... "name": ["Bob", "Bob", "Alice", "Alice"]}).set_index("age") >>> kdf.sort_index() # doctest: +NORMALIZE_WHITESPACE name age 2 Alice 2 Alice 5 Bob 5 Bob >>> new_kdf = kdf.spark.repartition(7) >>> new_kdf.to_spark().rdd.getNumPartitions() 7 >>> new_kdf.sort_index() # doctest: +NORMALIZE_WHITESPACE name age 2 Alice 2 Alice 5 Bob 5 Bob """ from pyspark.pandas.frame import DataFrame internal = self._kdf._internal.resolved_copy repartitioned_sdf = internal.spark_frame.repartition(num_partitions) return DataFrame(internal.with_new_sdf(repartitioned_sdf)) def coalesce(self, num_partitions: int) -> "ps.DataFrame": """ Returns a new DataFrame that has exactly `num_partitions` partitions. .. note:: This operation results in a narrow dependency, e.g. if you go from 1000 partitions to 100 partitions, there will not be a shuffle, instead each of the 100 new partitions will claim 10 of the current partitions. If a larger number of partitions is requested, it will stay at the current number of partitions. However, if you're doing a drastic coalesce, e.g. to num_partitions = 1, this may result in your computation taking place on fewer nodes than you like (e.g. one node in the case of num_partitions = 1). To avoid this, you can call repartition(). This will add a shuffle step, but means the current upstream partitions will be executed in parallel (per whatever the current partitioning is). Parameters ---------- num_partitions : int The target number of partitions. Returns ------- DataFrame Examples -------- >>> kdf = ps.DataFrame({"age": [5, 5, 2, 2], ... "name": ["Bob", "Bob", "Alice", "Alice"]}).set_index("age") >>> kdf.sort_index() # doctest: +NORMALIZE_WHITESPACE name age 2 Alice 2 Alice 5 Bob 5 Bob >>> new_kdf = kdf.spark.coalesce(1) >>> new_kdf.to_spark().rdd.getNumPartitions() 1 >>> new_kdf.sort_index() # doctest: +NORMALIZE_WHITESPACE name age 2 Alice 2 Alice 5 Bob 5 Bob """ from pyspark.pandas.frame import DataFrame internal = self._kdf._internal.resolved_copy coalesced_sdf = internal.spark_frame.coalesce(num_partitions) return DataFrame(internal.with_new_sdf(coalesced_sdf)) def checkpoint(self, eager: bool = True) -> "ps.DataFrame": """Returns a checkpointed version of this DataFrame. Checkpointing can be used to truncate the logical plan of this DataFrame, which is especially useful in iterative algorithms where the plan may grow exponentially. It will be saved to files inside the checkpoint directory set with `SparkContext.setCheckpointDir`. Parameters ---------- eager : bool Whether to checkpoint this DataFrame immediately Returns ------- DataFrame Examples -------- >>> kdf = ps.DataFrame({"a": ["a", "b", "c"]}) >>> kdf a 0 a 1 b 2 c >>> new_kdf = kdf.spark.checkpoint() # doctest: +SKIP >>> new_kdf # doctest: +SKIP a 0 a 1 b 2 c """ from pyspark.pandas.frame import DataFrame internal = self._kdf._internal.resolved_copy checkpointed_sdf = internal.spark_frame.checkpoint(eager) return DataFrame(internal.with_new_sdf(checkpointed_sdf)) def local_checkpoint(self, eager: bool = True) -> "ps.DataFrame": """Returns a locally checkpointed version of this DataFrame. Checkpointing can be used to truncate the logical plan of this DataFrame, which is especially useful in iterative algorithms where the plan may grow exponentially. Local checkpoints are stored in the executors using the caching subsystem and therefore they are not reliable. Parameters ---------- eager : bool Whether to locally checkpoint this DataFrame immediately Returns ------- DataFrame Examples -------- >>> kdf = ps.DataFrame({"a": ["a", "b", "c"]}) >>> kdf a 0 a 1 b 2 c >>> new_kdf = kdf.spark.local_checkpoint() >>> new_kdf a 0 a 1 b 2 c """ from pyspark.pandas.frame import DataFrame internal = self._kdf._internal.resolved_copy checkpointed_sdf = internal.spark_frame.localCheckpoint(eager) return DataFrame(internal.with_new_sdf(checkpointed_sdf)) @property def analyzed(self) -> "ps.DataFrame": """ Returns a new DataFrame with the analyzed Spark DataFrame. After multiple operations, the underlying Spark plan could grow huge and make the Spark planner take a long time to finish the planning. This function is for the workaround to avoid it. .. note:: After analyzed, operations between the analyzed DataFrame and the original one will **NOT** work without setting a config `compute.ops_on_diff_frames` to `True`. Returns ------- DataFrame Examples -------- >>> df = ps.DataFrame({"a": [1, 2, 3], "b": [4, 5, 6]}, columns=["a", "b"]) >>> df a b 0 1 4 1 2 5 2 3 6 The analyzed one should return the same value. >>> df.spark.analyzed a b 0 1 4 1 2 5 2 3 6 However, it won't work with the same anchor Series. >>> df + df.spark.analyzed Traceback (most recent call last): ... ValueError: ... enable 'compute.ops_on_diff_frames' option. >>> with ps.option_context('compute.ops_on_diff_frames', True): ... (df + df.spark.analyzed).sort_index() a b 0 2 8 1 4 10 2 6 12 """ from pyspark.pandas.frame import DataFrame return DataFrame(self._kdf._internal.resolved_copy) class CachedSparkFrameMethods(SparkFrameMethods): """Spark related features for cached DataFrame. This is usually created via `df.spark.cache()`.""" def __init__(self, frame: "CachedDataFrame"): super().__init__(frame) @property def storage_level(self) -> StorageLevel: """ Return the storage level of this cache. Examples -------- >>> import pyspark.pandas as ps >>> import pyspark >>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df dogs cats 0 0.2 0.3 1 0.0 0.6 2 0.6 0.0 3 0.2 0.1 >>> with df.spark.cache() as cached_df: ... print(cached_df.spark.storage_level) ... Disk Memory Deserialized 1x Replicated Set the StorageLevel to `MEMORY_ONLY`. >>> with df.spark.persist(pyspark.StorageLevel.MEMORY_ONLY) as cached_df: ... print(cached_df.spark.storage_level) ... Memory Serialized 1x Replicated """ return self._kdf._cached.storageLevel def unpersist(self) -> None: """ The `unpersist` function is used to uncache the pandas-on-Spark DataFrame when it is not used with `with` statement. Returns ------- None Examples -------- >>> df = ps.DataFrame([(.2, .3), (.0, .6), (.6, .0), (.2, .1)], ... columns=['dogs', 'cats']) >>> df = df.spark.cache() To uncache the dataframe, use `unpersist` function >>> df.spark.unpersist() """ if self._kdf._cached.is_cached: self._kdf._cached.unpersist() def _test(): import os import doctest import shutil import sys import tempfile import uuid import numpy import pandas from pyspark.sql import SparkSession import pyspark.pandas.spark.accessors os.chdir(os.environ["SPARK_HOME"]) globs = pyspark.pandas.spark.accessors.__dict__.copy() globs["np"] = numpy globs["pd"] = pandas globs["ps"] = pyspark.pandas spark = ( SparkSession.builder.master("local[4]") .appName("pyspark.pandas.spark.accessors tests") .getOrCreate() ) db_name = "db%s" % str(uuid.uuid4()).replace("-", "") spark.sql("CREATE DATABASE %s" % db_name) globs["db"] = db_name path = tempfile.mkdtemp() globs["path"] = path (failure_count, test_count) = doctest.testmod( pyspark.pandas.spark.accessors, globs=globs, optionflags=doctest.ELLIPSIS | doctest.NORMALIZE_WHITESPACE, ) shutil.rmtree(path, ignore_errors=True) spark.sql("DROP DATABASE IF EXISTS %s CASCADE" % db_name) spark.stop() if failure_count: sys.exit(-1) if __name__ == "__main__": _test()
var gulp = require("gulp"); var htmlone = require("gulp-htmlone"); var fs = require("fs"); var path = require("path"); var sftp = require('gulp-sftp'); gulp.task('build', function() { (function () { var baseCata = "weixin/view/"; fs.readdir(baseCata,function(err,catas){ catas.forEach(function(files){ var st = gulp.src(baseCata + files); st.pipe( htmlone({ keepliveSelector: '[keep]' }) ).pipe( gulp.dest('build/') ) }); }); }()); }); //ftp上传 gulp.task('push',['build'],function () { return gulp.src('build/**') .pipe(sftp({ host: '106.14.123.71', remotePath: '/home/weixin/wx_sdk_tasks/weixin/view/', //部署到服务器的路径 user: 'root', //帐号 pass: "2428347yu()", //密码 port: 22 //端口 })); });
$(function(){ initDatatable($('#breweries-list')); }); /** * @param table */ function initDatatable(table) { table.SearchableDatatable({ columnDefs: [ {"targets": 3, "orderable": false} ], responsive: true, serverSide: true, ajax: { url: table.data('url'), type: 'POST' } }); }
import rootReducers from './reducers'; import { createStore } from 'redux'; const storeRefactor = createStore(rootReducers); export default storeRefactor;
let messages = []; let messageBetty = document.getElementById("bettyString"); let row = document.getElementById("row"); let messageContainer = document.getElementById("contest"); let user; messages[0] = "Quien anda ahi?"; messages[1] = " hace tanto que no se de vos! como andas mamita?"; messages[2] = "Y si.. yo tmbien las extraño mucho, pero siempre las estoy cuidando desde aca.. Que es lo que extrañas?"; messages[3] = "Que andas necesitando mi china?"; messages[4] = "Y si! estas toda consumida mamita. Si estuviese ahi te haría un arroz con leche o un sanguche de jamon y queso"; messages[5] = "Si te hablase ahora te daría miedo!! como a tu hermanito cuando estuvo haciendo este regalo, se pego un re susto!!"; messages[6] = "Todas las noches te abrazo para que duermas bien! te abrazo hasta el infinito "; messages[7] = "Podes contarme lo que quieras mamita, decime que anda pasando.."; messages[8] = "Tu secreto esta guardado en mi corazon, sabes que podes contarme lo que quieras cuando quieras 💜"; let counter = 0; let _back = 0; function setMessage(index) { switch (index) { case 0: messageBetty.innerHTML = messages[0]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); var butt2 = document.createElement('button'); butt1.innerHTML = "Lari"; butt2.innerHTML = "Meli"; butt1.addEventListener("click", function () {user = "Larisita"}); butt2.addEventListener("click", function () {user = "Melanita"}); butt1.addEventListener("click", function () {setMessage(1);}); butt2.addEventListener("click", function () {setMessage(1);}); butt1.addEventListener("click", clear); butt2.addEventListener("click", clear); div.appendChild(butt1); div.appendChild(butt2); messageContainer.appendChild(div); break; case 1: // hola user _back = 0; messageBetty.innerHTML = "Hola " + user + messages[1]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); var butt2 = document.createElement('button'); butt1.innerHTML = "Te extraño mucho!!"; butt2.innerHTML = "Te ando necesitando!!"; butt1.addEventListener("click", function () {setMessage(2);}); butt2.addEventListener("click", function () {setMessage(3);}); butt1.addEventListener("click", clear); butt2.addEventListener("click", clear); div.appendChild(butt1); div.appendChild(butt2); var buttBack = document.createElement('button'); buttBack.innerHTML = "vovler"; buttBack.className += "backBtn"; buttBack.addEventListener("click", function () {setMessage(_back);}); buttBack.addEventListener("click", clear); div.appendChild(buttBack); messageContainer.appendChild(div); break; case 2: // que extrañas? _back = 1; messageBetty.innerHTML = messages[2]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); var butt2 = document.createElement('button'); var butt3 = document.createElement('button'); butt1.innerHTML = "Extraño tus comidas"; butt2.innerHTML = "Extraño tu voz"; butt3.innerHTML = "Extraño tus abrazos"; butt1.addEventListener("click", function () {setMessage(4);}); butt2.addEventListener("click", function () {setMessage(5);}); butt3.addEventListener("click", function () {setMessage(6);}); butt1.addEventListener("click", clear); butt2.addEventListener("click", clear); butt3.addEventListener("click", clear); div.appendChild(butt1); div.appendChild(butt2); div.appendChild(butt3); var buttBack = document.createElement('button'); buttBack.innerHTML = "vovler"; buttBack.className += "backBtn"; buttBack.addEventListener("click", function () {setMessage(_back);}); buttBack.addEventListener("click", clear); div.appendChild(buttBack); messageContainer.appendChild(div); break; case 3: _back = 1; // que andas necesitando? messageBetty.innerHTML = messages[3]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); var butt2 = document.createElement('button'); var butt3 = document.createElement('button'); butt1.innerHTML = "Necesito contarte secretos"; butt2.innerHTML = "Necesito tus abrazos"; butt3.innerHTML = "Necesito escucharte un ratito"; butt1.addEventListener("click", function () {setMessage(7);}); butt2.addEventListener("click", function () {setMessage(8);}); butt3.addEventListener("click", function () {setMessage(9);}); butt1.addEventListener("click", clear); butt2.addEventListener("click", clear); butt3.addEventListener("click", clear); div.appendChild(butt1); div.appendChild(butt2); div.appendChild(butt3); // back btn var buttBack = document.createElement('button'); buttBack.innerHTML = "vovler"; buttBack.className += "backBtn"; buttBack.addEventListener("click", function () {setMessage(_back);}); buttBack.addEventListener("click", clear); div.appendChild(buttBack); messageContainer.appendChild(div); break; case 4: _back = 2; // extraño comidas messageBetty.innerHTML = messages[4]; var div = document.createElement('div'); div.id = 'messBack'; var butt2 = document.createElement('button'); butt2.innerHTML = "volver"; butt2.className += "backBtn"; butt2.addEventListener("click", function () {setMessage(_back);}); butt2.addEventListener("click", clear); div.appendChild(butt2); messageContainer.appendChild(div); break; case 5: _back = 2; // extraño voz messageBetty.innerHTML = messages[5]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); butt1.innerHTML = "volver"; butt1.className += "backBtn"; butt1.addEventListener("click", function () {setMessage(_back);}); butt1.addEventListener("click", clear); div.appendChild(butt1); messageContainer.appendChild(div); break; case 6: _back = 2; // extraño abrazos messageBetty.innerHTML = messages[6] + user + "!"; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); butt1.innerHTML = "volver"; butt1.className += "backBtn"; butt1.addEventListener("click", function () {setMessage(_back);}); butt1.addEventListener("click", clear); div.appendChild(butt1); messageContainer.appendChild(div); break; case 7: _back = 3; // necesito contarte secretos messageBetty.innerHTML = messages[7]; var div = document.createElement('div'); div.id = 'messBack'; var textarea = document.createElement('textarea'); var butt1 = document.createElement('button'); butt1.innerHTML = "Contar"; butt1.addEventListener("click", function () {setMessage(10);}); textarea.placeholder = "decime algun secreto"; butt1.addEventListener("click", clear); div.appendChild(textarea); div.appendChild(butt1); // back btn var buttBack = document.createElement('button'); buttBack.innerHTML = "vovler"; buttBack.className += "backBtn"; buttBack.addEventListener("click", function () {setMessage(_back);}); buttBack.addEventListener("click", clear); div.appendChild(buttBack); messageContainer.appendChild(div); break; case 8: _back = 3; // necesito tus abrazos messageBetty.innerHTML = messages[6] + user + "!"; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); butt1.innerHTML = "volver"; butt1.className += "backBtn"; butt1.addEventListener("click", function () {setMessage(_back);}); butt1.addEventListener("click", clear); div.appendChild(butt1); messageContainer.appendChild(div); break; case 9: _back = 3; // necesito escucharte un ratito messageBetty.innerHTML = messages[5]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); butt1.innerHTML = "volver"; butt1.className += "backBtn"; butt1.addEventListener("click", function () {setMessage(_back);}); butt1.addEventListener("click", clear); div.appendChild(butt1); messageContainer.appendChild(div); break; case 10: _back = 7; createImg(window.width/2, window.height/2, 0); // necesito escucharte un ratito messageBetty.innerHTML = messages[8]; var div = document.createElement('div'); div.id = 'messBack'; var butt1 = document.createElement('button'); butt1.innerHTML = "volver"; butt1.className += "backBtn"; butt1.addEventListener("click", function () {setMessage(_back);}); butt1.addEventListener("click", clear); div.appendChild(butt1); messageContainer.appendChild(div); break; default: break; } } function goOn() { counter++ setMessage(counter); } function clear() { let messback = document.getElementById("messBack"); messback.remove(); } function getRndInteger(min, max) { return Math.floor(Math.random() * (max - min) ) + min; } setMessage(counter); // *********************************************************** // var canvas = document.getElementById('canvas'); // var context = canvas.getContext('2d'); document.body.onclick = function (e) { if (e.ctrlKey) createImg(e.clientX, e.clientY, 0); else if (e.altKey) createImg(e.clientX, e.clientY, 1); } function createImg(x, y, img) { let image = document.createElement('img'); image.className = 'giffID'; image.setAttribute("style", "position: absolute; left: "+(x-50)+"px; top: "+(y-50)+"px; width: 100px;"); if (img == 0){ image.setAttribute("src", "img/butterfly.gif"); } else if (img == 1){ image.setAttribute("src", "img/stars.gif"); } row.appendChild(image); console.log(x); console.log(y); setTimeout(); } function setTimeout() { $('.giffID').fadeOut(2000, function() { $(this).remove()}); }
var searchData= [ ['animation',['Animation',['../namespace_menu_stack_1_1_animation.html',1,'MenuStack']]], ['editor',['Editor',['../namespace_menu_stack_1_1_editor.html',1,'MenuStack']]], ['menustack',['MenuStack',['../namespace_menu_stack.html',1,'']]], ['navigation',['Navigation',['../namespace_menu_stack_1_1_navigation.html',1,'MenuStack']]] ];
import argparse import logging from xml_to_sheet.gspread_client import get_sheet VALID_ROLES = ['reader', 'writer'] parser = argparse.ArgumentParser(description='Create and/or share a worksheet.') parser.add_argument('--attempt_create', action='store_true', help='If set attempt to create sheet') parser.add_argument('--share_with_email', dest='share_with_email', help='Account to share the worksheet with') parser.add_argument('--role', dest='role', default='reader', choices=VALID_ROLES, help='Role to assign') args = parser.parse_args() sheet = get_sheet(attempt_to_create=args.attempt_create) if args.share_with_email: logging.info('Sharing sheet with {} as role {}'.format(args.share_with_email, args.role)) sheet.spreadsheet.share(args.share_with_email, perm_type='user', role=args.role)
/* * gulp-iconizer * Licensed under the MIT license. */ 'use strict'; const fs = require('fs'); const through = require('through2'); const gutil = require('gulp-util'); const PluginError = gutil.PluginError; function icon(name, opts) { opts = opts || {}; let size = opts.size ? `svg-icon${opts._beml.modPrefix}${opts.size}` : ''; let classes = `svg-icon svg-icon${opts._beml.modPrefix}${name} ${size} ${(opts.class || '')}`; classes = classes.trim(); opts.tag = (typeof opts.tag === 'undefined') ? 'div' : opts.tag; let icon = `<svg class="svg-icon${opts._beml.elemPrefix}link"><use xlink:href="#${name}" /></svg>`; return `<${opts.tag} class="${classes}">${wrapSpinner(icon, classes, opts)}</${opts.tag}>`; } function wrapSpinner(html, klass, opts) { if (klass.indexOf('spinner') > -1) { return `<${opts.tag} class="svg-icon${opts._beml.elemPrefix}spinner">${html}</${opts.tag}>`; } else { return html; } } function buildParamsFromString(string) { let match, attr, value; let params = {}; let attrsRegexp = /(\S+)=["']?((?:.(?!["']?\s+(?:\S+)=|[>"']))+.)["']?/gi; while (match = attrsRegexp.exec(string)) { attr = match[1]; value = match[2].replace(/'|"/, ''); params[attr] = value; } return params; } function replaceIconTags(src, opts) { let match, tag, params, name; let html = src.toString(); let iconRegexp = /<icon\s+([-=\w\d\c{}'"\s]+)\s*\/?>|<\/icon>/gi; while (match = iconRegexp.exec(html)) { tag = match[0]; params = buildParamsFromString(match[1]); name = params.name; delete params.name; Object.assign(params, opts); html = html.replace(tag, icon(name, params)); } return html; } function iconizeHtml(src, opts) { if (!fs.existsSync(opts.path)) { return src.toString(); } let sprite = fs.readFileSync(opts.path).toString(); let html = src.toString(); if (html.indexOf(sprite) === -1) { sprite = sprite.replace(/\n/g,''); sprite = sprite.replace(/<defs[\s\S]*?\/defs><path[\s\S]*?\s+?d=/g, '<path d='); sprite = sprite.replace(/<style[\s\S]*?\/style><path[\s\S]*?\s+?d=/g, '<path d='); sprite = sprite.replace(/\sfill[\s\S]*?(['"])[\s\S]*?\1/g, ''); sprite = sprite.replace(/(['"])[\s\S]*?\1/, function(match) { return match + ' class="main-svg-sprite"' }); html = html.replace(/<body.*?>/, function(match) { return `${match}\n\n ${sprite}\n` }); } return replaceIconTags(html, opts); } module.exports = function(opts) { return through.obj(function(file, enc, cb) { Object.assign({ elemPrefix: '__', modPrefix : '--', modDlmtr : '-' }, opts); if (file.isNull()) { cb(null, file); } let html = iconizeHtml(file.contents, opts); if (file.isBuffer()) { file.contents = new Buffer(html); } if (file.isStream()) { this.emit('error', new PluginError('gulp-iconizer', 'Streaming not supported')); return cb(); } this.push(file); cb(null, file); }); };
export default { ra: { width: 1792, height: 1792, paths: [{ d: 'M19 874q8-217 116-406t305-318h5q0 1-1 3-8 8-28 33.5t-52 76.5-60 110.5-44.5 135.5-14 150.5 39 157.5 108.5 154q50 50 102 69.5t90.5 11.5 69.5-23.5 47-32.5l16-16q39-51 53-116.5t6.5-122.5-21-107-26.5-80l-14-29q-10-25-30.5-49.5t-43-41-43.5-29.5-35-19l-13-6 104-115q39 17 78 52t59 61l19 27q1-48-18.5-103.5t-40.5-87.5l-20-31 161-183 160 181q-33 46-52.5 102.5t-22.5 90.5l-4 33q22-37 61.5-72.5t67.5-52.5l28-17 103 115q-44 14-85 50t-60 65l-19 29q-31 56-48 133.5t-7 170 57 156.5q33 45 77.5 60.5t85 5.5 76-26.5 57.5-33.5l21-16q60-53 96.5-115t48.5-121.5 10-121.5-18-118-37-107.5-45.5-93-45-72-34.5-47.5l-13-17q-14-13-7-13l10 3q40 29 62.5 46t62 50 64 58 58.5 65 55.5 77 45.5 88 38 103 23.5 117 10.5 136q3 259-108 465t-312 321-456 115q-185 0-351-74t-283.5-198-184-293-60.5-353z' }] } };
//connects to tee and offers fancy services var g_port = null; //Connects to an application through the messaging service //This requires the CA to be registered with chrome function tee_connect(hostname) { g_port = chrome.runtime.connectNative(hostname); g_port.onDisconnect.addListener(onDisconnected); g_port.onMessage.addListener(onNativeMessage); if(g_port) { return true; } else { return false; } } function tee_status() { return g_port ? true : false; } //takes command and parameters to send to tee //makes json and sends to port function tee_send_msg(param) { } function tee_generate_keypair(param) { } function tee_encrypt(param) { } function tee_decrypt(param) { } function tee_save_public_key(param) { } function tee_get_public_key(param) { } function tee_disconnect(param) { }
# coding=utf-8 # *** WARNING: this file was generated by the Pulumi SDK Generator. *** # *** Do not edit by hand unless you're certain you know what you are doing! *** import warnings import pulumi import pulumi.runtime from typing import Any, Mapping, Optional, Sequence, Union, overload from .. import _utilities __all__ = [ 'GetImageVersionResult', 'AwaitableGetImageVersionResult', 'get_image_version', 'get_image_version_output', ] @pulumi.output_type class GetImageVersionResult: def __init__(__self__, container_image=None, image_arn=None, image_version_arn=None, version=None): if container_image and not isinstance(container_image, str): raise TypeError("Expected argument 'container_image' to be a str") pulumi.set(__self__, "container_image", container_image) if image_arn and not isinstance(image_arn, str): raise TypeError("Expected argument 'image_arn' to be a str") pulumi.set(__self__, "image_arn", image_arn) if image_version_arn and not isinstance(image_version_arn, str): raise TypeError("Expected argument 'image_version_arn' to be a str") pulumi.set(__self__, "image_version_arn", image_version_arn) if version and not isinstance(version, int): raise TypeError("Expected argument 'version' to be a int") pulumi.set(__self__, "version", version) @property @pulumi.getter(name="containerImage") def container_image(self) -> Optional[str]: return pulumi.get(self, "container_image") @property @pulumi.getter(name="imageArn") def image_arn(self) -> Optional[str]: return pulumi.get(self, "image_arn") @property @pulumi.getter(name="imageVersionArn") def image_version_arn(self) -> Optional[str]: return pulumi.get(self, "image_version_arn") @property @pulumi.getter def version(self) -> Optional[int]: return pulumi.get(self, "version") class AwaitableGetImageVersionResult(GetImageVersionResult): # pylint: disable=using-constant-test def __await__(self): if False: yield self return GetImageVersionResult( container_image=self.container_image, image_arn=self.image_arn, image_version_arn=self.image_version_arn, version=self.version) def get_image_version(image_version_arn: Optional[str] = None, opts: Optional[pulumi.InvokeOptions] = None) -> AwaitableGetImageVersionResult: """ Resource Type definition for AWS::SageMaker::ImageVersion """ __args__ = dict() __args__['imageVersionArn'] = image_version_arn if opts is None: opts = pulumi.InvokeOptions() if opts.version is None: opts.version = _utilities.get_version() __ret__ = pulumi.runtime.invoke('aws-native:sagemaker:getImageVersion', __args__, opts=opts, typ=GetImageVersionResult).value return AwaitableGetImageVersionResult( container_image=__ret__.container_image, image_arn=__ret__.image_arn, image_version_arn=__ret__.image_version_arn, version=__ret__.version) @_utilities.lift_output_func(get_image_version) def get_image_version_output(image_version_arn: Optional[pulumi.Input[str]] = None, opts: Optional[pulumi.InvokeOptions] = None) -> pulumi.Output[GetImageVersionResult]: """ Resource Type definition for AWS::SageMaker::ImageVersion """ ...
import React, { useEffect, Fragment } from 'react' import { Link } from 'react-router-dom'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Spinner from '../layout/Spinner'; import { getCurrentProfile } from '../../actions/profile'; const Dashboard = ({ getCurrentProfile, auth: { user }, profile: { profile, loading } }) => { useEffect(() => { getCurrentProfile(); }, []); return loading && profile === null ? (<Spinner />) : (<Fragment> <h1 className="large text-primary">Dashboard</h1> <p className="lead"> <i className="fas fa-user"></i> Welcome {user && user.name} </p> { profile !== null ? <Fragment>has</Fragment> : <Fragment> <p>No tienes un perfil aun, agrega información</p> <Link to='/create-profile' className="btn btn-primary my-1"> Create Profile </Link> </Fragment> } </Fragment>); } Dashboard.propTypes = { getCurrentProfile: PropTypes.func.isRequired, auth: PropTypes.object.isRequired, profile: PropTypes.object.isRequired, }; const mapStateToProps = state => ({ auth: state.auth, profile: state.profile }); export default connect(mapStateToProps, { getCurrentProfile })(Dashboard);
# -*- coding: utf-8 -*- """ Copyright (C) 2017 Sebastian Golasch (plugin.video.netflix) Copyright (C) 2018 Caphm (original implementation module) Playback tracking and coordination of several actions during playback SPDX-License-Identifier: MIT See LICENSES/MIT.md for more information. """ import json import time import xbmc import resources.lib.common as common from resources.lib.globals import G from resources.lib.kodi import ui from resources.lib.utils.logging import LOG from .action_manager import ActionManager from .am_playback import AMPlayback from .am_section_skipping import AMSectionSkipper from .am_stream_continuity import AMStreamContinuity from .am_upnext_notifier import AMUpNextNotifier from .am_video_events import AMVideoEvents class ActionController(xbmc.Monitor): """ Tracks status and progress of video playbacks initiated by the add-on """ def __init__(self): xbmc.Monitor.__init__(self) self._init_data = None self.init_count = 0 self.tracking = False self.tracking_tick = False self.active_player_id = None self.action_managers = None self._last_player_state = {} self._is_pause_called = False common.register_slot(self.initialize_playback, common.Signals.PLAYBACK_INITIATED) def initialize_playback(self, data): """ Callback for AddonSignal when this add-on has initiated a playback """ # We convert the videoid only once for all action managers videoid = common.VideoId.from_dict(data['videoid']) data['videoid'] = videoid data['videoid_parent'] = videoid.derive_parent(common.VideoId.SHOW) if data['videoid_next_episode']: data['videoid_next_episode'] = common.VideoId.from_dict(data['videoid_next_episode']) self._init_data = data self.active_player_id = None self.tracking = True self.tracking_tick = False def _initialize_am(self): self._last_player_state = {} self._is_pause_called = False if not self._init_data: return self.action_managers = [ AMPlayback(), AMSectionSkipper(), AMStreamContinuity(), AMVideoEvents(), AMUpNextNotifier() ] self.init_count += 1 self._notify_all(ActionManager.call_initialize, self._init_data) self._init_data = None def onNotification(self, sender, method, data): # pylint: disable=unused-argument """ Callback for Kodi notifications that handles and dispatches playback events """ # WARNING: Do not get playerid from 'data', # Because when Up Next add-on play a video while we are inside Netflix add-on and # not externally like Kodi library, the playerid become -1 this id does not exist if not self.tracking or not method.startswith('Player.'): return try: if method == 'Player.OnPlay': if self.init_count > 0: # In this case the user has chosen to play another video while another one is in playing, # then we send the missing Stop event for the current video self._on_playback_stopped() self._initialize_am() elif method == 'Player.OnAVStart': self._on_playback_started() self.tracking_tick = True elif method == 'Player.OnSeek': self._on_playback_seek(json.loads(data)['player']['time']) elif method == 'Player.OnPause': self._is_pause_called = True self._on_playback_pause() elif method == 'Player.OnResume': # Kodi call this event instead the "Player.OnStop" event when you try to play a video # while another one is in playing (also if the current video is in pause) (not happen on RPI devices) # Can be one of following cases: # - When you use ctx menu "Play From Here", this happen when click to next button # - When you use UpNext add-on # - When you play a non-Netflix video when a Netflix video is in playback in background # - When you play a video over another in playback (back in menus) if not self._is_pause_called: return if self.init_count == 0: # This should never happen, we have to avoid this event when you try to play a video # while another non-netflix video is in playing return self._is_pause_called = False self._on_playback_resume() elif method == 'Player.OnStop': self.tracking = False if self.active_player_id is None: # if playback does not start due to an error in streams initialization # OnAVStart notification will not be called, then active_player_id will be None LOG.debug('ActionController: Player.OnStop event has been ignored') LOG.warn('ActionController: Action managers disabled due to a playback initialization error') self.action_managers = None self.init_count -= 1 return self._on_playback_stopped() except Exception: # pylint: disable=broad-except import traceback LOG.error(traceback.format_exc()) self.tracking = False self.tracking_tick = False self.init_count = 0 def on_service_tick(self): """ Notify to action managers that an interval of time has elapsed """ if self.tracking_tick and self.active_player_id is not None: player_state = self._get_player_state() if player_state: self._notify_all(ActionManager.call_on_tick, player_state) def _on_playback_started(self): player_id = _get_player_id() self._notify_all(ActionManager.call_on_playback_started, self._get_player_state(player_id)) if LOG.level == LOG.LEVEL_VERBOSE and G.ADDON.getSettingBool('show_codec_info'): common.json_rpc('Input.ExecuteAction', {'action': 'codecinfo'}) self.active_player_id = player_id def _on_playback_seek(self, time_override): if self.active_player_id is not None: player_state = self._get_player_state(time_override=time_override) if player_state: self._notify_all(ActionManager.call_on_playback_seek, player_state) def _on_playback_pause(self): if self.active_player_id is not None: player_state = self._get_player_state() if player_state: self._notify_all(ActionManager.call_on_playback_pause, player_state) def _on_playback_resume(self): if self.active_player_id is not None: player_state = self._get_player_state() if player_state: self._notify_all(ActionManager.call_on_playback_resume, player_state) def _on_playback_stopped(self): self.tracking_tick = False self.active_player_id = None # Immediately send the request to release the license common.send_signal(signal=common.Signals.RELEASE_LICENSE, non_blocking=True) self._notify_all(ActionManager.call_on_playback_stopped, self._last_player_state) self.action_managers = None self.init_count -= 1 def _notify_all(self, notification, data=None): LOG.debug('Notifying all action managers of {} (data={})', notification.__name__, data) for manager in self.action_managers: _notify_managers(manager, notification, data) def _get_player_state(self, player_id=None, time_override=None): try: player_state = common.json_rpc('Player.GetProperties', { 'playerid': self.active_player_id if player_id is None else player_id, 'properties': [ 'audiostreams', 'currentaudiostream', 'currentvideostream', 'subtitles', 'currentsubtitle', 'subtitleenabled', 'percentage', 'time'] }) except IOError as exc: LOG.warn('_get_player_state: {}', exc) return {} # convert time dict to elapsed seconds player_state['elapsed_seconds'] = (player_state['time']['hours'] * 3600 + player_state['time']['minutes'] * 60 + player_state['time']['seconds']) if time_override: player_state['time'] = time_override elapsed_seconds = (time_override['hours'] * 3600 + time_override['minutes'] * 60 + time_override['seconds']) player_state['percentage'] = player_state['percentage'] / player_state['elapsed_seconds'] * elapsed_seconds player_state['elapsed_seconds'] = elapsed_seconds # Sometimes may happen that when you stop playback the player status is partial, # this is because the Kodi player stop immediately but the stop notification (from the Monitor) # arrives late, meanwhile in this interval of time a service tick may occur. if ((player_state['audiostreams'] and player_state['elapsed_seconds']) or (player_state['audiostreams'] and not player_state['elapsed_seconds'] and not self._last_player_state)): # save player state self._last_player_state = player_state else: # use saved player state player_state = self._last_player_state return player_state def _notify_managers(manager, notification, data): notify_method = getattr(manager, notification.__name__) try: if data is not None: notify_method(data) else: notify_method() except Exception as exc: # pylint: disable=broad-except manager.enabled = False msg = '{} disabled due to exception: {}'.format(manager.name, exc) import traceback LOG.error(traceback.format_exc()) ui.show_notification(title=common.get_local_string(30105), msg=msg) def _get_player_id(): try: retry = 10 while retry: result = common.json_rpc('Player.GetActivePlayers') if result: return result[0]['playerid'] time.sleep(0.1) retry -= 1 LOG.warn('Player ID not obtained, fallback to ID 1') except IOError: LOG.error('Player ID not obtained, fallback to ID 1') return 1
var searchData= [ ['_7eapp_1082',['~App',['../class_lite_f_x_1_1_app.html#ab3d41231fffafc1a061dc0c1892a1a3e',1,'LiteFX::App']]], ['_7eappversion_1083',['~AppVersion',['../class_lite_f_x_1_1_app_version.html#a7e12e5920d9edd6dcbb1ce0f7ee98ffb',1,'LiteFX::AppVersion']]], ['_7ebufferattribute_1084',['~BufferAttribute',['../class_lite_f_x_1_1_rendering_1_1_buffer_attribute.html#a057f6c0b4aa0f16bd9fbdb489e56c94f',1,'LiteFX::Rendering::BufferAttribute']]], ['_7ebuilder_1085',['~Builder',['../class_lite_f_x_1_1_builder_3_01_t_derived_00_01_t_00_01std_1_1nullptr__t_00_01typename_01_t_pointer_01_4.html#a722a78fcdf391ad6529820117b84fff5',1,'LiteFX::Builder&lt; TDerived, T, std::nullptr_t, typename TPointer &gt;::~Builder()'],['../class_lite_f_x_1_1_builder.html#a9a467e50fc8f4db7e6d8ff5a2b54381c',1,'LiteFX::Builder::~Builder()']]], ['_7econsolesink_1086',['~ConsoleSink',['../class_lite_f_x_1_1_logging_1_1_console_sink.html#a34c501a909b8d0127d1dfd4708ad2660',1,'LiteFX::Logging::ConsoleSink']]], ['_7edepthstencilstate_1087',['~DepthStencilState',['../class_lite_f_x_1_1_rendering_1_1_depth_stencil_state.html#a1c907e451ad814b1a469892779c0c276',1,'LiteFX::Rendering::DepthStencilState']]], ['_7edirectx12backend_1088',['~DirectX12Backend',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_backend.html#a6584a46b3b4db0a5ca4b32d6e19f6997',1,'LiteFX::Rendering::Backends::DirectX12Backend']]], ['_7edirectx12barrier_1089',['~DirectX12Barrier',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_barrier.html#a861b90aa6cbcffc85b02346193aa3ddb',1,'LiteFX::Rendering::Backends::DirectX12Barrier']]], ['_7edirectx12buffer_1090',['~DirectX12Buffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_buffer.html#ac29672e59cf2f07515736c386ba0135f',1,'LiteFX::Rendering::Backends::DirectX12Buffer']]], ['_7edirectx12commandbuffer_1091',['~DirectX12CommandBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_command_buffer.html#a3949346a03f33c33bc806abb409a8665',1,'LiteFX::Rendering::Backends::DirectX12CommandBuffer']]], ['_7edirectx12computepipeline_1092',['~DirectX12ComputePipeline',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_pipeline.html#ae0d5205e439e458e2a16a512fcff0434',1,'LiteFX::Rendering::Backends::DirectX12ComputePipeline']]], ['_7edirectx12computepipelinebuilder_1093',['~DirectX12ComputePipelineBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_pipeline_builder.html#ae1705b14620022b1ce92507c0fc22387',1,'LiteFX::Rendering::Backends::DirectX12ComputePipelineBuilder']]], ['_7edirectx12computepipelinedescriptorsetlayoutbuilder_1094',['~DirectX12ComputePipelineDescriptorSetLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_pipeline_descriptor_set_layout_builder.html#acc6e29eed7ebdcc9619079214bb0297f',1,'LiteFX::Rendering::Backends::DirectX12ComputePipelineDescriptorSetLayoutBuilder']]], ['_7edirectx12computepipelinelayoutbuilder_1095',['~DirectX12ComputePipelineLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_pipeline_layout_builder.html#ab574507a0d3c4f2f6bc2ea60723829a4',1,'LiteFX::Rendering::Backends::DirectX12ComputePipelineLayoutBuilder']]], ['_7edirectx12computepipelinepushconstantslayoutbuilder_1096',['~DirectX12ComputePipelinePushConstantsLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_pipeline_push_constants_layout_builder.html#a7de9b8d60ad48b6eefc305733814a226',1,'LiteFX::Rendering::Backends::DirectX12ComputePipelinePushConstantsLayoutBuilder']]], ['_7edirectx12computeshaderprogrambuilder_1097',['~DirectX12ComputeShaderProgramBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_compute_shader_program_builder.html#a21663d8a18f9aeff7f0f15e9cf7706c5',1,'LiteFX::Rendering::Backends::DirectX12ComputeShaderProgramBuilder']]], ['_7edirectx12descriptorlayout_1098',['~DirectX12DescriptorLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_descriptor_layout.html#ab816cbff35f93cbe412b087669b1c86b',1,'LiteFX::Rendering::Backends::DirectX12DescriptorLayout']]], ['_7edirectx12descriptorset_1099',['~DirectX12DescriptorSet',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_descriptor_set.html#a4b4778cc1c9545ffb8543d831bdc305f',1,'LiteFX::Rendering::Backends::DirectX12DescriptorSet']]], ['_7edirectx12descriptorsetlayout_1100',['~DirectX12DescriptorSetLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_descriptor_set_layout.html#aa53e2b30d9d9dd05ddc7f4ed4452607f',1,'LiteFX::Rendering::Backends::DirectX12DescriptorSetLayout']]], ['_7edirectx12device_1101',['~DirectX12Device',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_device.html#a4de9a61aa66efed81c22fb1709647667',1,'LiteFX::Rendering::Backends::DirectX12Device']]], ['_7edirectx12deviceimpl_1102',['~DirectX12DeviceImpl',['../class_direct_x12_device_1_1_direct_x12_device_impl.html#a63c64d9e006ef69d06995562be392420',1,'DirectX12Device::DirectX12DeviceImpl']]], ['_7edirectx12framebuffer_1103',['~DirectX12FrameBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_frame_buffer.html#a17fec8fece43381c6a933f478fb83cce',1,'LiteFX::Rendering::Backends::DirectX12FrameBuffer']]], ['_7edirectx12graphicsadapter_1104',['~DirectX12GraphicsAdapter',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_graphics_adapter.html#a31d807a630de3730c50b8caa8165721a',1,'LiteFX::Rendering::Backends::DirectX12GraphicsAdapter']]], ['_7edirectx12graphicsfactory_1105',['~DirectX12GraphicsFactory',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_graphics_factory.html#ac50e50755eb20afebc66287312dbfbf6',1,'LiteFX::Rendering::Backends::DirectX12GraphicsFactory']]], ['_7edirectx12graphicsshaderprogrambuilder_1106',['~DirectX12GraphicsShaderProgramBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_graphics_shader_program_builder.html#a9a7bbefbed4fc38e1d0107e9a12273b0',1,'LiteFX::Rendering::Backends::DirectX12GraphicsShaderProgramBuilder']]], ['_7edirectx12image_1107',['~DirectX12Image',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_image.html#ac4ec92872ec68f3d73d643582e0d42f7',1,'LiteFX::Rendering::Backends::DirectX12Image']]], ['_7edirectx12indexbuffer_1108',['~DirectX12IndexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_index_buffer.html#a62616c2e962638da287215c190d431dc',1,'LiteFX::Rendering::Backends::DirectX12IndexBuffer']]], ['_7edirectx12indexbufferlayout_1109',['~DirectX12IndexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_index_buffer_layout.html#a8a1a78a5f3d0e779808f5582b95725a9',1,'LiteFX::Rendering::Backends::DirectX12IndexBufferLayout']]], ['_7edirectx12inputassembler_1110',['~DirectX12InputAssembler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_input_assembler.html#a7473bbf27a535011f56ef3d9674866db',1,'LiteFX::Rendering::Backends::DirectX12InputAssembler']]], ['_7edirectx12inputassemblerbuilder_1111',['~DirectX12InputAssemblerBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_input_assembler_builder.html#a25e32720ea38aed2053f4eb2228ad8df',1,'LiteFX::Rendering::Backends::DirectX12InputAssemblerBuilder']]], ['_7edirectx12inputattachmentmapping_1112',['~DirectX12InputAttachmentMapping',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_input_attachment_mapping.html#a964503e11d4807eee13be7ffc4e57e89',1,'LiteFX::Rendering::Backends::DirectX12InputAttachmentMapping']]], ['_7edirectx12pipelinelayout_1113',['~DirectX12PipelineLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_pipeline_layout.html#a0d96d3a814a90823ccf42ad899bfd264',1,'LiteFX::Rendering::Backends::DirectX12PipelineLayout']]], ['_7edirectx12pipelinestate_1114',['~DirectX12PipelineState',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_pipeline_state.html#a05cfc56f00601f21152a0a272e4a9de5',1,'LiteFX::Rendering::Backends::DirectX12PipelineState']]], ['_7edirectx12pushconstantslayout_1115',['~DirectX12PushConstantsLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_push_constants_layout.html#a0f16475de6995f9689c86632b1973390',1,'LiteFX::Rendering::Backends::DirectX12PushConstantsLayout']]], ['_7edirectx12pushconstantsrange_1116',['~DirectX12PushConstantsRange',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_push_constants_range.html#a6e42ada7c17d90e251d0fc9e6f8a042c',1,'LiteFX::Rendering::Backends::DirectX12PushConstantsRange']]], ['_7edirectx12queue_1117',['~DirectX12Queue',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_queue.html#a77d641cb49d8b4af2cfec09cef22413c',1,'LiteFX::Rendering::Backends::DirectX12Queue']]], ['_7edirectx12rasterizer_1118',['~DirectX12Rasterizer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_rasterizer.html#ab44fd643250a9677fe7fff5c5437cee1',1,'LiteFX::Rendering::Backends::DirectX12Rasterizer']]], ['_7edirectx12rasterizerbuilder_1119',['~DirectX12RasterizerBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_rasterizer_builder.html#a843e1d1b70dc67349148ed9c4122e461',1,'LiteFX::Rendering::Backends::DirectX12RasterizerBuilder']]], ['_7edirectx12renderpass_1120',['~DirectX12RenderPass',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pass.html#a2d900eae3164f8413d5b3e983acfe654',1,'LiteFX::Rendering::Backends::DirectX12RenderPass']]], ['_7edirectx12renderpassbuilder_1121',['~DirectX12RenderPassBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pass_builder.html#a9a1ef65f03d9e92f6d81d4a2fc48a275',1,'LiteFX::Rendering::Backends::DirectX12RenderPassBuilder']]], ['_7edirectx12renderpipeline_1122',['~DirectX12RenderPipeline',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pipeline.html#a8d21f97a5b9bb814cb086c2eed90eeb1',1,'LiteFX::Rendering::Backends::DirectX12RenderPipeline']]], ['_7edirectx12renderpipelinebuilder_1123',['~DirectX12RenderPipelineBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pipeline_builder.html#abdc386bb54dd2a19471beb41a5b0f8a0',1,'LiteFX::Rendering::Backends::DirectX12RenderPipelineBuilder']]], ['_7edirectx12renderpipelinedescriptorsetlayoutbuilder_1124',['~DirectX12RenderPipelineDescriptorSetLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pipeline_descriptor_set_layout_builder.html#aeaa41e84bd6c79ff0fa28aa03953e0a1',1,'LiteFX::Rendering::Backends::DirectX12RenderPipelineDescriptorSetLayoutBuilder']]], ['_7edirectx12renderpipelinelayoutbuilder_1125',['~DirectX12RenderPipelineLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pipeline_layout_builder.html#a1cffab027e2e65e77649f6547fb88f35',1,'LiteFX::Rendering::Backends::DirectX12RenderPipelineLayoutBuilder']]], ['_7edirectx12renderpipelinepushconstantslayoutbuilder_1126',['~DirectX12RenderPipelinePushConstantsLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_render_pipeline_push_constants_layout_builder.html#a5d291c642699701e6d7830304dfc1c07',1,'LiteFX::Rendering::Backends::DirectX12RenderPipelinePushConstantsLayoutBuilder']]], ['_7edirectx12runtimeobject_1127',['~DirectX12RuntimeObject',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_runtime_object.html#a53c943ef79d5270091375b154a43c253',1,'LiteFX::Rendering::Backends::DirectX12RuntimeObject']]], ['_7edirectx12sampler_1128',['~DirectX12Sampler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_sampler.html#accf85c1ceadcc6e12b03296042c7fb14',1,'LiteFX::Rendering::Backends::DirectX12Sampler']]], ['_7edirectx12shadermodule_1129',['~DirectX12ShaderModule',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_shader_module.html#a425c46b737cb519d81c8b1e867dddf80',1,'LiteFX::Rendering::Backends::DirectX12ShaderModule']]], ['_7edirectx12shaderprogram_1130',['~DirectX12ShaderProgram',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_shader_program.html#a572b4582072d23985ddeae04b9f99301',1,'LiteFX::Rendering::Backends::DirectX12ShaderProgram']]], ['_7edirectx12surface_1131',['~DirectX12Surface',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_surface.html#ac22a2fd1f1dfc882c1c9e23effe0eaf8',1,'LiteFX::Rendering::Backends::DirectX12Surface']]], ['_7edirectx12swapchain_1132',['~DirectX12SwapChain',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_swap_chain.html#a9f92756afefcf39b361610e50e2dbde7',1,'LiteFX::Rendering::Backends::DirectX12SwapChain']]], ['_7edirectx12vertexbuffer_1133',['~DirectX12VertexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_vertex_buffer.html#a92cda5b0cd03c48449e58b951d93d86c',1,'LiteFX::Rendering::Backends::DirectX12VertexBuffer']]], ['_7edirectx12vertexbufferlayout_1134',['~DirectX12VertexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_direct_x12_vertex_buffer_layout.html#afa671eb87c0b3f1680160c218550a693',1,'LiteFX::Rendering::Backends::DirectX12VertexBufferLayout']]], ['_7eexceptionbase_1135',['~ExceptionBase',['../class_lite_f_x_1_1_exception_base.html#aefa8d046f4fb595049ddf9c30a336e28',1,'LiteFX::ExceptionBase']]], ['_7eibackend_1136',['~IBackend',['../class_lite_f_x_1_1_i_backend.html#a7cf727b584a0a77f670cf783dd1761e2',1,'LiteFX::IBackend']]], ['_7eibarrier_1137',['~IBarrier',['../class_lite_f_x_1_1_rendering_1_1_i_barrier.html#a9986b88375d9f2ed6f1ad2a7994cc035',1,'LiteFX::Rendering::IBarrier']]], ['_7eibuffer_1138',['~IBuffer',['../class_lite_f_x_1_1_rendering_1_1_i_buffer.html#ad4ff299f483b97b2286a7d978058ca29',1,'LiteFX::Rendering::IBuffer']]], ['_7eibufferlayout_1139',['~IBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_i_buffer_layout.html#aebf7dba7a710a82a9b74b06fe1b20779',1,'LiteFX::Rendering::IBufferLayout']]], ['_7eicommandbuffer_1140',['~ICommandBuffer',['../class_lite_f_x_1_1_rendering_1_1_i_command_buffer.html#ae7cc16e5d88a7d52cf3904a8e646d937',1,'LiteFX::Rendering::ICommandBuffer']]], ['_7eicommandqueue_1141',['~ICommandQueue',['../class_lite_f_x_1_1_rendering_1_1_i_command_queue.html#a5a8156e016a24f6c5505a7a43e4f8b3a',1,'LiteFX::Rendering::ICommandQueue']]], ['_7eicomputepipeline_1142',['~IComputePipeline',['../class_lite_f_x_1_1_rendering_1_1_i_compute_pipeline.html#aa0b7dc9fd0b95115326e724f5ecc0a8d',1,'LiteFX::Rendering::IComputePipeline']]], ['_7eidescriptorlayout_1143',['~IDescriptorLayout',['../class_lite_f_x_1_1_rendering_1_1_i_descriptor_layout.html#afe64f0dae53a9c66c5dad53f7198729b',1,'LiteFX::Rendering::IDescriptorLayout']]], ['_7eidescriptorset_1144',['~IDescriptorSet',['../class_lite_f_x_1_1_rendering_1_1_i_descriptor_set.html#ab0ed24e2a439cefab4ab1dabde7a7246',1,'LiteFX::Rendering::IDescriptorSet']]], ['_7eidescriptorsetlayout_1145',['~IDescriptorSetLayout',['../class_lite_f_x_1_1_rendering_1_1_i_descriptor_set_layout.html#adc0495142646f71713eb51bf04c69d64',1,'LiteFX::Rendering::IDescriptorSetLayout']]], ['_7eidevicememory_1146',['~IDeviceMemory',['../class_lite_f_x_1_1_rendering_1_1_i_device_memory.html#a1899194e7d61373406c922cc5b336007',1,'LiteFX::Rendering::IDeviceMemory']]], ['_7eidirectx12buffer_1147',['~IDirectX12Buffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_direct_x12_buffer.html#a3f8963e345b3086f3d2cb1b4f6c5183f',1,'LiteFX::Rendering::Backends::IDirectX12Buffer']]], ['_7eidirectx12image_1148',['~IDirectX12Image',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_direct_x12_image.html#abb83ed2072c0773cc65a2a218de60b46',1,'LiteFX::Rendering::Backends::IDirectX12Image']]], ['_7eidirectx12indexbuffer_1149',['~IDirectX12IndexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_direct_x12_index_buffer.html#ad591d50697005dc501a7431adbced094',1,'LiteFX::Rendering::Backends::IDirectX12IndexBuffer']]], ['_7eidirectx12sampler_1150',['~IDirectX12Sampler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_direct_x12_sampler.html#aa39f588f6e7933d411839d57d448e9cb',1,'LiteFX::Rendering::Backends::IDirectX12Sampler']]], ['_7eidirectx12vertexbuffer_1151',['~IDirectX12VertexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_direct_x12_vertex_buffer.html#a3057634670596c5efd09715d95721359',1,'LiteFX::Rendering::Backends::IDirectX12VertexBuffer']]], ['_7eiframebuffer_1152',['~IFrameBuffer',['../class_lite_f_x_1_1_rendering_1_1_i_frame_buffer.html#a79553cafbe9ed2deac4d207f442da11e',1,'LiteFX::Rendering::IFrameBuffer']]], ['_7eigraphicsadapter_1153',['~IGraphicsAdapter',['../class_lite_f_x_1_1_rendering_1_1_i_graphics_adapter.html#a0ab6deada3027c51f0b91ae9190bbadd',1,'LiteFX::Rendering::IGraphicsAdapter']]], ['_7eigraphicsdevice_1154',['~IGraphicsDevice',['../class_lite_f_x_1_1_rendering_1_1_i_graphics_device.html#a59698c19d501cb3cd3638d83472fa23b',1,'LiteFX::Rendering::IGraphicsDevice']]], ['_7eigraphicsfactory_1155',['~IGraphicsFactory',['../class_lite_f_x_1_1_rendering_1_1_i_graphics_factory.html#a3eca22e2aeadcd934d38f2d850cbe375',1,'LiteFX::Rendering::IGraphicsFactory']]], ['_7eiimage_1156',['~IImage',['../class_lite_f_x_1_1_rendering_1_1_i_image.html#adb1660e306a4baf86d6ba9862a0ec612',1,'LiteFX::Rendering::IImage']]], ['_7eiindexbuffer_1157',['~IIndexBuffer',['../class_lite_f_x_1_1_rendering_1_1_i_index_buffer.html#ae6a82fdf753fa9e4be1565b68de5262e',1,'LiteFX::Rendering::IIndexBuffer']]], ['_7eiindexbufferlayout_1158',['~IIndexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_i_index_buffer_layout.html#a9316aeb097544bfe2b1b38c570e28802',1,'LiteFX::Rendering::IIndexBufferLayout']]], ['_7eiinputassembler_1159',['~IInputAssembler',['../class_lite_f_x_1_1_rendering_1_1_i_input_assembler.html#a24d0b5863651e6e9e111dccd29903e9f',1,'LiteFX::Rendering::IInputAssembler']]], ['_7eiinputattachmentmapping_1160',['~IInputAttachmentMapping',['../class_lite_f_x_1_1_rendering_1_1_i_input_attachment_mapping.html#acb4640d44cb9ff144ec3c9b75f799395',1,'LiteFX::Rendering::IInputAttachmentMapping']]], ['_7eiinputattachmentmappingsource_1161',['~IInputAttachmentMappingSource',['../class_lite_f_x_1_1_rendering_1_1_i_input_attachment_mapping_source.html#ad0f12341844888fd48cfdb72eca1b249',1,'LiteFX::Rendering::IInputAttachmentMappingSource']]], ['_7eimappable_1162',['~IMappable',['../class_lite_f_x_1_1_rendering_1_1_i_mappable.html#a3628b605ee4497bcef9e6eaf396d2249',1,'LiteFX::Rendering::IMappable']]], ['_7eimplement_1163',['~Implement',['../class_lite_f_x_1_1_implement.html#afe061821a54bf535e7418fbd1ff450cb',1,'LiteFX::Implement']]], ['_7eipipeline_1164',['~IPipeline',['../class_lite_f_x_1_1_rendering_1_1_i_pipeline.html#a36083bbadf9b62c91026d16cd0755d4e',1,'LiteFX::Rendering::IPipeline']]], ['_7eipipelinelayout_1165',['~IPipelineLayout',['../class_lite_f_x_1_1_rendering_1_1_i_pipeline_layout.html#a17006553780f56114ef367debc5a9d1e',1,'LiteFX::Rendering::IPipelineLayout']]], ['_7eipushconstantslayout_1166',['~IPushConstantsLayout',['../class_lite_f_x_1_1_rendering_1_1_i_push_constants_layout.html#a1112225a1526b3c49fdaebd8c591efef',1,'LiteFX::Rendering::IPushConstantsLayout']]], ['_7eipushconstantsrange_1167',['~IPushConstantsRange',['../class_lite_f_x_1_1_rendering_1_1_i_push_constants_range.html#a75f377ab0efab21c0e2d274b8f74d786',1,'LiteFX::Rendering::IPushConstantsRange']]], ['_7eirasterizer_1168',['~IRasterizer',['../class_lite_f_x_1_1_rendering_1_1_i_rasterizer.html#ac610d8927bb0301ea5eaa70a50d35b22',1,'LiteFX::Rendering::IRasterizer']]], ['_7eirenderbackend_1169',['~IRenderBackend',['../class_lite_f_x_1_1_rendering_1_1_i_render_backend.html#a5ec8bf870186e4df8ed1aa7d945181e9',1,'LiteFX::Rendering::IRenderBackend']]], ['_7eirenderpass_1170',['~IRenderPass',['../class_lite_f_x_1_1_rendering_1_1_i_render_pass.html#a9893c13b9c4a1834d6fb5abbe7a4520e',1,'LiteFX::Rendering::IRenderPass']]], ['_7eirenderpipeline_1171',['~IRenderPipeline',['../class_lite_f_x_1_1_rendering_1_1_i_render_pipeline.html#a7b484cbd0135271446ef338c4f74139c',1,'LiteFX::Rendering::IRenderPipeline']]], ['_7eirendertarget_1172',['~IRenderTarget',['../class_lite_f_x_1_1_rendering_1_1_i_render_target.html#a628b97390a68378b2454e995f7a89160',1,'LiteFX::Rendering::IRenderTarget']]], ['_7eiresource_1173',['~IResource',['../class_lite_f_x_1_1_i_resource.html#ac5bb8c6592b9b56d487d4851e213668d',1,'LiteFX::IResource']]], ['_7eisampler_1174',['~ISampler',['../class_lite_f_x_1_1_rendering_1_1_i_sampler.html#aa62c51714b0c8912497ae51d9111585f',1,'LiteFX::Rendering::ISampler']]], ['_7eiscissor_1175',['~IScissor',['../class_lite_f_x_1_1_rendering_1_1_i_scissor.html#ac6014f47826aae6d4284e0ff3ca4fc4b',1,'LiteFX::Rendering::IScissor']]], ['_7eishadermodule_1176',['~IShaderModule',['../class_lite_f_x_1_1_rendering_1_1_i_shader_module.html#a810274e3e6715a0dd572b50340e27935',1,'LiteFX::Rendering::IShaderModule']]], ['_7eishaderprogram_1177',['~IShaderProgram',['../class_lite_f_x_1_1_rendering_1_1_i_shader_program.html#a9c9fd5482836f513e760f13af8c7339d',1,'LiteFX::Rendering::IShaderProgram']]], ['_7eisurface_1178',['~ISurface',['../class_lite_f_x_1_1_rendering_1_1_i_surface.html#a4f4dc4da5c3ac7d4ae5aede723b5c56b',1,'LiteFX::Rendering::ISurface']]], ['_7eiswapchain_1179',['~ISwapChain',['../class_lite_f_x_1_1_rendering_1_1_i_swap_chain.html#a219f7304f35bf3fe4b22e06df375c501',1,'LiteFX::Rendering::ISwapChain']]], ['_7eivertexbuffer_1180',['~IVertexBuffer',['../class_lite_f_x_1_1_rendering_1_1_i_vertex_buffer.html#a76837c1100479851d187ffca44e5aa3e',1,'LiteFX::Rendering::IVertexBuffer']]], ['_7eivertexbufferlayout_1181',['~IVertexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_i_vertex_buffer_layout.html#a2db0ddca07931b5d082727f10b8ca12a',1,'LiteFX::Rendering::IVertexBufferLayout']]], ['_7eiviewport_1182',['~IViewport',['../class_lite_f_x_1_1_rendering_1_1_i_viewport.html#a67e618f066ae7871340da02c42fce0e0',1,'LiteFX::Rendering::IViewport']]], ['_7eivulkanbuffer_1183',['~IVulkanBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_vulkan_buffer.html#af7167f6f01468151853a1aeebdfa2fde',1,'LiteFX::Rendering::Backends::IVulkanBuffer']]], ['_7eivulkanimage_1184',['~IVulkanImage',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_vulkan_image.html#ab22501f914959426e572433db1813119',1,'LiteFX::Rendering::Backends::IVulkanImage']]], ['_7eivulkanindexbuffer_1185',['~IVulkanIndexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_vulkan_index_buffer.html#ac64eda877c61f55a63f0b7aebe1f319e',1,'LiteFX::Rendering::Backends::IVulkanIndexBuffer']]], ['_7eivulkansampler_1186',['~IVulkanSampler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_vulkan_sampler.html#a1243ef31829877f8e913f5247cda8a43',1,'LiteFX::Rendering::Backends::IVulkanSampler']]], ['_7eivulkanvertexbuffer_1187',['~IVulkanVertexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_i_vulkan_vertex_buffer.html#aecf96178b287da82354a56be0b330573',1,'LiteFX::Rendering::Backends::IVulkanVertexBuffer']]], ['_7elog_1188',['~Log',['../class_lite_f_x_1_1_logging_1_1_log.html#ab34c6e7856d2b711b7082cc93d980659',1,'LiteFX::Logging::Log']]], ['_7elogger_1189',['~Logger',['../class_lite_f_x_1_1_logging_1_1_logger.html#a3ba050973bd803e1b3061e83872c223b',1,'LiteFX::Logging::Logger']]], ['_7epimplptr_1190',['~PimplPtr',['../class_lite_f_x_1_1_pimpl_ptr.html#abd4d972498a019ce27861c4f7e589826',1,'LiteFX::PimplPtr']]], ['_7erasterizer_1191',['~Rasterizer',['../class_lite_f_x_1_1_rendering_1_1_rasterizer.html#a6a4818f3664b0cdd29a765a8a29771ed',1,'LiteFX::Rendering::Rasterizer']]], ['_7erendertarget_1192',['~RenderTarget',['../class_lite_f_x_1_1_rendering_1_1_render_target.html#ab35f6e447ba431743a988447e5853191',1,'LiteFX::Rendering::RenderTarget']]], ['_7eresource_1193',['~Resource',['../class_lite_f_x_1_1_resource.html#a143d2edded502a06e266f22a22510dba',1,'LiteFX::Resource']]], ['_7erollingfilesink_1194',['~RollingFileSink',['../class_lite_f_x_1_1_logging_1_1_rolling_file_sink.html#af0b6747bd56eae8ffb382b90dc708219',1,'LiteFX::Logging::RollingFileSink']]], ['_7escissor_1195',['~Scissor',['../class_lite_f_x_1_1_rendering_1_1_scissor.html#abc1d4f595db9c295f829777f9b23d530',1,'LiteFX::Rendering::Scissor']]], ['_7eviewport_1196',['~Viewport',['../class_lite_f_x_1_1_rendering_1_1_viewport.html#a819fbc86b2cfea0d960ced20652dcdb1',1,'LiteFX::Rendering::Viewport']]], ['_7evulkanbackend_1197',['~VulkanBackend',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_backend.html#a6a7afb6f8ab7a00ab7a54b07877db6fe',1,'LiteFX::Rendering::Backends::VulkanBackend']]], ['_7evulkanbackendimpl_1198',['~VulkanBackendImpl',['../class_vulkan_backend_1_1_vulkan_backend_impl.html#ac681ad304af75b80b1dc740b35704ab2',1,'VulkanBackend::VulkanBackendImpl']]], ['_7evulkanbarrier_1199',['~VulkanBarrier',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_barrier.html#af270753679e432ca4c4600c58bd2d615',1,'LiteFX::Rendering::Backends::VulkanBarrier']]], ['_7evulkanbuffer_1200',['~VulkanBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_buffer.html#a44ab62ef3847ffb5981aaa5f30d997e6',1,'LiteFX::Rendering::Backends::VulkanBuffer']]], ['_7evulkancommandbuffer_1201',['~VulkanCommandBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_command_buffer.html#acf6bce275854d8cd702ea7c35c4bc0f2',1,'LiteFX::Rendering::Backends::VulkanCommandBuffer']]], ['_7evulkancomputepipeline_1202',['~VulkanComputePipeline',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_pipeline.html#a400b4fa0a48c6c9016879fec9722f0e0',1,'LiteFX::Rendering::Backends::VulkanComputePipeline']]], ['_7evulkancomputepipelinebuilder_1203',['~VulkanComputePipelineBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_pipeline_builder.html#a453b667356a03ba03da4a01cf8953d81',1,'LiteFX::Rendering::Backends::VulkanComputePipelineBuilder']]], ['_7evulkancomputepipelinedescriptorsetlayoutbuilder_1204',['~VulkanComputePipelineDescriptorSetLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_pipeline_descriptor_set_layout_builder.html#a1646065f47b448dc8d7aef3e49c7217b',1,'LiteFX::Rendering::Backends::VulkanComputePipelineDescriptorSetLayoutBuilder']]], ['_7evulkancomputepipelinelayoutbuilder_1205',['~VulkanComputePipelineLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_pipeline_layout_builder.html#a92e9eb08ed2df57dc54074838b195b3b',1,'LiteFX::Rendering::Backends::VulkanComputePipelineLayoutBuilder']]], ['_7evulkancomputepipelinepushconstantslayoutbuilder_1206',['~VulkanComputePipelinePushConstantsLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_pipeline_push_constants_layout_builder.html#a974948115bebd7d16d2690e3a6828b06',1,'LiteFX::Rendering::Backends::VulkanComputePipelinePushConstantsLayoutBuilder']]], ['_7evulkancomputeshaderprogrambuilder_1207',['~VulkanComputeShaderProgramBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_compute_shader_program_builder.html#a7af0a0cea00ed0ed066ef720fe7d354e',1,'LiteFX::Rendering::Backends::VulkanComputeShaderProgramBuilder']]], ['_7evulkandescriptorlayout_1208',['~VulkanDescriptorLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_descriptor_layout.html#a94f1ac63e75f712f1e19d0eb31084dd1',1,'LiteFX::Rendering::Backends::VulkanDescriptorLayout']]], ['_7evulkandescriptorset_1209',['~VulkanDescriptorSet',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_descriptor_set.html#a60d799b5e0addc8b494f39f5ea91109f',1,'LiteFX::Rendering::Backends::VulkanDescriptorSet']]], ['_7evulkandescriptorsetlayout_1210',['~VulkanDescriptorSetLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_descriptor_set_layout.html#aa9ed42e575be66c638b6424278928d66',1,'LiteFX::Rendering::Backends::VulkanDescriptorSetLayout']]], ['_7evulkandevice_1211',['~VulkanDevice',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_device.html#af7dc274c6d4a58566a05a86245ce1c51',1,'LiteFX::Rendering::Backends::VulkanDevice']]], ['_7evulkandeviceimpl_1212',['~VulkanDeviceImpl',['../class_vulkan_device_1_1_vulkan_device_impl.html#a3684da0511c6f991bf241ed88a63a9bd',1,'VulkanDevice::VulkanDeviceImpl']]], ['_7evulkanframebuffer_1213',['~VulkanFrameBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_frame_buffer.html#affe309337d3f68bb7e0eb9d540c87552',1,'LiteFX::Rendering::Backends::VulkanFrameBuffer']]], ['_7evulkanframebufferimpl_1214',['~VulkanFrameBufferImpl',['../class_vulkan_frame_buffer_1_1_vulkan_frame_buffer_impl.html#a1634544ad6e3e1ad94a6e9ae4ce7a253',1,'VulkanFrameBuffer::VulkanFrameBufferImpl']]], ['_7evulkangraphicsadapter_1215',['~VulkanGraphicsAdapter',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_graphics_adapter.html#a61bf5c1d9e8144d9ef821dc1e1e444f9',1,'LiteFX::Rendering::Backends::VulkanGraphicsAdapter']]], ['_7evulkangraphicsfactory_1216',['~VulkanGraphicsFactory',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_graphics_factory.html#a8a532e72e3454411572c6f320f97acc6',1,'LiteFX::Rendering::Backends::VulkanGraphicsFactory']]], ['_7evulkangraphicsfactoryimpl_1217',['~VulkanGraphicsFactoryImpl',['../class_vulkan_graphics_factory_1_1_vulkan_graphics_factory_impl.html#a102fa1bfeb27f55a999544dac921f7fd',1,'VulkanGraphicsFactory::VulkanGraphicsFactoryImpl']]], ['_7evulkangraphicsshaderprogrambuilder_1218',['~VulkanGraphicsShaderProgramBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_graphics_shader_program_builder.html#a2828bfbbdf82ed2a93e76cf86650eeac',1,'LiteFX::Rendering::Backends::VulkanGraphicsShaderProgramBuilder']]], ['_7evulkanimage_1219',['~VulkanImage',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_image.html#a1ed2dd8352b78ea3a392d8ad751a7c7b',1,'LiteFX::Rendering::Backends::VulkanImage']]], ['_7evulkanindexbuffer_1220',['~VulkanIndexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_index_buffer.html#a9c3583b9ade8f5952c958fb2b8ac0fa9',1,'LiteFX::Rendering::Backends::VulkanIndexBuffer']]], ['_7evulkanindexbufferlayout_1221',['~VulkanIndexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_index_buffer_layout.html#abfc9763372d7048e93b74668312d0252',1,'LiteFX::Rendering::Backends::VulkanIndexBufferLayout']]], ['_7evulkaninputassembler_1222',['~VulkanInputAssembler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_input_assembler.html#a703a5a23b40fa1bceccbc9a7a786f05d',1,'LiteFX::Rendering::Backends::VulkanInputAssembler']]], ['_7evulkaninputassemblerbuilder_1223',['~VulkanInputAssemblerBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_input_assembler_builder.html#a45471feb17a88a2f317a25fe54e73f04',1,'LiteFX::Rendering::Backends::VulkanInputAssemblerBuilder']]], ['_7evulkaninputattachmentmapping_1224',['~VulkanInputAttachmentMapping',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_input_attachment_mapping.html#a69cadb791a7662c3995d96745ed0dee7',1,'LiteFX::Rendering::Backends::VulkanInputAttachmentMapping']]], ['_7evulkanpipelinelayout_1225',['~VulkanPipelineLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_pipeline_layout.html#a2870c702c1a6400d722b09cefca8bbda',1,'LiteFX::Rendering::Backends::VulkanPipelineLayout']]], ['_7evulkanpipelinestate_1226',['~VulkanPipelineState',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_pipeline_state.html#a5b2296680f2cc8c78eca2ed2bff5e8cf',1,'LiteFX::Rendering::Backends::VulkanPipelineState']]], ['_7evulkanpushconstantslayout_1227',['~VulkanPushConstantsLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_push_constants_layout.html#a41bfba29ee96f8ae1cbe4725a47a9aca',1,'LiteFX::Rendering::Backends::VulkanPushConstantsLayout']]], ['_7evulkanpushconstantsrange_1228',['~VulkanPushConstantsRange',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_push_constants_range.html#a0cc0684c9e28ecec692208823051e580',1,'LiteFX::Rendering::Backends::VulkanPushConstantsRange']]], ['_7evulkanqueue_1229',['~VulkanQueue',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_queue.html#ac033627126f86138df2b4c758c6f78c2',1,'LiteFX::Rendering::Backends::VulkanQueue']]], ['_7evulkanqueueimpl_1230',['~VulkanQueueImpl',['../class_vulkan_queue_1_1_vulkan_queue_impl.html#a8ebf687d2f2014ef1ab7adfe17ce4399',1,'VulkanQueue::VulkanQueueImpl']]], ['_7evulkanrasterizer_1231',['~VulkanRasterizer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_rasterizer.html#a8715e9802fb9d008f9f0da6e4459807e',1,'LiteFX::Rendering::Backends::VulkanRasterizer']]], ['_7evulkanrasterizerbuilder_1232',['~VulkanRasterizerBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_rasterizer_builder.html#a76311a92e31355ece199d176cd93e850',1,'LiteFX::Rendering::Backends::VulkanRasterizerBuilder']]], ['_7evulkanrenderpass_1233',['~VulkanRenderPass',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pass.html#a7098f0ade944c72a3c643d8cab034aa1',1,'LiteFX::Rendering::Backends::VulkanRenderPass']]], ['_7evulkanrenderpassbuilder_1234',['~VulkanRenderPassBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pass_builder.html#a71b638a663a813bc315b298021b5b1ce',1,'LiteFX::Rendering::Backends::VulkanRenderPassBuilder']]], ['_7evulkanrenderpipeline_1235',['~VulkanRenderPipeline',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pipeline.html#a5f2a664a671f5e000304bab1fe920ecd',1,'LiteFX::Rendering::Backends::VulkanRenderPipeline']]], ['_7evulkanrenderpipelinebuilder_1236',['~VulkanRenderPipelineBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pipeline_builder.html#a6ce64f0e4b588d471bd7553a7dfaabca',1,'LiteFX::Rendering::Backends::VulkanRenderPipelineBuilder']]], ['_7evulkanrenderpipelinedescriptorsetlayoutbuilder_1237',['~VulkanRenderPipelineDescriptorSetLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pipeline_descriptor_set_layout_builder.html#a245bd6196e7023d8fdb1600d0d2d29e9',1,'LiteFX::Rendering::Backends::VulkanRenderPipelineDescriptorSetLayoutBuilder']]], ['_7evulkanrenderpipelinelayoutbuilder_1238',['~VulkanRenderPipelineLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pipeline_layout_builder.html#a483ab64ebfce4407cbd5f96bd8456387',1,'LiteFX::Rendering::Backends::VulkanRenderPipelineLayoutBuilder']]], ['_7evulkanrenderpipelinepushconstantslayoutbuilder_1239',['~VulkanRenderPipelinePushConstantsLayoutBuilder',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_render_pipeline_push_constants_layout_builder.html#a2a545500af663f79c15b04412eff6ca9',1,'LiteFX::Rendering::Backends::VulkanRenderPipelinePushConstantsLayoutBuilder']]], ['_7evulkanruntimeobject_1240',['~VulkanRuntimeObject',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_runtime_object.html#a69179bb91e7b2078a3609e2b81187867',1,'LiteFX::Rendering::Backends::VulkanRuntimeObject']]], ['_7evulkansampler_1241',['~VulkanSampler',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_sampler.html#a9dc084739697646105b3c920d3fe3135',1,'LiteFX::Rendering::Backends::VulkanSampler']]], ['_7evulkanshadermodule_1242',['~VulkanShaderModule',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_shader_module.html#a65d060740a91dfa8c493964fa7a15d74',1,'LiteFX::Rendering::Backends::VulkanShaderModule']]], ['_7evulkanshaderprogram_1243',['~VulkanShaderProgram',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_shader_program.html#ab3723b685b9a483d582c155a4aa5a886',1,'LiteFX::Rendering::Backends::VulkanShaderProgram']]], ['_7evulkansurface_1244',['~VulkanSurface',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_surface.html#a5a6c3318fa97ed09b41d2cbd65f0a996',1,'LiteFX::Rendering::Backends::VulkanSurface']]], ['_7evulkanswapchain_1245',['~VulkanSwapChain',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_swap_chain.html#a85c713526eba9e21895b42c9176d2898',1,'LiteFX::Rendering::Backends::VulkanSwapChain']]], ['_7evulkanswapchainimpl_1246',['~VulkanSwapChainImpl',['../class_vulkan_swap_chain_1_1_vulkan_swap_chain_impl.html#a626164dee1db645ee07cbd2def17027f',1,'VulkanSwapChain::VulkanSwapChainImpl']]], ['_7evulkanvertexbuffer_1247',['~VulkanVertexBuffer',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_vertex_buffer.html#aaf239560f52c88a378417614b3b42d59',1,'LiteFX::Rendering::Backends::VulkanVertexBuffer']]], ['_7evulkanvertexbufferlayout_1248',['~VulkanVertexBufferLayout',['../class_lite_f_x_1_1_rendering_1_1_backends_1_1_vulkan_vertex_buffer_layout.html#aaf209783aef9b07e420b5ed80e9c191c',1,'LiteFX::Rendering::Backends::VulkanVertexBufferLayout']]] ];
# Tencent is pleased to support the open source community by making ncnn available. # # Copyright (C) 2021 THL A29 Limited, a Tencent company. All rights reserved. # # Licensed under the BSD 3-Clause License (the "License"); you may not use this file except # in compliance with the License. You may obtain a copy of the License at # # https://opensource.org/licenses/BSD-3-Clause # # Unless required by applicable law or agreed to in writing, software distributed # under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR # CONDITIONS OF ANY KIND, either express or implied. See the License for the # specific language governing permissions and limitations under the License. import torch import torch.nn as nn import torch.nn.functional as F class Model(nn.Module): def __init__(self): super(Model, self).__init__() self.lstm_0_0 = nn.LSTM(input_size=32, hidden_size=16) self.lstm_0_1 = nn.LSTM(input_size=16, hidden_size=16, num_layers=3, bias=False) self.lstm_0_2 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, bidirectional=True) self.lstm_0_3 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, bidirectional=True) self.lstm_0_4 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, bidirectional=True) self.lstm_1_0 = nn.LSTM(input_size=25, hidden_size=16, batch_first=True) self.lstm_1_1 = nn.LSTM(input_size=16, hidden_size=16, num_layers=3, bias=False, batch_first=True) self.lstm_1_2 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, batch_first=True, bidirectional=True) self.lstm_1_3 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, batch_first=True, bidirectional=True) self.lstm_1_4 = nn.LSTM(input_size=16, hidden_size=16, num_layers=4, bias=True, batch_first=True, bidirectional=True) def forward(self, x, y): x = x.permute(1, 0, 2) x0, _ = self.lstm_0_0(x) x1, _ = self.lstm_0_1(x0) x2, (h0, c0) = self.lstm_0_2(x1) x3, (h1, c1) = self.lstm_0_3(x1, (h0, c0)) x4, _ = self.lstm_0_4(x1, (h1, c1)) y0, _ = self.lstm_1_0(y) y1, _ = self.lstm_1_1(y0) y2, (h2, c2) = self.lstm_1_2(y1) y3, (h3, c3) = self.lstm_1_3(y1, (h2, c2)) y4, _ = self.lstm_1_4(y1, (h3, c3)) x2 = x2.permute(1, 0, 2) x3 = x3.permute(1, 0, 2) x4 = x4.permute(1, 0, 2) return x2, x3, x4, y2, y3, y4 def test(): net = Model().half().float() net.eval() torch.manual_seed(0) x = torch.rand(1, 10, 32) y = torch.rand(1, 12, 25) a = net(x, y) # export torchscript mod = torch.jit.trace(net, (x, y)) mod.save("test_nn_LSTM.pt") # torchscript to pnnx import os os.system("../../src/pnnx test_nn_LSTM.pt inputshape=[1,10,32],[1,12,25]") # ncnn inference import test_nn_LSTM_ncnn b = test_nn_LSTM_ncnn.test_inference() for a0, b0 in zip(a, b): if not torch.allclose(a0, b0, 1e-3, 1e-3): return False return True if __name__ == "__main__": if test(): exit(0) else: exit(1)
import { createApp } from "vue"; import app from "./app.vue"; // import Greeting from "./components/Greeting"; const vm = createApp(app); // vm.component("Greeting", Greeting); vm.mount("#app");
# urlnorm.py - Normalize URLs # Copyright (C) 2010 Kurt McKee <[email protected]> # # This program is free software: you can redistribute it and/or modify # it under the terms of the GNU Lesser General Public License as published by # the Free Software Foundation, either version 3 of the License, or # (at your option) any later version. # # This program is distributed in the hope that it will be useful, # but WITHOUT ANY WARRANTY; without even the implied warranty of # MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the # GNU Lesser General Public License for more details. # # You should have received a copy of the GNU Lesser General Public License # along with this program. If not, see <http://www.gnu.org/licenses/>. __author__ = "Kurt McKee <[email protected]>" import re import urllib import urlparse DEFAULT_PORTS = { 'http': u'80', 'https': u'443', } NETLOC = re.compile(""" ^ (?: (?P<username>[^:@]+)? (?: : (?P<password>[^@]*) )? @ )? (?P<hostname>[^:]+) (?: : (?P<port>[0-9]*) )? $ """, re.VERBOSE, ) PERCENT_ENCODING = re.compile("%([0-9a-f]{2})", re.IGNORECASE) UNACCEPTABLE_QUERY_CHARS = re.compile("([^A-Za-z0-9_.~/-])") # http://www.pc-help.org/obscure.htm # http://www.securelist.com/en/blog/148/ # Translate the IP address from octal, decimal, and hex # into a base 10 quadruple octet (like 127.0.0.1) NUMERIC_IP = re.compile(""" ^ (?: (?P<o0>(?:[0-9]+)|(?:0x[0-9a-f]+)) [.] )? (?: (?P<o1>(?:[0-9]+)|(?:0x[0-9a-f]+)) [.] )? (?: (?P<o2>(?:[0-9]+)|(?:0x[0-9a-f]+)) [.] )? (?P<o3>(?:[0-9]+)|(?:0x[0-9a-f]+)) $ """, re.VERBOSE | re.IGNORECASE ) _pre_plugins = [] _post_plugins = [] def register_pre_plugin(fn): _pre_plugins.append(fn) def register_post_plugin(fn): _post_plugins.append(fn) def urlnorm(url, base=None): newurl = url.strip() newurl = ''.join((v for u in newurl.split('\n') for v in u.split('\r'))) if newurl.lower().startswith('feed:'): newurl = newurl[5:] if base is not None: newurl = urlparse.urljoin(base.strip(), newurl) for fn in _pre_plugins: newurl = fn(newurl) newurl = _normalize_percent_encoding(newurl) parts = _urlparse(newurl) if parts is None: return url parts.update(_split_netloc(parts['netloc'])) parts['scheme'] = _normalize_scheme(parts['scheme']) parts['port'] = _normalize_port(parts['port'], parts['scheme']) parts['path'] = _normalize_path(parts['path']) parts['hostname'] = _normalize_hostname(parts.get('hostname', '')) parts['query'] = _split_query(parts['query']) for fn in _post_plugins: parts.update(fn(parts)) return _join_parts(parts) def _urlparse(url): parts = dict(zip(('scheme', 'netloc', 'path', 'params', 'query', 'fragment'), urlparse.urlparse(url) )) if (not parts['scheme'] and not parts['netloc']) or \ ( not parts['netloc'] and parts['path'] and parts['path'][0] in map(str, range(10)) and url.startswith('%s:%s' % (parts['scheme'], parts['path'])) ): # url may not have included a scheme, like 'domain.example' # url may have been in the form 'domain.example:8080' parts = dict(zip(('scheme', 'netloc', 'path', 'params', 'query', 'fragment'), urlparse.urlparse('http://%s' % url) )) elif parts['scheme'].lower() not in ('http', 'https'): return None return parts def _join_parts(parts): url = '%s://' % parts['scheme'] if parts['username']: url += parts['username'] if parts['password']: url += ':%s' % parts['password'] url += '@' url += parts['hostname'] if parts['port']: url += ':%s' % parts['port'] url += parts['path'] if parts['params']: url += ';%s' % parts['params'] if parts['query']: url += '?%s' % _join_query(parts['query']) if parts['fragment']: url += '#%s' % parts['fragment'] return url def _split_netloc(netloc): parts_netloc = NETLOC.match(netloc) if parts_netloc is not None: return parts_netloc.groupdict() return {'username': '', 'password': '', 'hostname': '', 'port': ''} def _normalize_scheme(scheme): return scheme.lower() or 'http' def _normalize_port(port, scheme): if scheme in DEFAULT_PORTS and DEFAULT_PORTS[scheme] == port: return '' return port def _normalize_percent_encoding(txt): unreserved = u'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789-_.~' def repl(hexpair): if unichr(int(hexpair.group(1), 16)) in unreserved: return unichr(int(hexpair.group(1), 16)) return u'%%%s' % hexpair.group(1).upper() return re.sub(PERCENT_ENCODING, repl, txt) def _normalize_hostname(hostname): hostname = hostname.lower() if hostname.endswith('.'): hostname = hostname[:-1] ip = NUMERIC_IP.match(hostname) if ip is not None: ip = filter(None, ip.groups()) decimal_ip = 0 for i in range(len(ip)): base = (10, 8, 16)[(ip[i][0:1] == '0') + (ip[i][1:2] == 'x')] decimal_ip += ( (long(ip[i] or '0', base) & (256**[1, 4-i][len(ip)==i+1]-1)) << (8*[3-i, 0][len(ip)==i+1]) ) new_ip = '.'.join([unicode((decimal_ip >> (8*octet)) & 255) for octet in (3, 2, 1, 0)]) hostname = new_ip return hostname def _normalize_path(path): path = path.split('/') endslash = False if path[-1] == '': endslash = True path = filter(None, path) pos = 0 for i in range(len(path)): if path[i] == '.': path[i] = None elif path[i] == '..': path[pos] = None if pos > 0: pos -= 1 path[i] = None elif path[i]: path[pos] = path[i] if pos < i: path[i] = None pos += 1 path.insert(0, '') if endslash: path.append('') return '/'.join(filter(lambda x: x is not None, path)) or '/' def _split_query(query): # The following code's basic logic was found in the Python 2.6 # urlparse library, but was modified due to differing needs ret = {} queries = [j for i in query.split('&') for j in i.split(';')] if queries == ['']: return ret for q in queries: nv = q.split('=', 1) if len(nv) == 1: # Differentiate between `?n=` and ?n` nv.append(None) ret.setdefault(nv[0], []).append(nv[1]) return ret def _join_query(qdict): def replace(s): return u'%%%s' % hex(ord(s.group(1)))[2:].upper() ret = '' for k in sorted(qdict.keys()): for v in sorted(qdict[k]): if v is None: ret += '&%s' % (re.sub(UNACCEPTABLE_QUERY_CHARS, replace, k),) elif not v: ret += '&%s=' % (re.sub(UNACCEPTABLE_QUERY_CHARS, replace, k),) else: ret += '&%s=%s' % (re.sub(UNACCEPTABLE_QUERY_CHARS, replace, k), re.sub(UNACCEPTABLE_QUERY_CHARS, replace, v) ) return ret[1:]
"""FastAPI Router Contoller, FastAPI utility to allow Controller Class usage""" from fastapi_router_controller.lib.controller import Controller as Controller from fastapi_router_controller.lib.controller import OPEN_API_TAGS as ControllersTags from fastapi_router_controller.lib.controller_loader import ( ControllerLoader as ControllerLoader, ) __all__ = ["Controller", "ControllersTags", "ControllerLoader"]
const socket = io(); // Elementes const $messageForm = document.querySelector('#message-form'); const $messageFormInput = $messageForm.querySelector('input'); const $messageFormButton = $messageForm.querySelector('button'); const $sendLocationButton = document.querySelector('#send-location'); const $messages = document.querySelector('#messages'); // Templates const messageTemplate = document.querySelector('#message-template').innerHTML; const locationMessageTemplate = document.querySelector( '#location-message-template' ).innerHTML; const sidebarTemplate = document.querySelector('#sidebar-template').innerHTML; // Options const { username, room } = Qs.parse(location.search, { ignoreQueryPrefix: true }); const autoscroll = () => { const $newMessage = $messages.lastElementChild; const newMessageStyles = getComputedStyle($newMessage); const newMessageMargin = parseInt(newMessageStyles.marginBottom); const newMessageHeight = $newMessage.offsetHeight + newMessageMargin; const visibleHeight = $messages.offsetHeight; const containerHeight = $messages.scrollHeight; const scrollOffset = $messages.scrollTop + visibleHeight; if (containerHeight - newMessageHeight <= scrollOffset) { $messages.scrollTop = $messages.scrollHeight; } }; socket.on('sendMessage', message => { const html = Mustache.render(messageTemplate, { username: message.username, message: message.text, createdAt: moment(message.createdAt).format('hh:mm A') }); $messages.insertAdjacentHTML('beforeend', html); autoscroll(); }); socket.on('roomData', ({ room, users }) => { const html = Mustache.render(sidebarTemplate, { room, users }); document.querySelector('#sidebar').innerHTML = html; }); socket.on('sendLocationMessage', locationMessage => { const html = Mustache.render(locationMessageTemplate, { username: locationMessage.username, locationURL: locationMessage.url, createdAt: moment(locationMessage.createdAt).format('hh:mm A') }); $messages.insertAdjacentHTML('beforeend', html); autoscroll(); }); document.querySelector('#message-form').addEventListener('submit', e => { $messageFormButton.setAttribute('disabled', 'disabled'); e.preventDefault(); const inputMessage = e.target.elements.message.value; socket.emit('newMessage', inputMessage, error => { $messageFormButton.removeAttribute('disabled'); if (error) { return alert(error); } $messageFormInput.value = ''; $messageFormInput.focus(); console.log('Message delivered!'); }); }); $sendLocationButton.addEventListener('click', () => { $sendLocationButton.setAttribute('disabled', 'disabled'); if (!navigator.geolocation) { return alert('Geolocation is not supported by your browser!'); } navigator.geolocation.getCurrentPosition(position => { socket.emit( 'sendLocation', { latitude: position.coords.latitude, longitude: position.coords.longitude }, () => { console.log('Location shared!'); $sendLocationButton.removeAttribute('disabled'); } ); }); }); socket.emit('join', { username, room }, error => { if (error) { alert(error); location.href = '/'; } });
import { createStore } from 'vuex' import c from '@/constants' import { saveItem, getItem } from '@/plugins/localStorageProvider' const state = { api_credits: 0, API_USAGE_ERRORS: '', coin_code: '', currency: '', number_of_periods: 0, cryptos: [] } const getters = { [c.VUEX.GETTERS.API_DAILY_USAGE](state){ return state.api_credits }, [c.VUEX.GETTERS.API_USAGE_ERRORS](state){ return state.API_USAGE_ERRORS }, [c.VUEX.GETTERS.COIN_CODE](state){ if (!state.coin_code || state.coin_code === ''){ state.coin_code = getItem(c.LOCALSTORE.COIN_CODE,'') } return state.coin_code }, [c.VUEX.GETTERS.CURRENCY](state){ if (!state.currency || state.currency === ''){ state.currency = getItem(c.LOCALSTORE.CURRENCY,'') } return state.currency }, [c.VUEX.GETTERS.NUMBER_OF_PERIODS](state){ if (!state.number_of_periods || state.number_of_periods === 0){ state.number_of_periods = parseInt(getItem(c.LOCALSTORE.NUMBER_OF_PERIODS,0)) } return state.number_of_periods }, [c.VUEX.GETTERS.CRYPTOS](state){ if (!state.cryptos || state.cryptos.length === 0){ state.cryptos = getItem(c.LOCALSTORE.CRYPTOS,[]) } return state.cryptos } } const mutations = { [c.VUEX.MUTATIONS.UPDATE_DAILY_USAGE](state, val){ state.api_credits = val }, [c.VUEX.MUTATIONS.UPDATE_USAGE_ERRORS](state, val){ state.API_USAGE_ERRORS = val }, [c.VUEX.MUTATIONS.UPDATE_COIN_CODE](state, val){ state.coin_code = val }, [c.VUEX.MUTATIONS.UPDATE_CURRENCY](state, val){ state.currency = val }, [c.VUEX.MUTATIONS.UPDATE_NUMBER_OF_PERIODS](state, val){ state.number_of_periods = val }, [c.VUEX.MUTATIONS.ADD_CRYPTO](state, payload){ if (state.cryptos === null || !state.cryptos) return const pos = state.cryptos.findIndex(function(el){ return el.code === payload.code }) if (pos === -1) { state.cryptos.push(payload) } }, [c.VUEX.MUTATIONS.REMOVE_CRYPTO](state, payload){ if (state.cryptos === null || !state.cryptos) return state.cryptos = state.cryptos.filter(function(el){ return el.code !== payload.code }) } } export const store = createStore({ state, getters, mutations, plugins: [saveItem] })
import React from "react"; import { CollapsibleMenu, Section } from "./Menu"; import Ascensions from "./listings/Ascensions"; import Preferences from "./listings/Preferences"; import About from "./listings/About"; import Credits from "./listings/Credits"; import "./SemiCookie.scss"; export default function SemiCookieUI() { return ( <div id="SemiCookieMenu"> <CollapsibleMenu title="SemiCookie"> <Section title="Ascensions"> <Ascensions /> </Section> <Section title="Preferences"> <Preferences /> </Section> <Section title="About"> <About /> </Section> <Section title="Credits"> <Credits /> </Section> </CollapsibleMenu> </div> ); }
/** * angularjs.fileUploadModel * AngularJS directive used for picking up file(s) on input of type "file" to be made available in the $scope and assigned to the binded model * @version v1.0.0 - 2019-08-02 * @link https://github.com/omostan/fileUploadModel.git * @author Stanley Omoregie <[email protected]> (http://www.omotech.com)> * @license MIT License, http://www.opensource.org/licenses/MIT */ (function(angular){"use strict";angular.module("angularjs.fileUploadModel",[]).directive("fileUploadModel",fileUploadModel);fileUploadModel.$inject=["$log"];function fileUploadModel($log){return{require:"ngModel",restrict:"A",scope:{ngModel:"=",ngChange:"&",type:"@"},link:fn_link};function fn_link(scope,element,attrs,ngModel){if(scope.type.toLowerCase()!=="file"){return}var isMultiple=attrs.multiple;element.bind("change",function(){scope.files=[];angular.forEach(element[0].files,function(file){var fileObj={name:file.name,size:file.size,url:URL.createObjectURL(file),_file:file};scope.files.push(fileObj)});isMultiple?ngModel.$setViewValue(scope.files):ngModel.$setViewValue(scope.files[0]);scope.ngChange()})}}})(window.angular);
/** * * HAAR.js Feature Detection Library based on Viola-Jones Haar Detection algorithm * port of jViolaJones for Java (http://code.google.com/p/jviolajones/) to JavaScript and Node * * https://github.com/foo123/HAAR.js * @version: @@VERSION@@ * * Supports parallel "map-reduce" computation both in browser and node using parallel.js library * https://github.com/adambom/parallel.js (included) * **/ "use strict"; // the export object var HAAR = { VERSION : "@@VERSION@@" }, Detector, Feature, proto = 'prototype', undef = undefined; var // typed arrays substitute Array32F = (typeof Float32Array !== "undefined") ? Float32Array : Array, Array8U = (typeof Uint8Array !== "undefined") ? Uint8Array : Array, /* Array64F = (typeof Float64Array !== "undefined") ? Float64Array : Array, Array8I = (typeof Int8Array !== "undefined") ? Int8Array : Array, Array16I = (typeof Int16Array !== "undefined") ? Int16Array : Array, Array32I = (typeof Int32Array !== "undefined") ? Int32Array : Array, Array16U = (typeof Uint16Array !== "undefined") ? Uint16Array : Array, Array32U = (typeof Uint32Array !== "undefined") ? Uint32Array : Array, */ // math functions brevity Abs=Math.abs, Max=Math.max, Min=Math.min, Floor=Math.floor, Round=Math.round, Sqrt=Math.sqrt, slice=Array[proto].slice ; // // Private methods for detection // // compute grayscale image, integral image (SAT) and squares image (Viola-Jones) function integralImage(im, w, h/*, selection*/) { var imLen=im.length, count=w*h , sum, sum2, i, j, k, y, g , gray = new Array8U(count) // Viola-Jones , integral = new Array32F(count), squares = new Array32F(count) // Lienhart et al. extension using tilted features , tilted = new Array32F(count) ; // first row j=0; i=0; sum=sum2=0; while (j<w) { // use fixed-point gray-scale transform, close to openCV transform // https://github.com/mtschirs/js-objectdetect/issues/3 // 0,29901123046875 0,58697509765625 0,114013671875 with roundoff g = ((4899 * im[i] + 9617 * im[i + 1] + 1868 * im[i + 2]) + 8192) >>> 14; g &= 255; sum += g; sum2 += /*(*/(g*g); //&0xFFFFFFFF) >>> 0; // SAT(-1, y) = SAT(x, -1) = SAT(-1, -1) = 0 // SAT(x, y) = SAT(x, y-1) + SAT(x-1, y) + I(x, y) - SAT(x-1, y-1) <-- integral image // RSAT(-1, y) = RSAT(x, -1) = RSAT(x, -2) = RSAT(-1, -1) = RSAT(-1, -2) = 0 // RSAT(x, y) = RSAT(x-1, y-1) + RSAT(x+1, y-1) - RSAT(x, y-2) + I(x, y) + I(x, y-1) <-- rotated(tilted) integral image at 45deg gray[j] = g; integral[j] = sum; squares[j] = sum2; tilted[j] = g; j++; i+=4; } // other rows k=0; y=1; j=w; i=(w<<2); sum=sum2=0; while (i<imLen) { // use fixed-point gray-scale transform, close to openCV transform // https://github.com/mtschirs/js-objectdetect/issues/3 // 0,29901123046875 0,58697509765625 0,114013671875 with roundoff g = ((4899 * im[i] + 9617 * im[i + 1] + 1868 * im[i + 2]) + 8192) >>> 14; g &= 255; sum += g; sum2 += /*(*/(g*g); //&0xFFFFFFFF) >>> 0; // SAT(-1, y) = SAT(x, -1) = SAT(-1, -1) = 0 // SAT(x, y) = SAT(x, y-1) + SAT(x-1, y) + I(x, y) - SAT(x-1, y-1) <-- integral image // RSAT(-1, y) = RSAT(x, -1) = RSAT(x, -2) = RSAT(-1, -1) = RSAT(-1, -2) = 0 // RSAT(x, y) = RSAT(x-1, y-1) + RSAT(x+1, y-1) - RSAT(x, y-2) + I(x, y) + I(x, y-1) <-- rotated(tilted) integral image at 45deg gray[j] = g; integral[j] = integral[j-w] + sum; squares[j] = squares[j-w] + sum2; tilted[j] = tilted[j+1-w] + (g + gray[j-w]) + ((y>1) ? tilted[j-w-w] : 0) + ((k>0) ? tilted[j-1-w] : 0); k++; j++; i+=4; if (k>=w) { k=0; y++; sum=sum2=0; } } return {gray:gray, integral:integral, squares:squares, tilted:tilted}; } // compute Canny edges on gray-scale image to speed up detection if possible function integralCanny(gray, w, h) { var i, j, k, sum, grad_x, grad_y, ind0, ind1, ind2, ind_1, ind_2, count=gray.length, lowpass = new Array8U(count), canny = new Array32F(count) ; // first, second rows, last, second-to-last rows for (i=0; i<w; i++) { lowpass[i]=0; lowpass[i+w]=0; lowpass[i+count-w]=0; lowpass[i+count-w-w]=0; canny[i]=0; canny[i+count-w]=0; } // first, second columns, last, second-to-last columns for (j=0, k=0; j<h; j++, k+=w) { lowpass[0+k]=0; lowpass[1+k]=0; lowpass[w-1+k]=0; lowpass[w-2+k]=0; canny[0+k]=0; canny[w-1+k]=0; } // gauss lowpass for (i=2; i<w-2; i++) { sum=0; for (j=2, k=(w<<1); j<h-2; j++, k+=w) { ind0 = i+k; ind1 = ind0+w; ind2 = ind1+w; ind_1 = ind0-w; ind_2 = ind_1-w; /* Original Code sum = 0; sum += 2 * grayImage[- 2 + ind_2]; sum += 4 * grayImage[- 2 + ind_1]; sum += 5 * grayImage[- 2 + ind0]; sum += 4 * grayImage[- 2 + ind1]; sum += 2 * grayImage[- 2 + ind2]; sum += 4 * grayImage[- 1 + ind_2]; sum += 9 * grayImage[- 1 + ind_1]; sum += 12 * grayImage[- 1 + ind0]; sum += 9 * grayImage[- 1 + ind1]; sum += 4 * grayImage[- 1 + ind2]; sum += 5 * grayImage[0 + ind_2]; sum += 12 * grayImage[0 + ind_1]; sum += 15 * grayImage[0 + ind0]; sum += 12 * grayImage[i + 0 + ind1]; sum += 5 * grayImage[0 + ind2]; sum += 4 * grayImage[1 + ind_2]; sum += 9 * grayImage[1 + ind_1]; sum += 12 * grayImage[1 + ind0]; sum += 9 * grayImage[1 + ind1]; sum += 4 * grayImage[1 + ind2]; sum += 2 * grayImage[2 + ind_2]; sum += 4 * grayImage[2 + ind_1]; sum += 5 * grayImage[2 + ind0]; sum += 4 * grayImage[2 + ind1]; sum += 2 * grayImage[2 + ind2]; */ // use as simple fixed-point arithmetic as possible (only addition/subtraction and binary shifts) // http://stackoverflow.com/questions/11703599/unsigned-32-bit-integers-in-javascript // http://stackoverflow.com/questions/6232939/is-there-a-way-to-correctly-multiply-two-32-bit-integers-in-javascript/6422061#6422061 // http://stackoverflow.com/questions/6798111/bitwise-operations-on-32-bit-unsigned-ints // https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Bitwise_Operators#%3E%3E%3E_%28Zero-fill_right_shift%29 sum = /*(*/(0 + (gray[ind_2-2] << 1) + (gray[ind_1-2] << 2) + (gray[ind0-2] << 2) + (gray[ind0-2]) + (gray[ind1-2] << 2) + (gray[ind2-2] << 1) + (gray[ind_2-1] << 2) + (gray[ind_1-1] << 3) + (gray[ind_1-1]) + (gray[ind0-1] << 4) - (gray[ind0-1] << 2) + (gray[ind1-1] << 3) + (gray[ind1-1]) + (gray[ind2-1] << 2) + (gray[ind_2] << 2) + (gray[ind_2]) + (gray[ind_1] << 4) - (gray[ind_1] << 2) + (gray[ind0] << 4) - (gray[ind0]) + (gray[ind1] << 4) - (gray[ind1] << 2) + (gray[ind2] << 2) + (gray[ind2]) + (gray[ind_2+1] << 2) + (gray[ind_1+1] << 3) + (gray[ind_1+1]) + (gray[ind0+1] << 4) - (gray[ind0+1] << 2) + (gray[ind1+1] << 3) + (gray[ind1+1]) + (gray[ind2+1] << 2) + (gray[ind_2+2] << 1) + (gray[ind_1+2] << 2) + (gray[ind0+2] << 2) + (gray[ind0+2]) + (gray[ind1+2] << 2) + (gray[ind2+2] << 1) );// &0xFFFFFFFF ) >>> 0; /* Original Code grad[ind0] = sum/159 = sum*0.0062893081761006; */ // sum of coefficients = 159, factor = 1/159 = 0,0062893081761006 // 2^14 = 16384, 16384/2 = 8192 // 2^14/159 = 103,0440251572322304 =~ 103 +/- 2^13 //grad[ind0] = (( ((sum << 6)&0xFFFFFFFF)>>>0 + ((sum << 5)&0xFFFFFFFF)>>>0 + ((sum << 3)&0xFFFFFFFF)>>>0 + ((8192-sum)&0xFFFFFFFF)>>>0 ) >>> 14) >>> 0; lowpass[ind0] = ((((103*sum + 8192)&0xFFFFFFFF) >>> 14)&0xFF) >>> 0; } } // sobel gradient for (i=1; i<w-1 ; i++) { //sum=0; for (j=1, k=w; j<h-1; j++, k+=w) { // compute coords using simple add/subtract arithmetic (faster) ind0=k+i; ind1=ind0+w; ind_1=ind0-w; grad_x = ((0 - lowpass[ind_1-1] + lowpass[ind_1+1] - lowpass[ind0-1] - lowpass[ind0-1] + lowpass[ind0+1] + lowpass[ind0+1] - lowpass[ind1-1] + lowpass[ind1+1] ))//&0xFFFFFFFF ; grad_y = ((0 + lowpass[ind_1-1] + lowpass[ind_1] + lowpass[ind_1] + lowpass[ind_1+1] - lowpass[ind1-1] - lowpass[ind1] - lowpass[ind1] - lowpass[ind1+1] ))//&0xFFFFFFFF ; //sum += (Abs(grad_x) + Abs(grad_y))&0xFFFFFFFF; canny[ind0] = ( Abs(grad_x) + Abs(grad_y) );//&0xFFFFFFFF; } } // integral canny // first row i=0; sum=0; while (i<w) { sum += canny[i]; canny[i] = sum;//&0xFFFFFFFF; i++; } // other rows i=w; k=0; sum=0; while (i<count) { sum += canny[i]; canny[i] = (canny[i-w] + sum);//&0xFFFFFFFF; i++; k++; if (k>=w) { k=0; sum=0; } } return canny; } // merge the detected features if needed function merge(rects, min_neighbors, ratio, selection) { var rlen=rects.length, ref = new Array(rlen), feats=[], nb_classes = 0, neighbors, r, found=false, i, j, n, t, ri; // original code // find number of neighbour classes for (i = 0; i < rlen; i++) ref[i] = 0; for (i = 0; i < rlen; i++) { found = false; for (j = 0; j < i; j++) { if (rects[j].almostEqual(rects[i])) { found = true; ref[i] = ref[j]; } } if (!found) { ref[i] = nb_classes; nb_classes++; } } // merge neighbor classes neighbors = new Array(nb_classes); r = new Array(nb_classes); for (i = 0; i < nb_classes; i++) { neighbors[i] = 0; r[i] = new Feature(); } for (i = 0; i < rlen; i++) { ri=ref[i]; neighbors[ri]++; r[ri].add(rects[i]); } for (i = 0; i < nb_classes; i++) { n = neighbors[i]; if (n >= min_neighbors) { t=1/(n + n); ri = new Feature( t*(r[i].x * 2 + n), t*(r[i].y * 2 + n), t*(r[i].width * 2 + n), t*(r[i].height * 2 + n) ); feats.push(ri); } } if (ratio != 1) { ratio=1.0/ratio; } // filter inside rectangles rlen=feats.length; for (i=0; i<rlen; i++) { for (j=i+1; j<rlen; j++) { if (!feats[i].isInside && feats[i].inside(feats[j])) { feats[i].isInside=true; } else if (!feats[j].isInside && feats[j].inside(feats[i])) { feats[j].isInside=true; } } } i=rlen; while (--i >= 0) { if (feats[i].isInside) { feats.splice(i, 1); } else { // scaled down, scale them back up if (ratio != 1) feats[i].scale(ratio); //feats[i].x+=selection.x; feats[i].y+=selection.y; feats[i].round().computeArea(); } } // sort according to size // (a deterministic way to present results under different cases) return feats.sort(byArea); } // area used as compare func for sorting function byArea(a, b) { return a.area-b.area; } // serial index used as compare func for sorting function byOrder(a, b) { return a.index-b.index; } /* splice subarray (not used) http://stackoverflow.com/questions/1348178/a-better-way-to-splice-an-array-into-an-array-in-javascript Array.prototype.splice.apply(d[0], [prev, 0].concat(d[1])); */ // used for parallel "reduce" computation function mergeSteps(d) { // concat and sort according to serial ordering if (d[1].length) d[0]=d[0].concat(d[1]).sort(byOrder); return d[0]; } // used for parallel, asynchronous and/or synchronous computation function detectSingleStep(self) { var Sqrt = Sqrt || Math.sqrt, ret = [], haar = self.haardata, haar_stages = haar.stages, scaledSelection = self.scaledSelection, w = scaledSelection.width, h = scaledSelection.height, imArea=w*h, imArea1=imArea-1, sizex = haar.size1, sizey = haar.size2, xstep, ystep, xsize, ysize, startx = scaledSelection.x, starty = scaledSelection.y, startty, x, y, ty, tyw, tys, sl = haar_stages.length, p0, p1, p2, p3, xl, yl, s, t, bx1, bx2, by1, by2, swh, inv_area, total_x, total_x2, vnorm, edges_density, pass, cL = self.cannyLow, cH = self.cannyHigh, stage, threshold, trees, tl, canny = self.canny, integral = self.integral, squares = self.squares, tilted = self.tilted, t, cur_node_ind, where, features, feature, rects, nb_rects, thresholdf, rect_sum, kr, r, x1, y1, x2, y2, x3, y3, x4, y4, rw, rh, yw, yh, sum, scale = self.scale, increment = self.increment, index = self.i||0, doCanny = self.doCannyPruning ; bx1=0; bx2=w-1; by1=0; by2=imArea-w; xsize = ~~(scale * sizex); xstep = ~~(xsize * increment); ysize = ~~(scale * sizey); ystep = ~~(ysize * increment); //ysize = xsize; ystep = xstep; tyw = ysize*w; tys = ystep*w; startty = starty*tys; xl = w-xsize; yl = h-ysize; swh = xsize*ysize; inv_area = 1.0/swh; for (y=starty, ty=startty; y<yl; y+=ystep, ty+=tys) { for (x=startx; x<xl; x+=xstep) { p0 = x-1 + ty-w; p1 = p0 + xsize; p2 = p0 + tyw; p3 = p2 + xsize; // clamp p0 = (p0<0) ? 0 : (p0>imArea1) ? imArea1 : p0; p1 = (p1<0) ? 0 : (p1>imArea1) ? imArea1 : p1; p2 = (p2<0) ? 0 : (p2>imArea1) ? imArea1 : p2; p3 = (p3<0) ? 0 : (p3>imArea1) ? imArea1 : p3; if (doCanny) { // avoid overflow edges_density = inv_area * (canny[p3] - canny[p2] - canny[p1] + canny[p0]); if (edges_density < cL || edges_density > cH) continue; } // pre-compute some values for speed // avoid overflow total_x = inv_area * (integral[p3] - integral[p2] - integral[p1] + integral[p0]); // avoid overflow total_x2 = inv_area * (squares[p3] - squares[p2] - squares[p1] + squares[p0]); vnorm = total_x2 - total_x * total_x; vnorm = (vnorm > 1) ? Sqrt(vnorm) : /*vnorm*/ 1 ; pass = true; for (s = 0; s < sl; s++) { // Viola-Jones HAAR-Stage evaluator stage = haar_stages[s]; threshold = stage.thres; trees = stage.trees; tl = trees.length; sum=0; for (t = 0; t < tl; t++) { // // inline the tree and leaf evaluators to avoid function calls per-loop (faster) // // Viola-Jones HAAR-Tree evaluator features = trees[t].feats; cur_node_ind = 0; while (true) { feature = features[cur_node_ind]; // Viola-Jones HAAR-Leaf evaluator rects = feature.rects; nb_rects = rects.length; thresholdf = feature.thres; rect_sum = 0; if (feature.tilt) { // tilted rectangle feature, Lienhart et al. extension for (kr = 0; kr < nb_rects; kr++) { r = rects[kr]; // this produces better/larger features, possible rounding effects?? x1 = x + ~~(scale * r[0]); y1 = (y-1 + ~~(scale * r[1])) * w; x2 = x + ~~(scale * (r[0] + r[2])); y2 = (y-1 + ~~(scale * (r[1] + r[2]))) * w; x3 = x + ~~(scale * (r[0] - r[3])); y3 = (y-1 + ~~(scale * (r[1] + r[3]))) * w; x4 = x + ~~(scale * (r[0] + r[2] - r[3])); y4 = (y-1 + ~~(scale * (r[1] + r[2] + r[3]))) * w; // clamp x1 = (x1<bx1) ? bx1 : (x1>bx2) ? bx2 : x1; x2 = (x2<bx1) ? bx1 : (x2>bx2) ? bx2 : x2; x3 = (x3<bx1) ? bx1 : (x3>bx2) ? bx2 : x3; x4 = (x4<bx1) ? bx1 : (x4>bx2) ? bx2 : x4; y1 = (y1<by1) ? by1 : (y1>by2) ? by2 : y1; y2 = (y2<by1) ? by1 : (y2>by2) ? by2 : y2; y3 = (y3<by1) ? by1 : (y3>by2) ? by2 : y3; y4 = (y4<by1) ? by1 : (y4>by2) ? by2 : y4; // RSAT(x-h+w, y+w+h-1) + RSAT(x, y-1) - RSAT(x-h, y+h-1) - RSAT(x+w, y+w-1) // x4 y4 x1 y1 x3 y3 x2 y2 rect_sum+= r[4] * (tilted[x4 + y4] - tilted[x3 + y3] - tilted[x2 + y2] + tilted[x1 + y1]); } } else { // orthogonal rectangle feature, Viola-Jones original for (kr = 0; kr < nb_rects; kr++) { r = rects[kr]; // this produces better/larger features, possible rounding effects?? x1 = x-1 + ~~(scale * r[0]); x2 = x-1 + ~~(scale * (r[0] + r[2])); y1 = (w) * (y-1 + ~~(scale * r[1])); y2 = (w) * (y-1 + ~~(scale * (r[1] + r[3]))); // clamp x1 = (x1<bx1) ? bx1 : (x1>bx2) ? bx2 : x1; x2 = (x2<bx1) ? bx1 : (x2>bx2) ? bx2 : x2; y1 = (y1<by1) ? by1 : (y1>by2) ? by2 : y1; y2 = (y2<by1) ? by1 : (y2>by2) ? by2 : y2; // SAT(x-1, y-1) + SAT(x+w-1, y+h-1) - SAT(x-1, y+h-1) - SAT(x+w-1, y-1) // x1 y1 x2 y2 x1 y1 x2 y1 rect_sum+= r[4] * (integral[x2 + y2] - integral[x1 + y2] - integral[x2 + y1] + integral[x1 + y1]); } } where = (rect_sum * inv_area < thresholdf * vnorm) ? 0 : 1; // END Viola-Jones HAAR-Leaf evaluator if (where) { if (feature.has_r) { sum += feature.r_val; break; } else { cur_node_ind = feature.r_node; } } else { if (feature.has_l) { sum += feature.l_val; break; } else { cur_node_ind = feature.l_node; } } } // END Viola-Jones HAAR-Tree evaluator } pass = (sum > threshold) ? true : false; // END Viola-Jones HAAR-Stage evaluator if (!pass) break; } if (pass) { ret.push({ index: index, x: x, y: y, width: xsize, height: ysize }); } } } // return any features found in this step return ret; } // called when detection ends, calls user-defined callback if any function detectEnd(self, rects) { for (var i=0, l=rects.length; i<l; i++) rects[i] = new Feature(rects[i]); self.objects = merge(rects, self.min_neighbors, self.Ratio, self.Selection); self.Ready = true; if (self.onComplete) self.onComplete.call(self); } /**[DOC_MARKDOWN] * * ####Detector Methods * [/DOC_MARKDOWN]**/ // // // // HAAR Detector Class (with the haar cascade data) /**[DOC_MARKDOWN] * __constructor(haardata, Parallel)__ * ```javascript * new detector(haardata, Parallel); * ``` * * __Explanation of parameters__ * * * _haardata_ : The actual haardata (as generated by haartojs tool), this is specific per feature, openCV haar data can be used. * * _Parallel_ : Optional, this is the _Parallel_ object, as returned by the _parallel.js_ script (included). It enables HAAR.js to run parallel computations both in browser and node (can be much faster) [/DOC_MARKDOWN]**/ Detector = HAAR.Detector = function(haardata, Parallel) { var self = this; self.haardata = haardata || null; self.Ready = false; self.doCannyPruning = false; self.Canvas = null; self.Selection = null; self.scaledSelection = null; self.objects = null; self.TimeInterval = null; self.DetectInterval = 30; self.Ratio = 0.5; self.cannyLow = 20; self.cannyHigh = 100; self.Parallel= Parallel || null; self.onComplete = null; }; Detector[proto] = { constructor: Detector, haardata: null, Canvas: null, objects: null, Selection: null, scaledSelection: null, Ratio: 0.5, origWidth: 0, origHeight: 0, width: 0, height: 0, DetectInterval: 30, TimeInterval: null, doCannyPruning: false, cannyLow: 20, cannyHigh: 100, canny: null, integral: null, squares: null, tilted: null, Parallel: null, Ready: false, onComplete: null, /**[DOC_MARKDOWN] * __dispose()__ * ```javascript * detector.dispose(); * ``` * * Disposes the detector and clears space of data cached [/DOC_MARKDOWN]**/ dispose: function() { var self = this; if ( self.DetectInterval ) clearTimeout( self.DetectInterval ); self.DetectInterval = null; self.TimeInterval = null; self.haardata = null; self.Canvas = null; self.objects = null; self.Selection = null; self.scaledSelection = null; self.Ratio = null; self.origWidth = null; self.origHeight = null; self.width = null; self.height = null; self.doCannyPruning = null; self.cannyLow = null; self.cannyHigh = null; self.canny = null; self.integral = null; self.squares = null; self.tilted = null; self.Parallel = null; self.Ready = null; self.onComplete = null; return self; }, // clear the image and detector data // reload the image to re-compute the needed image data (.image method) // and re-set the detector haar data (.cascade method) /**[DOC_MARKDOWN] * __clearCache()__ * ```javascript * detector.clearCache(); * ``` * * Clear any cached image data and haardata in case space is an issue. Use image method and cascade method (see below) to re-set image and haar data [/DOC_MARKDOWN]**/ clearCache: function() { var self = this; self.haardata = null; self.canny = null; self.integral = null; self.squares = null; self.tilted = null; self.Selection = null; self.scaledSelection = null; return self; }, // set haardata, use same detector with cached data, to detect different feature /**[DOC_MARKDOWN] * __cascade(haardata)__ * ```javascript * detector.cascade(haardata); * ``` * * Allow to use same detector (with its cached image data), to detect different feature on same image, by using another cascade. This way any image pre-processing is done only once * * __Explanation of parameters__ * * * _haardata_ : The actual haardata (as generated by haartojs tool), this is specific per feature, openCV haar data can be used. [/DOC_MARKDOWN]**/ cascade: function(haardata) { this.haardata = haardata || null; return this; }, // set haardata, use same detector with cached data, to detect different feature /**[DOC_MARKDOWN] * __parallel(Parallel)__ * ```javascript * detector.paralell(Parallel | false); * ``` * * Enable/disable parallel processing (passing the Parallel Object or null/false) * * __Explanation of parameters__ * * * _Parallel_ : The actual Parallel object used in parallel.js (included) [/DOC_MARKDOWN]**/ parallel: function(Parallel) { this.Parallel = Parallel || null; return this; }, // set image for detector along with scaling (and an optional canvas, eg for node) /**[DOC_MARKDOWN] * __image(ImageOrVideoOrCanvas, scale, CanvasClass)__ * ```javascript * detector.image(ImageOrVideoOrCanvas, scale, CanvasClass); * ``` * * __Explanation of parameters__ * * * _ImageOrVideoOrCanvas_ : an actual Image or Video element or Canvas Object (in this case they are equivalent). * * _scale_ : The percent of scaling from the original image, so detection proceeds faster on a smaller image (default __0.5__ ). __NOTE__ scaling might alter the detection results sometimes, if having problems opt towards 1 (slower) * * _CanvasClass_ : This is optional and used only when running in node (passing the node-canvas object). [/DOC_MARKDOWN]**/ image: function(image, scale) { var self = this; if (image) { let integralImg, w, h, sw, sh, r; r = self.Ratio = (undef === scale) ? 0.5 : scale; self.Ready = false; w = self.origWidth = image.width; h = self.origHeight = image.height; sw = self.width = Round(r * w); sh = self.height = Round(r * h); integralImg = integralImage(image.data, image.width, image.height/*, self.scaledSelection*/); self.integral = integralImg.integral; self.squares = integralImg.squares; self.tilted = integralImg.tilted; self.canny = integralCanny(integralImg.gray, sw, sh/*, self.scaledSelection.width, self.scaledSelection.height*/); integralImg.gray = null; integralImg.integral = null; integralImg.squares = null; integralImg.tilted = null; integralImg = null; } return self; }, // detector set detection interval /**[DOC_MARKDOWN] * __interval(detectionInterval)__ * ```javascript * detector.interval(detectionInterval); * ``` * * __Explanation of parameters__ * * * _detectionInterval_ : interval to run the detection asynchronously (if not parallel) in microseconds (default __30__). [/DOC_MARKDOWN]**/ interval: function(it) { if (it>0) this.DetectInterval = it; return this; }, // customize canny prunning thresholds for best results /**[DOC_MARKDOWN] * __cannyThreshold({low: lowThreshold, high: highThreshold})__ * ```javascript * detector.cannyThreshold({low: lowThreshold, high: highThreshold}); * ``` * * Set the thresholds when Canny Pruning is used, for extra fine-tuning. * Canny Pruning detects the number/density of edges in a given region. A region with too few or too many edges is unlikely to be a feature. * Default values work fine in most cases, however depending on image size and the specific feature, some fine tuning could be needed * * __Explanation of parameters__ * * * _low_ : (Optional) The low threshold (default __20__ ). * * _high_ : (Optional) The high threshold (default __100__ ). [/DOC_MARKDOWN]**/ cannyThreshold: function(thres) { (thres && undef!==thres.low) && (this.cannyLow = thres.low); (thres && undef!==thres.high) && (this.cannyHigh = thres.high); return this; }, // set custom detection region as selection /**[DOC_MARKDOWN] * __select|selection('auto'|object|feature|x [,y, width, height])__ * ```javascript * detector.selection('auto'|object|feature|x [,y, width, height]); * ``` * * Allow to set a custom region in the image to confine the detection process only in that region (eg detect nose while face already detected) * * __Explanation of parameters__ * * * _1st parameter_ : This can be the string 'auto' which sets the whole image as the selection, or an object ie: {x:10, y:'auto', width:100, height:'auto'} (every param set as 'auto' will take the default image value) or a detection rectangle/feature, or a x coordinate (along with rest coordinates). * * _y_ : (Optional) the selection start y coordinate, can be an actual value or 'auto' (y=0) * * _width_ : (Optional) the selection width, can be an actual value or 'auto' (width=image.width) * * _height_ : (Optional) the selection height, can be an actual value or 'auto' (height=image.height) * * The actual selection rectangle/feature is available as this.Selection or detector.Selection [/DOC_MARKDOWN]**/ select: function(/* ..variable args here.. */) { var args = slice.call(arguments), argslen=args.length; if (1==argslen && 'auto'==args[0] || !argslen) this.Selection = null; else this.Selection = Feature[proto].data.apply(new Feature(), args); return this; }, // detector on complete callback /**[DOC_MARKDOWN] * __complete(callback)__ * ```javascript * detector.complete(callback); * ``` * * Set the callback handler when detection completes (for parallel and asynchronous detection) * * __Explanation of parameters__ * * * _callback_ : The user-defined callback function (will be called within the detectors scope, the value of 'this' will be the detector instance). [/DOC_MARKDOWN]**/ complete: function(callback) { this.onComplete = callback || null; return this; }, // Detector detect method to start detection /**[DOC_MARKDOWN] * __detect(baseScale, scale_inc, increment, min_neighbors, doCannyPruning)__ * ```javascript * detector.detect(baseScale, scale_inc, increment, min_neighbors, doCannyPruning); * ``` * * __Explanation of parameters__ ([JViolaJones Parameters](http://code.google.com/p/jviolajones/wiki/Parameters)) * * * *baseScale* : The initial ratio between the window size and the Haar classifier size (default __1__ ). * * *scale_inc* : The scale increment of the window size, at each step (default __1.25__ ). * * *increment* : The shift of the window at each sub-step, in terms of percentage of the window size (default __0.5__ ). * * *min_neighbors* : The minimum numbers of similar rectangles needed for the region to be considered as a feature (avoid noise) (default __1__ ) * * *doCannyPruning* : enable Canny Pruning to pre-detect regions unlikely to contain features, in order to speed up the execution (optional default __true__ ). [/DOC_MARKDOWN]**/ detect: function(baseScale, scale_inc, increment, min_neighbors, doCannyPruning) { var self = this; var haardata = self.haardata, sizex = haardata.size1, sizey = haardata.size2, selection, scaledSelection, width = self.width, height = self.height, origWidth = self.origWidth, origHeight = self.origHeight, maxScale, scale, integral = self.integral, squares = self.squares, tilted = self.tilted, canny = self.canny, cannyLow = self.cannyLow, cannyHigh = self.cannyHigh ; if (!self.Selection) self.Selection = new Feature(0, 0, origWidth, origHeight); selection = self.Selection; selection.x = ('auto'==selection.x) ? 0 : selection.x; selection.y = ('auto'==selection.y) ? 0 : selection.y; selection.width = ('auto'==selection.width) ? origWidth : selection.width; selection.height = ('auto'==selection.height) ? origHeight : selection.height; scaledSelection = self.scaledSelection = selection.clone().scale(self.Ratio).round(); baseScale = (undef === baseScale) ? 1.0 : baseScale; scale_inc = (undef === scale_inc) ? 1.25 : scale_inc; increment = (undef === increment) ? 0.5 : increment; min_neighbors = (undef === min_neighbors) ? 1 : min_neighbors; doCannyPruning = self.doCannyPruning = (undef === doCannyPruning) ? true : doCannyPruning; maxScale = self.maxScale = Min(width/sizex, height/sizey); scale = self.scale = baseScale; self.min_neighbors = min_neighbors; self.scale_inc = scale_inc; self.increment = increment; self.Ready = false; // needs parallel.js library (included) var parallel = self.Parallel; if (parallel && parallel.isSupported()) { var data=[], sc, i=0; for (sc=baseScale; sc<=maxScale; sc*=scale_inc) { data.push({ haardata : haardata, width : width, height : height, scaledSelection : {x:scaledSelection.x, y:scaledSelection.y, width:scaledSelection.width, height:scaledSelection.height}, integral : integral, squares : squares, tilted : tilted, doCannyPruning : doCannyPruning, canny : (doCannyPruning) ? canny : null, cannyLow : cannyLow, cannyHigh : cannyHigh, maxScale : maxScale, min_neighbors : min_neighbors, scale_inc : scale_inc, increment : increment, scale : sc, // current scale to check i : i++ // serial ordering }); } // needs parallel.js library (included) // parallelize the detection, using map-reduce // should also work in Nodejs (using child processes) new parallel(data, {synchronous: false}) .require( byOrder, detectSingleStep, mergeSteps ) .map( detectSingleStep ).reduce( mergeSteps ) .then( function(rects){ detectEnd(self, rects); } ) ; } else { // else detect asynchronously using fixed intervals var rects = [], detectAsync = function() { if (self.scale <= self.maxScale) { rects = rects.concat( detectSingleStep(self) ); // increase scale self.scale *= self.scale_inc; self.TimeInterval = setTimeout(detectAsync, self.DetectInterval); } else { clearTimeout( self.TimeInterval ); detectEnd(self, rects); } } ; self.TimeInterval = setTimeout(detectAsync, self.DetectInterval); } return self; }, /**[DOC_MARKDOWN] * __detectSync(baseScale, scale_inc, increment, min_neighbors, doCannyPruning)__ * ```javascript * var features = detector.detectSync(baseScale, scale_inc, increment, min_neighbors, doCannyPruning); * ``` * * Run detector synchronously in one step, instead of parallel or asynchronously. Can be useful when immediate results are needed. Due to massive amount of processing the UI thread may be blocked. * * __Explanation of parameters__ (similar to *detect* method) * [/DOC_MARKDOWN]**/ detectSync: function(baseScale, scale_inc, increment, min_neighbors, doCannyPruning) { var self = this, scale, maxScale, sizex = self.haardata.size1, sizey = self.haardata.size2; if (!self.Selection) self.Selection = new Feature(0, 0, self.origWidth, self.origHeight); self.Selection.x = ('auto'==self.Selection.x) ? 0 : self.Selection.x; self.Selection.y = ('auto'==self.Selection.y) ? 0 : self.Selection.y; self.Selection.width = ('auto'==self.Selection.width) ? self.origWidth : self.Selection.width; self.Selection.height = ('auto'==self.Selection.height) ? self.origHeight : self.Selection.height; self.scaledSelection = self.Selection.clone().scale(self.Ratio).round(); baseScale = (typeof baseScale == 'undefined') ? 1.0 : baseScale; scale_inc = (typeof scale_inc == 'undefined') ? 1.25 : scale_inc; increment = (typeof increment == 'undefined') ? 0.5 : increment; min_neighbors = (typeof min_neighbors == 'undefined') ? 1 : min_neighbors; self.doCannyPruning = (typeof doCannyPruning == 'undefined') ? true : doCannyPruning; maxScale = self.maxScale = Min(self.width/sizex, self.height/sizey); scale = self.scale = baseScale; self.min_neighbors = min_neighbors; self.scale_inc = scale_inc; self.increment = increment; self.Ready = false; // detect synchronously var rects = []; // detection loop while (scale <= maxScale) { rects = rects.concat( detectSingleStep(self) ); // increase scale self.scale = scale *= scale_inc; } // merge any features found for (var i=0, l=rects.length; i<l; i++) rects[i] = new Feature(rects[i]); self.objects = merge(rects, self.min_neighbors, self.Ratio, self.Selection); self.Ready = true; // return results return self.objects; } }; // aliases Detector[proto].selection = Detector[proto].select; // // // // Feature/Rectangle Class (arguably better than generic Object) Feature = HAAR.Feature = function(x, y, w, h, i) { this.data(x, y, w, h, i); }; Feature[proto] = { constructor: Feature, index: 0, x: 0, y: 0, width: 0, height: 0, area: 0, isInside: false, data: function(x, y, w, h, i) { var self = this; if (x && (x instanceof Feature)) { self.copy(x); } else if (x && (x instanceof Object)) { self.x = x.x || 0; self.y = x.y || 0; self.width = x.width || 0; self.height = x.height || 0; self.index = x.index || 0; self.area = x.area || 0; self.isInside = x.isInside || false; } else { self.x = x || 0; self.y = y || 0; self.width = w || 0; self.height = h || 0; self.index = i || 0; self.area = 0; self.isInside = false; } return self; }, add: function (f) { var self = this; self.x += f.x; self.y += f.y; self.width += f.width; self.height += f.height; return self; }, scale: function(s) { var self = this; self.x *= s; self.y *= s; self.width *= s; self.height *= s; return self; }, round: function() { var self = this; self.x = ~~(self.x+0.5); self.y = ~~(self.y+0.5); self.width = ~~(self.width+0.5); self.height = ~~(self.height+0.5); return self; }, computeArea: function() { var self = this; self.area = self.width*self.height; return self.area; }, inside: function(f) { var self = this; return !!( (self.x >= f.x) && (self.y >= f.y) && (self.x+self.width <= f.x+f.width) && (self.y+self.height <= f.y+f.height) ); }, contains: function(f) { return f.inside(this); }, equal: function(f) { var self = this; return !!( (f.x === self.x) && (f.y === self.y) && (f.width === self.width) && (f.height === self.height) ); }, almostEqual: function(f) { var self = this, d1=Max(f.width, self.width)*0.2, d2=Max(f.height, self.height)*0.2; //var d1=Max(f.width, this.width)*0.5, d2=Max(f.height, this.height)*0.5; //var d2=d1=Max(f.width, this.width, f.height, this.height)*0.4; return !!( Abs(self.x-f.x) <= d1 && Abs(self.y-f.y) <= d2 && Abs(self.width-f.width) <= d1 && Abs(self.height-f.height) <= d2 ); }, clone: function() { var self = this, f = new Feature(); f.x = self.x; f.y = self.y; f.width = self.width; f.height = self.height; f.index = self.index; f.area = self.area; f.isInside = self.isInside; return f; }, copy: function(f) { var self = this; if ( f && (f instanceof Feature) ) { self.x = f.x; self.y = f.y; self.width = f.width; self.height = f.height; self.index = f.index; self.area = f.area; self.isInside = f.isInside; } return self; }, toString: function() { return ['[ x:', this.x, 'y:', this.y, 'width:', this.width, 'height:', this.height, ']'].join(' '); } };
(function() { 'use strict'; angular .module('blocks.authInterceptor') .factory('authInterceptor', authInterceptor); /* @ngInject */ function authInterceptor(authToken) { return { request: function(config) { var token = authToken.getToken(); if (token) { config.headers.Authorization = 'Bearer ' + token; } return config; }, response: function(response) { return response; } }; } })();
const en = { common: { or: 'or', cancel: 'Cancel', reset: 'Reset', save: 'Save', search: 'Search', edit: 'Edit', remove: 'Remove', new: 'New', export: 'Export to Excel', noDataToExport: 'No data to export', import: 'Import', discard: 'Discard', yes: 'Yes', no: 'No', pause: 'Pause', areYouSure: 'Are you sure?', view: 'View', destroy: 'Delete', mustSelectARow: 'Must select a row', }, app: { title: '', }, entities: { pet: { name: 'pet', label: '', menu: '', exporterFileName: 'pet_export', list: { menu: '', title: '', }, create: { success: 'pet saved successfully', }, update: { success: 'pet saved successfully', }, destroy: { success: 'pet deleted successfully', }, destroyAll: { success: 'pet(s) deleted successfully', }, edit: { title: 'Edit pet', }, fields: { id: '', 'owner': '', 'name': '', 'type': '', 'breed': '', 'size': '', 'bookings': '', createdAt: 'Created at', updatedAt: 'Updated at', createdAtRange: 'Created at', }, enumerators: { 'type': { 'cat': '', 'dog': '', }, 'size': { 'small': '', 'medium': '', 'large': '', }, }, new: { title: 'New pet', }, view: { title: 'View pet', }, importer: { title: 'Import pets', fileName: 'pet_import_template', hint: 'Files/Images columns must be the URLs of the files separated by space.', }, }, booking: { name: 'booking', label: '', menu: '', exporterFileName: 'booking_export', list: { menu: '', title: '', }, create: { success: 'booking saved successfully', }, update: { success: 'booking saved successfully', }, destroy: { success: 'booking deleted successfully', }, destroyAll: { success: 'booking(s) deleted successfully', }, edit: { title: 'Edit booking', }, fields: { id: '', 'owner': '', 'pet': '', 'arrivalRange': '', 'arrival': '', 'departureRange': '', 'departure': '', 'clientNotes': '', 'employeeNotes': '', 'photos': '', 'status': '', 'cancellationNotes': '', 'feeRange': '', 'fee': '', 'receipt': '', createdAt: 'Created at', updatedAt: 'Updated at', createdAtRange: 'Created at', }, enumerators: { 'status': { 'booked': '', 'progress': '', 'cancelled': '', 'completed': '', }, }, new: { title: 'New booking', }, view: { title: 'View booking', }, importer: { title: 'Import bookings', fileName: 'booking_import_template', hint: 'Files/Images columns must be the URLs of the files separated by space.', }, }, }, auth: { profile: { title: 'Edit Profile', success: 'Profile updated successfully', }, createAnAccount: 'Create an account', rememberMe: 'Remember me', forgotPassword: 'Forgot password', signin: 'Sign in', signup: 'Sign up', signout: 'Sign out', alreadyHaveAnAccount: 'Already have an account? Sign in.', signinWithAnotherAccount: 'Sign in with another account', emailUnverified: { message: `Please confirm your email at <strong>{0}</strong> to confinue.`, submit: `Resend email verification`, }, emptyPermissions: { message: `You have no permissions yet. Wait for the admin to grant you privileges.`, }, passwordReset: { message: 'Send password reset email', error: `Email not recognized`, }, emailAddressVerificationEmail: { error: `Email not recognized`, }, verificationEmailSuccess: `Verification email sent successfully`, passwordResetSuccess: `Password reset email sent successfully`, }, roles: { owner: { label: 'Owner', description: 'Full access to all resources', }, editor: { label: 'Editor', description: 'Edit access to all resources', }, viewer: { label: 'Viewer', description: 'View access to all resources', }, auditLogViewer: { label: 'Audit Log Viewer', description: 'Access to view audit logs', }, iamSecurityReviewer: { label: 'Security Reviewer', description: `Full access to manage users roles`, }, entityEditor: { label: 'Entity Editor', description: 'Edit access to all entities', }, entityViewer: { label: 'Entity Viewer', description: 'View access to all entities', }, petEditor: { label: 'pet Editor', description: 'Edit access to pet', }, petViewer: { label: 'pet Viewer', description: 'View access to pet', }, bookingEditor: { label: 'booking Editor', description: 'Edit access to booking', }, bookingViewer: { label: 'booking Viewer', description: 'View access to booking', }, }, iam: { title: 'Identity and Access Management', menu: 'IAM', disable: 'Disable', disabled: 'Disabled', enabled: 'Enabled', enable: 'Enable', doEnableSuccess: 'User enabled successfully', doDisableSuccess: 'User disabled successfully', doDisableAllSuccess: 'User(s) disabled successfully', doEnableAllSuccess: 'User(s) enabled successfully', doAddSuccess: 'User(s) saved successfully', doUpdateSuccess: 'User saved successfully', viewBy: 'View By', users: { name: 'users', label: 'Users', exporterFileName: 'users_export', doRemoveAllSelectedSuccess: 'Permissions removed successfully', }, roles: { label: 'Roles', doRemoveAllSelectedSuccess: 'Permissions removed successfully', }, edit: { title: 'Edit User', }, new: { title: 'New User(s)', emailsHint: 'Separate multiple email addresses using the comma character.', }, view: { title: 'View User', activity: 'Activity', }, importer: { title: 'Import Users', fileName: 'users_import_template', hint: 'Files/Images columns must be the URLs of the files separated by space. Relationships must be the ID of the referenced records separated by space. Roles must be the role ids separated by space.', }, errors: { userAlreadyExists: 'User with this email already exists', userNotFound: 'User not found', disablingHimself: `You can't disable yourself`, revokingOwnPermission: `You can't revoke your own owner permission`, }, }, user: { fields: { id: 'Id', authenticationUid: 'Authentication Uid', avatars: 'Avatar', email: 'Email', emails: 'Email(s)', fullName: 'Name', firstName: 'First Name', lastName: 'Last Name', status: 'Status', disabled: 'Disabled', phoneNumber: 'Phone Number', role: 'Role', createdAt: 'Created at', updatedAt: 'Updated at', roleUser: 'Role/User', roles: 'Roles', createdAtRange: 'Created at', password: 'Password', rememberMe: 'Remember me', }, enabled: 'Enabled', disabled: 'Disabled', validations: { // eslint-disable-next-line email: 'Email ${value} is invalid', }, }, auditLog: { menu: 'Audit Logs', title: 'Audit Logs', exporterFileName: 'audit_log_export', entityNamesHint: 'Separate multiple entities using the comma character.', fields: { id: 'Id', timestampRange: 'Period', entityName: 'Entity', entityNames: 'Entities', entityId: 'Entity ID', action: 'Action', values: 'Values', timestamp: 'Date', createdByEmail: 'User Email', }, }, settings: { title: 'Settings', menu: 'Settings', save: { success: 'Settings saved successfully. The page will reload in {0} seconds for changes to take effect.', }, fields: { theme: 'Theme', }, colors: { default: 'Default', cyan: 'Cyan', 'geek-blue': 'Geek Blue', gold: 'Gold', lime: 'Lime', magenta: 'Magenta', orange: 'Orange', 'polar-green': 'Polar Green', purple: 'Purple', red: 'Red', volcano: 'Volcano', yellow: 'Yellow', }, }, home: { menu: 'Home', message: `This page uses fake data for demonstration purposes only. You can edit it at frontend/view/home/HomePage.js.`, charts: { day: 'Day', red: 'Red', green: 'Green', yellow: 'Yellow', grey: 'Grey', blue: 'Blue', sales: 'Sales', visitor: 'Visitors', months: { 1: 'January', 2: 'February', 3: 'March', 4: 'April', 5: 'May', 6: 'June', 7: 'July', }, eating: 'Eating', drinking: 'Drinking', sleeping: 'Sleeping', designing: 'Designing', coding: 'Coding', cycling: 'Cycling', running: 'Running', customer: 'Customer', }, }, errors: { backToHome: 'Back to home', 403: `Sorry, you don't have access to this page`, 404: 'Sorry, the page you visited does not exist', 500: 'Sorry, the server is reporting an error', forbidden: { message: 'Forbidden', }, validation: { message: 'An error occurred', }, defaultErrorMessage: 'Ops, an error occurred', }, // See https://github.com/jquense/yup#using-a-custom-locale-dictionary /* eslint-disable */ validation: { mixed: { default: '${path} is invalid', required: '${path} is required', oneOf: '${path} must be one of the following values: ${values}', notOneOf: '${path} must not be one of the following values: ${values}', notType: ({ path, type, value, originalValue }) => { return `${path} must be a ${type}`; }, }, string: { length: '${path} must be exactly ${length} characters', min: '${path} must be at least ${min} characters', max: '${path} must be at most ${max} characters', matches: '${path} must match the following: "${regex}"', email: '${path} must be a valid email', url: '${path} must be a valid URL', trim: '${path} must be a trimmed string', lowercase: '${path} must be a lowercase string', uppercase: '${path} must be a upper case string', selected: '${path} must be selected', }, number: { min: '${path} must be greater than or equal to ${min}', max: '${path} must be less than or equal to ${max}', lessThan: '${path} must be less than ${less}', moreThan: '${path} must be greater than ${more}', notEqual: '${path} must be not equal to ${notEqual}', positive: '${path} must be a positive number', negative: '${path} must be a negative number', integer: '${path} must be an integer', }, date: { min: '${path} field must be later than ${min}', max: '${path} field must be at earlier than ${max}', }, boolean: {}, object: { noUnknown: '${path} field cannot have keys not specified in the object shape', }, array: { min: '${path} field must have at least ${min} items', max: '${path} field must have less than or equal to ${max} items', }, }, /* eslint-disable */ fileUploader: { upload: 'Upload', image: 'You must upload an image', size: 'File is too big. Max allowed size is {0}', formats: `Invalid format. Must be '{0}'.`, }, importer: { line: 'Line', status: 'Status', pending: 'Pending', imported: 'Imported', error: 'Error', total: `{0} imported, {1} pending and {2} with error`, importedMessage: `Processed {0} of {1}.`, noNavigateAwayMessage: 'Do not navigate away from this page or import will be stopped.', completed: { success: 'Import completed. All rows were successfully imported.', someErrors: 'Processing completed, but some rows were unable to be imported.', allErrors: 'Import failed. There are no valid rows.', }, form: { downloadTemplate: 'Download the template', hint: 'Click or drag the file to this area to continue', }, list: { discardConfirm: 'Are you sure? Non-imported data will be lost.', }, errors: { invalidFileEmpty: 'The file is empty', invalidFileExcel: 'Only excel (.xlsx) files are allowed', invalidFileUpload: 'Invalid file. Make sure you are using the last version of the template.', importHashRequired: 'Import hash is required', importHashExistent: 'Data has already been imported', }, }, autocomplete: { loading: 'Loading...', }, imagesViewer: { noImage: 'No image', }, firebaseErrors: { 'auth/user-disabled': 'Your account is disabled', 'auth/user-not-found': `Sorry, we don't recognize your credentials`, 'auth/wrong-password': `Sorry, we don't recognize your credentials`, 'auth/weak-password': 'This password is too weak', 'auth/email-already-in-use': 'Email is already in use', 'auth/invalid-email': 'Please provide a valid email', 'auth/account-exists-with-different-credential': 'Email is already in use for a different authentication method.', 'auth/credential-already-in-use': 'Credentials are already in use', }, }; export default en;
const solid_microphone_slash = `<svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 640 512"><path d="M633.82 458.1l-157.8-121.96C488.61 312.13 496 285.01 496 256v-48c0-8.84-7.16-16-16-16h-16c-8.84 0-16 7.16-16 16v48c0 17.92-3.96 34.8-10.72 50.2l-26.55-20.52c3.1-9.4 5.28-19.22 5.28-29.67V96c0-53.02-42.98-96-96-96s-96 42.98-96 96v45.36L45.47 3.37C38.49-2.05 28.43-.8 23.01 6.18L3.37 31.45C-2.05 38.42-.8 48.47 6.18 53.9l588.36 454.73c6.98 5.43 17.03 4.17 22.46-2.81l19.64-25.27c5.41-6.97 4.16-17.02-2.82-22.45zM400 464h-56v-33.77c11.66-1.6 22.85-4.54 33.67-8.31l-50.11-38.73c-6.71.4-13.41.87-20.35.2-55.85-5.45-98.74-48.63-111.18-101.85L144 241.31v6.85c0 89.64 63.97 169.55 152 181.69V464h-56c-8.84 0-16 7.16-16 16v16c0 8.84 7.16 16 16 16h160c8.84 0 16-7.16 16-16v-16c0-8.84-7.16-16-16-16z"/></svg>`; export default solid_microphone_slash;
#! /usr/bin/env python import os, sys, optparse, math copyargs = sys.argv[:] for i in range(len(copyargs)): if copyargs[i] == "": copyargs[i] = "\"\"" if copyargs[i].find(" ") != -1: copyargs[i] = "\"%s\"" % copyargs[i] commandline = " ".join(copyargs) prog = sys.argv[0] usage = """./%(prog)s DIRNAME ITERATIONS INITIALGEOM INPUTFILES [options] Creates (overwrites) a directory for each of the iterations and creates (overwrites) submitJobs.sh with the submission sequence and dependencies. DIRNAME directories will be named DIRNAME01, DIRNAME02, etc. ITERATIONS number of iterations INITIALGEOM SQLite file containing muon geometry with tag names DTAlignmentRcd, DTAlignmentErrorExtendedRcd, CSCAlignmentRcd, CSCAlignmentErrorExtendedRcd INPUTFILES Python file defining 'fileNames', a list of input files as strings (create with findQualityFiles.py)""" % vars() parser = optparse.OptionParser(usage) parser.add_option("-j", "--jobs", help="approximate number of \"gather\" subjobs", type="int", default=50, dest="subjobs") parser.add_option("-s", "--submitJobs", help="alternate name of submitJobs.sh script (please include .sh extension); a file with this name will be OVERWRITTEN", type="string", default="submitJobs.sh", dest="submitJobs") parser.add_option("-b", "--big", help="if invoked, subjobs will also be run on cmscaf1nd", action="store_true", dest="big") parser.add_option("-u", "--user_mail", help="if invoked, send mail to a specified email destination. If \"-u\" is not present, the default destination LSB_MAILTO in lsf.conf will be used", type="string", dest="user_mail") parser.add_option("--mapplots", help="if invoked, draw \"map plots\"", action="store_true", dest="mapplots") parser.add_option("--segdiffplots", help="if invoked, draw \"segment-difference plots\"", action="store_true", dest="segdiffplots") parser.add_option("--curvatureplots", help="if invoked, draw \"curvature plots\"", action="store_true", dest="curvatureplots") parser.add_option("--globalTag", help="GlobalTag for alignment/calibration conditions (typically all conditions except muon and tracker alignment)", type="string", default="CRAFT0831X_V1::All", dest="globaltag") parser.add_option("--trackerconnect", help="connect string for tracker alignment (frontier://FrontierProd/CMS_COND_310X_ALIGN or sqlite_file:...)", type="string", default="", dest="trackerconnect") parser.add_option("--trackeralignment", help="name of TrackerAlignmentRcd tag", type="string", default="Alignments", dest="trackeralignment") parser.add_option("--trackerAPEconnect", help="connect string for tracker APEs (frontier://... or sqlite_file:...)", type="string", default="", dest="trackerAPEconnect") parser.add_option("--trackerAPE", help="name of TrackerAlignmentErrorExtendedRcd tag (tracker APEs)", type="string", default="AlignmentErrorsExtended", dest="trackerAPE") parser.add_option("--trackerBowsconnect", help="connect string for tracker Surface Deformations (frontier://... or sqlite_file:...)", type="string", default="", dest="trackerBowsconnect") parser.add_option("--trackerBows", help="name of TrackerSurfaceDeformationRcd tag", type="string", default="TrackerSurfaceDeformations", dest="trackerBows") parser.add_option("--gprcdconnect", help="connect string for GlobalPositionRcd (frontier://... or sqlite_file:...)", type="string", default="", dest="gprcdconnect") parser.add_option("--gprcd", help="name of GlobalPositionRcd tag", type="string", default="GlobalPosition", dest="gprcd") parser.add_option("--iscosmics", help="if invoked, use cosmic track refitter instead of the standard one", action="store_true", dest="iscosmics") parser.add_option("--station123params", help="alignable parameters for DT stations 1, 2, 3 (see SWGuideAlignmentAlgorithms#Selection_of_what_to_align)", type="string", default="111111", dest="station123params") parser.add_option("--station4params", help="alignable parameters for DT station 4", type="string", default="100011", dest="station4params") parser.add_option("--cscparams", help="alignable parameters for CSC chambers", type="string", default="100011", dest="cscparams") parser.add_option("--minTrackPt", help="minimum allowed track transverse momentum (in GeV)", type="string", default="0", dest="minTrackPt") parser.add_option("--maxTrackPt", help="maximum allowed track transverse momentum (in GeV)", type="string", default="1000", dest="maxTrackPt") parser.add_option("--minTrackP", help="minimum allowed track momentum (in GeV)", type="string", default="0", dest="minTrackP") parser.add_option("--maxTrackP", help="maximum allowed track momentum (in GeV)", type="string", default="10000", dest="maxTrackP") parser.add_option("--minTrackerHits", help="minimum number of tracker hits", type="int", default=15, dest="minTrackerHits") parser.add_option("--maxTrackerRedChi2", help="maximum tracker chi^2 per degrees of freedom", type="string", default="10", dest="maxTrackerRedChi2") parser.add_option("--notAllowTIDTEC", help="if invoked, do not allow tracks that pass through the tracker's TID||TEC region (not recommended)", action="store_true", dest="notAllowTIDTEC") parser.add_option("--twoBin", help="if invoked, apply the \"two-bin method\" to control charge-antisymmetric errors", action="store_true", dest="twoBin") parser.add_option("--weightAlignment", help="if invoked, segments will be weighted by ndf/chi^2 in the alignment", action="store_true", dest="weightAlignment") parser.add_option("--minAlignmentSegments", help="minimum number of segments required to align a chamber", type="int", default=5, dest="minAlignmentHits") parser.add_option("--notCombineME11", help="if invoced, treat ME1/1a and ME1/1b as separate objects", action="store_true", dest="notCombineME11") parser.add_option("--maxEvents", help="maximum number of events", type="string", default="-1", dest="maxEvents") parser.add_option("--skipEvents", help="number of events to be skipped", type="string", default="0", dest="skipEvents") parser.add_option("--validationLabel", help="if given nonempty string RUNLABEL, diagnostics and creation of plots will be run in the end of the last iteration; the RUNLABEL will be used to mark a run; the results will be put into a RUNLABEL_DATESTAMP.tgz tarball", type="string", default="", dest="validationLabel") parser.add_option("--maxResSlopeY", help="maximum residual slope y component", type="string", default="10", dest="maxResSlopeY") parser.add_option("--motionPolicyNSigma", help="minimum nsigma(deltax) position displacement in order to move a chamber for the final alignment result; default NSIGMA=3", type="int", default=3, dest="motionPolicyNSigma") parser.add_option("--noCleanUp", help="if invoked, temporary plotting???.root and *.tmp files would not be removed at the end of each align job", action="store_true", dest="noCleanUp") parser.add_option("--noCSC", help="if invoked, CSC endcap chambers would not be processed", action="store_true", dest="noCSC") parser.add_option("--noDT", help="if invoked, DT barrel chambers would not be processed", action="store_true", dest="noDT") parser.add_option("--createMapNtuple", help="if invoked while mapplots are switched on, a special ntuple would be created", action="store_true", dest="createMapNtuple") parser.add_option("--inputInBlocks", help="if invoked, assume that INPUTFILES provides a list of files already groupped into job blocks, -j has no effect in that case", action="store_true", dest="inputInBlocks") parser.add_option("--json", help="If present with JSON file as argument, use JSON file for good lumi mask. "+\ "The latest JSON file is available at /afs/cern.ch/cms/CAF/CMSCOMM/COMM_DQM/certification/Collisions11/7TeV/Prompt/", type="string", default="", dest="json") parser.add_option("--createAlignNtuple", help="if invoked, debug ntuples with residuals would be created during gather jobs", action="store_true", dest="createAlignNtuple") parser.add_option("--residualsModel", help="functional residuals model. Possible vaslues: pureGaussian2D (default), pureGaussian, GaussPowerTails, ROOTVoigt, powerLawTails", type="string", default="pureGaussian2D", dest="residualsModel") parser.add_option("--useResiduals", help="select residuals to use, possible values: 1111, 1110, 1100, 1010, 0010 that correspond to x y dxdz dydz residuals", type="string", default="1110", dest="useResiduals") parser.add_option("--peakNSigma", help="if >0, only residuals peaks within n-sigma multidimentional ellipsoid would be considered in the alignment fit", type="string", default="-1.", dest="peakNSigma") parser.add_option("--preFilter", help="if invoked, MuonAlignmentPreFilter module would be invoked in the Path's beginning. Can significantly speed up gather jobs.", action="store_true", dest="preFilter") parser.add_option("--muonCollectionTag", help="If empty, use trajectories. If not empty, it's InputTag of muons collection to use in tracker muons based approach, e.g., 'newmuons' or 'muons'", type="string", default="", dest="muonCollectionTag") parser.add_option("--maxDxy", help="maximum track impact parameter with relation to beamline", type="string", default="1000.", dest="maxDxy") parser.add_option("--minNCrossedChambers", help="minimum number of muon chambers that a track is required to cross", type="string", default="3", dest="minNCrossedChambers") parser.add_option("--extraPlots", help="produce additional plots with geometry, reports differences, and corrections visulizations", action="store_true", dest="extraPlots") if len(sys.argv) < 5: raise SystemError("Too few arguments.\n\n"+parser.format_help()) DIRNAME = sys.argv[1] ITERATIONS = int(sys.argv[2]) INITIALGEOM = sys.argv[3] INPUTFILES = sys.argv[4] options, args = parser.parse_args(sys.argv[5:]) user_mail = options.user_mail mapplots_ingeneral = options.mapplots segdiffplots_ingeneral = options.segdiffplots curvatureplots_ingeneral = options.curvatureplots globaltag = options.globaltag trackerconnect = options.trackerconnect trackeralignment = options.trackeralignment trackerAPEconnect = options.trackerAPEconnect trackerAPE = options.trackerAPE trackerBowsconnect = options.trackerBowsconnect trackerBows = options.trackerBows gprcdconnect = options.gprcdconnect gprcd = options.gprcd iscosmics = str(options.iscosmics) station123params = options.station123params station4params = options.station4params cscparams = options.cscparams muonCollectionTag = options.muonCollectionTag minTrackPt = options.minTrackPt maxTrackPt = options.maxTrackPt minTrackP = options.minTrackP maxTrackP = options.maxTrackP maxDxy = options.maxDxy minTrackerHits = str(options.minTrackerHits) maxTrackerRedChi2 = options.maxTrackerRedChi2 minNCrossedChambers = options.minNCrossedChambers allowTIDTEC = str(not options.notAllowTIDTEC) twoBin = str(options.twoBin) weightAlignment = str(options.weightAlignment) minAlignmentHits = str(options.minAlignmentHits) combineME11 = str(not options.notCombineME11) maxEvents = options.maxEvents skipEvents = options.skipEvents validationLabel = options.validationLabel maxResSlopeY = options.maxResSlopeY theNSigma = options.motionPolicyNSigma residualsModel = options.residualsModel peakNSigma = options.peakNSigma preFilter = not not options.preFilter extraPlots = options.extraPlots useResiduals = options.useResiduals #print "check: ", allowTIDTEC, combineME11, preFilter doCleanUp = not options.noCleanUp createMapNtuple = not not options.createMapNtuple createAlignNtuple = not not options.createAlignNtuple doCSC = True if options.noCSC: doCSC = False doDT = True if options.noDT: doDT = False if options.noCSC and options.noDT: print "cannot do --noCSC and --noDT at the same time!" sys.exit() json_file = options.json fileNames=[] fileNamesBlocks=[] execfile(INPUTFILES) njobs = options.subjobs if (options.inputInBlocks): njobs = len(fileNamesBlocks) if njobs==0: print "while --inputInBlocks is specified, the INPUTFILES has no blocks!" sys.exit() stepsize = int(math.ceil(1.*len(fileNames)/options.subjobs)) pwd = str(os.getcwd()) copytrackerdb = "" if trackerconnect[0:12] == "sqlite_file:": copytrackerdb += "%s " % trackerconnect[12:] if trackerAPEconnect[0:12] == "sqlite_file:": copytrackerdb += "%s " % trackerAPEconnect[12:] if trackerBowsconnect[0:12] == "sqlite_file:": copytrackerdb += "%s " % trackerBowsconnect[12:] if gprcdconnect[0:12] == "sqlite_file:": copytrackerdb += "%s " % gprcdconnect[12:] ##################################################################### # step 0: convert initial geometry to xml INITIALXML = INITIALGEOM + '.xml' if INITIALGEOM[-3:]=='.db': INITIALXML = INITIALGEOM[:-3] + '.xml' print "Converting",INITIALGEOM,"to",INITIALXML," ...will be done in several seconds..." print "./Alignment/MuonAlignmentAlgorithms/scripts/convertSQLiteXML.py %s %s --gprcdconnect %s --gprcd %s" % (INITIALGEOM,INITIALXML,gprcdconnect,gprcd) exit_code = os.system("./Alignment/MuonAlignmentAlgorithms/scripts/convertSQLiteXML.py %s %s --gprcdconnect %s --gprcd %s" % (INITIALGEOM,INITIALXML,gprcdconnect,gprcd)) if exit_code>0: print "problem: conversion exited with code:", exit_code sys.exit() ##################################################################### def writeGatherCfg(fname, my_vars): file(fname, "w").write("""#/bin/sh # %(commandline)s export ALIGNMENT_CAFDIR=`pwd` cd %(pwd)s eval `scramv1 run -sh` export ALIGNMENT_AFSDIR=`pwd` export ALIGNMENT_INPUTFILES='%(inputfiles)s' export ALIGNMENT_ITERATION=%(iteration)d export ALIGNMENT_JOBNUMBER=%(jobnumber)d export ALIGNMENT_MAPPLOTS=%(mapplots)s export ALIGNMENT_SEGDIFFPLOTS=%(segdiffplots)s export ALIGNMENT_CURVATUREPLOTS=%(curvatureplots)s export ALIGNMENT_GLOBALTAG=%(globaltag)s export ALIGNMENT_INPUTDB=%(inputdb)s export ALIGNMENT_TRACKERCONNECT=%(trackerconnect)s export ALIGNMENT_TRACKERALIGNMENT=%(trackeralignment)s export ALIGNMENT_TRACKERAPECONNECT=%(trackerAPEconnect)s export ALIGNMENT_TRACKERAPE=%(trackerAPE)s export ALIGNMENT_TRACKERBOWSCONNECT=%(trackerBowsconnect)s export ALIGNMENT_TRACKERBOWS=%(trackerBows)s export ALIGNMENT_GPRCDCONNECT=%(gprcdconnect)s export ALIGNMENT_GPRCD=%(gprcd)s export ALIGNMENT_ISCOSMICS=%(iscosmics)s export ALIGNMENT_STATION123PARAMS=%(station123params)s export ALIGNMENT_STATION4PARAMS=%(station4params)s export ALIGNMENT_CSCPARAMS=%(cscparams)s export ALIGNMENT_MUONCOLLECTIONTAG=%(muonCollectionTag)s export ALIGNMENT_MINTRACKPT=%(minTrackPt)s export ALIGNMENT_MAXTRACKPT=%(maxTrackPt)s export ALIGNMENT_MINTRACKP=%(minTrackP)s export ALIGNMENT_MAXTRACKP=%(maxTrackP)s export ALIGNMENT_MAXDXY=%(maxDxy)s export ALIGNMENT_MINTRACKERHITS=%(minTrackerHits)s export ALIGNMENT_MAXTRACKERREDCHI2=%(maxTrackerRedChi2)s export ALIGNMENT_MINNCROSSEDCHAMBERS=%(minNCrossedChambers)s export ALIGNMENT_ALLOWTIDTEC=%(allowTIDTEC)s export ALIGNMENT_TWOBIN=%(twoBin)s export ALIGNMENT_WEIGHTALIGNMENT=%(weightAlignment)s export ALIGNMENT_MINALIGNMENTHITS=%(minAlignmentHits)s export ALIGNMENT_COMBINEME11=%(combineME11)s export ALIGNMENT_MAXEVENTS=%(maxEvents)s export ALIGNMENT_SKIPEVENTS=%(skipEvents)s export ALIGNMENT_MAXRESSLOPEY=%(maxResSlopeY)s export ALIGNMENT_DO_DT=%(doDT)s export ALIGNMENT_DO_CSC=%(doCSC)s export ALIGNMENT_JSON=%(json_file)s export ALIGNMENT_CREATEMAPNTUPLE=%(createMapNtuple)s #export ALIGNMENT_CREATEALIGNNTUPLE=%(createAlignNtuple)s export ALIGNMENT_PREFILTER=%(preFilter)s if [ \"zzz$ALIGNMENT_JSON\" != \"zzz\" ]; then cp -f $ALIGNMENT_JSON $ALIGNMENT_CAFDIR/ fi cp -f %(directory)sgather_cfg.py %(inputdbdir)s%(inputdb)s %(copytrackerdb)s $ALIGNMENT_CAFDIR/ cd $ALIGNMENT_CAFDIR/ ls -l cmsRun gather_cfg.py ls -l cp -f *.tmp %(copyplots)s $ALIGNMENT_AFSDIR/%(directory)s """ % my_vars) ##################################################################### def writeAlignCfg(fname, my_vars): file("%salign.sh" % directory, "w").write("""#!/bin/sh # %(commandline)s export ALIGNMENT_CAFDIR=`pwd` cd %(pwd)s eval `scramv1 run -sh` export ALIGNMENT_AFSDIR=`pwd` export ALIGNMENT_INPUTDB=%(inputdb)s export ALIGNMENT_ITERATION=%(iteration)d export ALIGNMENT_GLOBALTAG=%(globaltag)s export ALIGNMENT_TRACKERCONNECT=%(trackerconnect)s export ALIGNMENT_TRACKERALIGNMENT=%(trackeralignment)s export ALIGNMENT_TRACKERAPECONNECT=%(trackerAPEconnect)s export ALIGNMENT_TRACKERAPE=%(trackerAPE)s export ALIGNMENT_TRACKERBOWSCONNECT=%(trackerBowsconnect)s export ALIGNMENT_TRACKERBOWS=%(trackerBows)s export ALIGNMENT_GPRCDCONNECT=%(gprcdconnect)s export ALIGNMENT_GPRCD=%(gprcd)s export ALIGNMENT_ISCOSMICS=%(iscosmics)s export ALIGNMENT_STATION123PARAMS=%(station123params)s export ALIGNMENT_STATION4PARAMS=%(station4params)s export ALIGNMENT_CSCPARAMS=%(cscparams)s export ALIGNMENT_MINTRACKPT=%(minTrackPt)s export ALIGNMENT_MAXTRACKPT=%(maxTrackPt)s export ALIGNMENT_MINTRACKP=%(minTrackP)s export ALIGNMENT_MAXTRACKP=%(maxTrackP)s export ALIGNMENT_MINTRACKERHITS=%(minTrackerHits)s export ALIGNMENT_MAXTRACKERREDCHI2=%(maxTrackerRedChi2)s export ALIGNMENT_ALLOWTIDTEC=%(allowTIDTEC)s export ALIGNMENT_TWOBIN=%(twoBin)s export ALIGNMENT_WEIGHTALIGNMENT=%(weightAlignment)s export ALIGNMENT_MINALIGNMENTHITS=%(minAlignmentHits)s export ALIGNMENT_COMBINEME11=%(combineME11)s export ALIGNMENT_MAXRESSLOPEY=%(maxResSlopeY)s export ALIGNMENT_CLEANUP=%(doCleanUp)s export ALIGNMENT_CREATEALIGNNTUPLE=%(createAlignNtuple)s export ALIGNMENT_RESIDUALSMODEL=%(residualsModel)s export ALIGNMENT_PEAKNSIGMA=%(peakNSigma)s export ALIGNMENT_USERESIDUALS=%(useResiduals)s cp -f %(directory)salign_cfg.py %(inputdbdir)s%(inputdb)s %(directory)s*.tmp %(copytrackerdb)s $ALIGNMENT_CAFDIR/ export ALIGNMENT_PLOTTINGTMP=`find %(directory)splotting0*.root -maxdepth 1 -size +0 -print 2> /dev/null` # if it's 1st or last iteration, combine _plotting.root files into one: if [ \"$ALIGNMENT_ITERATION\" != \"111\" ] || [ \"$ALIGNMENT_ITERATION\" == \"%(ITERATIONS)s\" ]; then #nfiles=$(ls %(directory)splotting0*.root 2> /dev/null | wc -l) if [ \"zzz$ALIGNMENT_PLOTTINGTMP\" != \"zzz\" ]; then hadd -f1 %(directory)s%(director)s_plotting.root %(directory)splotting0*.root #if [ $? == 0 ] && [ \"$ALIGNMENT_CLEANUP\" == \"True\" ]; then rm %(directory)splotting0*.root; fi fi fi if [ \"$ALIGNMENT_CLEANUP\" == \"True\" ] && [ \"zzz$ALIGNMENT_PLOTTINGTMP\" != \"zzz\" ]; then rm $ALIGNMENT_PLOTTINGTMP fi cd $ALIGNMENT_CAFDIR/ export ALIGNMENT_ALIGNMENTTMP=`find alignment*.tmp -maxdepth 1 -size +1k -print 2> /dev/null` ls -l cmsRun align_cfg.py cp -f MuonAlignmentFromReference_report.py $ALIGNMENT_AFSDIR/%(directory)s%(director)s_report.py cp -f MuonAlignmentFromReference_outputdb.db $ALIGNMENT_AFSDIR/%(directory)s%(director)s.db cp -f MuonAlignmentFromReference_plotting.root $ALIGNMENT_AFSDIR/%(directory)s%(director)s.root cd $ALIGNMENT_AFSDIR ./Alignment/MuonAlignmentAlgorithms/scripts/convertSQLiteXML.py %(directory)s%(director)s.db %(directory)s%(director)s.xml --noLayers --gprcdconnect $ALIGNMENT_GPRCDCONNECT --gprcd $ALIGNMENT_GPRCD export ALIGNMENT_ALIGNMENTTMP=`find %(directory)salignment*.tmp -maxdepth 1 -size +1k -print 2> /dev/null` if [ \"$ALIGNMENT_CLEANUP\" == \"True\" ] && [ \"zzz$ALIGNMENT_ALIGNMENTTMP\" != \"zzz\" ]; then rm $ALIGNMENT_ALIGNMENTTMP echo " " fi # if it's not 1st or last iteration, do some clean up: if [ \"$ALIGNMENT_ITERATION\" != \"1\" ] && [ \"$ALIGNMENT_ITERATION\" != \"%(ITERATIONS)s\" ]; then if [ \"$ALIGNMENT_CLEANUP\" == \"True\" ] && [ -e %(directory)s%(director)s.root ]; then rm %(directory)s%(director)s.root fi fi # if it's last iteration, apply chamber motion policy if [ \"$ALIGNMENT_ITERATION\" == \"%(ITERATIONS)s\" ]; then # convert this iteration's geometry into detailed xml ./Alignment/MuonAlignmentAlgorithms/scripts/convertSQLiteXML.py %(directory)s%(director)s.db %(directory)s%(director)s_extra.xml --gprcdconnect $ALIGNMENT_GPRCDCONNECT --gprcd $ALIGNMENT_GPRCD # perform motion policy ./Alignment/MuonAlignmentAlgorithms/scripts/motionPolicyChamber.py \ %(INITIALXML)s %(directory)s%(director)s_extra.xml \ %(directory)s%(director)s_report.py \ %(directory)s%(director)s_final.xml \ --nsigma %(theNSigma)s # convert the resulting xml into the final sqlite geometry ./Alignment/MuonAlignmentAlgorithms/scripts/convertSQLiteXML.py %(directory)s%(director)s_final.xml %(directory)s%(director)s_final.db --gprcdconnect $ALIGNMENT_GPRCDCONNECT --gprcd $ALIGNMENT_GPRCD fi """ % my_vars) ##################################################################### def writeValidationCfg(fname, my_vars): file(fname, "w").write("""#!/bin/sh # %(commandline)s export ALIGNMENT_CAFDIR=`pwd` mkdir files mkdir out cd %(pwd)s eval `scramv1 run -sh` ALIGNMENT_AFSDIR=`pwd` ALIGNMENT_ITERATION=%(iteration)d ALIGNMENT_MAPPLOTS=None ALIGNMENT_SEGDIFFPLOTS=None ALIGNMENT_CURVATUREPLOTS=None ALIGNMENT_EXTRAPLOTS=%(extraPlots)s export ALIGNMENT_GPRCDCONNECT=%(gprcdconnect)s export ALIGNMENT_GPRCD=%(gprcd)s export ALIGNMENT_DO_DT=%(doDT)s export ALIGNMENT_DO_CSC=%(doCSC)s # copy the scripts to CAFDIR cd Alignment/MuonAlignmentAlgorithms/scripts/ cp -f plotscripts.py $ALIGNMENT_CAFDIR/ cp -f mutypes.py $ALIGNMENT_CAFDIR/ cp -f alignmentValidation.py $ALIGNMENT_CAFDIR/ cp -f phiedges_fitfunctions.C $ALIGNMENT_CAFDIR/ cp -f createTree.py $ALIGNMENT_CAFDIR/ cp -f signConventions.py $ALIGNMENT_CAFDIR/ cp -f convertSQLiteXML.py $ALIGNMENT_CAFDIR/ cp -f wrapperExtraPlots.sh $ALIGNMENT_CAFDIR/ cd - cp Alignment/MuonAlignmentAlgorithms/test/browser/tree* $ALIGNMENT_CAFDIR/out/ # copy the results to CAFDIR cp -f %(directory1)s%(director1)s_report.py $ALIGNMENT_CAFDIR/files/ cp -f %(directory)s%(director)s_report.py $ALIGNMENT_CAFDIR/files/ cp -f %(directory1)s%(director1)s.root $ALIGNMENT_CAFDIR/files/ cp -f %(directory)s%(director)s.root $ALIGNMENT_CAFDIR/files/ if [ -e %(directory1)s%(director1)s_plotting.root ] && [ -e %(directory)s%(director)s_plotting.root ]; then cp -f %(directory1)s%(director1)s_plotting.root $ALIGNMENT_CAFDIR/files/ cp -f %(directory)s%(director)s_plotting.root $ALIGNMENT_CAFDIR/files/ ALIGNMENT_MAPPLOTS=%(mapplots)s ALIGNMENT_SEGDIFFPLOTS=%(segdiffplots)s ALIGNMENT_CURVATUREPLOTS=%(curvatureplots)s fi dtcsc="" if [ $ALIGNMENT_DO_DT == \"True\" ]; then dtcsc="--dt" fi if [ $ALIGNMENT_DO_CSC == \"True\" ]; then dtcsc="${dtcsc} --csc" fi cd $ALIGNMENT_CAFDIR/ echo \" ### Start running ###\" date # do fits and median plots first ./alignmentValidation.py -l %(validationLabel)s -i $ALIGNMENT_CAFDIR --i1 files --iN files --i1prefix %(director1)s --iNprefix %(director)s -o $ALIGNMENT_CAFDIR/out --createDirSructure --dt --csc --fit --median if [ $ALIGNMENT_MAPPLOTS == \"True\" ]; then ./alignmentValidation.py -l %(validationLabel)s -i $ALIGNMENT_CAFDIR --i1 files --iN files --i1prefix %(director1)s --iNprefix %(director)s -o $ALIGNMENT_CAFDIR/out $dtcsc --map fi if [ $ALIGNMENT_SEGDIFFPLOTS == \"True\" ]; then ./alignmentValidation.py -l %(validationLabel)s -i $ALIGNMENT_CAFDIR --i1 files --iN files --i1prefix %(director1)s --iNprefix %(director)s -o $ALIGNMENT_CAFDIR/out $dtcsc --segdiff fi if [ $ALIGNMENT_CURVATUREPLOTS == \"True\" ]; then ./alignmentValidation.py -l %(validationLabel)s -i $ALIGNMENT_CAFDIR --i1 files --iN files --i1prefix %(director1)s --iNprefix %(director)s -o $ALIGNMENT_CAFDIR/out $dtcsc --curvature fi if [ $ALIGNMENT_EXTRAPLOTS == \"True\" ]; then if [ \"zzz%(copytrackerdb)s\" != \"zzz\" ]; then cp -f $ALIGNMENT_AFSDIR/%(copytrackerdb)s $ALIGNMENT_CAFDIR/ fi cp $ALIGNMENT_AFSDIR/inertGlobalPositionRcd.db . ./convertSQLiteXML.py $ALIGNMENT_AFSDIR/%(INITIALGEOM)s g0.xml --noLayers --gprcdconnect $ALIGNMENT_GPRCDCONNECT --gprcd $ALIGNMENT_GPRCD ./wrapperExtraPlots.sh -n $ALIGNMENT_ITERATION -i $ALIGNMENT_AFSDIR -0 g0.xml -z -w %(station123params)s %(dir_no_)s mkdir out/extra cd %(dir_no_)s mv MB ../out/extra/ mv ME ../out/extra/ cd - fi # run simple diagnostic ./alignmentValidation.py -l %(validationLabel)s -i $ALIGNMENT_CAFDIR --i1 files --iN files --i1prefix %(director1)s --iNprefix %(director)s -o $ALIGNMENT_CAFDIR/out --dt --csc --diagnostic # fill the tree browser structure: ./createTree.py -i $ALIGNMENT_CAFDIR/out timestamp=`date \"+%%y-%%m-%%d %%H:%%M:%%S\"` echo \"%(validationLabel)s.plots (${timestamp})\" > out/label.txt ls -l out/ timestamp=`date +%%Y%%m%%d%%H%%M%%S` tar czf %(validationLabel)s_${timestamp}.tgz out cp -f %(validationLabel)s_${timestamp}.tgz $ALIGNMENT_AFSDIR/ """ % my_vars) ##################################################################### #SUPER_SPECIAL_XY_AND_DXDZ_ITERATIONS = True SUPER_SPECIAL_XY_AND_DXDZ_ITERATIONS = False bsubfile = ["#!/bin/sh", ""] bsubnames = [] last_align = None directory = "" for iteration in range(1, ITERATIONS+1): if iteration == 1: inputdb = INITIALGEOM inputdbdir = directory[:] else: inputdb = director + ".db" inputdbdir = directory[:] directory = "%s%02d/" % (DIRNAME, iteration) director = directory[:-1] dir_no_ = DIRNAME if DIRNAME[-1]=='_': dir_no_ = DIRNAME[:-1] os.system("rm -rf %s; mkdir %s" % (directory, directory)) os.system("cp Alignment/MuonAlignmentAlgorithms/python/gather_cfg.py %s" % directory) os.system("cp Alignment/MuonAlignmentAlgorithms/python/align_cfg.py %s" % directory) bsubfile.append("cd %s" % directory) mapplots = False if mapplots_ingeneral and (iteration == 1 or iteration == 3 or iteration == 5 or iteration == 7 or iteration == 9 or iteration == ITERATIONS): mapplots = True segdiffplots = False if segdiffplots_ingeneral and (iteration == 1 or iteration == ITERATIONS): segdiffplots = True curvatureplots = False if curvatureplots_ingeneral and (iteration == 1 or iteration == ITERATIONS): curvatureplots = True ### gather.sh runners for njobs for jobnumber in range(njobs): if not options.inputInBlocks: inputfiles = " ".join(fileNames[jobnumber*stepsize:(jobnumber+1)*stepsize]) else: inputfiles = " ".join(fileNamesBlocks[jobnumber]) if mapplots or segdiffplots or curvatureplots: copyplots = "plotting*.root" else: copyplots = "" if len(inputfiles) > 0: gather_fileName = "%sgather%03d.sh" % (directory, jobnumber) writeGatherCfg(gather_fileName, vars()) os.system("chmod +x %s" % gather_fileName) bsubfile.append("echo %sgather%03d.sh" % (directory, jobnumber)) if last_align is None: waiter = "" else: waiter = "-w \"ended(%s)\"" % last_align if options.big: queue = "cmscaf1nd" else: queue = "cmscaf1nh" bsubfile.append("bsub -R \"type==SLC6_64\" -q %s -J \"%s_gather%03d\" -u youremail.tamu.edu %s gather%03d.sh" % (queue, director, jobnumber, waiter, jobnumber)) bsubnames.append("ended(%s_gather%03d)" % (director, jobnumber)) ### align.sh if SUPER_SPECIAL_XY_AND_DXDZ_ITERATIONS: if ( iteration == 1 or iteration == 3 or iteration == 5 or iteration == 7 or iteration == 9): tmp = station123params, station123params, useResiduals station123params, station123params, useResiduals = "000010", "000010", "0010" writeAlignCfg("%salign.sh" % directory, vars()) station123params, station123params, useResiduals = tmp elif ( iteration == 2 or iteration == 4 or iteration == 6 or iteration == 8 or iteration == 10): tmp = station123params, station123params, useResiduals station123params, station123params, useResiduals = "110001", "100001", "1100" writeAlignCfg("%salign.sh" % directory, vars()) station123params, station123params, useResiduals = tmp else: writeAlignCfg("%salign.sh" % directory, vars()) os.system("chmod +x %salign.sh" % directory) bsubfile.append("echo %salign.sh" % directory) if user_mail: bsubfile.append("bsub -R \"type==SLC6_64\" -q cmscaf1nd -J \"%s_align\" -u %s -w \"%s\" align.sh" % (director, user_mail, " && ".join(bsubnames))) else: bsubfile.append("bsub -R \"type==SLC6_64\" -q cmscaf1nd -J \"%s_align\" -w \"%s\" align.sh" % (director, " && ".join(bsubnames))) #bsubfile.append("cd ..") bsubnames = [] last_align = "%s_align" % director ### after the last iteration (optionally) do diagnostics run if len(validationLabel) and iteration == ITERATIONS: # do we have plotting files created? directory1 = "%s01/" % DIRNAME director1 = directory1[:-1] writeValidationCfg("%svalidation.sh" % directory, vars()) os.system("chmod +x %svalidation.sh" % directory) bsubfile.append("echo %svalidation.sh" % directory) if user_mail: bsubfile.append("bsub -R \"type==SLC6_64\" -q cmscaf1nd -J \"%s_validation\" -u %s -w \"ended(%s)\" validation.sh" % (director, user_mail, last_align)) else: bsubfile.append("bsub -R \"type==SLC6_64\" -q cmscaf1nd -J \"%s_validation\" -w \"ended(%s)\" validation.sh" % (director, last_align)) bsubfile.append("cd ..") bsubfile.append("") file(options.submitJobs, "w").write("\n".join(bsubfile)) os.system("chmod +x %s" % options.submitJobs)
/** * Copyright 2021 Google LLC * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ import * as model from './model.js'; import * as parser from './parser.js'; import * as path from 'path'; import * as fs from 'fs'; import { Features } from '../features/helpers.js'; import * as types from '../../types/index.js'; import { fetchAllTo } from '../source/fetcher.js'; import fg from 'fast-glob'; import { parseOverride } from './override.js'; import { convertFromIdl } from './idl-convert.js'; import { buildLimit } from '../limit.js'; import { cache } from '../source/cache.js'; import { findDependentNamespaces } from './helper.js'; // @ts-ignore import JSON5 from 'json5'; // @ts-ignore import * as tmp from 'tmp'; const definitionPaths = [ 'extensions/common/api', 'chrome/common/extensions/api', 'chrome/common/apps/platform_apps/api', ]; // These are used entirely to run `idl_parser.py`. const toolsPaths = [ 'tools/json_schema_compiler', 'tools/json_comment_eater', 'ppapi/generators', 'third_party/ply', ]; const defaultRevision = 'master'; const featureFileMatch = /^_(\w+)_features.json$/; /** * Prepares information on Chrome extension APIs at the given revision. * * @param {Partial<types.MainOptions>} options * @return {Promise<types.MainResult>} */ export async function prepareNamespaces(options = {}) { const o = /** @type {types.MainOptions} */ (Object.assign({ revision: defaultRevision, toolsRevision: defaultRevision, symbols: null, cacheIdlParse: true, nodocRemove: true, }, options)); const tmpobj = tmp.dirSync(); const workPath = tmpobj.name; /** @type {types.RawFeatureFile} */ const features = {}; /** @type {types.RawNamespace[]} */ const sources = []; try { const defitionsPromise = fetchAllTo(workPath, definitionPaths, o.revision); const toolsPromise = fetchAllTo(workPath, toolsPaths, o.toolsRevision); await defitionsPromise; await toolsPromise; const allFiles = []; for (const p of definitionPaths) { const cwd = path.join(workPath, p); const all = fg.sync('**/*.{json,idl}', { cwd }); allFiles.push(...all.map((filename) => path.join(cwd, filename))); } /** @type {(filename: string) => Promise<Buffer>} */ const limitConvertFromIdl = buildLimit(convertFromIdl.bind(null, workPath)); // Walk over every found .json/.idl file and add to the output mix. await Promise.all(allFiles.map(async (filename) => { const ext = path.extname(filename); const basename = path.basename(filename); /** @type {string} */ let raw; if (ext === '.idl') { let out; if (o.cacheIdlParse) { // Cache this work for ~60s as default. const rel = path.relative(workPath, filename); out = await cache(`idl#${rel}`, limitConvertFromIdl.bind(null, filename)); } else { out = await limitConvertFromIdl(filename); } raw = out.toString('utf-8'); } else if (ext === '.json') { raw = fs.readFileSync(filename, 'utf-8'); } else { return; } let json; try { json = JSON5.parse(raw); } catch (e) { console.warn('bad JSON from', filename, 'ext was?', ext, 'length', raw.length, 'got e', e); console.warn(raw); process.exit(1); throw e; } if (!basename.startsWith('_')) { sources.push(...json); return; } // Check if this is actually a feature file (e.g., _api_feature.json). const m = featureFileMatch.exec(basename); if (m) { const type = m[1]; for (const id in json) { const key = `${type}:${id}`; if (key in features) { throw new Error(`got duplicate feature key: ${key}`); } features[key] = json[id]; } } })); } finally { await fs.promises.rm(workPath, { recursive: true }); } const stats = { features: Object.keys(features).length, namespaces: sources.length, skipped: /** @type {string[]} */ ([]), }; /** @type {{[name: string]: model.Namespace}} */ const all = {}; const allNamespaceNames = sources.map((raw) => raw.namespace); const f = new Features(features, o.symbols); const p = new parser.JSONSchemaParser(f, allNamespaceNames); sources.forEach((raw) => { let namespace; try { ({ namespace } = p.parse(raw)); } catch (e) { console.warn('failed to parse'); console.warn(raw); throw e; } // This is a Private or Internal API that is not included in general display. if (namespace.nodoc) { stats.skipped.push(raw.namespace); if (o.nodocRemove) { return; } } all[namespace.name] = namespace; }); parseOverride(all); // Remove nodoc. We've already removed nodoc _namespaces_ here. if (o.nodocRemove) { for (const name in all) { const namespace = all[name]; namespace.traverse((_path, prop) => { // If we return true from a traversal, the node is removed. if (prop.nodoc) { return true; } }); } } // Calculate dependencies between namespaces. /** @type {{[namespace: string]: string[]}} */ const deps = {}; for (const name in all) { const d = findDependentNamespaces(all[name], allNamespaceNames);; deps[name] = d; } // TODO: do something with deps return {namespaces: all, stats}; }
from flask import Flask, Request, request, json app = Flask(__name__) class Person: def __init__(self): self.firstName = "" self.lastName = "" self.age = 0 def load(self, json): jsonAttr = list(json.keys()) for attr in vars(self): if attr in jsonAttr: self.__setattr__(attr, json[attr]) def __repr__(self): return "FirstName = "+self.firstName+" Last Name = "+ self.lastName+ " age = "+str(self.age) def customdec(function): number = 0 def wrapper(*args, **kwargs): nonlocal number print("Request #"+str(number)) return function(*args,**kwargs) return wrapper @app.route("/", methods=['POST']) @customdec def hello(): p = Person() p.load(json.loads(request.data)) return "Hello, World!" if __name__ == "__main__": app.run(port=8989)
#!/usr/bin/python3 # -*- coding: utf-8 -*- """ This code uses a user-defined database, image directory, image file extension, and darkframe to loop through the Tetra database and generate inputs for the opencv camera calibration routine """ ################################ #LOAD LIBRARIES ################################ import os import sys import cv2 import json import time import pathlib import numpy as np from PIL import Image from scipy.io import savemat from tetra3_Cal import Tetra3 ################################ #USER INPUT ################################ db_name = 'test_db' path_to_images = '' image_file_extension = '.jpg' darkframe_filename = '' estimated_full_angle_fov = 20 verbose = True ################################ #MAIN CODE ################################ # figure out if a database exists for Tetra if isinstance(db_name, str): path = (pathlib.Path(__file__).parent / db_name).with_suffix('.npz') else: path = pathlib.Path(path).with_suffix('.npz') # if not, create one if not os.path.exists(path): print("\nUnable to find specified database: " + str(path)) print(" Generating database...") t3 = Tetra3() #this initializes stuff t3.generate_database(max_fov = estimated_full_angle_fov, save_as=db_name) #this builds a database print(" ...complete\n\n") # init Tetra w/ database t3 = Tetra3(db_name) # find darkframe if darkframe_filename == '': print("\nDarkframe file not provided, proceeding without darkframe subtraction.\n") darkframe_filename = None else: darkframe_filename = os.path.join(path_to_images, darkframe_filename) if os.path.exists(darkframe_filename): print('\nDarkframe found! Applying to calibration images...\n') else: darkframe_filename = None print("\nUnable to find darkframe, proceeding without darkframe subtraction.\n") # define variables and start processing path = pathlib.Path(path_to_images) solution_list = [] AllProjs = np.array([[0,0,0]]) AllCents = np.array([[0,0]]) num_images = 0 for impath in path.glob('*'+image_file_extension): num_images+=1 print('Attempting to solve image: ' + str(impath)) start_time = time.time() img = cv2.imread(str(impath), cv2.IMREAD_GRAYSCALE) if img is None: print("ERROR ["+str(__name__)+"]:Image file "+impath+" does not exist in path. ") sys.exit() if verbose: print('Loaded image in {} seconds'.format(time.time()-start_time)) image_size = (img.shape[1],img.shape[0]) # tuple required, input args flipped if darkframe_filename is not None: darkframe = cv2.imread(darkframe_filename, cv2.IMREAD_GRAYSCALE) img = cv2.subtract(img, darkframe) solved = t3.solve_from_image(img, fov_estimate=estimated_full_angle_fov) # Adding e.g. fov_estimate=11.4, fov_max_error=.1 may improve performance try: Vecs = [] ProjVecs = [] R = solved['Rmat'] Cents = np.array(solved['MatchCentroids']) Cents[:,[0,1]] = Cents[:,[1,0]] #print(Cents) #Swap rows because tetra uses centroids in (y,x) AllCents = np.append(AllCents, Cents, axis = 0) i=0 angY = 90 * (np.pi/180) RotY = np.array([[np.cos(angY), 0, -np.sin(angY)], [0,1,0], [np.sin(angY), 0, np.cos(angY)]]) angZ = -90 * (np.pi/180) RotZ = np.array([[np.cos(angZ), -np.sin(angZ), 0 ], [np.sin(angZ), np.cos(angZ), 0], [0,0,1]]) for tup in solved['MatchVectors']: v = np.array(tup[1]).transpose() #print(v) vcam = np.dot(RotZ, np.dot(RotY, np.dot(R, v))) #Project Vector onto z = 1 proj = np.array([(vcam[0]/vcam[2]),(vcam[1]/vcam[2]), 0]) #print(proj) AllProjs = np.append(AllProjs, [proj], axis = 0) ProjVecs.append(proj) Vecs.append(vcam) i+=1 imgdict = {'R_inertial_to_camera_guess': R, 'uvd_meas': Cents, 'CAT_FOV':Vecs, 'Projections':ProjVecs, 'NumStars': len(Vecs), 'FOV': solved['FOV']} solution_list.append(imgdict) print(" ...success! (took " +str(time.time()-start_time)[:8]+" seconds)") except: print(' ...FAILED to solve \n') # if some of the images were solved, use the solutions to calibrate the camera if len(solution_list) > 0: print("\n\nFound ("+str(len(solution_list))+") solutions out of (" + str(num_images)+") images\n") solved = solution_list[0] # these seem to be fairly consistent, though one day we may want to average all fovguess = solved['FOV'] flpix = image_size[0]/(2*np.tan(np.deg2rad(fovguess)/2)) matGuess = np.array([[flpix, 0,(image_size[0]/2) - 0.5 ], [0, flpix, (image_size[1]/2)-0.5], [0, 0, 1]]) AllCents = np.delete(AllCents, 0, axis = 0).astype('float32') AllProjs = np.delete(AllProjs, 0, axis = 0).astype('float32') RMS_reproj_err_pix, mtx, dist, rvecs, tvecs = cv2.calibrateCamera([AllProjs], [AllCents], image_size, matGuess, None, flags=(cv2.CALIB_USE_INTRINSIC_GUESS+cv2.CALIB_FIX_PRINCIPAL_POINT)) [fovx, fovy, fl, pp, ar] = cv2.calibrationMatrixValues(mtx, image_size, 4.8e-3*image_size[0], 4.8e-3*image_size[1] ) # Note that this may not work without an accurate detector size (Args 3 and 4) print("\nReprojection Error (pix, RMS): " + str(RMS_reproj_err_pix)) print("\nFoV (x,y): "+str(fovx)+", "+str(fovy)) print("Focal Length (pix): " + str(flpix)) print("Focal Length (mm): " + str(fl)) print("\nCamera Matrix: "+ str(mtx)) print("\nDist: " + str(dist)) print("\nRvecs: " + str(rvecs)) print("\nTvecs: " + str(tvecs)) print("") # populate dict dist_l=dist.tolist() newcameramtx_l = mtx.tolist() # in this case, cy is vp and cx is up. cam_cal_dict = {'camera_matrix': newcameramtx_l, 'dist_coefs': dist_l, 'resolution':[image_size[0],image_size[1]], 'camera_model':'Brown','k1':dist_l[0][0],'k2':dist_l[0][1],'k3':dist_l[0][4],'p1':dist_l[0][2],'p2':dist_l[0][3],'fx':newcameramtx_l[0][0],'fy':newcameramtx_l[1][1],'up':newcameramtx_l[0][2],'vp':newcameramtx_l[1][2],'skew':newcameramtx_l[0][1], 'RMS_reproj_err_pix':RMS_reproj_err_pix} # save usr_in = 'generic_cam_params' usr_in_split = usr_in.split('.json') usr_in = usr_in_split[0] cam_config_dir = os.path.join(os.path.dirname(os.path.dirname(os.path.dirname(os.path.dirname(os.getcwd())))),'data','cam_config') full_cam_file_path = os.path.join(cam_config_dir,usr_in+'.json') with open(full_cam_file_path, 'w') as fp: json.dump(cam_cal_dict, fp, indent=2) print("\n\nCamera parameter file saved to: " + str(full_cam_file_path) +"\n\n") else: print("\n\n\nNo solutions found (at all). Exiting unsuccessfully...\n\n\n")
const DIG = require("discord-image-generation"); const Discord = require("discord.js"); module.exports = { config: { name: "rip", description: "RIP!", aliases: ["rip"], usage: "", accessableby: "" }, run: async (client, message, args) => { // const m = client.findMember(message, args, true); let user = (await message.mentions.members.first()) || message.guild.members.cache.get(args[0]) || message.guild.members.cache.find( r => r.user.username.toLowerCase() === args.join(" ").toLocaleLowerCase() ) || message.guild.members.cache.find( r => r.displayName.toLowerCase() === args.join(" ").toLocaleLowerCase() ) || message.member; let m = await message.channel.send("**Please Wait...**"); let avatar = user.user.displayAvatarURL({ dynamic: false, format: "png" }); let img = await new DIG.Rip().getImage(avatar); let attach = new Discord.MessageAttachment(img, "rip.png"); m.delete({ timeout: 5000 }); message.channel.send(attach); } };
import React, { Component } from "react"; class CartMenu extends Component { constructor(porps){ super() } render(){ return( <div className="col-lg-3 col-12 cart-right-body"> <div id="free-ship-rater" className="row"> <div className="tittle-block col-12"> <p>Congrats! You’ve earned FREE shipping</p> </div> <div className="rate-bar col-12"> <div className="progress"> <div className="progress-bar bg-rate-bar" role="progressbar" aria-valuenow="5" aria-valuemin="0" aria-valuemax="5" style={{width: (98)+'%'}}> </div> </div> <div className="free-ship-rate"> <span className="pull-left">AED 0</span> <span className="pull-right">AED 200</span> </div> </div> </div> <div id="invoice-wrap" className="row"> <div className="col-12 apply-coupon"> <div className="input-group mb-3 "> <input type="text" id="name" className="form-control" required/> <label className="form-control-placeholder" for="name">Enter coupon code</label> <button className="btn btn-outline-secondary" type="button" id="button-addon2">APPLY</button> </div> </div> <div className="col-12 order-summary"> <h5>Order Summary</h5> <p>Subtotal <span className="price pull-right">AED 123133.90</span></p> <p>Discount <span className="discount pull-right">AED 3133.90</span></p> <p>Shipping <span className="shiping pull-right">AED 133.90</span></p> <p>Shipping <span className="shiping-free pull-right">Free</span></p> <hr/> <p className="grand-total"><span className="total">Total</span> <small>(Inclussive of VAT)</small> <span class="total-price pull-right">AED 123133.90</span></p> <p className="emi-cart">EMI is available for this purchase.</p> </div> </div> <div id="secure-checkout-container" className="row buynow-container"> <button role="button" className="buynowbutton"> SECURE CHECKOUT </button> </div> <div id="payment-option" className="row payment-option-container"> <ul> <li><img src="images/pay1.png"/></li> <li><img src="images/pay2.png"/></li> <li><img src="images/pay3.png"/></li> <li><img src="images/pay4.png"/></li> <li><img src="images/pay5.png"/></li> <li><img src="images/pay6.png"/></li> </ul> </div> </div> ); } } export default CartMenu;
from __future__ import absolute_import, unicode_literals ###################### # MEZZANINE SETTINGS # ###################### # The following settings are already defined with default values in # the ``defaults.py`` module within each of Mezzanine's apps, but are # common enough to be put here, commented out, for convenient # overriding. Please consult the settings documentation for a full list # of settings Mezzanine implements: # http://mezzanine.jupo.org/docs/configuration.html#default-settings # Controls the ordering and grouping of the admin menu. # # ADMIN_MENU_ORDER = ( # ("Content", ("pages.Page", "blog.BlogPost", # "generic.ThreadedComment", ("Media Library", "fb_browse"),)), # ("Site", ("sites.Site", "redirects.Redirect", "conf.Setting")), # ("Users", ("auth.User", "auth.Group",)), # ) # A three item sequence, each containing a sequence of template tags # used to render the admin dashboard. # # DASHBOARD_TAGS = ( # ("blog_tags.quick_blog", "mezzanine_tags.app_list"), # ("comment_tags.recent_comments",), # ("mezzanine_tags.recent_actions",), # ) # A sequence of templates used by the ``page_menu`` template tag. Each # item in the sequence is a three item sequence, containing a unique ID # for the template, a label for the template, and the template path. # These templates are then available for selection when editing which # menus a page should appear in. Note that if a menu template is used # that doesn't appear in this setting, all pages will appear in it. # PAGE_MENU_TEMPLATES = ( # (1, "Top navigation bar", "pages/menus/dropdown.html"), # (2, "Left-hand tree", "pages/menus/tree.html"), # (3, "Footer", "pages/menus/footer.html"), # ) # A sequence of fields that will be injected into Mezzanine's (or any # library's) models. Each item in the sequence is a four item sequence. # The first two items are the dotted path to the model and its field # name to be added, and the dotted path to the field class to use for # the field. The third and fourth items are a sequence of positional # args and a dictionary of keyword args, to use when creating the # field instance. When specifying the field class, the path # ``django.models.db.`` can be omitted for regular Django model fields. # # EXTRA_MODEL_FIELDS = ( # ( # # Dotted path to field. # "mezzanine.blog.models.BlogPost.image", # # Dotted path to field class. # "somelib.fields.ImageField", # # Positional args for field class. # ("Image",), # # Keyword args for field class. # {"blank": True, "upload_to": "blog"}, # ), # # Example of adding a field to *all* of Mezzanine's content types: # ( # "mezzanine.pages.models.Page.another_field", # "IntegerField", # 'django.db.models.' is implied if path is omitted. # ("Another name",), # {"blank": True, "default": 1}, # ), # ) # Setting to turn on featured images for blog posts. Defaults to False. # # BLOG_USE_FEATURED_IMAGE = True # If True, the south application will be automatically added to the # INSTALLED_APPS setting. USE_SOUTH = True ######################## # MAIN DJANGO SETTINGS # ######################## # People who get code error notifications. # In the format (('Full Name', '[email protected]'), # ('Full Name', '[email protected]')) ADMINS = ( # ('Your Name', '[email protected]'), ) MANAGERS = ADMINS # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # On Unix systems, a value of None will cause Django to use the same # timezone as the operating system. # If running in a Windows environment this must be set to the same as your # system time zone. TIME_ZONE = None # If you set this to True, Django will use timezone-aware datetimes. USE_TZ = True # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = "en" # Supported languages _ = lambda s: s LANGUAGES = ( ('en', _('English')), ) # A boolean that turns on/off debug mode. When set to ``True``, stack traces # are displayed for error pages. Should always be set to ``False`` in # production. Best set to ``True`` in local_settings.py DEBUG = False # Whether a user's session cookie expires when the Web browser is closed. SESSION_EXPIRE_AT_BROWSER_CLOSE = True SITE_ID = 1 # If you set this to False, Django will make some optimizations so as not # to load the internationalization machinery. USE_I18N = False # Tuple of IP addresses, as strings, that: # * See debug comments, when DEBUG is true # * Receive x-headers INTERNAL_IPS = ("127.0.0.1",) # List of callables that know how to import templates from various sources. TEMPLATE_LOADERS = ( "django.template.loaders.filesystem.Loader", "django.template.loaders.app_directories.Loader", ) AUTHENTICATION_BACKENDS = ("mezzanine.core.auth_backends.MezzanineBackend",) # List of finder classes that know how to find static files in # various locations. STATICFILES_FINDERS = ( "django.contrib.staticfiles.finders.FileSystemFinder", "django.contrib.staticfiles.finders.AppDirectoriesFinder", # 'django.contrib.staticfiles.finders.DefaultStorageFinder', ) # The numeric mode to set newly-uploaded files to. The value should be # a mode you'd pass directly to os.chmod. FILE_UPLOAD_PERMISSIONS = 0o644 ############# # DATABASES # ############# DATABASES = { "default": { # Add "postgresql_psycopg2", "mysql", "sqlite3" or "oracle". "ENGINE": "django.db.backends.", # DB name or path to database file if using sqlite3. "NAME": "", # Not used with sqlite3. "USER": "", # Not used with sqlite3. "PASSWORD": "", # Set to empty string for localhost. Not used with sqlite3. "HOST": "", # Set to empty string for default. Not used with sqlite3. "PORT": "", } } ######### # PATHS # ######### import os # Full filesystem path to the project. PROJECT_ROOT = os.path.dirname(os.path.abspath(__file__)) # Name of the directory for the project. PROJECT_DIRNAME = PROJECT_ROOT.split(os.sep)[-1] # Every cache key will get prefixed with this value - here we set it to # the name of the directory the project is in to try and use something # project specific. CACHE_MIDDLEWARE_KEY_PREFIX = PROJECT_DIRNAME # URL prefix for static files. # Example: "http://media.lawrence.com/static/" STATIC_URL = "/static/" # Absolute path to the directory static files should be collected to. # Don't put anything in this directory yourself; store your static files # in apps' "static/" subdirectories and in STATICFILES_DIRS. # Example: "/home/media/media.lawrence.com/static/" STATIC_ROOT = os.path.join(PROJECT_ROOT, STATIC_URL.strip("/")) # URL that handles the media served from MEDIA_ROOT. Make sure to use a # trailing slash. # Examples: "http://media.lawrence.com/media/", "http://example.com/media/" MEDIA_URL = STATIC_URL + "media/" # Absolute filesystem path to the directory that will hold user-uploaded files. # Example: "/home/media/media.lawrence.com/media/" MEDIA_ROOT = os.path.join(PROJECT_ROOT, *MEDIA_URL.strip("/").split("/")) # Package/module name to import the root urlpatterns from for the project. ROOT_URLCONF = "%s.urls" % PROJECT_DIRNAME # Put strings here, like "/home/html/django_templates" # or "C:/www/django/templates". # Always use forward slashes, even on Windows. # Don't forget to use absolute paths, not relative paths. TEMPLATE_DIRS = (os.path.join(PROJECT_ROOT, "templates"),) ################ # APPLICATIONS # ################ INSTALLED_APPS = ( "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.redirects", "django.contrib.sessions", "django.contrib.sites", "django.contrib.sitemaps", "django.contrib.staticfiles", "mezzanine.boot", "mezzanine.conf", "mezzanine.core", "mezzanine.generic", "mezzanine.blog", "mezzanine.forms", "mezzanine.pages", "mezzanine.galleries", "mezzanine.twitter", #"mezzanine.accounts", #"mezzanine.mobile", ) # List of processors used by RequestContext to populate the context. # Each one should be a callable that takes the request object as its # only parameter and returns a dictionary to add to the context. TEMPLATE_CONTEXT_PROCESSORS = ( "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", "django.core.context_processors.debug", "django.core.context_processors.i18n", "django.core.context_processors.static", "django.core.context_processors.media", "django.core.context_processors.request", "django.core.context_processors.tz", "mezzanine.conf.context_processors.settings", "mezzanine.pages.context_processors.page", ) # List of middleware classes to use. Order is important; in the request phase, # these middleware classes will be applied in the order given, and in the # response phase the middleware will be applied in reverse order. MIDDLEWARE_CLASSES = ( "mezzanine.core.middleware.UpdateCacheMiddleware", "django.contrib.sessions.middleware.SessionMiddleware", "django.middleware.locale.LocaleMiddleware", "django.contrib.auth.middleware.AuthenticationMiddleware", "django.middleware.common.CommonMiddleware", "django.middleware.csrf.CsrfViewMiddleware", "django.contrib.messages.middleware.MessageMiddleware", "mezzanine.core.request.CurrentRequestMiddleware", "mezzanine.core.middleware.RedirectFallbackMiddleware", "mezzanine.core.middleware.TemplateForDeviceMiddleware", "mezzanine.core.middleware.TemplateForHostMiddleware", "mezzanine.core.middleware.AdminLoginInterfaceSelectorMiddleware", "mezzanine.core.middleware.SitePermissionMiddleware", # Uncomment the following if using any of the SSL settings: # "mezzanine.core.middleware.SSLRedirectMiddleware", "mezzanine.pages.middleware.PageMiddleware", "mezzanine.core.middleware.FetchFromCacheMiddleware", ) # Store these package names here as they may change in the future since # at the moment we are using custom forks of them. PACKAGE_NAME_FILEBROWSER = "filebrowser_safe" PACKAGE_NAME_GRAPPELLI = "grappelli_safe" ######################### # OPTIONAL APPLICATIONS # ######################### # These will be added to ``INSTALLED_APPS``, only if available. OPTIONAL_APPS = ( "debug_toolbar", "django_extensions", "compressor", PACKAGE_NAME_FILEBROWSER, PACKAGE_NAME_GRAPPELLI, ) ################### # DEPLOY SETTINGS # ################### # These settings are used by the default fabfile.py provided. # Check fabfile.py for defaults. # FABRIC = { # "SSH_USER": "", # SSH username for host deploying to # "HOSTS": ALLOWED_HOSTS[:1], # List of hosts to deploy to (eg, first host) # "DOMAINS": ALLOWED_HOSTS, # Domains for public site # "REPO_URL": "ssh://[email protected]/user/project", # Project's repo URL # "VIRTUALENV_HOME": "", # Absolute remote path for virtualenvs # "PROJECT_NAME": "", # Unique identifier for project # "REQUIREMENTS_PATH": "requirements.txt", # Project's pip requirements # "GUNICORN_PORT": 8000, # Port gunicorn will listen on # "LOCALE": "en_US.UTF-8", # Should end with ".UTF-8" # "DB_PASS": "", # Live database password # "ADMIN_PASS": "", # Live admin user password # "SECRET_KEY": SECRET_KEY, # "NEVERCACHE_KEY": NEVERCACHE_KEY, # } ################## # LOCAL SETTINGS # ################## # Allow any settings to be defined in local_settings.py which should be # ignored in your version control system allowing for settings to be # defined per machine. try: from local_settings import * except ImportError: pass #################### # DYNAMIC SETTINGS # #################### # set_dynamic_settings() will rewrite globals based on what has been # defined so far, in order to provide some better defaults where # applicable. We also allow this settings module to be imported # without Mezzanine installed, as the case may be when using the # fabfile, where setting the dynamic settings below isn't strictly # required. try: from mezzanine.utils.conf import set_dynamic_settings except ImportError: pass else: set_dynamic_settings(globals())
asyncTest('isPlainObject', function () { expect(15); var iframe; // The use case that we want to match ok(can.isPlainObject({}), '{}'); // Not objects shouldn't be matched ok(!can.isPlainObject(''), 'string'); ok(!can.isPlainObject(0) && !can.isPlainObject(1), 'number'); ok(!can.isPlainObject(true) && !can.isPlainObject(false), 'boolean'); ok(!can.isPlainObject(null), 'null'); ok(!can.isPlainObject(undefined), 'undefined'); // Arrays shouldn't be matched ok(!can.isPlainObject([]), 'array'); // Instantiated objects shouldn't be matched ok(!can.isPlainObject(new Date()), 'new Date'); var fnplain = function () {}; // Functions shouldn't be matched ok(!can.isPlainObject(fnplain), 'fn'); /** @constructor */ var fn = function () {}; // Again, instantiated objects shouldn't be matched ok(!can.isPlainObject(new fn()), 'new fn (no methods)'); // Makes the function a little more realistic // (and harder to detect, incidentally) fn.prototype.someMethod = function () {}; // Again, instantiated objects shouldn't be matched ok(!can.isPlainObject(new fn()), 'new fn'); // DOM Element ok(!can.isPlainObject(document.createElement('div')), 'DOM Element'); // Window ok(!can.isPlainObject(window), 'window'); try { can.isPlainObject(window.location); ok(true, 'Does not throw exceptions on host objects'); } catch (e) { ok(false, 'Does not throw exceptions on host objects -- FAIL'); } try { iframe = document.createElement('iframe'); document.body.appendChild(iframe); window.iframeDone = function (otherObject) { // Objects from other windows should be matched ok(can.isPlainObject(new otherObject()), 'new otherObject'); document.body.removeChild(iframe); start(); }; var doc = iframe.contentDocument || iframe.contentWindow.document; doc.open(); doc.write('<body onload=\'window.parent.iframeDone(Object);\'>'); doc.close(); } catch (e) { document.body.removeChild(iframe); ok(true, 'new otherObject - iframes not supported'); start(); } });
const { dbModify } = require("../../utils/db"); const { baseConfig } = require("../../utils/checks"); const { serverLog } = require("../../utils/logs"); const { fetchUser } = require("../../utils/misc.js"); const { string } = require("../../utils/strings"); module.exports = { controls: { name: "unblock", permission: 3, usage: "unblock [user]", aliases: ["allow", "unbl"], description: "Unblocks a user from using the bot in this server", enabled: true, examples: "`{{p}}unblock @Brightness™`\nUnblocks Brightness™ from using the bot in this server\n\n`{{p}}unblock 255834596766253057 Accidentally blocked`\nUnblocks a user with ID 255834596766253057 from using the bot in this server with reason \"Accidentally blocked\"", permissions: ["VIEW_CHANNEL", "SEND_MESSAGES", "USE_EXTERNAL_EMOJIS"], cooldown: 5 }, do: async (locale, message, client, args, Discord) => { let [returned, qServerDB] = await baseConfig(locale, message.guild); if (returned) return message.channel.send(returned); let guildLocale = qServerDB.config.locale; if (!args[0]) return message.channel.send(string(locale, "BLOCK_NO_ARGS_ERROR", {}, "error")); let user = await fetchUser(args[0], client); if (!user || user.id === "0") return message.channel.send(string(locale, "INVALID_USER_ERROR", {}, "error")); if (!qServerDB.config.blocklist.includes(user.id) && !qServerDB.config.blocklist.find(b => b.id === user.id && b.expires > Date.now())) return message.channel.send(string(locale, "USER_NOT_BLOCKED_ERROR", {}, "error")); let reason; if (args[1]) { reason = args.splice(1).join(" "); if (reason.length > 1024) return message.channel.send(string(locale, "BLOCK_REASON_TOO_LONG_ERROR", {}, "error")); } qServerDB.config.blocklist.splice(qServerDB.config.blocklist.findIndex(u => typeof u === "object" ? u.id === user.id : u === user.id), 1); await dbModify("Server", { id: message.guild.id }, qServerDB); message.channel.send(`${string(locale, "UNBLOCK_SUCCESS", { user: user.tag, id: user.id },"success")}${reason ? `\n> ${string(locale, "BLOCK_REASON_HEADER")} ${reason}` : ""}`, { disableMentions: "all" }); if (qServerDB.config.channels.log) { let logEmbed = new Discord.MessageEmbed() .setAuthor(string(guildLocale, "UNBLOCK_LOG_TITLE", { staff: message.author.tag, user: user.tag }), message.author.displayAvatarURL({format: "png", dynamic: true})) .setDescription(string(guildLocale, "BLOCK_USER_DATA", { tag: user.tag, id: user.id, mention: `<@${user.id}>` })) .setFooter(string(guildLocale, "STAFF_MEMBER_LOG_FOOTER", { id: message.author.id })) .setTimestamp() .setColor(client.colors.green); reason ? logEmbed.addField(string(guildLocale, "BLOCK_REASON_HEADER"), reason) : null; serverLog(logEmbed, qServerDB, client); } } };
# -*- coding: utf-8 -*- """Identity Services Engine getAllSXPLocalBindings data model. Copyright (c) 2021 Cisco and/or its affiliates. Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. """ from __future__ import ( absolute_import, division, print_function, unicode_literals, ) import fastjsonschema import json from ciscoisesdk.exceptions import MalformedRequest from builtins import * class JSONSchemaValidatorF845Bd746A5C00967FE66178C5Edbf(object): """getAllSXPLocalBindings request schema definition.""" def __init__(self): super(JSONSchemaValidatorF845Bd746A5C00967FE66178C5Edbf, self).__init__() self._validator = fastjsonschema.compile(json.loads( '''{ "$schema": "http://json-schema.org/draft-04/schema#", "properties": { "SearchResult": { "properties": { "nextPage": { "properties": { "href": { "type": "string" }, "rel": { "type": "string" }, "type": { "type": "string" } }, "type": "object" }, "previousPage": { "properties": { "href": { "type": "string" }, "rel": { "type": "string" }, "type": { "type": "string" } }, "type": "object" }, "resources": { "items": { "properties": { "description": { "type": "string" }, "id": { "type": "string" }, "link": { "properties": { "href": { "type": "string" }, "rel": { "type": "string" }, "type": { "type": "string" } }, "type": "object" }, "name": { "type": "string" } }, "type": "object" }, "type": "array" }, "total": { "type": "integer" } }, "type": "object" } }, "required": [ "SearchResult" ], "type": "object" }'''.replace("\n" + ' ' * 16, '') )) def validate(self, request): try: self._validator(request) except fastjsonschema.exceptions.JsonSchemaException as e: raise MalformedRequest( '{} is invalid. Reason: {}'.format(request, e.message) )
import warnings from collections import OrderedDict from pathlib import Path from pkg_resources import EntryPoint from . import ICompiler as ICompilerModule from . import defaults, utils from .KaitaiCompilerException import KaitaiCompilerException defaultPriority = 0 class BackendDescriptor: __slots__ = ("entryPoint", "name", "prio", "issues") def __init__(self, entryPoint: EntryPoint, name: str, prio: int = defaultPriority, issues: set = None) -> None: self.entryPoint = entryPoint self.name = name self.prio = prio if issues: issues = set(issues) self.issues = issues @property def broken(self) -> bool: return self.prio < 0 def recognizeBackends(b: EntryPoint) -> BackendDescriptor: if hasattr(b.__class__, "__slots__") and "metadata" in b.__class__.__slots__: metadata = b.metadata else: encoded = b.name.split("@", 1) b.name = encoded[0] if len(encoded) > 1: try: metadata = utils.json.loads(encoded[1]) except BaseException: warnings.warn("Entry point " + repr(b) + " is invalid. The value after @ must be must be a valid JSON!.") return BackendDescriptor(b, b.name, prio=-1) # broken, so not using else: metadata = None if metadata is not None: if isinstance(metadata, int): return BackendDescriptor(b, b.name, prio=metadata) # it is priority elif isinstance(metadata, dict): return BackendDescriptor(b, b.name, **metadata) else: warnings.warn("Entry point " + repr(b) + " is invalid. The value after @ must be must be eithera dict, or a number!.") return BackendDescriptor(b, b.name, prio=-1) # broken, so not using else: return BackendDescriptor(b, b.name) def discoverBackends() -> OrderedDict: import pkg_resources pts = pkg_resources.iter_entry_points(group="kaitai_struct_compile") backendsList = sorted(filter(lambda b: not b.broken, map(recognizeBackends, pts)), key=lambda b: b.prio, reverse=True) return OrderedDict(((b.name, b) for b in backendsList)) discoveredBackends = discoverBackends() def selectBackend(tolerableIssues=None, backendsPresent=None, forcedBackend=None) -> None: if backendsPresent is None: backendsPresent = discoveredBackends if tolerableIssues is None: tolerableIssues = utils.getTolerableIssuesFromEnv() if forcedBackend is None: forcedBackend = utils.getForcedBackendFromEnv() if forcedBackend: backendsPresent = {forcedBackend: backendsPresent[forcedBackend]} for b in backendsPresent.values(): if b.issues: if b.issues - tolerableIssues: continue try: init = b.entryPoint.load() return init(ICompilerModule, KaitaiCompilerException, utils, defaults) except Exception as ex: warnings.warn(repr(ex) + " when loading backend " + b.entryPoint.name) pass ChosenBackend = selectBackend()
(window["webpackJsonp"]=window["webpackJsonp"]||[]).push([[779],{CZrw:function(e,a,c){"use strict";c.r(a);var t=c("q1tI"),i={icon:{tag:"svg",attrs:{viewBox:"64 64 896 896",focusable:"false"},children:[{tag:"path",attrs:{d:"M512 64C264.6 64 64 264.6 64 512s200.6 448 448 448 448-200.6 448-448S759.4 64 512 64zm-44.4 672C353.1 736 236 680.4 236 588.9c0-47.8 30.2-103.1 82.3-155.3 69.5-69.6 150.6-101.4 181.1-70.8 13.5 13.5 14.8 36.8 6.1 64.6-4.5 14 13.1 6.3 13.1 6.3 56.2-23.6 105.2-25 123.1.7 9.6 13.7 8.6 32.8-.2 55.1-4.1 10.2 1.3 11.8 9 14.1 31.7 9.8 66.9 33.6 66.9 75.5.2 69.5-99.7 156.9-249.8 156.9zm207.3-290.8a34.9 34.9 0 00-7.2-34.1 34.68 34.68 0 00-33.1-10.7 18.24 18.24 0 01-7.6-35.7c24.1-5.1 50.1 2.3 67.7 21.9 17.7 19.6 22.4 46.3 14.9 69.8a18.13 18.13 0 01-22.9 11.7 18.18 18.18 0 01-11.8-22.9zm106 34.3s0 .1 0 0a21.1 21.1 0 01-26.6 13.7 21.19 21.19 0 01-13.6-26.7c11-34.2 4-73.2-21.7-101.8a104.04 104.04 0 00-98.9-32.1 21.14 21.14 0 01-25.1-16.3 21.07 21.07 0 0116.2-25.1c49.4-10.5 102.8 4.8 139.1 45.1 36.3 40.2 46.1 95.1 30.6 143.2zm-334.5 6.1c-91.4 9-160.7 65.1-154.7 125.2 5.9 60.1 84.8 101.5 176.2 92.5 91.4-9.1 160.7-65.1 154.7-125.3-5.9-60.1-84.8-101.5-176.2-92.4zm80.2 141.7c-18.7 42.3-72.3 64.8-117.8 50.1-43.9-14.2-62.5-57.7-43.3-96.8 18.9-38.4 68-60.1 111.5-48.8 45 11.7 68 54.2 49.6 95.5zm-93-32.2c-14.2-5.9-32.4.2-41.2 13.9-8.8 13.8-4.7 30.2 9.3 36.6 14.3 6.5 33.2.3 42-13.8 8.8-14.3 4.2-30.6-10.1-36.7zm34.9-14.5c-5.4-2.2-12.2.5-15.4 5.8-3.1 5.4-1.4 11.5 4.1 13.8 5.5 2.3 12.6-.3 15.8-5.8 3-5.6 1-11.8-4.5-13.8z"}}]},name:"weibo-circle",theme:"outlined"},n=i,r=c("6VBw"),s=function(e,a){return t["createElement"](r["a"],Object.assign({},e,{ref:a,icon:n}))};s.displayName="WeiboCircleOutlined";a["default"]=t["forwardRef"](s)}}]);
// @flow export { default } from './Overlay.web';
webpackJsonp([0],[function(e,t,r){"use strict";r(1);var o=r(2),n=r(24);o.platformBrowserDynamic().bootstrapModule(n.AppModule)},function(e,t){e.exports="// removed by extract-text-webpack-plugin"},,,,,,,,,,,,,,,,,,,,,,,function(e,t,r){"use strict";var o=this&&this.__decorate||function(e,t,r,o){var n,s=arguments.length,i=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(n=e[c])&&(i=(s<3?n(i):s>3?n(t,r,i):n(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=r(4),i=r(22),c=r(25),a=r(26),p=r(36),d=r(42),h=r(53),l=function(){function AppModule(){}return AppModule}();l=o([s.NgModule({imports:[i.BrowserModule,c.HttpModule,a.InMemoryWebApiModule.forRoot(h.InMemoryEntryService)],providers:[d.EntryService],declarations:[p.AppComponent,d.EntryComponent,d.EntryListComponent],bootstrap:[p.AppComponent]}),n("design:paramtypes",[])],l),t.AppModule=l},,function(e,t,r){!function(e,o){o(t,r(4),r(25),r(6),r(27))}(this,function(e,t,r,o,n){"use strict";function createErrorResponse(e,t,o){return new r.ResponseOptions({body:{error:""+o},url:e.url,headers:new r.Headers({"Content-Type":"application/json"}),status:t})}function createObservableResponse(e,t){return new o.Observable(function(r){return emitResponse(r,e,t),function(){}})}function emitResponse(e,t,o){o.url=o.url||t.url,o=setStatusText(o);var n=new r.Response(o);isSuccess(n.status)?(e.next(n),e.complete()):e.error(n)}function removeTrailingSlash(e){return e.replace(/\/$/,"")}function isSuccess(e){return e>=200&&e<300}function setStatusText(e){try{var t=i[e.status];return e.statusText=t?t.text:"Unknown Status",e}catch(e){return new r.ResponseOptions({status:s.INTERNAL_SERVER_ERROR,statusText:"Invalid Server Operation"})}}function inMemoryBackendServiceFactory(e,t,r){var o=new d(e,t,r);return o}var s={CONTINUE:100,SWITCHING_PROTOCOLS:101,OK:200,CREATED:201,ACCEPTED:202,NON_AUTHORITATIVE_INFORMATION:203,NO_CONTENT:204,RESET_CONTENT:205,PARTIAL_CONTENT:206,MULTIPLE_CHOICES:300,MOVED_PERMANTENTLY:301,FOUND:302,SEE_OTHER:303,NOT_MODIFIED:304,USE_PROXY:305,TEMPORARY_REDIRECT:307,BAD_REQUEST:400,UNAUTHORIZED:401,PAYMENT_REQUIRED:402,FORBIDDEN:403,NOT_FOUND:404,METHOD_NOT_ALLOWED:405,NOT_ACCEPTABLE:406,PROXY_AUTHENTICATION_REQUIRED:407,REQUEST_TIMEOUT:408,CONFLICT:409,GONE:410,LENGTH_REQUIRED:411,PRECONDITION_FAILED:412,PAYLOAD_TO_LARGE:413,URI_TOO_LONG:414,UNSUPPORTED_MEDIA_TYPE:415,RANGE_NOT_SATISFIABLE:416,EXPECTATION_FAILED:417,IM_A_TEAPOT:418,UPGRADE_REQUIRED:426,INTERNAL_SERVER_ERROR:500,NOT_IMPLEMENTED:501,BAD_GATEWAY:502,SERVICE_UNAVAILABLE:503,GATEWAY_TIMEOUT:504,HTTP_VERSION_NOT_SUPPORTED:505,PROCESSING:102,MULTI_STATUS:207,IM_USED:226,PERMANENT_REDIRECT:308,UNPROCESSABLE_ENTRY:422,LOCKED:423,FAILED_DEPENDENCY:424,PRECONDITION_REQUIRED:428,TOO_MANY_REQUESTS:429,REQUEST_HEADER_FIELDS_TOO_LARGE:431,UNAVAILABLE_FOR_LEGAL_REASONS:451,VARIANT_ALSO_NEGOTIATES:506,INSUFFICIENT_STORAGE:507,NETWORK_AUTHENTICATION_REQUIRED:511},i={100:{code:100,text:"Continue",description:'"The initial part of a request has been received and has not yet been rejected by the server."',spec_title:"RFC7231#6.2.1",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.2.1"},101:{code:101,text:"Switching Protocols",description:'"The server understands and is willing to comply with the client\'s request, via the Upgrade header field, for a change in the application protocol being used on this connection."',spec_title:"RFC7231#6.2.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.2.2"},200:{code:200,text:"OK",description:'"The request has succeeded."',spec_title:"RFC7231#6.3.1",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.1"},201:{code:201,text:"Created",description:'"The request has been fulfilled and has resulted in one or more new resources being created."',spec_title:"RFC7231#6.3.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.2"},202:{code:202,text:"Accepted",description:'"The request has been accepted for processing, but the processing has not been completed."',spec_title:"RFC7231#6.3.3",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.3"},203:{code:203,text:"Non-Authoritative Information",description:'"The request was successful but the enclosed payload has been modified from that of the origin server\'s 200 (OK) response by a transforming proxy."',spec_title:"RFC7231#6.3.4",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.4"},204:{code:204,text:"No Content",description:'"The server has successfully fulfilled the request and that there is no additional content to send in the response payload body."',spec_title:"RFC7231#6.3.5",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.5"},205:{code:205,text:"Reset Content",description:'"The server has fulfilled the request and desires that the user agent reset the "document view", which caused the request to be sent, to its original state as received from the origin server."',spec_title:"RFC7231#6.3.6",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.6"},206:{code:206,text:"Partial Content",description:'"The server is successfully fulfilling a range request for the target resource by transferring one or more parts of the selected representation that correspond to the satisfiable ranges found in the requests\'s Range header field."',spec_title:"RFC7233#4.1",spec_href:"http://tools.ietf.org/html/rfc7233#section-4.1"},300:{code:300,text:"Multiple Choices",description:'"The target resource has more than one representation, each with its own more specific identifier, and information about the alternatives is being provided so that the user (or user agent) can select a preferred representation by redirecting its request to one or more of those identifiers."',spec_title:"RFC7231#6.4.1",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.1"},301:{code:301,text:"Moved Permanently",description:'"The target resource has been assigned a new permanent URI and any future references to this resource ought to use one of the enclosed URIs."',spec_title:"RFC7231#6.4.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.2"},302:{code:302,text:"Found",description:'"The target resource resides temporarily under a different URI."',spec_title:"RFC7231#6.4.3",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.3"},303:{code:303,text:"See Other",description:'"The server is redirecting the user agent to a different resource, as indicated by a URI in the Location header field, that is intended to provide an indirect response to the original request."',spec_title:"RFC7231#6.4.4",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.4"},304:{code:304,text:"Not Modified",description:'"A conditional GET request has been received and would have resulted in a 200 (OK) response if it were not for the fact that the condition has evaluated to false."',spec_title:"RFC7232#4.1",spec_href:"http://tools.ietf.org/html/rfc7232#section-4.1"},305:{code:305,text:"Use Proxy",description:"*deprecated*",spec_title:"RFC7231#6.4.5",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.5"},307:{code:307,text:"Temporary Redirect",description:'"The target resource resides temporarily under a different URI and the user agent MUST NOT change the request method if it performs an automatic redirection to that URI."',spec_title:"RFC7231#6.4.7",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.4.7"},400:{code:400,text:"Bad Request",description:'"The server cannot or will not process the request because the received syntax is invalid, nonsensical, or exceeds some limitation on what the server is willing to process."',spec_title:"RFC7231#6.5.1",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.1"},401:{code:401,text:"Unauthorized",description:'"The request has not been applied because it lacks valid authentication credentials for the target resource."',spec_title:"RFC7235#6.3.1",spec_href:"http://tools.ietf.org/html/rfc7235#section-3.1"},402:{code:402,text:"Payment Required",description:"*reserved*",spec_title:"RFC7231#6.5.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.2"},403:{code:403,text:"Forbidden",description:'"The server understood the request but refuses to authorize it."',spec_title:"RFC7231#6.5.3",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.3"},404:{code:404,text:"Not Found",description:'"The origin server did not find a current representation for the target resource or is not willing to disclose that one exists."',spec_title:"RFC7231#6.5.4",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.4"},405:{code:405,text:"Method Not Allowed",description:'"The method specified in the request-line is known by the origin server but not supported by the target resource."',spec_title:"RFC7231#6.5.5",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.5"},406:{code:406,text:"Not Acceptable",description:'"The target resource does not have a current representation that would be acceptable to the user agent, according to the proactive negotiation header fields received in the request, and the server is unwilling to supply a default representation."',spec_title:"RFC7231#6.5.6",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.6"},407:{code:407,text:"Proxy Authentication Required",description:'"The client needs to authenticate itself in order to use a proxy."',spec_title:"RFC7231#6.3.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.3.2"},408:{code:408,text:"Request Timeout",description:'"The server did not receive a complete request message within the time that it was prepared to wait."',spec_title:"RFC7231#6.5.7",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.7"},409:{code:409,text:"Conflict",description:'"The request could not be completed due to a conflict with the current state of the resource."',spec_title:"RFC7231#6.5.8",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.8"},410:{code:410,text:"Gone",description:'"Access to the target resource is no longer available at the origin server and that this condition is likely to be permanent."',spec_title:"RFC7231#6.5.9",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.9"},411:{code:411,text:"Length Required",description:'"The server refuses to accept the request without a defined Content-Length."',spec_title:"RFC7231#6.5.10",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.10"},412:{code:412,text:"Precondition Failed",description:'"One or more preconditions given in the request header fields evaluated to false when tested on the server."',spec_title:"RFC7232#4.2",spec_href:"http://tools.ietf.org/html/rfc7232#section-4.2"},413:{code:413,text:"Payload Too Large",description:'"The server is refusing to process a request because the request payload is larger than the server is willing or able to process."',spec_title:"RFC7231#6.5.11",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.11"},414:{code:414,text:"URI Too Long",description:'"The server is refusing to service the request because the request-target is longer than the server is willing to interpret."',spec_title:"RFC7231#6.5.12",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.12"},415:{code:415,text:"Unsupported Media Type",description:'"The origin server is refusing to service the request because the payload is in a format not supported by the target resource for this method."',spec_title:"RFC7231#6.5.13",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.13"},416:{code:416,text:"Range Not Satisfiable",description:'"None of the ranges in the request\'s Range header field overlap the current extent of the selected resource or that the set of ranges requested has been rejected due to invalid ranges or an excessive request of small or overlapping ranges."',spec_title:"RFC7233#4.4",spec_href:"http://tools.ietf.org/html/rfc7233#section-4.4"},417:{code:417,text:"Expectation Failed",description:'"The expectation given in the request\'s Expect header field could not be met by at least one of the inbound servers."',spec_title:"RFC7231#6.5.14",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.14"},418:{code:418,text:"I'm a teapot",description:'"1988 April Fools Joke. Returned by tea pots requested to brew coffee."',spec_title:"RFC 2324",spec_href:"https://tools.ietf.org/html/rfc2324"},426:{code:426,text:"Upgrade Required",description:'"The server refuses to perform the request using the current protocol but might be willing to do so after the client upgrades to a different protocol."',spec_title:"RFC7231#6.5.15",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.5.15"},500:{code:500,text:"Internal Server Error",description:'"The server encountered an unexpected condition that prevented it from fulfilling the request."',spec_title:"RFC7231#6.6.1",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.1"},501:{code:501,text:"Not Implemented",description:'"The server does not support the functionality required to fulfill the request."',spec_title:"RFC7231#6.6.2",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.2"},502:{code:502,text:"Bad Gateway",description:'"The server, while acting as a gateway or proxy, received an invalid response from an inbound server it accessed while attempting to fulfill the request."',spec_title:"RFC7231#6.6.3",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.3"},503:{code:503,text:"Service Unavailable",description:'"The server is currently unable to handle the request due to a temporary overload or scheduled maintenance, which will likely be alleviated after some delay."',spec_title:"RFC7231#6.6.4",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.4"},504:{code:504,text:"Gateway Time-out",description:'"The server, while acting as a gateway or proxy, did not receive a timely response from an upstream server it needed to access in order to complete the request."',spec_title:"RFC7231#6.6.5",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.5"},505:{code:505,text:"HTTP Version Not Supported",description:'"The server does not support, or refuses to support, the protocol version that was used in the request message."',spec_title:"RFC7231#6.6.6",spec_href:"http://tools.ietf.org/html/rfc7231#section-6.6.6"},102:{code:102,text:"Processing",description:'"An interim response to inform the client that the server has accepted the complete request, but has not yet completed it."',spec_title:"RFC5218#10.1",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.1"},207:{code:207,text:"Multi-Status",description:'"Status for multiple independent operations."',spec_title:"RFC5218#10.2",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.2"},226:{code:226,text:"IM Used",description:'"The server has fulfilled a GET request for the resource, and the response is a representation of the result of one or more instance-manipulations applied to the current instance."',spec_title:"RFC3229#10.4.1",spec_href:"http://tools.ietf.org/html/rfc3229#section-10.4.1"},308:{code:308,text:"Permanent Redirect",description:'"The target resource has been assigned a new permanent URI and any future references to this resource SHOULD use one of the returned URIs. [...] This status code is similar to 301 Moved Permanently (Section 7.3.2 of rfc7231), except that it does not allow rewriting the request method from POST to GET."',spec_title:"RFC7238",spec_href:"http://tools.ietf.org/html/rfc7238"},422:{code:422,text:"Unprocessable Entity",description:'"The server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions."',spec_title:"RFC5218#10.3",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.3"},423:{code:423,text:"Locked",description:'"The source or destination resource of a method is locked."',spec_title:"RFC5218#10.4",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.4"},424:{code:424,text:"Failed Dependency",description:'"The method could not be performed on the resource because the requested action depended on another action and that action failed."',spec_title:"RFC5218#10.5",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.5"},428:{code:428,text:"Precondition Required",description:'"The origin server requires the request to be conditional."',spec_title:"RFC6585#3",spec_href:"http://tools.ietf.org/html/rfc6585#section-3"},429:{code:429,text:"Too Many Requests",description:'"The user has sent too many requests in a given amount of time ("rate limiting")."',spec_title:"RFC6585#4",spec_href:"http://tools.ietf.org/html/rfc6585#section-4"},431:{code:431,text:"Request Header Fields Too Large",description:'"The server is unwilling to process the request because its header fields are too large."',spec_title:"RFC6585#5",spec_href:"http://tools.ietf.org/html/rfc6585#section-5"},451:{code:451,text:"Unavailable For Legal Reasons",description:'"The server is denying access to the resource in response to a legal demand."',spec_title:"draft-ietf-httpbis-legally-restricted-status",spec_href:"http://tools.ietf.org/html/draft-ietf-httpbis-legally-restricted-status"},506:{code:506,text:"Variant Also Negotiates",description:'"The server has an internal configuration error: the chosen variant resource is configured to engage in transparent content negotiation itself, and is therefore not a proper end point in the negotiation process."',spec_title:"RFC2295#8.1",spec_href:"http://tools.ietf.org/html/rfc2295#section-8.1"},507:{code:507,text:"Insufficient Storage",description:'The method could not be performed on the resource because the server is unable to store the representation needed to successfully complete the request."',spec_title:"RFC5218#10.6",spec_href:"http://tools.ietf.org/html/rfc2518#section-10.6"},511:{code:511,text:"Network Authentication Required",description:'"The client needs to authenticate to gain network access."',spec_title:"RFC6585#6",spec_href:"http://tools.ietf.org/html/rfc6585#section-6"}},c=function(){function InMemoryDbService(){}return InMemoryDbService}(),a=function(){function InMemoryBackendConfigArgs(){}return InMemoryBackendConfigArgs}(),p=function(){function InMemoryBackendConfig(e){void 0===e&&(e={}),Object.assign(this,{caseSensitiveSearch:!1,defaultResponseOptions:new r.BaseResponseOptions,delay:500,delete404:!1,passThruUnknownUrl:!1,post204:!0,put204:!0,apiBase:void 0,host:void 0,rootPath:void 0},e)}return InMemoryBackendConfig.decorators=[{type:t.Injectable}],InMemoryBackendConfig.ctorParameters=function(){return[{type:a}]},InMemoryBackendConfig}(),d=function(){function InMemoryBackendService(e,t,r){this.injector=e,this.inMemDbService=t,this.config=new p,this.resetDb();var o=this.getLocation("./");this.config.host=o.host,this.config.rootPath=o.pathname,Object.assign(this.config,r||{}),this.setPassThruBackend()}return InMemoryBackendService.prototype.createConnection=function(e){var t;try{t=this.handleRequest(e)}catch(r){var o=r.message||r,n=createErrorResponse(e,s.INTERNAL_SERVER_ERROR,""+o);t=this.addDelay(createObservableResponse(e,n))}return{readyState:r.ReadyState.Done,request:e,response:t}},InMemoryBackendService.prototype.handleRequest=function(e){var t,o=this.inMemDbService.parseUrl?this.inMemDbService.parseUrl(e.url):this.parseUrl(e.url),n=o.base,i=o.collectionName,c=o.id,a=o.query,p=o.resourceUrl,d=this.db[i],h={req:e,base:n,collection:d,collectionName:i,headers:new r.Headers({"Content-Type":"application/json"}),id:this.parseId(d,c),query:a,resourceUrl:p},l=r.RequestMethod[e.method||0].toLowerCase();if(/commands\/$/i.test(h.base))return this.commands(h);if(this.inMemDbService[l]){var f={requestInfo:h,db:this.db,config:this.config,passThruBackend:this.passThruBackend},u=this.inMemDbService[l](f);return this.addDelay(u)}return h.collection?this.addDelay(this.collectionHandler(h)):this.passThruBackend?this.passThruBackend.createConnection(e).response:(t=createErrorResponse(e,s.NOT_FOUND,"Collection '"+i+"' not found"),this.addDelay(createObservableResponse(e,t)))},InMemoryBackendService.prototype.addDelay=function(e){var t=this.config.delay;return 0===t?e:e.delay(t||500)},InMemoryBackendService.prototype.applyQuery=function(e,t){var r=[],o=this.config.caseSensitiveSearch?void 0:"i";t.paramsMap.forEach(function(e,t){e.forEach(function(e){return r.push({name:t,rx:new RegExp(decodeURI(e),o)})})});var n=r.length;return n?e.filter(function(e){for(var t=!0,o=n;t&&o;){o-=1;var s=r[o];t=s.rx.test(e[s.name])}return t}):e},InMemoryBackendService.prototype.clone=function(e){return JSON.parse(JSON.stringify(e))},InMemoryBackendService.prototype.collectionHandler=function(e){var t=this,n=e.req;return new o.Observable(function(o){var i;switch(n.method){case r.RequestMethod.Get:i=t.get(e);break;case r.RequestMethod.Post:i=t.post(e);break;case r.RequestMethod.Put:i=t.put(e);break;case r.RequestMethod.Delete:i=t.delete(e);break;default:i=createErrorResponse(n,s.METHOD_NOT_ALLOWED,"Method not allowed")}return t.inMemDbService.responseInterceptor&&(i=t.inMemDbService.responseInterceptor(i,e)),emitResponse(o,e.req,i),function(){}})},InMemoryBackendService.prototype.commands=function(e){var t,o=e.collectionName.toLowerCase(),n=e.req.method;switch(o){case"resetdb":this.resetDb(),t=new r.ResponseOptions({status:s.OK});break;case"config":if(n===r.RequestMethod.Get)t=new r.ResponseOptions({body:this.clone(this.config),status:s.OK});else{var i=JSON.parse(e.req.text()||"{}");Object.assign(this.config,i),this.setPassThruBackend(),t=new r.ResponseOptions({status:s.NO_CONTENT})}break;default:t=createErrorResponse(e.req,s.INTERNAL_SERVER_ERROR,'Unknown command "'+o+'"')}return createObservableResponse(e.req,t)},InMemoryBackendService.prototype.delete=function(e){var t=e.id,o=e.collection,n=e.collectionName,i=e.headers,c=e.req;if(!t)return createErrorResponse(c,s.NOT_FOUND,'Missing "'+n+'" id');var a=this.removeById(o,t);return new r.ResponseOptions({headers:i,status:a||!this.config.delete404?s.NO_CONTENT:s.NOT_FOUND})},InMemoryBackendService.prototype.findById=function(e,t){return e.find(function(e){return e.id===t})},InMemoryBackendService.prototype.genId=function(e){var t=0;return e.reduce(function(e,r){t=Math.max(t,"number"==typeof r.id?r.id:t)},void 0),t+1},InMemoryBackendService.prototype.get=function(e){var t=e.id,o=e.query,n=e.collection,i=e.collectionName,c=e.headers,a=e.req,p=n;return t?p=this.findById(n,t):o&&(p=this.applyQuery(n,o)),p?new r.ResponseOptions({body:{data:this.clone(p)},headers:c,status:s.OK}):createErrorResponse(a,s.NOT_FOUND,"'"+i+"' with id='"+t+"' not found")},InMemoryBackendService.prototype.getLocation=function(e){var t=document.createElement("a");return t.href=e,t},InMemoryBackendService.prototype.indexOf=function(e,t){return e.findIndex(function(e){return e.id===t})},InMemoryBackendService.prototype.parseId=function(e,t){if(e&&void 0!=t){var r=e[0]&&"number"==typeof e[0].id;if(r){var o=parseFloat(t);return isNaN(o)?t:o}return t}},InMemoryBackendService.prototype.parseUrl=function(e){try{var t=this.getLocation(e),o=this.config.rootPath.length,n="";t.host!==this.config.host&&(o=1,n=t.protocol+"//"+t.host+"/");var s=t.pathname.substring(o),i=s.split("/"),c=0,a=void 0;void 0==this.config.apiBase?a=i[c++]:(a=removeTrailingSlash(this.config.apiBase.trim()),c=a?a.split("/").length:0),a+="/";var p=i[c++];p=p&&p.split(".")[0];var d=i[c++],h=t.search&&new r.URLSearchParams(t.search.substr(1)),l=n+a+p+"/";return{base:a,collectionName:p,id:d,query:h,resourceUrl:l}}catch(t){var f="unable to parse url '"+e+"'; original error: "+t.message;throw new Error(f)}},InMemoryBackendService.prototype.post=function(e){var t=e.collection,o=e.headers,n=e.id,i=e.req,c=e.resourceUrl,a=JSON.parse(i.text());void 0==a.id&&(a.id=n||this.genId(t)),n=a.id;var p=this.indexOf(t,n),d={data:this.clone(a)};if(p>-1){t[p]=a;var h=this.config.post204?{headers:o,status:s.NO_CONTENT}:{headers:o,body:d,status:s.OK};return new r.ResponseOptions(h)}return t.push(a),o.set("Location",c+"/"+n),new r.ResponseOptions({headers:o,body:d,status:s.CREATED})},InMemoryBackendService.prototype.put=function(e){var t=e.id,o=e.collection,n=e.collectionName,i=e.headers,c=e.req,a=JSON.parse(c.text());if(void 0==a.id)return createErrorResponse(c,s.NOT_FOUND,"Missing '"+n+"' id");if(t!==a.id)return createErrorResponse(c,s.BAD_REQUEST,'"'+n+'" id does not match item.id');var p=this.indexOf(o,t),d={data:this.clone(a)};if(p>-1){o[p]=a;var h=this.config.put204?{headers:i,status:s.NO_CONTENT}:{headers:i,body:d,status:s.OK};return new r.ResponseOptions(h)}return o.push(a),new r.ResponseOptions({headers:i,body:d,status:s.CREATED})},InMemoryBackendService.prototype.removeById=function(e,t){var r=this.indexOf(e,t);return r>-1&&(e.splice(r,1),!0)},InMemoryBackendService.prototype.resetDb=function(){this.db=this.inMemDbService.createDb()},InMemoryBackendService.prototype.setPassThruBackend=function(){if(this.passThruBackend=void 0,this.config.passThruUnknownUrl)try{var e=this.injector.get(r.BrowserXhr),t=this.injector.get(r.ResponseOptions),o=this.injector.get(r.XSRFStrategy);this.passThruBackend=new r.XHRBackend(e,t,o)}catch(e){throw e.message="Cannot create passThru404 backend; "+(e.message||""),e}},InMemoryBackendService.decorators=[{type:t.Injectable}],InMemoryBackendService.ctorParameters=function(){return[{type:t.Injector},{type:c},{type:a,decorators:[{type:t.Inject,args:[p]},{type:t.Optional}]}]},InMemoryBackendService}(),h=function(){function InMemoryWebApiModule(){}return InMemoryWebApiModule.forRoot=function(e,t){return{ngModule:InMemoryWebApiModule,providers:[{provide:c,useClass:e},{provide:p,useValue:t}]}},InMemoryWebApiModule.decorators=[{type:t.NgModule,args:[{providers:[{provide:r.XHRBackend,useFactory:inMemoryBackendServiceFactory,deps:[t.Injector,c,p]}]}]}],InMemoryWebApiModule.ctorParameters=function(){return[]},InMemoryWebApiModule}();e.STATUS=s,e.STATUS_CODE_INFO=i,e.createErrorResponse=createErrorResponse,e.createObservableResponse=createObservableResponse,e.emitResponse=emitResponse,e.InMemoryDbService=c,e.InMemoryBackendConfigArgs=a,e.removeTrailingSlash=removeTrailingSlash,e.InMemoryBackendConfig=p,e.isSuccess=isSuccess,e.setStatusText=setStatusText,e.InMemoryBackendService=d,e.inMemoryBackendServiceFactory=inMemoryBackendServiceFactory,e.InMemoryWebApiModule=h,Object.defineProperty(e,"__esModule",{value:!0})})},,,,,,,,,,function(e,t,r){"use strict";var o=this&&this.__decorate||function(e,t,r,o){var n,s=arguments.length,i=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(n=e[c])&&(i=(s<3?n(i):s>3?n(t,r,i):n(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=r(4);r(37);var i=function(){function AppComponent(){this.emoji=["🎉","😍","😜","👍"]}return AppComponent.prototype.changeEmoji=function(){this.activeEmoji=this.emoji[Math.floor(Math.random()*this.emoji.length)]},AppComponent}();i=o([s.Component({selector:"app-root",template:r(41)}),n("design:paramtypes",[])],i),t.AppComponent=i},function(e,t){},,,,function(e,t){e.exports="<h1 (click)=changeEmoji()>Hello Angular {{activeEmoji}}</h1>\r\n\r\n<app-entry-list></app-entry-list>\r\n"},function(e,t,r){"use strict";function __export(e){for(var r in e)t.hasOwnProperty(r)||(t[r]=e[r])}__export(r(43)),__export(r(44)),__export(r(48))},function(e,t,r){"use strict";var o=this&&this.__decorate||function(e,t,r,o){var n,s=arguments.length,i=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(n=e[c])&&(i=(s<3?n(i):s>3?n(t,r,i):n(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)},s=r(4),i=r(25),c=function(){function EntryService(e){this.http=e}return EntryService.prototype.getEntries=function(){return this.http.get("/app/entries").toPromise().then(function(e){return e.json().data})},EntryService}();c=o([s.Injectable(),n("design:paramtypes",[i.Http])],c),t.EntryService=c},function(e,t,r){"use strict";var o=this&&this.__decorate||function(e,t,r,o){var n,s=arguments.length,i=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(n=e[c])&&(i=(s<3?n(i):s>3?n(t,r,i):n(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};r(45);var s=r(4),i=r(43),c=function(){function EntryListComponent(e){this.entryService=e}return EntryListComponent.prototype.ngOnInit=function(){var e=this;this.entryService.getEntries().then(function(t){return e.entries=t})},EntryListComponent}();c=o([s.Component({selector:"app-entry-list",template:r(47)}),n("design:paramtypes",[i.EntryService])],c),t.EntryListComponent=c},37,,function(e,t){e.exports='<app-entry *ngFor="let entry of entries" [entry]="entry">\r\n\r\n</app-entry>\r\n'},function(e,t,r){"use strict";var o=this&&this.__decorate||function(e,t,r,o){var n,s=arguments.length,i=s<3?t:null===o?o=Object.getOwnPropertyDescriptor(t,r):o;if("object"==typeof Reflect&&"function"==typeof Reflect.decorate)i=Reflect.decorate(e,t,r,o);else for(var c=e.length-1;c>=0;c--)(n=e[c])&&(i=(s<3?n(i):s>3?n(t,r,i):n(t,r))||i);return s>3&&i&&Object.defineProperty(t,r,i),i},n=this&&this.__metadata||function(e,t){if("object"==typeof Reflect&&"function"==typeof Reflect.metadata)return Reflect.metadata(e,t)};r(49);var s=r(4),i=r(51),c=function(){function EntryComponent(){}return EntryComponent}();o([s.Input(),n("design:type",i.Entry)],c.prototype,"entry",void 0),c=o([s.Component({selector:"app-entry",template:r(52)}),n("design:paramtypes",[])],c),t.EntryComponent=c},37,,function(e,t){"use strict";var r=function(){function Entry(){}return Entry}();t.Entry=r},function(e,t){e.exports='\r\n<figure>\r\n\r\n <h2>{{entry.title}}</h2>\r\n\r\n <img src="{{entry.photo}}">\r\n\r\n <figcaption>{{entry.description}}</figcaption>\r\n\r\n</figure>\r\n\r\n<div class="actions">\r\n\r\n <button type=\'button\' (click)=\'isLiked = !isLiked\' [ngClass]="{liked: isLiked}">♥</button>\r\n\r\n <button type=\'button\' (click)=\'showComments = !showComments\' >Comments: {{entry.comments.length}}</button>\r\n\r\n</div>\r\n\r\n<div class="comments" *ngIf="showComments">\r\n\r\n <div class="comment" *ngFor="let comment of entry.comments">\r\n\r\n <p><strong>{{comment.name}}:</strong> {{comment.comment}}</p>\r\n\r\n </div>\r\n\r\n</div>\r\n'},function(e,t,r){"use strict";var o=function(){function InMemoryEntryService(){}return InMemoryEntryService.prototype.createDb=function(){var e=[{id:1,title:"Burning Sundown Behind Trees",description:"A view of the setting sun through trees",photo:r(54),comments:[{id:1,name:"Jane Smith",comment:"This is my favorite! I love it!"}]},{id:2,title:"Water Lilies and Algas",description:"Still water with floating lilies",photo:r(55),comments:[{id:2,name:"Kyle Jones",comment:"Nice!"},{id:3,name:"Alecia Clark",comment:"All the greens make this amazing."}]},{id:3,title:"German Steam Engine",description:"Trains at the station",photo:r(56),comments:[]},{id:4,title:"Red Sun Stripe at Horizon",description:"Green fields and a glimpse of sunlight",photo:r(57),comments:[{id:4,name:"Steve Johnson",comment:"It looks like trouble is on the way." },{id:5,name:"Becky M",comment:"I imagine this was a shot of a storm that just passed."}]},{id:5,title:"Sundown Behind Fields",description:"Clouds taking form at sun set",photo:r(58),comments:[{id:6,name:"Lisa Frank",comment:"Beautiful!"}]}];return{entries:e}},InMemoryEntryService}();t.InMemoryEntryService=o},function(e,t,r){e.exports=r.p+"/assets/Burning-sundown-behind-trees.e021ce0bd0c4b835a803b1cb84bd654d.jpg"},function(e,t,r){e.exports=r.p+"/assets/Water-lilies-and-algas.be15b89f33e23be6195a8a39d59856ce.jpg"},function(e,t,r){e.exports=r.p+"/assets/German-steam-engine-No.4.f732e5a9a9942cfc6a3592f6df31835a.jpg"},function(e,t,r){e.exports=r.p+"/assets/Red-sun-stripe-at-horizon.0335b6c2e00bde48d380c5fc0f783210.jpg"},function(e,t,r){e.exports=r.p+"/assets/Sundown-behind-fields.519215051a43091704d1ad35184811ef.jpg"}]); //# sourceMappingURL=app.61ee373360722f5e4219.js.map
/** * @file main * @author imcuttle * @date 2018/4/4 */ // const injectInfoPlugin = require('../src') describe('injectInfoPlugin', function () { it.skip('should spec', function () {}) })
# Copyright 2015 The TensorFlow Authors. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. # ============================================================================== """Utilities used by convolution layers.""" from __future__ import absolute_import from __future__ import division from __future__ import print_function import itertools import numpy as np from six.moves import range # pylint: disable=redefined-builtin from tensorflow.python.frozen_keras import backend def convert_data_format(data_format, ndim): if data_format == 'channels_last': if ndim == 3: return 'NWC' elif ndim == 4: return 'NHWC' elif ndim == 5: return 'NDHWC' else: raise ValueError('Input rank not supported:', ndim) elif data_format == 'channels_first': if ndim == 3: return 'NCW' elif ndim == 4: return 'NCHW' elif ndim == 5: return 'NCDHW' else: raise ValueError('Input rank not supported:', ndim) else: raise ValueError('Invalid data_format:', data_format) def normalize_tuple(value, n, name): """Transforms a single integer or iterable of integers into an integer tuple. Arguments: value: The value to validate and convert. Could an int, or any iterable of ints. n: The size of the tuple to be returned. name: The name of the argument being validated, e.g. "strides" or "kernel_size". This is only used to format error messages. Returns: A tuple of n integers. Raises: ValueError: If something else than an int/long or iterable thereof was passed. """ if isinstance(value, int): return (value,) * n else: try: value_tuple = tuple(value) except TypeError: raise ValueError('The `' + name + '` argument must be a tuple of ' + str(n) + ' integers. Received: ' + str(value)) if len(value_tuple) != n: raise ValueError('The `' + name + '` argument must be a tuple of ' + str(n) + ' integers. Received: ' + str(value)) for single_value in value_tuple: try: int(single_value) except (ValueError, TypeError): raise ValueError('The `' + name + '` argument must be a tuple of ' + str(n) + ' integers. Received: ' + str(value) + ' ' 'including element ' + str(single_value) + ' of type' + ' ' + str(type(single_value))) return value_tuple def conv_output_length(input_length, filter_size, padding, stride, dilation=1): """Determines output length of a convolution given input length. Arguments: input_length: integer. filter_size: integer. padding: one of "same", "valid", "full", "causal" stride: integer. dilation: dilation rate, integer. Returns: The output length (integer). """ if input_length is None: return None assert padding in {'same', 'valid', 'full', 'causal'} dilated_filter_size = filter_size + (filter_size - 1) * (dilation - 1) if padding in ['same', 'causal']: output_length = input_length elif padding == 'valid': output_length = input_length - dilated_filter_size + 1 elif padding == 'full': output_length = input_length + dilated_filter_size - 1 return (output_length + stride - 1) // stride def conv_input_length(output_length, filter_size, padding, stride): """Determines input length of a convolution given output length. Arguments: output_length: integer. filter_size: integer. padding: one of "same", "valid", "full". stride: integer. Returns: The input length (integer). """ if output_length is None: return None assert padding in {'same', 'valid', 'full'} if padding == 'same': pad = filter_size // 2 elif padding == 'valid': pad = 0 elif padding == 'full': pad = filter_size - 1 return (output_length - 1) * stride - 2 * pad + filter_size def deconv_output_length(input_length, filter_size, padding, output_padding=None, stride=0, dilation=1): """Determines output length of a transposed convolution given input length. Arguments: input_length: Integer. filter_size: Integer. padding: one of `"same"`, `"valid"`, `"full"`. output_padding: Integer, amount of padding along the output dimension. Can be set to `None` in which case the output length is inferred. stride: Integer. dilation: Integer. Returns: The output length (integer). """ assert padding in {'same', 'valid', 'full'} if input_length is None: return None # Get the dilated kernel size filter_size = filter_size + (filter_size - 1) * (dilation - 1) # Infer length if output padding is None, else compute the exact length if output_padding is None: if padding == 'valid': length = input_length * stride + max(filter_size - stride, 0) elif padding == 'full': length = input_length * stride - (stride + filter_size - 2) elif padding == 'same': length = input_length * stride else: if padding == 'same': pad = filter_size // 2 elif padding == 'valid': pad = 0 elif padding == 'full': pad = filter_size - 1 length = ((input_length - 1) * stride + filter_size - 2 * pad + output_padding) return length def normalize_data_format(value): if value is None: value = backend.image_data_format() data_format = value.lower() if data_format not in {'channels_first', 'channels_last'}: raise ValueError('The `data_format` argument must be one of ' '"channels_first", "channels_last". Received: ' + str(value)) return data_format def normalize_padding(value): if isinstance(value, (list, tuple)): return value padding = value.lower() if padding not in {'valid', 'same', 'causal'}: raise ValueError('The `padding` argument must be a list/tuple or one of ' '"valid", "same" (or "causal", only for `Conv1D). ' 'Received: ' + str(padding)) return padding def convert_kernel(kernel): """Converts a Numpy kernel matrix from Theano format to TensorFlow format. Also works reciprocally, since the transformation is its own inverse. This is used for converting legacy Theano-saved model files. Arguments: kernel: Numpy array (3D, 4D or 5D). Returns: The converted kernel. Raises: ValueError: in case of invalid kernel shape or invalid data_format. """ kernel = np.asarray(kernel) if not 3 <= kernel.ndim <= 5: raise ValueError('Invalid kernel shape:', kernel.shape) slices = [slice(None, None, -1) for _ in range(kernel.ndim)] no_flip = (slice(None, None), slice(None, None)) slices[-2:] = no_flip return np.copy(kernel[slices]) def conv_kernel_mask(input_shape, kernel_shape, strides, padding): """Compute a mask representing the connectivity of a convolution operation. Assume a convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)` to produce an output with shape `(d_out1, ..., d_outN)`. This method returns a boolean array of shape `(d_in1, ..., d_inN, d_out1, ..., d_outN)` with `True` entries indicating pairs of input and output locations that are connected by a weight. Example: >>> input_shape = (4,) >>> kernel_shape = (2,) >>> strides = (1,) >>> padding = "valid" >>> conv_kernel_mask(input_shape, kernel_shape, strides, padding) array([[ True, False, False], [ True, True, False], [False, True, True], [False, False, True]]) where rows and columns correspond to inputs and outputs respectively. Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. Returns: A boolean 2N-D `np.ndarray` of shape `(d_in1, ..., d_inN, d_out1, ..., d_outN)`, where `(d_out1, ..., d_outN)` is the spatial shape of the output. `True` entries in the mask represent pairs of input-output locations that are connected by a weight. Raises: ValueError: if `input_shape`, `kernel_shape` and `strides` don't have the same number of dimensions. NotImplementedError: if `padding` is not in {`"same"`, `"valid"`}. """ if padding not in {'same', 'valid'}: raise NotImplementedError('Padding type %s not supported. ' 'Only "valid" and "same" ' 'are implemented.' % padding) in_dims = len(input_shape) if isinstance(kernel_shape, int): kernel_shape = (kernel_shape,) * in_dims if isinstance(strides, int): strides = (strides,) * in_dims kernel_dims = len(kernel_shape) stride_dims = len(strides) if kernel_dims != in_dims or stride_dims != in_dims: raise ValueError('Number of strides, input and kernel dimensions must all ' 'match. Received: %d, %d, %d.' % (stride_dims, in_dims, kernel_dims)) output_shape = conv_output_shape(input_shape, kernel_shape, strides, padding) mask_shape = input_shape + output_shape mask = np.zeros(mask_shape, np.bool) output_axes_ticks = [range(dim) for dim in output_shape] for output_position in itertools.product(*output_axes_ticks): input_axes_ticks = conv_connected_inputs(input_shape, kernel_shape, output_position, strides, padding) for input_position in itertools.product(*input_axes_ticks): mask[input_position + output_position] = True return mask def conv_kernel_idxs(input_shape, kernel_shape, strides, padding, filters_in, filters_out, data_format): """Yields output-input tuples of indices in a CNN layer. The generator iterates over all `(output_idx, input_idx)` tuples, where `output_idx` is an integer index in a flattened tensor representing a single output image of a convolutional layer that is connected (via the layer weights) to the respective single input image at `input_idx` Example: >>> input_shape = (2, 2) >>> kernel_shape = (2, 1) >>> strides = (1, 1) >>> padding = "valid" >>> filters_in = 1 >>> filters_out = 1 >>> data_format = "channels_last" >>> list(conv_kernel_idxs(input_shape, kernel_shape, strides, padding, ... filters_in, filters_out, data_format)) [(0, 0), (0, 2), (1, 1), (1, 3)] Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. filters_in: `int`, number if filters in the input to the layer. filters_out: `int', number if filters in the output of the layer. data_format: string, "channels_first" or "channels_last". Yields: The next tuple `(output_idx, input_idx)`, where `output_idx` is an integer index in a flattened tensor representing a single output image of a convolutional layer that is connected (via the layer weights) to the respective single input image at `input_idx`. Raises: ValueError: if `data_format` is neither `"channels_last"` nor `"channels_first"`, or if number of strides, input, and kernel number of dimensions do not match. NotImplementedError: if `padding` is neither `"same"` nor `"valid"`. """ if padding not in ('same', 'valid'): raise NotImplementedError('Padding type %s not supported. ' 'Only "valid" and "same" ' 'are implemented.' % padding) in_dims = len(input_shape) if isinstance(kernel_shape, int): kernel_shape = (kernel_shape,) * in_dims if isinstance(strides, int): strides = (strides,) * in_dims kernel_dims = len(kernel_shape) stride_dims = len(strides) if kernel_dims != in_dims or stride_dims != in_dims: raise ValueError('Number of strides, input and kernel dimensions must all ' 'match. Received: %d, %d, %d.' % (stride_dims, in_dims, kernel_dims)) output_shape = conv_output_shape(input_shape, kernel_shape, strides, padding) output_axes_ticks = [range(dim) for dim in output_shape] if data_format == 'channels_first': concat_idxs = lambda spatial_idx, filter_idx: (filter_idx,) + spatial_idx elif data_format == 'channels_last': concat_idxs = lambda spatial_idx, filter_idx: spatial_idx + (filter_idx,) else: raise ValueError('Data format %s not recognized.' '`data_format` must be "channels_first" or ' '"channels_last".' % data_format) for output_position in itertools.product(*output_axes_ticks): input_axes_ticks = conv_connected_inputs(input_shape, kernel_shape, output_position, strides, padding) for input_position in itertools.product(*input_axes_ticks): for f_in in range(filters_in): for f_out in range(filters_out): out_idx = np.ravel_multi_index( multi_index=concat_idxs(output_position, f_out), dims=concat_idxs(output_shape, filters_out)) in_idx = np.ravel_multi_index( multi_index=concat_idxs(input_position, f_in), dims=concat_idxs(input_shape, filters_in)) yield (out_idx, in_idx) def conv_connected_inputs(input_shape, kernel_shape, output_position, strides, padding): """Return locations of the input connected to an output position. Assume a convolution with given parameters is applied to an input having N spatial dimensions with `input_shape = (d_in1, ..., d_inN)`. This method returns N ranges specifying the input region that was convolved with the kernel to produce the output at position `output_position = (p_out1, ..., p_outN)`. Example: >>> input_shape = (4, 4) >>> kernel_shape = (2, 1) >>> output_position = (1, 1) >>> strides = (1, 1) >>> padding = "valid" >>> conv_connected_inputs(input_shape, kernel_shape, output_position, ... strides, padding) [range(1, 3), range(1, 2)] Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. output_position: tuple of size N: `(p_out1, ..., p_outN)`, a single position in the output of the convolution. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. Returns: N ranges `[[p_in_left1, ..., p_in_right1], ..., [p_in_leftN, ..., p_in_rightN]]` specifying the region in the input connected to output_position. """ ranges = [] ndims = len(input_shape) for d in range(ndims): left_shift = int(kernel_shape[d] / 2) right_shift = kernel_shape[d] - left_shift center = output_position[d] * strides[d] if padding == 'valid': center += left_shift start = max(0, center - left_shift) end = min(input_shape[d], center + right_shift) ranges.append(range(start, end)) return ranges def conv_output_shape(input_shape, kernel_shape, strides, padding): """Return the output shape of an N-D convolution. Forces dimensions where input is empty (size 0) to remain empty. Args: input_shape: tuple of size N: `(d_in1, ..., d_inN)`, spatial shape of the input. kernel_shape: tuple of size N, spatial shape of the convolutional kernel / receptive field. strides: tuple of size N, strides along each spatial dimension. padding: type of padding, string `"same"` or `"valid"`. Returns: tuple of size N: `(d_out1, ..., d_outN)`, spatial shape of the output. """ dims = range(len(kernel_shape)) output_shape = [ conv_output_length(input_shape[d], kernel_shape[d], padding, strides[d]) for d in dims ] output_shape = tuple( [0 if input_shape[d] == 0 else output_shape[d] for d in dims]) return output_shape
export default { lang: 'de', dir: 'ltr', common: { ok: 'OK', cancel: 'Abbrechen', key_backspace: 'Rücktaste', key_del: 'Löschen', key_down: 'nach unten', key_up: 'nach oben', more_opts: 'Mehr Optionen', url: 'URL', width: 'Breite', height: 'Höhe' }, misc: { powered_by: 'powered by' }, ui: { toggle_stroke_tools: 'Zeige/Verberge weitere Linien-Werkzeuge', palette_info: 'Klick zum Ändern der Füllfarbe, Shift-Klick zum Ändern der Linienfarbe', zoom_level: 'vergrößern', panel_drag: 'Nach links/rechts ziehen, um die Größe vom Seitenpanel zu ändern', quality: 'Quality:', pathNodeTooltip: 'Drag node to move it. Double-click node to change segment type', pathCtrlPtTooltip: 'Drag control point to adjust curve properties', pick_stroke_paint_opacity: 'Pick a Stroke Paint and Opacity', pick_fill_paint_opacity: 'Pick a Fill Paint and Opacity' }, properties: { id: 'Element identifizieren', fill_color: 'Füllfarbe ändern', stroke_color: 'Linienfarbe ändern', stroke_style: 'Linienstil ändern', stroke_width: 'Linienbreite ändern', pos_x: 'Ändere die X-Koordinate', pos_y: 'Ändere die Y-Koordinate', linecap_butt: 'Form der Linienendung: Stumpf', linecap_round: 'Form der Linienendung: Rund', linecap_square: 'Form der Linienendung: Rechteckig', linejoin_bevel: 'Zusammentreffen von zwei Linien: abgeschrägte Kante', linejoin_miter: 'Zusammentreffen von zwei Linien: Gehrung', linejoin_round: 'Zusammentreffen von zwei Linien: Rund', angle: 'Drehwinkel ändern', blur: 'Ändere Wert des Gaußschen Weichzeichners', opacity: 'Opazität des ausgewählten Objekts ändern', circle_cx: 'Kreiszentrum (cx) ändern', circle_cy: 'Kreiszentrum (cy) ändern', circle_r: 'Kreisradius (r) ändern', ellipse_cx: 'Ellipsenzentrum (cx) ändern', ellipse_cy: 'Ellipsenzentrum (cy) ändern', ellipse_rx: 'Ellipsenradius (x) ändern', ellipse_ry: 'Ellipsenradius (y) ändern', line_x1: 'X-Koordinate des Linienanfangs ändern', line_x2: 'X-Koordinate des Linienendes ändern', line_y1: 'Y-Koordinate des Linienanfangs ändern', line_y2: 'Y-Koordinate des Linienendes ändern', rect_height: 'Höhe des Rechtecks ändern', rect_width: 'Breite des Rechtecks ändern', corner_radius: 'Eckenradius des Rechtecks ändern', image_width: 'Bildbreite ändern', image_height: 'Bildhöhe ändern', image_url: 'URL ändern', node_x: 'Ändere die X-Koordinate des Knoten', node_y: 'Ändere die Y-Koordinate des Knoten', seg_type: 'Ändere den Typ des Segments', straight_segments: 'Gerade', curve_segments: 'Kurve', text_contents: 'Textinhalt erstellen und bearbeiten', font_family: 'Schriftart wählen', font_size: 'Schriftgröße einstellen', bold: 'Fetter Text', italic: 'Kursiver Text', text_anchor_start: 'Den Text linksbündig ausrichten', text_anchor_middle: 'Den Text zentriert ausrichten', text_anchor_end: 'Den Text rechtsbündig ausrichten' }, tools: { main_menu: 'Hauptmenü', bkgnd_color_opac: 'Hintergrundfarbe ändern / Opazität', connector_no_arrow: 'Kein Pfeil', fitToContent: 'An den Inhalt anpassen', fit_to_all: 'An gesamten Inhalt anpassen', fit_to_canvas: 'An die Zeichenfläche anpassen', fit_to_layer_content: 'An Inhalt der Ebene anpassen', fit_to_sel: 'An die Auswahl anpassen', align_relative_to: 'Relativ zu einem anderem Objekt ausrichten …', relativeTo: 'im Vergleich zu:', page: 'Seite', largest_object: 'größtes Objekt', selected_objects: 'gewählte Objekte', smallest_object: 'kleinstes Objekt', new_doc: 'Neues Bild', open_doc: 'Bild öffnen', export_img: 'Export', save_doc: 'Bild speichern', import_doc: 'Importiere SVG', align_to_page: 'Element an Seite ausrichten', align_bottom: 'Unten ausrichten', align_center: 'Zentriert ausrichten', align_left: 'Linksbündig ausrichten', align_middle: 'In der Mitte ausrichten', align_right: 'Rechtsbündig ausrichten', align_top: 'Oben ausrichten', mode_select: 'Objekte auswählen und verändern', mode_fhpath: 'Freihandlinien zeichnen', mode_line: 'Linien zeichnen', mode_rect: 'Rechteck-Werkzeug', mode_square: 'Quadrat-Werkzeug', mode_fhrect: 'Freihand-Rechteck', mode_ellipse: 'Ellipse', mode_circle: 'Kreis', mode_fhellipse: 'Freihand-Ellipse', mode_path: 'Pfad zeichnen', mode_text: 'Text erstellen und bearbeiten', mode_image: 'Bild einfügen', mode_zoom: 'Zoomfaktor vergrößern oder verringern', no_embed: 'Hinweis: Dieses Bild kann nicht eingebettet werden. Eine Anzeige hängt von diesem Pfad ab.', undo: 'Rückgängig', redo: 'Wiederherstellen', tool_source: 'Quellcode bearbeiten', wireframe_mode: 'Drahtmodell-Modus', clone: 'Element(e) klonen', del: 'Element(e) löschen', group_elements: 'Element(e) gruppieren', make_link: 'Link erstellen', set_link_url: 'Link setzen (leer lassen zum Entfernen)', to_path: 'Gewähltes Objekt in einen Pfad konvertieren', reorient_path: 'Neuausrichtung des Pfades', ungroup: 'Gruppierung aufheben', docprops: 'Dokument-Eigenschaften', editor_homepage: 'SVG-Edit Home Page', move_bottom: 'Die gewählten Objekte nach ganz unten verschieben', move_top: 'Die gewählten Objekte nach ganz oben verschieben', node_clone: 'Klone den Knoten', node_delete: 'Lösche den Knoten', node_link: 'Gekoppelte oder separate Kontrollpunkte für die Bearbeitung des Pfades', add_subpath: 'Teilpfad hinzufügen', openclose_path: 'Öffne/Verbinde Unterpfad', source_save: 'Änderungen akzeptieren', cut: 'Ausschneiden', copy: 'Kopieren', paste: 'Einfügen', paste_in_place: 'Bei Originalposition einfügen', delete: 'Löschen', group: 'Gruppieren', move_front: 'Nach ganz oben verschieben', move_up: 'Hochschieben', move_down: 'Herunterschieben', move_back: 'Nach ganz unten verschieben' }, layers: { layer: 'Ebene', layers: 'Ebenen', del: 'Ebene löschen', move_down: 'Ebene nach unten verschieben', new: 'Neue Ebene', rename: 'Ebene umbenennen', move_up: 'Ebene nach oben verschieben', dupe: 'Ebene duplizieren', merge_down: 'Nach unten zusammenführen', merge_all: 'Alle zusammenführen', move_elems_to: 'Verschiebe ausgewählte Objekte:', move_selected: 'Verschiebe ausgewählte Objekte auf eine andere Ebene' }, config: { image_props: 'Bildeigenschaften', doc_title: 'Titel', doc_dims: 'Dimension der Zeichenfläche', included_images: 'Eingefügte Bilder', image_opt_embed: 'Daten einbetten (lokale Dateien)', image_opt_ref: 'Benutze die Dateireferenz', editor_prefs: 'Editor-Einstellungen', icon_size: 'Symbol-Abmessungen', language: 'Sprache', background: 'Editor-Hintergrund', editor_img_url: 'Bild-URL', editor_bg_note: 'Anmerkung: Der Hintergrund wird mit dem Bild nicht gespeichert.', icon_large: 'Groß', icon_medium: 'Mittel', icon_small: 'Klein', icon_xlarge: 'Sehr Groß', select_predefined: 'Auswahl einer vordefinierten:', units_and_rulers: 'Einheiten und Lineale', show_rulers: 'Zeige Lineale', base_unit: 'Basiseinheit:', grid: 'Gitternetz', snapping_onoff: 'Einrasten an/aus', snapping_stepsize: 'Einrastabstand:', grid_color: 'Gitterfarbe' }, notification: { invalidAttrValGiven: 'Fehlerhafter Wert', noContentToFitTo: 'Kein Inhalt anzupassen', dupeLayerName: 'Eine Ebene hat bereits diesen Namen', enterUniqueLayerName: 'Verwenden Sie einen eindeutigen Namen für die Ebene', enterNewLayerName: 'Geben Sie bitte einen neuen Namen für die Ebene ein', layerHasThatName: 'Eine Ebene hat bereits diesen Namen', QmoveElemsToLayer: "Verschiebe ausgewählte Objekte in die Ebene '%s'?", QwantToClear: 'Möchten Sie die Zeichnung löschen?\nDadurch wird auch die Rückgängig-Funktion zurückgesetzt!', QwantToOpen: 'Möchten Sie eine neue Datei öffnen?\nDadurch wird auch die Rückgängig-Funktion zurückgesetzt!', QerrorsRevertToSource: 'Es gibt Parser-Fehler in der SVG-Quelle.\nDie Original-SVG wiederherstellen?', QignoreSourceChanges: 'Sollen die Änderungen an der SVG-Quelle ignoriert werden?', featNotSupported: 'Diese Eigenschaft wird nicht unterstützt', enterNewImgURL: 'Geben Sie die URL für das neue Bild an', defsFailOnSave: 'Hinweis: Aufgrund eines Fehlers in Ihrem Browser kann dieses Bild falsch angezeigt werden (fehlende Gradienten oder Elemente). Es wird jedoch richtig angezeigt, sobald es gespeichert wird.', loadingImage: 'Bild wird geladen, bitte warten ...', saveFromBrowser: "Select 'Save As...' in your browser (possibly via file menu or right-click context-menu) to save this image as a {{type}} file.", noteTheseIssues: 'Beachten Sie außerdem die folgenden Probleme: ', unsavedChanges: 'Es sind nicht-gespeicherte Änderungen vorhanden.', enterNewLinkURL: 'Geben Sie die neue URL ein', errorLoadingSVG: 'Fehler: Kann SVG-Daten nicht laden', URLLoadFail: 'Kann von dieser URL nicht laden', retrieving: "Retrieving '%s' ...", popupWindowBlocked: 'Popup window may be blocked by browser', exportNoBlur: 'Blurred elements will appear as un-blurred', exportNoforeignObject: 'foreignObject elements will not appear', exportNoDashArray: 'Strokes will appear filled', exportNoText: 'Text may not appear as expected' } };
$(document).ready(function(){ $("#guardar").click(function(validar){ var buscar=$("#palabra").val(); var nombres=$("#nombres").val(); var apellidos=$("#apellidos").val(); var foto=$("#imagen").val(); if(buscar.length=="" && nombres.length=="" && apellidos.length=="" && foto.length==""){ $("#palabra").focus(); $("#palabra").css({"border":"2px solid red"}); $("#validarpalabra").fadeIn(1000); $("#nombres").css({"border":"2px solid red"}); $("#validarnombre").fadeIn(1000); $("#apellidos").css({"border":"2px solid red"}); $("#validarapellidos").fadeIn(1000); $("#imagen").css({"border":"2px solid red"}); $("#validarimagen").fadeIn(1000); return false; }else{ $("#validarpalabra").fadeOut(); $("#validarnombre").fadeOut(); $("#validarapellidos").fadeOut(); $("#validarimagen").fadeOut(); } if(foto.length==""){ $("#imagen").css({"border":"2px solid red"}); $("#validarimagen").fadeIn(1000); return false; } }); $("#palabra").keypress(function(){ var buscar=$("#palabra").val(); if(buscar!=""){ $("#palabra").css({"border":"none"}); $("#validarpalabra").fadeOut(); }else{ $("#palabra").css({"border":"2px solid red"}); $("#validarpalabra").fadeIn(1000); } }); $("#nombres").keypress(function(){ var nombres=$("#nombres").val(); if(nombres!=""){ $("#nombres").css({"border":"none"}); $("#validarnombre").fadeOut(); }else{ $("#nombres").css({"border":"2px solid red"}); $("#validarnombre").fadeIn(1000); } }); $("#apellidos").keypress(function(){ var apellidos=$("#apellidos").val(); if(apellidos!=""){ $("#apellidos").css({"border":"none"}); $("#validarapellidos").fadeOut(); }else{ $("#apellidos").css({"border":"2px solid red"}); $("#validarapellidos").fadeIn(1000); } }); $("#imagen").keypress(function(){ var imagen=$("#imagen").val(); if(imagen.val()!=""){ $("#imagen").css({"border":"none"}); $("#validarimagen").fadeOut(); }else{ $("#imagen").css({"border":"2px solid red"}); $("#validarimagen").fadeIn(1000); }}); });
import React, { useState } from "react" import XIcon from "../../shared/XIcon" const GlobalNetworkSection = () => { const countries = [ { class: "argentina", title: "Argentina", items: ["Travel", "Experiences", "Innovation"], }, { class: "brazil", title: "Brazil", items: ["Travel", "Experiences"], }, { class: "uruguay", title: "Uruguay", items: ["Travel", "Experiences"], }, { class: "colombia", title: "Colombia", items: ["Experiences"], }, { class: "chile", title: "Chile", items: ["Travel"], }, { class: "peru", title: "Peru", items: ["Travel", "Experiences"], }, { class: "paraguay", title: "Paraguay", items: ["Travel", "Experiences"], }, { class: "ecuador", title: "Ecuador", items: ["Experiences"], }, { class: "mexico", title: "Mexico", items: ["Travel", "Experiences"], }, { class: "usa", title: "USA", items: ["Experiences"], }, { class: "canada", title: "Canada", items: ["Experiences"], }, { class: "india", title: "India", items: ["Experiences"], }, { class: "singapore", title: "Singapore", items: ["Experiences"], }, { class: "spain", title: "Spain", items: ["Travel"], }, { class: "turkish", title: "Turkey", items: ["Travel"], }, { class: "centroamerica", title: "Centro América", items: ["Travel", "Experiences"], }, { class: "south-africa", title: "South Africa", items: ["Experiences"], }, { class: "south-korea", title: "South Korea", items: ["Experiences"], }, { class: "honk-kong", title: "Honk Kong", items: ["Experiences"], }, { class: "japan", title: "Japan", items: ["Experiences"], }, ] const [selectedCountry, setSelectedCountry] = useState(countries[0]) const selectCountry = country => { console.log("selected is: ", country) setSelectedCountry(country) } const selectCountryMobile = e => { const countryIndex = e.target.value setSelectedCountry(countries[countryIndex]) } return ( <section className="home__global" id="network"> <div className="container px-0 py-5"> <div className="home__global--title has-text-centered"> <h3 className="is-size-4 has-text-primary"> Global Network </h3> <p> Our <b>adventurous spirit</b> moves us to keep always developing our business network. </p> <p> We have operations in more tan <b>10 countries</b> on different continents. </p> </div> <div className="columns is-multiline is-centered py-5 my-5"> <div className="column is-5-tablet is-3-desktop info-container"> <div className="select-mobile"> <select name="countries" onChange={selectCountryMobile} id="#countries-select" > {countries.map((country, i) => ( <option value={i}>{country.title}</option> ))} </select> </div> <div className="map-info"> <h4 className="is-size-5 has-text-primary mb-5"> {selectedCountry.title} </h4> <ul className="map-info--list"> {selectedCountry.items.map((item, i) => ( <li key={`selected-item-${i}`}>{item}</li> ))} </ul> </div> </div> <div className="column is-12 is-6-desktop has-text-centered"> <div className="dynamic-map"> <img src="/map.svg" alt="MAPA" /> {countries.map((country, i) => ( <button key={i} className={country.class} title={country.title} onClick={() => selectCountry(country)} ></button> ))} </div> </div> <div className="column is-hidden-mobile is-3"></div> </div> <div className="home__global--x-icon"> <a href="#"> <XIcon width="25px" height="25px" color="#0066FF" /> </a> </div> </div> </section> ) } export default GlobalNetworkSection
import Plugin from '@ckeditor/ckeditor5-core/src/plugin'; import Collection from '@ckeditor/ckeditor5-utils/src/collection'; import { addListToDropdown, createDropdown ,addToolbarToDropdown} from '@ckeditor/ckeditor5-ui/src/dropdown/utils'; import uploadEditing from './uploadEditing.js' //引入命令 import FileDialogButtonView from '@ckeditor/ckeditor5-upload/src/ui/filedialogbuttonview'; export default class uploadVideoButton extends Plugin { static get requires() { return [ uploadEditing ]; } init() { const editor = this.editor; editor.ui.componentFactory.add( 'uploadVideo', locale => { const dropdownView = createDropdown( locale,); //创建可下拉视图 dropdownView.buttonView.set( { //设置下拉视图按钮样式 withText: true, label: '文件解析', tooltip: true, } ); const uploadFile = new FileDialogButtonView( locale ); //上传文件button const uploadWord = new FileDialogButtonView( locale ); const uploadPPT = new FileDialogButtonView( locale ); function closeUI() { editor.editing.view.focus(); dropdownView.isOpen = false; } uploadFile.set( { acceptedType: '*', allowMultipleFiles: false } ); uploadWord.set( { acceptedType: '*', allowMultipleFiles: false } ); uploadPPT.set( { acceptedType: '*', allowMultipleFiles: false } ); uploadFile.buttonView.set( { withText: true, label: '上传视频文件', commandName:'uploadVideo', tooltip: true } ); uploadWord.buttonView.set( { withText: true, label: '上传word文档', commandName:'uploadWord', tooltip: true } ); uploadPPT.buttonView.set( { withText: true, label: '上传PPT文件', commandName:'uploadPPT', tooltip: true } ); const beforeUpload = this.editor.config.get('upload').beforeUpload //video uploadFile.on( 'done', ( evt, files ) => { const types = ["video/mp4"] var file = files[0] var size =file.size / 1024 / 1024 if(types.indexOf(file.type)==-1 && file.name.indexOf('.mp4')==-1){ beforeUpload&&beforeUpload('请选择MP4格式文件') return } if(size>500){ beforeUpload&&beforeUpload('mp4文件不能大于500M') return } editor.commands.get( 'uploadVideo' ).execute( { file: files[0] } ) closeUI() } ); //word uploadWord.on( 'done', ( evt, files ) => { const types = ["application/vnd.openxmlformats-officedocument.wordprocessingml.document"] var file = files[0] var size =file.size / 1024 / 1024 if(types.indexOf(file.type)==-1 && file.name.indexOf('.docx')==-1){ beforeUpload&&beforeUpload('请选择docx格式文件') return } if(size>50){ beforeUpload&&beforeUpload('docx文件不能大于50M') return } editor.commands.get( 'uploadWord' ).execute( { file: files[0] } ) closeUI() } ); //ppt uploadPPT.on( 'done', ( evt, files ) => { const types = ["application/vnd.openxmlformats-officedocument.presentationml.presentation"] var file = files[0] var size =file.size / 1024 / 1024 if(types.indexOf(file.type)==-1 && file.name.indexOf('.pptx')==-1){ beforeUpload&&beforeUpload('请选择pptx格式文件') return } if(size>50){ beforeUpload&&beforeUpload('ppt文件不能大于50M') return } editor.commands.get( 'uploadPPT' ).execute( { file: files[0] } ) closeUI() } ); // const items = new Collection(); //创建下拉菜单 // const enterUrl = { //定义输入地址按钮 // type: 'button', // model: new Model( { // withText: true, // label: '上传word文档', // commandName:'enterUrl' // } ) // }; // this.listenTo( dropdownView, 'execute', evt => { // editor.execute( 'uploadFile' ) // } ); addToolbarToDropdown( dropdownView, [uploadFile,uploadWord,uploadPPT] ); dropdownView.toolbarView.isVertical = true; // items.add({ // type:'button', // model:uploadFile // }); //将按钮放入列表中 // items.add( { // type:'button', // model:uploadWord // } ); // items.add( { // type:'button', // model:uploadPPT // } ); // addListToDropdown(dropdownView,items) //将列表放入下拉按钮中 return dropdownView; } ); } }
//// [genericCallWithObjectTypeArgsAndConstraints5.ts] // Generic call with constraints infering type parameter from object member properties class C { x: string; } class D { x: string; y: string; } function foo<T, U extends T>(t: T, t2: U) { return (x: T) => t2; } var c: C; var d: D; var r2 = foo(d, c); // the constraints are self-referencing, no downstream error var r9 = foo(() => 1, () => { }); // the constraints are self-referencing, no downstream error function other<T, U extends T>() { var r5 = foo<T, U>(c, d); // error } //// [genericCallWithObjectTypeArgsAndConstraints5.js] // Generic call with constraints infering type parameter from object member properties var C = /** @class */ (function () { function C() { } return C; }()); var D = /** @class */ (function () { function D() { } return D; }()); function foo(t, t2) { return function (x) { return t2; }; } var c; var d; var r2 = foo(d, c); // the constraints are self-referencing, no downstream error var r9 = foo(function () { return 1; }, function () { }); // the constraints are self-referencing, no downstream error function other() { var r5 = foo(c, d); // error }
// ==UserScript== // @namespace https://tampermonkey.myso.kr/ // @exclude * // ==UserLibrary== // @name prototype.collections // @description prototype.collections 스크립트 // @copyright 2021, myso (https://tampermonkey.myso.kr) // @license Apache-2.0 // @version 1.0.8 // ==/UserScript== // ==/UserLibrary== // ==OpenUserJS== // @author myso // ==/OpenUserJS== (function () { Object.pick = function(object, ...filter) { let keys = Object.keys(object).filter((key)=>filter.includes(key)); return keys.reduce((out, key)=>(out[key] = object[key], out), {}); } Object.omit = function(object, ...filter) { let keys = Object.keys(object).filter((key)=>!filter.includes(key)); return keys.reduce((out, key)=>(out[key] = object[key], out), {}); } Object.conservation = function(object, ...filter) { let keys = Object.keys(object).filter((key)=>!filter.includes(key)); keys.map((key)=>delete object[key]); } Object.exclusion = function(object, ...filter) { let keys = Object.keys(object).filter((key)=>filter.includes(key)); keys.map((key)=>delete object[key]); } Array.prototype.excludes = function(x) { return !this.includes(x); } function ArrayClass(Clazz) { let prototypeArray = Object.getOwnPropertyNames(Array.prototype); let prototypeClazz = Object.getOwnPropertyNames(Clazz.prototype); let prototype = prototypeArray.filter(prototypeClazz.excludes.bind(prototypeClazz)); prototype.push(Symbol.iterator, Symbol.unscopables); prototype.map(prototypeName=>{ if(typeof Clazz.prototype[prototypeName] !== 'undefined') return; Clazz.prototype[prototypeName] = Array.prototype[prototypeName]; }); } ArrayClass(NodeList); ArrayClass(DOMTokenList); ArrayClass(HTMLCollection); DOMTokenList.prototype.startsWith = function(className) { return this.find(o=>o.startsWith(className)); } DOMTokenList.prototype.endsWith = function(className) { return this.find(o=>o.endsWith(className)); } })();
suite('controllers/controls', function() { /*jshint maxlen:false*/ 'use strict'; suiteSetup(function(done) { var self = this; requirejs([ 'app', 'lib/camera/camera', 'controllers/controls', 'views/controls', 'lib/settings', 'lib/setting' ], function( App, Camera, ControlsController, ControlsView, Settings, Setting) { self.App = App; self.Camera = Camera; self.ControlsController = ControlsController.ControlsController; self.ControlsView = ControlsView; self.Settings = Settings; self.Setting = Setting; done(); }); }); setup(function() { this.app = sinon.createStubInstance(this.App); this.app.camera = sinon.createStubInstance(this.Camera); this.app.settings = sinon.createStubInstance(this.Settings); this.app.settings.mode = sinon.createStubInstance(this.Setting); this.app.views = { controls: sinon.createStubInstance(this.ControlsView) }; this.app.activity = { allowedTypes: {} }; // Fake available modes this.app.settings.mode.get .withArgs('options') .returns([{ key: 'picture' }, { key: 'video' }]); // Aliases this.controls = this.app.views.controls; this.view = this.app.views.controls; this.settings = this.app.settings; this.controller = new this.ControlsController(this.app); this.state = {}; }); teardown(function() { delete this.controller; }); suite('ControlsController()', function() { test('Should *not* show the cancel button when *not* within a \'pick\' activity', function() { assert.isTrue(this.app.views.controls.set.calledWith('cancel', false)); }); test('Should show the cancel button when within activity', function() { this.app.activity.pick = true; this.state.controller = new this.ControlsController(this.app); assert.isTrue(this.app.views.controls.set.calledWith('cancel', true)); }); test('It sets the mode to the value of the \'mode\' setting', function() { // Test 'picture' this.app.settings.mode.selected.returns('picture'); var controller = new this.ControlsController(this.app); sinon.assert.calledWith(this.view.setMode, 'picture'); this.view.set.reset(); // Test 'video' this.app.settings.mode.selected.returns('video'); controller = new this.ControlsController(this.app); sinon.assert.calledWith(this.view.setMode, 'video'); this.view.set.reset(); }); test('Should call the preview when click on thumbnail', function() { assert.ok(this.view.on.calledWith('click:thumbnail')); }); test('Should remove the capture button highlight when shutter fires', function() { sinon.assert.calledWith(this.app.on, 'camera:shutter'); // Call the callback this.app.on.withArgs('camera:shutter').args[0][1](); sinon.assert.calledWith(this.view.unset, 'capture-active'); }); test('Should disable the controls when the camera is busy', function() { // Call the callback and check the view was disabled this.app.on.withArgs('busy').args[0][1](); sinon.assert.called(this.view.disable); }); suite('app.once(\'loaded\')', function() { setup(function() { // Call the callback this.app.once.withArgs('loaded').args[0][1](); }); test('It enables the controls', function() { sinon.assert.called(this.view.enable); }); test('It \'restores\' the controls when the camera is \'ready\' from thereon after', function() { sinon.assert.calledWith(this.app.on, 'ready', this.controller.restore); }); }); test('Should hide the controls when the timer is started', function() { sinon.assert.calledWith(this.app.on, 'timer:started', this.controller.onTimerStarted); }); test('Should restore the controls when the timer is cleared', function() { sinon.assert.calledWith(this.app.on, 'timer:cleared', this.controller.onTimerStopped); sinon.assert.calledWith(this.app.on, 'timer:ended', this.controller.onTimerStopped); }); test('Should disable the view intitially until camera is ready', function() { sinon.assert.called(this.view.disable); }); }); suite('ControlsController#configureMode()', function() { test('It\'s not switchable when only one mode is available', function() { // Fake avaialable modes this.app.settings.mode.get .withArgs('options') .returns([{ key: 'picture' }]); this.controller.configureMode(); assert.isTrue(this.view.disable.calledWith('switch')); }); }); suite('ControlsController#onCaptureClick', function() { setup(function() { sinon.spy(this.controller, 'captureHighlightOn'); this.controller.onCaptureClick(); }); test('Should highlight the capture button', function() { assert.isTrue(this.controller.captureHighlightOn.calledOnce); }); test('Should fire a \'capture\' event on the app', function() { assert.isTrue(this.app.emit.calledWith('capture')); }); }); suite('ControlsController.onViewModeChanged()', function() { test('It switches to the next mode setting', function() { this.controller.onViewModeChanged(); sinon.assert.notCalled(this.view.enable); sinon.assert.called(this.settings.mode.next); }); }); });
const { Probot } = require('probot') const labelOfTheDay = require('../lib/label-of-the-day') describe('scheduled-merge', () => { let probot, probotScheduler, app, api, label beforeEach(() => { api = nock('https://api.github.com') probot = new Probot({ githubToken: 'test' }) label = labelOfTheDay() probotScheduler = td.replace('probot-scheduler') app = probot.load(require('..')) }) test('starts probot-scheduler', async () => { td.verify(probotScheduler(app, { delay: false })) }) test('does nothing when no label is found', async () => { api.get(`/repos/fake/stuff/labels/${label}`) .reply(404, { message: 'Not Found', documentation_url: 'https://developer.github.com/v3/issues/labels/#get-a-single-label' }) await probot.receive({ name: 'schedule.repository', payload: { 'repository': { 'name': 'stuff', 'owner': { 'login': 'fake' } } } }) }) test('does nothing when label is found but no pulls are open', async () => { api.get(`/repos/fake/stuff/labels/${label}`).reply(200, { name: label }) api.get('/repos/fake/stuff/issues') .query({ 'labels': label, 'state': 'open' }) .reply(200, []) await probot.receive({ name: 'schedule.repository', payload: { 'repository': { 'name': 'stuff', 'owner': { 'login': 'fake' } } } }) }) test('merges PR when labeled, open, and mergeable', async () => { api.get(`/repos/fake/stuff/labels/${label}`).reply(200, { name: label }) api.get('/repos/fake/stuff/issues') .query({ 'labels': label, 'state': 'open' }) .reply(200, [{ url: 'fake pull url', number: 999, labels: [{ name: label }], state: 'open' }]) api.put('/repos/fake/stuff/pulls/999/merge').reply(200) await probot.receive({ name: 'schedule.repository', payload: { 'repository': { 'name': 'stuff', 'owner': { 'login': 'fake' } } } }) }) test('leaves a comment when a PR is not mergeable', async () => { api.get(`/repos/fake/stuff/labels/${label}`).reply(200, { name: label }) api.get('/repos/fake/stuff/issues') .query({ 'labels': label, 'state': 'open' }) .reply(200, [{ number: 999 }]) api.put('/repos/fake/stuff/pulls/999/merge') .reply(405, { 'message': 'Pull Request is not mergeable' }) api.post('/repos/fake/stuff/issues/999/comments', { body: 'Failed to automatically merge with error: **Pull Request is not mergeable**' }).reply(201) await probot.receive({ name: 'schedule.repository', payload: { 'repository': { 'name': 'stuff', 'owner': { 'login': 'fake' } } } }) }) })
# Copyright 2016 Google Inc. All Rights Reserved. # # Licensed under the Apache License, Version 2.0 (the "License"); # you may not use this file except in compliance with the License. # You may obtain a copy of the License at # # http://www.apache.org/licenses/LICENSE-2.0 # # Unless required by applicable law or agreed to in writing, software # distributed under the License is distributed on an "AS IS" BASIS, # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. # See the License for the specific language governing permissions and # limitations under the License. """CRM API Folders utilities.""" from googlecloudsdk.api_lib.util import apis from googlecloudsdk.core import resources FOLDERS_API_VERSION = 'v2beta1' def FoldersClient(): return apis.GetClientInstance('cloudresourcemanager', FOLDERS_API_VERSION) def FoldersRegistry(): registry = resources.REGISTRY.Clone() registry.RegisterApiByName('cloudresourcemanager', FOLDERS_API_VERSION) return registry def FoldersService(): return FoldersClient().folders def FoldersMessages(): return apis.GetMessagesModule('cloudresourcemanager', FOLDERS_API_VERSION) def FolderNameToId(folder_name): return folder_name[len('folders/'):] def FolderIdToName(folder_id): return 'folders/{0}'.format(folder_id) def GetFolder(folder_id): return FoldersService().Get( FoldersMessages().CloudresourcemanagerFoldersGetRequest( foldersId=folder_id)) def GetIamPolicy(folder_id): messages = FoldersMessages() request = messages.CloudresourcemanagerFoldersGetIamPolicyRequest( foldersId=folder_id, getIamPolicyRequest=messages.GetIamPolicyRequest()) return FoldersService().GetIamPolicy(request) def SetIamPolicy(folder_id, policy, update_mask=None): """Calls /google.cloud.resourcemanager.v2beta1.Folders.SetIamPolicy.""" messages = FoldersMessages() set_iam_policy_request = messages.SetIamPolicyRequest( policy=policy, updateMask=update_mask) request = messages.CloudresourcemanagerFoldersSetIamPolicyRequest( foldersId=folder_id, setIamPolicyRequest=set_iam_policy_request) return FoldersService().SetIamPolicy(request) def GetUri(resource): """Returns the uri for resource.""" folder_id = FolderNameToId(resource.name) folder_ref = FoldersRegistry().Parse( None, params={'foldersId': folder_id}, collection='cloudresourcemanager.folders') return folder_ref.SelfLink()
import PropTypes from 'prop-types'; import React from 'react'; import muiThemeable from 'material-ui/styles/muiThemeable'; import CartIcon from 'material-ui/svg-icons/action/shopping-cart'; import EuroIcon from 'material-ui/svg-icons/action/euro-symbol'; import DateIcon from 'material-ui/svg-icons/action/date-range'; import VatwareCircularProgress from '../shared/VatwareCircularProgress'; import { ColumnsObject, InvoiceArray } from './Proptypes'; const Icons = [ <EuroIcon color="white" />, <CartIcon color="white" />, <DateIcon color="white" /> ]; const getBackground = (status) => { if (status && status.Value === 'Rejected') return 'url(\'/content/img/hero-bg-red.png\')'; if (status && status.Value === 'Approved') return 'url(\'/content/img/hero-bg-green.png\')'; return 'url(\'/content/img/hero-bg-blue.png\')'; }; const SovosHeroBanner = ({ invoiceNumber, attempts, exeuctingAction, invoice, columns, containerStyle, textStyle, muiTheme, isLoading }) => { const styles = { container: { backgroundImage: isLoading ? 'none' : getBackground(invoice.find(x => x.Key === 'RESERVED_CurrentState')), height: 210, opacity: 0.9, lineHeight: '18px', display: 'flex', alignItems: 'center', padding: 20, ...containerStyle }, title: { ...muiTheme.heroBanner.title, ...textStyle }, subtitles: { ...muiTheme.heroBanner.subtitles, ...textStyle }, statusSubtitle: { ...muiTheme.heroBanner.subtitles, ...textStyle, fontSize: '0.9rem' }, icons: { color: 'rgb(255, 255, 255)', fontFamily: 'Roboto, sans-serif', fontSize: '18px', fontWeight: '300', margin: '1.25rem 50px 1.25rem 0px' }, sideContainer: { width: '100%', display: 'flex', justifyContent: 'flex-end' }, text: { position: 'relative', top: '-5px', padding: '5px' }, status: { backgroundColor: 'rgba(0, 0, 0, 0.7)', padding: '20px', textAlign: 'center', borderRadius: '3px', height: '65px', display: 'flex', flexDirection: 'column', alignItems: 'center', justifyContent: 'center' } }; const getDisplayStatus = (status) => { if (status === null) return 'Pending'; return status; }; return ( <div> <div style={ styles.container }> <div className="col-sm-8 col-md-9"> <span style={ styles.title }>Sale #{invoiceNumber}</span> <div style={ { display: 'flex', alignItems: 'center' } }> {columns.length > 0 ? columns.map((col, index) => <div style={ styles.icons } key={ index }> {Icons[index]}<span style={ styles.text }>{`${invoice.find(x => x.Key === col.ObjectPath).Value} ${col.Name}`}</span> </div>) : null} </div> </div> <div className="col-sm-4 col-md-3"> <div style={ styles.status }> { exeuctingAction && <VatwareCircularProgress /> } { !exeuctingAction && <div> { !isLoading && <p style={ styles.subtitles }>{getDisplayStatus(invoice.find(x => x.Key === 'RESERVED_CurrentState').Value)}</p>} { !isLoading && attempts > 0 && <p style={ styles.statusSubtitle }>{`${attempts} attempts`}</p> } </div> } </div> </div> </div> </div> ); }; SovosHeroBanner.propTypes = { invoiceNumber: PropTypes.string, attempts: PropTypes.number, columns: PropTypes.arrayOf(ColumnsObject), invoice: InvoiceArray, containerStyle: PropTypes.object, textStyle: PropTypes.object, muiTheme: PropTypes.object.isRequired, exeuctingAction: PropTypes.bool.isRequired, isLoading: PropTypes.bool }; SovosHeroBanner.defaultProps = { invoice: [], attempts: 0 }; export default muiThemeable()(SovosHeroBanner);
const {Router} = require('express'); const CarModel = require('../persistence/car-models'); const router = new Router(); router.post('/', async (request, response) => { try { const {model, color, production_year} = request.body; if (!model || !color || !production_year) { return response .status(400) .json({message: 'model, color and production year must be provided'}); } const carModel = await CarModel.create(model, color, production_year); return response.status(200).json(carModel); } catch (error) { console.error( `createCarModel({ car model: ${request.body.model} }) >> Error: ${error.stack}` ); response.status(500).json(); } }); router.get('/', async (request, response) => { try { const {id} = request.body; if (!id) { return response .status(400) .json({message: 'id must be provided'}); } const carModel = await CarModel.find(id); if (!carModel) { return response.status(400).json({message: 'car model does not exists'}); } return response.status(200).json(carModel); } catch (error) { console.error( `findCarModel({ car model id: ${request.body.id} }) >> Error: ${error.stack}` ); response.status(500).json(); } }); router.put('/', async (request, response) => { try { const {id, model, color, production_year} = request.body; if (!id || !model || !color || !production_year) { return response .status(400) .json({message: 'id, model, color and production year must be provided'}); } const carModel = await CarModel.update(id, model, color, production_year); return response.status(200).json(carModel); } catch (error) { console.error( `updateCarModel({ car model id: ${request.body.id} }) >> Error: ${error.stack}` ); response.status(500).json(); } }); router.delete('/', async (request, response) => { try { const {id} = request.body; if (!id) { return response .status(400) .json({message: 'id must be provided'}); } await CarModel.delete(id); response.status(200).json(); } catch (error) { console.error(`DELETE car model with id: ${request.body.id} >> ${error.stack}`); response.status(500).json(); } }); module.exports = router;
"use strict"; /* * ATTENTION: An "eval-source-map" devtool has been used. * This devtool is neither made for production nor for readable output files. * It uses "eval()" calls to create a separate source file with attached SourceMaps in the browser devtools. * If you are trying to read the output file, select a different devtool (https://webpack.js.org/configuration/devtool/) * or disable the default devtool with "devtool: false". * If you are looking for production-ready output files, see mode: "production" (https://webpack.js.org/configuration/mode/). */ self["webpackHotUpdate_N_E"]("pages/index",{ /***/ "./components/header.js": /*!******************************!*\ !*** ./components/header.js ***! \******************************/ /***/ (function(module, __webpack_exports__, __webpack_require__) { eval("__webpack_require__.r(__webpack_exports__);\n/* harmony import */ var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__ = __webpack_require__(/*! react/jsx-dev-runtime */ \"./node_modules/react/jsx-dev-runtime.js\");\n/* harmony import */ var react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0___default = /*#__PURE__*/__webpack_require__.n(react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__);\n/* harmony import */ var styled_components__WEBPACK_IMPORTED_MODULE_2__ = __webpack_require__(/*! styled-components */ \"./node_modules/styled-components/dist/styled-components.browser.esm.js\");\n/* harmony import */ var next_image__WEBPACK_IMPORTED_MODULE_1__ = __webpack_require__(/*! next/image */ \"./node_modules/next/image.js\");\n/* harmony import */ var next_image__WEBPACK_IMPORTED_MODULE_1___default = /*#__PURE__*/__webpack_require__.n(next_image__WEBPACK_IMPORTED_MODULE_1__);\n\n\n\nfunction _taggedTemplateLiteral(strings, raw) {\n if (!raw) {\n raw = strings.slice(0);\n }\n return Object.freeze(Object.defineProperties(strings, {\n raw: {\n value: Object.freeze(raw)\n }\n }));\n}\nvar _this = undefined;\nfunction _templateObject() {\n var data = _taggedTemplateLiteral([\n \"\\n display: flex;\\n align-items: center;\\n justify-content: space-between;\\n padding: 50px 100px;\\n background-color: #EEEDDE;\\n position: sticky;\\n @media(max-width: 768px) {\\n padding: 10px;\\n }\\n \"\n ]);\n _templateObject = function _templateObject() {\n return data;\n };\n return data;\n}\nfunction _templateObject1() {\n var data = _taggedTemplateLiteral([\n \"\\n display: flex;\\n list-style-type: none;\\n justify-content: space-between;\\n @media(max-width: 768px) {\\n display: none;\\n }\\n \"\n ]);\n _templateObject1 = function _templateObject1() {\n return data;\n };\n return data;\n}\nfunction _templateObject2() {\n var data = _taggedTemplateLiteral([\n \"\\n display: none;\\n @media(max-width: 768px) {\\n display: inline;\\n }\\n \"\n ]);\n _templateObject2 = function _templateObject2() {\n return data;\n };\n return data;\n}\nfunction _templateObject3() {\n var data = _taggedTemplateLiteral([\n \"\\n width: 570px;\\n \"\n ]);\n _templateObject3 = function _templateObject3() {\n return data;\n };\n return data;\n}\nfunction _templateObject4() {\n var data = _taggedTemplateLiteral([\n \"\\n width: 20px;\\n height: 3px;\\n background-color: transparent;\\n border-radius: 20px;\\n \"\n ]);\n _templateObject4 = function _templateObject4() {\n return data;\n };\n return data;\n}\nfunction _templateObject5() {\n var data = _taggedTemplateLiteral([\n \"\\n display: flex;\\n flex-direction: column;\\n align-items: center;\\n cursor: pointer;\\n &:hover {\\n \",\n \" {\\n background-color: #F6762E;\\n }\\n font-weight: 600;\\n }\\n \"\n ]);\n _templateObject5 = function _templateObject5() {\n return data;\n };\n return data;\n}\nfunction _templateObject6() {\n var data = _taggedTemplateLiteral([\n \"\\n display: flex;\\n \"\n ]);\n _templateObject6 = function _templateObject6() {\n return data;\n };\n return data;\n}\nvar Header = function() {\n var Headers = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].header(_templateObject());\n var Ul = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].ul(_templateObject1());\n var Figure = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].figure(_templateObject2());\n var Nav = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].nav(_templateObject3());\n var Line = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].div(_templateObject4());\n var Li = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].li(_templateObject5(), Line);\n var Span = styled_components__WEBPACK_IMPORTED_MODULE_2__[\"default\"].li(_templateObject6());\n return(/*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Headers, {\n children: [\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(\"h1\", {\n children: \"0home\"\n }, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 55,\n columnNumber: 13\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Nav, {\n children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Ul, {\n children: [\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Li, {\n children: [\n \"Home \",\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Line, {}, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 58,\n columnNumber: 30\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 58,\n columnNumber: 21\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Li, {\n children: [\n \"About \",\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Line, {}, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 59,\n columnNumber: 31\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 59,\n columnNumber: 21\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Span, {\n children: [\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Li, {\n children: [\n \"Properties \",\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Line, {}, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 61,\n columnNumber: 40\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 61,\n columnNumber: 25\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)((next_image__WEBPACK_IMPORTED_MODULE_1___default()), {\n src: \"/arrow.png\",\n width: 24,\n height: 20,\n alt: \"dropdown\"\n }, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 62,\n columnNumber: 25\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 60,\n columnNumber: 21\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Li, {\n children: [\n \"Contact \",\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Line, {}, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 64,\n columnNumber: 33\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 64,\n columnNumber: 21\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 57,\n columnNumber: 17\n }, _this)\n }, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 56,\n columnNumber: 13\n }, _this),\n /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)(Figure, {\n children: /*#__PURE__*/ (0,react_jsx_dev_runtime__WEBPACK_IMPORTED_MODULE_0__.jsxDEV)((next_image__WEBPACK_IMPORTED_MODULE_1___default()), {\n src: \"/menu.svg\",\n width: 42,\n height: 42,\n alt: \"menu\"\n }, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 68,\n columnNumber: 17\n }, _this)\n }, void 0, false, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 67,\n columnNumber: 13\n }, _this)\n ]\n }, void 0, true, {\n fileName: \"C:\\\\Users\\\\daril\\\\Documents\\\\nextjs\\\\restate\\\\components\\\\header.js\",\n lineNumber: 54,\n columnNumber: 9\n }, _this));\n};\n_c = Header;\n/* harmony default export */ __webpack_exports__[\"default\"] = (Header);\nvar _c;\n$RefreshReg$(_c, \"Header\");\n\n\n;\n // Wrapped in an IIFE to avoid polluting the global scope\n ;\n (function () {\n var _a, _b;\n // Legacy CSS implementations will `eval` browser code in a Node.js context\n // to extract CSS. For backwards compatibility, we need to check we're in a\n // browser context before continuing.\n if (typeof self !== 'undefined' &&\n // AMP / No-JS mode does not inject these helpers:\n '$RefreshHelpers$' in self) {\n // @ts-ignore __webpack_module__ is global\n var currentExports = module.exports;\n // @ts-ignore __webpack_module__ is global\n var prevExports = (_b = (_a = module.hot.data) === null || _a === void 0 ? void 0 : _a.prevExports) !== null && _b !== void 0 ? _b : null;\n // This cannot happen in MainTemplate because the exports mismatch between\n // templating and execution.\n self.$RefreshHelpers$.registerExportsForReactRefresh(currentExports, module.id);\n // A module can be accepted automatically based on its exports, e.g. when\n // it is a Refresh Boundary.\n if (self.$RefreshHelpers$.isReactRefreshBoundary(currentExports)) {\n // Save the previous exports on update so we can compare the boundary\n // signatures.\n module.hot.dispose(function (data) {\n data.prevExports = currentExports;\n });\n // Unconditionally accept an update to this module, we'll check if it's\n // still a Refresh Boundary later.\n // @ts-ignore importMeta is replaced in the loader\n module.hot.accept();\n // This field is set when the previous version of this module was a\n // Refresh Boundary, letting us know we need to check for invalidation or\n // enqueue an update.\n if (prevExports !== null) {\n // A boundary can become ineligible if its exports are incompatible\n // with the previous exports.\n //\n // For example, if you add/remove/change exports, we'll want to\n // re-execute the importing modules, and force those components to\n // re-render. Similarly, if you convert a class component to a\n // function, we want to invalidate the boundary.\n if (self.$RefreshHelpers$.shouldInvalidateReactRefreshBoundary(prevExports, currentExports)) {\n module.hot.invalidate();\n }\n else {\n self.$RefreshHelpers$.scheduleUpdate();\n }\n }\n }\n else {\n // Since we just executed the code for the module, it's possible that the\n // new exports made it ineligible for being a boundary.\n // We only care about the case when we were _previously_ a boundary,\n // because we already accepted this update (accidental side effect).\n var isNoLongerABoundary = prevExports !== null;\n if (isNoLongerABoundary) {\n module.hot.invalidate();\n }\n }\n }\n })();\n//# sourceURL=[module]\n//# sourceMappingURL=data:application/json;charset=utf-8;base64,eyJ2ZXJzaW9uIjozLCJmaWxlIjoiLi9jb21wb25lbnRzL2hlYWRlci5qcy5qcyIsIm1hcHBpbmdzIjoiOzs7Ozs7O0FBQXNDO0FBQ1I7Ozs7Ozs7Ozs7Ozs7O1FBRUksQ0FVOUI7Ozs7Ozs7OztRQUNxQixDQU9yQjs7Ozs7Ozs7O1FBQzZCLENBSzdCOzs7Ozs7Ozs7UUFDdUIsQ0FFdkI7Ozs7Ozs7OztRQUN3QixDQUt4Qjs7Ozs7Ozs7O1FBQ3FCLENBTWI7UUFBTyxDQUtmOzs7Ozs7Ozs7UUFDdUIsQ0FFdkI7Ozs7Ozs7QUFqREosR0FBSyxDQUFDRSxNQUFNLEdBQUcsUUFBUSxHQUFGLENBQUM7SUFDbEIsR0FBSyxDQUFDQyxPQUFPLEdBQUdILGdFQUFhO0lBVzdCLEdBQUssQ0FBQ0ssRUFBRSxHQUFHTCw0REFBUztJQVFwQixHQUFLLENBQUNPLE1BQU0sR0FBR1AsZ0VBQWE7SUFNNUIsR0FBSyxDQUFDUyxHQUFHLEdBQUdULDZEQUFVO0lBR3RCLEdBQUssQ0FBQ1csSUFBSSxHQUFHWCw2REFBVTtJQU12QixHQUFLLENBQUNhLEVBQUUsR0FBR2IsNERBQVMscUJBTVZXLElBQUk7SUFNZCxHQUFLLENBQUNJLElBQUksR0FBR2YsNERBQVM7SUFHdEIsTUFBTSw2RUFDREcsT0FBTzs7d0ZBQ0hhLENBQUU7MEJBQUMsQ0FBSzs7Ozs7O3dGQUNSUCxHQUFHO3NHQUNDSixFQUFFOztvR0FDRVEsRUFBRTs7Z0NBQUMsQ0FBSzs0R0FBQ0YsSUFBSTs7Ozs7Ozs7Ozs7b0dBQ2JFLEVBQUU7O2dDQUFDLENBQU07NEdBQUNGLElBQUk7Ozs7Ozs7Ozs7O29HQUNkSSxJQUFJOzs0R0FDQUYsRUFBRTs7d0NBQUMsQ0FBVztvSEFBQ0YsSUFBSTs7Ozs7Ozs7Ozs7NEdBQ25CVixtREFBSztvQ0FBQ2dCLEdBQUcsRUFBQyxDQUFZO29DQUFDQyxLQUFLLEVBQUUsRUFBRTtvQ0FBRUMsTUFBTSxFQUFFLEVBQUU7b0NBQUVDLEdBQUcsRUFBQyxDQUFVOzs7Ozs7Ozs7Ozs7b0dBRWhFUCxFQUFFOztnQ0FBQyxDQUFROzRHQUFDRixJQUFJOzs7Ozs7Ozs7Ozs7Ozs7Ozs7Ozs7O3dGQUd4QkosTUFBTTtzR0FDRk4sbURBQUs7b0JBQUNnQixHQUFHLEVBQUMsQ0FBVztvQkFBQ0MsS0FBSyxFQUFFLEVBQUU7b0JBQUVDLE1BQU0sRUFBRSxFQUFFO29CQUFFQyxHQUFHLEVBQUMsQ0FBTTs7Ozs7Ozs7Ozs7Ozs7Ozs7QUFJeEUsQ0FBQztLQXJFS2xCLE1BQU07QUF1RVosK0RBQWVBLE1BQU0iLCJzb3VyY2VzIjpbIndlYnBhY2s6Ly9fTl9FLy4vY29tcG9uZW50cy9oZWFkZXIuanM/YzA5OCJdLCJzb3VyY2VzQ29udGVudCI6WyJpbXBvcnQgc3R5bGVkIGZyb20gXCJzdHlsZWQtY29tcG9uZW50c1wiXHJcbmltcG9ydCBJbWFnZSBmcm9tIFwibmV4dC9pbWFnZVwiXHJcbmNvbnN0IEhlYWRlciA9ICgpID0+IHtcclxuICAgIGNvbnN0IEhlYWRlcnMgPSBzdHlsZWQuaGVhZGVyYFxyXG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XHJcbiAgICAgICAgYWxpZ24taXRlbXM6IGNlbnRlcjtcclxuICAgICAgICBqdXN0aWZ5LWNvbnRlbnQ6IHNwYWNlLWJldHdlZW47XHJcbiAgICAgICAgcGFkZGluZzogNTBweCAxMDBweDtcclxuICAgICAgICBiYWNrZ3JvdW5kLWNvbG9yOiAjRUVFRERFO1xyXG4gICAgICAgIHBvc2l0aW9uOiBzdGlja3k7XHJcbiAgICAgICAgQG1lZGlhKG1heC13aWR0aDogNzY4cHgpIHtcclxuICAgICAgICAgICAgcGFkZGluZzogMTBweDtcclxuICAgICAgICB9XHJcbiAgICBgXHJcbiAgICBjb25zdCBVbCA9IHN0eWxlZC51bGBcclxuICAgICAgICBkaXNwbGF5OiBmbGV4O1xyXG4gICAgICAgIGxpc3Qtc3R5bGUtdHlwZTogbm9uZTtcclxuICAgICAgICBqdXN0aWZ5LWNvbnRlbnQ6IHNwYWNlLWJldHdlZW47XHJcbiAgICAgICAgQG1lZGlhKG1heC13aWR0aDogNzY4cHgpIHtcclxuICAgICAgICAgICAgZGlzcGxheTogbm9uZTtcclxuICAgICAgICB9XHJcbiAgICBgXHJcbiAgICBjb25zdCBGaWd1cmUgPSBzdHlsZWQuZmlndXJlYFxyXG4gICAgICAgIGRpc3BsYXk6IG5vbmU7XHJcbiAgICAgICAgQG1lZGlhKG1heC13aWR0aDogNzY4cHgpIHtcclxuICAgICAgICAgICAgZGlzcGxheTogaW5saW5lO1xyXG4gICAgICAgIH1cclxuICAgIGBcclxuICAgIGNvbnN0IE5hdiA9IHN0eWxlZC5uYXZgXHJcbiAgICAgICAgd2lkdGg6IDU3MHB4O1xyXG4gICAgYFxyXG4gICAgY29uc3QgTGluZSA9IHN0eWxlZC5kaXZgXHJcbiAgICAgICAgd2lkdGg6IDIwcHg7XHJcbiAgICAgICAgaGVpZ2h0OiAzcHg7XHJcbiAgICAgICAgYmFja2dyb3VuZC1jb2xvcjogdHJhbnNwYXJlbnQ7XHJcbiAgICAgICAgYm9yZGVyLXJhZGl1czogMjBweDtcclxuICAgIGBcclxuICAgIGNvbnN0IExpID0gc3R5bGVkLmxpYFxyXG4gICAgICAgIGRpc3BsYXk6IGZsZXg7XHJcbiAgICAgICAgZmxleC1kaXJlY3Rpb246IGNvbHVtbjtcclxuICAgICAgICBhbGlnbi1pdGVtczogY2VudGVyO1xyXG4gICAgICAgIGN1cnNvcjogcG9pbnRlcjtcclxuICAgICAgICAmOmhvdmVyIHtcclxuICAgICAgICAgICAgJHtMaW5lfSB7XHJcbiAgICAgICAgICAgICAgICBiYWNrZ3JvdW5kLWNvbG9yOiAjRjY3NjJFO1xyXG4gICAgICAgICAgICB9XHJcbiAgICAgICAgICAgIGZvbnQtd2VpZ2h0OiA2MDA7XHJcbiAgICAgICAgfVxyXG4gICAgYFxyXG4gICAgY29uc3QgU3BhbiA9IHN0eWxlZC5saWBcclxuICAgICAgICBkaXNwbGF5OiBmbGV4O1xyXG4gICAgYFxyXG4gICAgcmV0dXJuIChcclxuICAgICAgICA8SGVhZGVycz5cclxuICAgICAgICAgICAgPGgxPjBob21lPC9oMT5cclxuICAgICAgICAgICAgPE5hdj5cclxuICAgICAgICAgICAgICAgIDxVbD5cclxuICAgICAgICAgICAgICAgICAgICA8TGk+SG9tZSA8TGluZT48L0xpbmU+PC9MaT5cclxuICAgICAgICAgICAgICAgICAgICA8TGk+QWJvdXQgPExpbmU+PC9MaW5lPjwvTGk+XHJcbiAgICAgICAgICAgICAgICAgICAgPFNwYW4+XHJcbiAgICAgICAgICAgICAgICAgICAgICAgIDxMaT5Qcm9wZXJ0aWVzIDxMaW5lPjwvTGluZT48L0xpPlxyXG4gICAgICAgICAgICAgICAgICAgICAgICA8SW1hZ2Ugc3JjPVwiL2Fycm93LnBuZ1wiIHdpZHRoPXsyNH0gaGVpZ2h0PXsyMH0gYWx0PVwiZHJvcGRvd25cIiAvPlxyXG4gICAgICAgICAgICAgICAgICAgIDwvU3Bhbj5cclxuICAgICAgICAgICAgICAgICAgICA8TGk+Q29udGFjdCA8TGluZT48L0xpbmU+PC9MaT5cclxuICAgICAgICAgICAgICAgIDwvVWw+XHJcbiAgICAgICAgICAgIDwvTmF2PlxyXG4gICAgICAgICAgICA8RmlndXJlPlxyXG4gICAgICAgICAgICAgICAgPEltYWdlIHNyYz0nL21lbnUuc3ZnJyB3aWR0aD17NDJ9IGhlaWdodD17NDJ9IGFsdD1cIm1lbnVcIiAvPlxyXG4gICAgICAgICAgICA8L0ZpZ3VyZT5cclxuICAgICAgICA8L0hlYWRlcnM+XHJcbiAgICApXHJcbn1cclxuXHJcbmV4cG9ydCBkZWZhdWx0IEhlYWRlciJdLCJuYW1lcyI6WyJzdHlsZWQiLCJJbWFnZSIsIkhlYWRlciIsIkhlYWRlcnMiLCJoZWFkZXIiLCJVbCIsInVsIiwiRmlndXJlIiwiZmlndXJlIiwiTmF2IiwibmF2IiwiTGluZSIsImRpdiIsIkxpIiwibGkiLCJTcGFuIiwiaDEiLCJzcmMiLCJ3aWR0aCIsImhlaWdodCIsImFsdCJdLCJzb3VyY2VSb290IjoiIn0=\n//# sourceURL=webpack-internal:///./components/header.js\n"); /***/ }) });
from __future__ import annotations import math import wx import wx.grid as gridlib import wx.lib.scrolledpanel as scroll_pan from dials.array_family import flex from dials.viewer.from_flex_to_wxbitmap import wxbitmap_convert class grid_frame(wx.Frame): def __init__(self, parent, title): super().__init__(parent, title=title, size=wx.DefaultSize) def frame_ini_img(self, in_upper_panel, text_data=None): self.img_panel = in_upper_panel if text_data is not None: self.myGrid = text_data self.my_sizer = wx.BoxSizer(wx.VERTICAL) if text_data is not None: self.my_sizer.Add( self.myGrid, proportion=3, flag=wx.EXPAND | wx.ALL, border=3 ) self.my_sizer.SetMinSize((900, 600)) self.SetSizer(self.my_sizer) self.my_sizer.Fit(self) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) def OnCloseWindow(self, event): wx.Exit() class flex_3d_frame(wx.Frame): def __init__(self, parent, title): super().__init__(parent, title=title, size=wx.DefaultSize) self.table_exist = False def frame_ini_img(self, in_upper_panel, text_data=None): self.img_panel = in_upper_panel self.myGrid = None if text_data is not None: self.myGrid = text_data self.my_sizer = wx.BoxSizer(wx.VERTICAL) self.my_sizer.Add( self.img_panel, proportion=2, flag=wx.EXPAND | wx.ALL, border=3 ) if text_data is not None: self.my_sizer.Add( self.myGrid, proportion=3, flag=wx.EXPAND | wx.ALL, border=3 ) self.my_sizer.SetMinSize((400, 200)) self.SetSizer(self.my_sizer) self.my_sizer.Fit(self) self.Bind(wx.EVT_CLOSE, self.OnCloseWindow) def OnCloseWindow(self, event): if not self.table_exist: # print "from flex_3d_frame self.myGrid = None" event.Skip() else: # print "from flex_3d_frame self.myGrid .NEQ. None" wx.Exit() class TupTable(gridlib.GridTableBase): def __init__(self, data, rowLabels=None, colLabels=None): super().__init__() self.data = data self.rowLabels = rowLabels self.colLabels = colLabels def GetNumberRows(self): return len(self.data) def GetNumberCols(self): return len(self.data[0]) def GetColLabelValue(self, col): if self.colLabels: return self.colLabels[col] def GetRowLabelValue(self, row): if self.rowLabels: return str(self.rowLabels[row]) def IsEmptyCell(self, row, col): return False def GetValue(self, row, col): return self.data[row][col] def SetValue(self, row, col, value): pass class MyGrid(gridlib.Grid): def __init__(self, parent_frame): self.parent_fr = parent_frame super().__init__(parent_frame) def ini_n_intro(self, table_in): self.lst_keys = [] self.data = [] self.sorted_flags = [] for key in table_in.keys(): if key != "shoebox": col_label = str(key) col_content = list(map(str, table_in[key])) str_len = bigger_size(col_label, col_content) if str_len > len(col_label): lng_dif = int(float(str_len - len(col_label)) * 1.6) add_str = " " * lng_dif col_label = add_str + col_label + add_str else: col_label = " " + col_label + " " self.lst_keys.append(col_label) self.data.append(col_content) self.sorted_flags.append(True) self.lst_keys.append("lst pos") self.data.append(list(range(len(table_in)))) self.sorted_flags.append(True) self.last_col_num = len(self.lst_keys) - 1 self.data = tuple(zip(*self.data)) self.EnableEditing(True) self.EnableDragGridSize(True) self.set_my_table(self.last_col_num) self.Bind(gridlib.EVT_GRID_CELL_LEFT_CLICK, self.OnCellLeftClick) self.Bind(gridlib.EVT_GRID_LABEL_LEFT_CLICK, self.OnLabelLeftClick) def OnLabelLeftClick(self, evt): if evt.GetCol() == -1: self.repaint_img(evt.GetRow()) else: self.set_my_table(evt.GetCol()) evt.Skip() def set_my_table(self, col_to_sort): self.sorted_flags[col_to_sort] = not self.sorted_flags[col_to_sort] try: tupldata = sorted( self.data, key=lambda x: int(x[col_to_sort]), reverse=self.sorted_flags[col_to_sort], ) print("using key=lambda x: int(x[col_to_sort])") except Exception: try: tupldata = sorted( self.data, key=lambda x: float(x[col_to_sort]), reverse=self.sorted_flags[col_to_sort], ) print("using key=lambda x: float(x[col_to_sort])") except Exception: tupldata = sorted( self.data, key=lambda x: tuple(eval(str(x[col_to_sort]))), reverse=self.sorted_flags[col_to_sort], ) print("using key=lambda x: tuple(x[col_to_sort])") colLabels = tuple(self.lst_keys) rowLabels = tuple(range(len(tupldata))) tableBase = TupTable(tupldata, rowLabels, colLabels) # self.AutoSizeColumns(False) self.SetTable(tableBase, takeOwnership=True) self.Refresh() # self.AutoSizeColumn(1) for i in range(len(self.lst_keys)): self.AutoSizeColLabelSize(i) # self.AutoSizeColumns(True) def OnCellLeftClick(self, evt): self.repaint_img(evt.GetRow()) evt.Skip() def repaint_img(self, clikd_row): new_row = int(self.GetCellValue(clikd_row, self.last_col_num)) self.parent_fr.img_panel.update_img_w_row_pos(new_row) class flex_arr_img_panel(wx.Panel): def __init__(self, parent_frame): super().__init__(parent_frame) self.show_nums = True self.show_mask = True self.palette = "black2white" self.row_pos = 0 self.Pframe = parent_frame self.local_bbox = (0, 0, 2, 2, 4, 4) def ini_n_intro(self, data_in_one, data_in_two=None): self.scale = 1.0 if isinstance(data_in_one, flex.reflection_table): self.table = data_in_one self.assign_row_pos() else: self.first_lst_in, self.segn_lst_in = data_in_one, data_in_two print("flex array entered") self.local_bbox = None self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_left = buttons_panel(self) self.panel_right = multi_img_scrollable(self, self.bmp_lst) sizer = wx.BoxSizer(wx.HORIZONTAL) sizer.Add(self.panel_left, 0, wx.EXPAND) sizer.Add(self.panel_right, 1, wx.EXPAND) self.SetSizer(sizer) self.Show(True) def assign_row_pos(self): try: self.first_lst_in, self.segn_lst_in = ( self.table[self.row_pos]["shoebox"].data, self.table[self.row_pos]["shoebox"].mask, ) self.local_bbox = self.table[self.row_pos]["bbox"] except Exception: self.first_lst_in, self.segn_lst_in = None, None def _mi_list_of_wxbitmaps(self, re_scaling=False): if not re_scaling: if self.show_mask: self.lst_bmp_obj = wxbitmap_convert(self.first_lst_in, self.segn_lst_in) else: self.lst_bmp_obj = wxbitmap_convert(self.first_lst_in, None) return self.lst_bmp_obj.get_wxbitmap_lst( show_nums=self.show_nums, palette=self.palette, scale=self.scale ) else: return self.lst_bmp_obj.scaling(scale=self.scale) def update_img_w_row_pos(self, num): self.row_pos = num self.assign_row_pos() self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_hide_nums(self): self.show_nums = False self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_show_nums(self): self.show_nums = True self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_show_mask(self): self.show_mask = True self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_hide_mask(self): self.show_mask = False self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_change_palette(self, palette_name=None): if palette_name is None: print("Something went wrong") else: self.palette = palette_name self.bmp_lst = self._mi_list_of_wxbitmaps() self.panel_right.img_refresh(self.bmp_lst) def to_re_zoom(self, rot_sn): if rot_sn > 0: for ntimes in range(int(math.fabs(rot_sn))): self.scale = self.scale * 1.05 if self.scale > 3.0: # Maximum possible zoom reached self.scale = 3.0 elif rot_sn < 0: for ntimes in range(int(math.fabs(rot_sn))): self.scale = self.scale * 0.95 if self.scale < 0.2: # Minimum possible zoom reached self.scale = 0.2 self.bmp_lst = self._mi_list_of_wxbitmaps(re_scaling=True) self.panel_right.img_refresh(self.bmp_lst) class multi_img_scrollable(scroll_pan.ScrolledPanel): def __init__(self, outer_panel, i_bmp_in): super().__init__(outer_panel) self.parent_panel = outer_panel self.lst_2d_bmp = i_bmp_in self.SetBackgroundColour(wx.Colour(200, 200, 200)) self.mainSizer = wx.BoxSizer(wx.VERTICAL) self.n_img = 0 self.img_lst_v_sizer = wx.BoxSizer(wx.VERTICAL) self.set_scroll_content() self.mainSizer.Add(self.img_lst_v_sizer, 0, wx.CENTER | wx.ALL, 10) self.SetSizer(self.mainSizer) self.SetupScrolling() self.SetScrollRate(1, 1) self.Mouse_Pos_x = -1 self.Mouse_Pos_y = -1 self.old_Mouse_Pos_x = -1 self.old_Mouse_Pos_y = -1 self.Bind(wx.EVT_MOUSEWHEEL, self.OnMouseWheel) self.Bind(wx.EVT_MOTION, self.OnMouseMotion) self.Bind(wx.EVT_LEFT_DOWN, self.OnLeftButDown) self.Bind(wx.EVT_LEFT_UP, self.OnLeftButUp) self.Bind(wx.EVT_IDLE, self.OnIdle) self.scroll_rot = 0 def OnLeftButDown(self, event): self.Bdwn = True self.old_Mouse_Pos_x, self.old_Mouse_Pos_y = event.GetPosition() def OnLeftButUp(self, event): self.Bdwn = False _ = event.GetPosition() def set_scroll_content(self): self.img_lst_v_sizer.Clear(True) for lst_1d in self.lst_2d_bmp: img_lst_hor_sizer = wx.BoxSizer(wx.HORIZONTAL) for i, i_bmp in enumerate(lst_1d): local_bitmap = wx.StaticBitmap(self, bitmap=i_bmp) if self.parent_panel.local_bbox is None: slice_string = "Slice[" + str(i) + ":" + str(i + 1) + ", :, :]" else: bbx = self.parent_panel.local_bbox slice_string = "Image # " + str(bbx[4] + i) slice_sub_info_txt = wx.StaticText(self, -1, slice_string) sigle_slice_sizer = wx.BoxSizer(wx.VERTICAL) sigle_slice_sizer.Clear(True) sigle_slice_sizer.Add( local_bitmap, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=2 ) sigle_slice_sizer.Add( slice_sub_info_txt, proportion=0, flag=wx.ALIGN_CENTRE | wx.ALL, border=2, ) img_lst_hor_sizer.Add( sigle_slice_sizer, proportion=0, flag=wx.ALIGN_CENTER | wx.ALL, border=2, ) self.img_lst_v_sizer.Add(img_lst_hor_sizer, 0, wx.CENTER | wx.ALL, 10) self.n_img += 1 self.parent_panel.Pframe.Layout() self.SetScrollRate(1, 1) def OnMouseMotion(self, event): self.Mouse_Pos_x, self.Mouse_Pos_y = event.GetPosition() def OnMouseWheel(self, event): # Getting amount of scroll steps to do sn_mov = math.copysign(1, float(event.GetWheelRotation())) self.scroll_rot += sn_mov # Getting relative position of scrolling area to keep after scrolling v_size_x, v_size_y = self.GetVirtualSize() self.Mouse_Pos_x, self.Mouse_Pos_y = event.GetPosition() View_start_x, View_start_y = self.GetViewStart() self.x_uni = float(View_start_x + self.Mouse_Pos_x) / float(v_size_x) self.y_uni = float(View_start_y + self.Mouse_Pos_y) / float(v_size_y) def img_refresh(self, i_bmp_new): self.lst_2d_bmp = i_bmp_new self.set_scroll_content() def OnIdle(self, event): if self.scroll_rot != 0: self.SetScrollRate(1, 1) self.parent_panel.to_re_zoom(self.scroll_rot) self.scroll_rot = 0 v_size_x, v_size_y = self.GetVirtualSize() new_scroll_pos_x = float(self.x_uni * v_size_x - self.Mouse_Pos_x) new_scroll_pos_y = float(self.y_uni * v_size_y - self.Mouse_Pos_y) self.Scroll(new_scroll_pos_x, new_scroll_pos_y) else: if self.old_Mouse_Pos_x != -1 and self.old_Mouse_Pos_y != -1: # print "need to move IMG" pass self.old_Mouse_Pos_x = self.Mouse_Pos_x self.old_Mouse_Pos_y = self.Mouse_Pos_y class buttons_panel(wx.Panel): def __init__(self, outer_panel): super().__init__(outer_panel) self.parent_panel = outer_panel Show_Its_CheckBox = wx.CheckBox(self, -1, "Show I nums") Show_Its_CheckBox.SetValue(True) Show_Its_CheckBox.Bind(wx.EVT_CHECKBOX, self.OnItsCheckbox) self.my_sizer = wx.BoxSizer(wx.VERTICAL) self.my_sizer.Add(Show_Its_CheckBox, proportion=0, flag=wx.ALIGN_TOP, border=5) if self.parent_panel.segn_lst_in is not None: Show_Msk_CheckBox = wx.CheckBox(self, -1, "Show Mask") Show_Msk_CheckBox.SetValue(True) Show_Msk_CheckBox.Bind(wx.EVT_CHECKBOX, self.OnMskCheckbox) self.my_sizer.Add( Show_Msk_CheckBox, proportion=0, flag=wx.ALIGN_TOP, border=5 ) masck_conv_str = "\n Mask Convention:" masck_conv_str += "\n [Valid] = \\\\\\\\\\\\ " masck_conv_str += "\n [Foreground] = ////// " masck_conv_str += "\n [Background] = |||||| " masck_conv_str += "\n [BackgroundUsed] = ------" label_mask = wx.StaticText(self, -1, masck_conv_str) self.my_sizer.Add(label_mask, proportion=0, flag=wx.ALIGN_TOP, border=5) label_palette = wx.StaticText(self, -1, "\nColour Palettes") self.RadButtb2w = wx.RadioButton(self, -1, "black2white") self.RadButtw2b = wx.RadioButton(self, -1, "white2black") self.RadButtha = wx.RadioButton(self, -1, "hot ascend") self.RadButthd = wx.RadioButton(self, -1, "hot descend") self.RadButtb2w.Bind(wx.EVT_RADIOBUTTON, self.OnButtb2w) self.RadButtw2b.Bind(wx.EVT_RADIOBUTTON, self.OnButtw2b) self.RadButtha.Bind(wx.EVT_RADIOBUTTON, self.OnButtha) self.RadButthd.Bind(wx.EVT_RADIOBUTTON, self.OnButthd) self.my_sizer.Add(label_palette, proportion=0, flag=wx.ALIGN_TOP, border=5) self.my_sizer.Add(self.RadButtb2w, proportion=0, flag=wx.ALIGN_TOP, border=5) self.my_sizer.Add(self.RadButtw2b, proportion=0, flag=wx.ALIGN_TOP, border=5) self.my_sizer.Add(self.RadButtha, proportion=0, flag=wx.ALIGN_TOP, border=5) self.my_sizer.Add(self.RadButthd, proportion=0, flag=wx.ALIGN_TOP, border=5) self.my_sizer.SetMinSize((50, 300)) self.SetSizer(self.my_sizer) def OnButtb2w(self, event): self.OnButtUpdate() def OnButtw2b(self, event): self.OnButtUpdate() def OnButtha(self, event): self.OnButtUpdate() def OnButthd(self, event): self.OnButtUpdate() def OnButtUpdate(self): print("OnButtUpdate(self):") if self.RadButtb2w.GetValue(): self.parent_panel.to_change_palette("black2white") elif self.RadButtw2b.GetValue(): self.parent_panel.to_change_palette("white2black") elif self.RadButtha.GetValue(): self.parent_panel.to_change_palette("hot ascend") else: self.parent_panel.to_change_palette("hot descend") def OnItsCheckbox(self, event): if event.IsChecked(): self.parent_panel.to_show_nums() else: self.parent_panel.to_hide_nums() def OnMskCheckbox(self, event): if event.IsChecked(): self.parent_panel.to_show_mask() else: self.parent_panel.to_hide_mask() def bigger_size(str_label, lst_col): lng_label_ini = len(str_label) lng_lst_col = len(lst_col) lng_final = lng_label_ini if lng_lst_col < 30: pos_lst = list(range(lng_lst_col)) else: pos_lst = list(range(15)) pos_lst += list(range(lng_lst_col - 15, lng_lst_col)) lng_cel_zero = 0 for pos in pos_lst: lng_cel_pos = len(str(lst_col[pos])) if lng_cel_pos > lng_cel_zero: lng_cel_zero = lng_cel_pos if lng_cel_zero > lng_label_ini: lng_final = lng_cel_zero return lng_final
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * The production EmptyStatement ; is evaluated as follows Return (normal, empty, empty) * * @path ch12/12.3/S12.3_A1.js * @description Using EmptyStatement ; */ ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;; ;;;;; ;;;;;; ;; ;; ;;;;;; ;;;;;;;; ;; ;; ;;;;; ;;;;; ;; ;;;; ;;;; ;; ;; ;; ;; ;; ;;;;; ;;;;; ;;;; ;; ;;;; ;; ;;;;;; ;; ;;;; ;;;;; ;;;;; ;; ;; ;; ;; ;; ;; ;; ;;;;; ;;;;; ;;;;;; ;; ;; ;; ;; ;; ;;;;; ;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;;